clang 23.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
38#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
40#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
41#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
43#include "clang/Sema/DeclSpec.h"
46#include "clang/Sema/Lookup.h"
48#include "clang/Sema/Scope.h"
51#include "clang/Sema/SemaARM.h"
52#include "clang/Sema/SemaCUDA.h"
53#include "clang/Sema/SemaHLSL.h"
55#include "clang/Sema/SemaObjC.h"
58#include "clang/Sema/SemaPPC.h"
60#include "clang/Sema/SemaSYCL.h"
62#include "clang/Sema/SemaWasm.h"
63#include "clang/Sema/Template.h"
64#include "llvm/ADT/ArrayRef.h"
65#include "llvm/ADT/STLForwardCompat.h"
66#include "llvm/ADT/ScopeExit.h"
67#include "llvm/ADT/SmallPtrSet.h"
68#include "llvm/ADT/SmallString.h"
69#include "llvm/ADT/StringExtras.h"
70#include "llvm/ADT/StringRef.h"
71#include "llvm/Support/SaveAndRestore.h"
72#include "llvm/TargetParser/Triple.h"
73#include <algorithm>
74#include <cstring>
75#include <optional>
76#include <unordered_map>
77
78using namespace clang;
79using namespace sema;
80
82 if (OwnedType) {
83 Decl *Group[2] = { OwnedType, Ptr };
85 }
86
88}
89
90namespace {
91
92class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
93 public:
94 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
95 bool AllowTemplates = false,
96 bool AllowNonTemplates = true)
97 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
98 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
99 WantExpressionKeywords = false;
100 WantCXXNamedCasts = false;
101 WantRemainingKeywords = false;
102 }
103
104 bool ValidateCandidate(const TypoCorrection &candidate) override {
105 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
106 if (!AllowInvalidDecl && ND->isInvalidDecl())
107 return false;
108
109 if (getAsTypeTemplateDecl(ND))
110 return AllowTemplates;
111
112 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
113 if (!IsType)
114 return false;
115
116 if (AllowNonTemplates)
117 return true;
118
119 // An injected-class-name of a class template (specialization) is valid
120 // as a template or as a non-template.
121 if (AllowTemplates) {
122 auto *RD = dyn_cast<CXXRecordDecl>(ND);
123 if (!RD || !RD->isInjectedClassName())
124 return false;
125 RD = cast<CXXRecordDecl>(RD->getDeclContext());
126 return RD->getDescribedClassTemplate() ||
128 }
129
130 return false;
131 }
132
133 return !WantClassName && candidate.isKeyword();
134 }
135
136 std::unique_ptr<CorrectionCandidateCallback> clone() override {
137 return std::make_unique<TypeNameValidatorCCC>(*this);
138 }
139
140 private:
141 bool AllowInvalidDecl;
142 bool WantClassName;
143 bool AllowTemplates;
144 bool AllowNonTemplates;
145};
146
147} // end anonymous namespace
148
150 TypeDecl *TD, SourceLocation NameLoc) {
151 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
152 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
153 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
154 FoundRD->isInjectedClassName() &&
155 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
156 Diag(NameLoc,
158 ? diag::ext_out_of_line_qualified_id_type_names_constructor
159 : diag::err_out_of_line_qualified_id_type_names_constructor)
160 << TD->getIdentifier() << /*Type=*/1
161 << 0 /*if any keyword was present, it was 'typename'*/;
162 }
163
164 DiagnoseUseOfDecl(TD, NameLoc);
165 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
191 if (BaseRD) {
192 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
193 Base.getType().getCanonicalType())) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
207 CTD->findPartialSpecialization(Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(&II)) {
215 if (!isa<TypeDecl>(ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
257 // allowed. We'll fully resolve the lookup during template instantiation.
258 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259
260 ASTContext &Context = S.Context;
261 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
262 QualType T =
263 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274}
275
277 Scope *S, CXXScopeSpec *SS, bool isClassName,
278 bool HasTrailingDot, ParsedType ObjectTypePtr,
279 bool IsCtorOrDtorName,
280 bool WantNontrivialTypeSourceInfo,
281 bool IsClassTemplateDeductionContext,
282 ImplicitTypenameContext AllowImplicitTypename,
283 IdentifierInfo **CorrectedII) {
284 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
285 // FIXME: Consider allowing this outside C++1z mode as an extension.
286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
288 !HasTrailingDot;
289
290 // Determine where we will perform name lookup.
291 DeclContext *LookupCtx = nullptr;
292 if (ObjectTypePtr) {
293 QualType ObjectType = ObjectTypePtr.get();
294 if (ObjectType->isRecordType())
295 LookupCtx = computeDeclContext(ObjectType);
296 } else if (SS && SS->isNotEmpty()) {
297 LookupCtx = computeDeclContext(*SS, false);
298
299 if (!LookupCtx) {
300 if (isDependentScopeSpecifier(*SS)) {
301 // C++ [temp.res]p3:
302 // A qualified-id that refers to a type and in which the
303 // nested-name-specifier depends on a template-parameter (14.6.2)
304 // shall be prefixed by the keyword typename to indicate that the
305 // qualified-id denotes a type, forming an
306 // elaborated-type-specifier (7.1.5.3).
307 //
308 // We therefore do not perform any name lookup if the result would
309 // refer to a member of an unknown specialization.
310 // In C++2a, in several contexts a 'typename' is not required. Also
311 // allow this as an extension.
312 if (IsImplicitTypename) {
313 if (AllowImplicitTypename == ImplicitTypenameContext::No)
314 return nullptr;
315 SourceLocation QualifiedLoc = SS->getRange().getBegin();
316 // FIXME: Defer the diagnostic after we build the type and use it.
317 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
318 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
319 SS->getScopeRep(), &II);
321 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
322 }
323
324 // We know from the grammar that this name refers to a type,
325 // so build a dependent node to describe the type.
326 if (WantNontrivialTypeSourceInfo)
327 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
328 (ImplicitTypenameContext)IsImplicitTypename)
329 .get();
330
333 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
335 SourceLocation(), QualifierLoc, II, NameLoc);
336 return ParsedType::make(T);
337 }
338
339 return nullptr;
340 }
341
342 if (!LookupCtx->isDependentContext() &&
343 RequireCompleteDeclContext(*SS, LookupCtx))
344 return nullptr;
345 }
346
347 // In the case where we know that the identifier is a class name, we know that
348 // it is a type declaration (struct, class, union or enum) so we can use tag
349 // name lookup.
350 //
351 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
352 // the component name of the type-name or simple-template-id is type-only.
353 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
354 LookupResult Result(*this, &II, NameLoc, Kind);
355 if (LookupCtx) {
356 // Perform "qualified" name lookup into the declaration context we
357 // computed, which is either the type of the base of a member access
358 // expression or the declaration context associated with a prior
359 // nested-name-specifier.
360 LookupQualifiedName(Result, LookupCtx);
361
362 if (ObjectTypePtr && Result.empty()) {
363 // C++ [basic.lookup.classref]p3:
364 // If the unqualified-id is ~type-name, the type-name is looked up
365 // in the context of the entire postfix-expression. If the type T of
366 // the object expression is of a class type C, the type-name is also
367 // looked up in the scope of class C. At least one of the lookups shall
368 // find a name that refers to (possibly cv-qualified) T.
369 LookupName(Result, S);
370 }
371 } else {
372 // Perform unqualified name lookup.
373 LookupName(Result, S);
374
375 // For unqualified lookup in a class template in MSVC mode, look into
376 // dependent base classes where the primary class template is known.
377 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
378 if (ParsedType TypeInBase =
379 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
380 return TypeInBase;
381 }
382 }
383
384 NamedDecl *IIDecl = nullptr;
385 UsingShadowDecl *FoundUsingShadow = nullptr;
386 switch (Result.getResultKind()) {
388 if (CorrectedII) {
389 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
390 AllowDeducedTemplate);
391 TypoCorrection Correction =
392 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
394 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
396 bool MemberOfUnknownSpecialization;
398 TemplateName.setIdentifier(NewII, NameLoc);
400 CXXScopeSpec NewSS, *NewSSPtr = SS;
401 if (SS && NNS) {
402 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
403 NewSSPtr = &NewSS;
404 }
405 if (Correction && (NNS || NewII != &II) &&
406 // Ignore a correction to a template type as the to-be-corrected
407 // identifier is not a template (typo correction for template names
408 // is handled elsewhere).
409 !(getLangOpts().CPlusPlus && NewSSPtr &&
410 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
411 Template, MemberOfUnknownSpecialization))) {
412 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
413 isClassName, HasTrailingDot, ObjectTypePtr,
414 IsCtorOrDtorName,
415 WantNontrivialTypeSourceInfo,
416 IsClassTemplateDeductionContext);
417 if (Ty) {
418 diagnoseTypo(Correction,
419 PDiag(diag::err_unknown_type_or_class_name_suggest)
420 << Result.getLookupName() << isClassName);
421 if (SS && NNS)
422 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
423 *CorrectedII = NewII;
424 return Ty;
425 }
426 }
427 }
428 Result.suppressDiagnostics();
429 return nullptr;
431 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
432 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
433 SS->getScopeRep(), &II);
434 TypeLocBuilder TLB;
438 TL.setNameLoc(NameLoc);
439 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
440 }
441 [[fallthrough]];
444 Result.suppressDiagnostics();
445 return nullptr;
446
448 // Recover from type-hiding ambiguities by hiding the type. We'll
449 // do the lookup again when looking for an object, and we can
450 // diagnose the error then. If we don't do this, then the error
451 // about hiding the type will be immediately followed by an error
452 // that only makes sense if the identifier was treated like a type.
453 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
454 Result.suppressDiagnostics();
455 return nullptr;
456 }
457
458 // Look to see if we have a type anywhere in the list of results.
459 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
460 Res != ResEnd; ++Res) {
461 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
463 RealRes) ||
464 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
465 if (!IIDecl ||
466 // Make the selection of the recovery decl deterministic.
467 RealRes->getLocation() < IIDecl->getLocation()) {
468 IIDecl = RealRes;
469 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
470 }
471 }
472 }
473
474 if (!IIDecl) {
475 // None of the entities we found is a type, so there is no way
476 // to even assume that the result is a type. In this case, don't
477 // complain about the ambiguity. The parser will either try to
478 // perform this lookup again (e.g., as an object name), which
479 // will produce the ambiguity, or will complain that it expected
480 // a type name.
481 Result.suppressDiagnostics();
482 return nullptr;
483 }
484
485 // We found a type within the ambiguous lookup; diagnose the
486 // ambiguity and then return that type. This might be the right
487 // answer, or it might not be, but it suppresses any attempt to
488 // perform the name lookup again.
489 break;
490
492 IIDecl = Result.getFoundDecl();
493 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
494 break;
495 }
496
497 assert(IIDecl && "Didn't find decl");
498
499 TypeLocBuilder TLB;
500 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
501 checkTypeDeclType(LookupCtx,
502 IsImplicitTypename ? DiagCtorKind::Implicit
504 TD, NameLoc);
505 QualType T;
506 if (FoundUsingShadow) {
507 T = Context.getUsingType(ElaboratedTypeKeyword::None,
508 SS ? SS->getScopeRep() : std::nullopt,
509 FoundUsingShadow);
510 if (!WantNontrivialTypeSourceInfo)
511 return ParsedType::make(T);
512 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
515 NameLoc);
516 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
518 SS ? SS->getScopeRep() : std::nullopt, Tag,
519 /*OwnsTag=*/false);
520 if (!WantNontrivialTypeSourceInfo)
521 return ParsedType::make(T);
522 auto TL = TLB.push<TagTypeLoc>(T);
524 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
526 TL.setNameLoc(NameLoc);
527 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
528 TN && !isa<ObjCTypeParamDecl>(TN)) {
529 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
530 SS ? SS->getScopeRep() : std::nullopt, TN);
531 if (!WantNontrivialTypeSourceInfo)
532 return ParsedType::make(T);
533 TLB.push<TypedefTypeLoc>(T).set(
534 /*ElaboratedKeywordLoc=*/SourceLocation(),
536 NameLoc);
537 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
538 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
539 SS ? SS->getScopeRep() : std::nullopt,
540 UD);
541 if (!WantNontrivialTypeSourceInfo)
542 return ParsedType::make(T);
543 TLB.push<UnresolvedUsingTypeLoc>(T).set(
544 /*ElaboratedKeywordLoc=*/SourceLocation(),
546 NameLoc);
547 } else {
548 T = Context.getTypeDeclType(TD);
549 if (!WantNontrivialTypeSourceInfo)
550 return ParsedType::make(T);
552 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
553 else
554 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
555 }
556 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
557 }
558
559 if (getLangOpts().HLSL) {
560 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
561 getAsTemplateNameDecl(IIDecl, /*AllowFunctionTemplates=*/false,
562 /*AllowDependent=*/false))) {
563 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(TD, NameLoc);
564 if (!ShorthandTy.isNull())
565 return ParsedType::make(ShorthandTy);
566 }
567 }
568
569 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
570 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
571 if (!HasTrailingDot) {
572 // FIXME: Support UsingType for this case.
573 QualType T = Context.getObjCInterfaceType(IDecl);
574 if (!WantNontrivialTypeSourceInfo)
575 return ParsedType::make(T);
576 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
577 TL.setNameLoc(NameLoc);
578 // FIXME: Pass in this source location.
579 TL.setNameEndLoc(NameLoc);
580 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
581 }
582 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
583 (void)DiagnoseUseOfDecl(UD, NameLoc);
584 // Recover with 'int'
585 return ParsedType::make(Context.IntTy);
586 } else if (AllowDeducedTemplate) {
587 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
588 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
589 // FIXME: Support UsingType here.
590 TemplateName Template = Context.getQualifiedTemplateName(
591 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
592 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
593 QualType T = Context.getDeducedTemplateSpecializationType(
595 Template);
598 TL.setNameLoc(NameLoc);
599 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
601 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
602 }
603 }
604
605 // As it's not plausibly a type, suppress diagnostics.
606 Result.suppressDiagnostics();
607 return nullptr;
608}
609
610// Builds a fake NNS for the given decl context.
613 for (;; DC = DC->getLookupParent()) {
614 DC = DC->getPrimaryContext();
615 auto *ND = dyn_cast<NamespaceDecl>(DC);
616 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
617 return NestedNameSpecifier(Context, ND, std::nullopt);
618 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
619 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
622 }
623 llvm_unreachable("something isn't in TU scope?");
624}
625
626/// Find the parent class with dependent bases of the innermost enclosing method
627/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
628/// up allowing unqualified dependent type names at class-level, which MSVC
629/// correctly rejects.
630static const CXXRecordDecl *
632 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
633 DC = DC->getPrimaryContext();
634 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
635 if (MD->getParent()->hasAnyDependentBases())
636 return MD->getParent();
637 }
638 return nullptr;
639}
640
642 SourceLocation NameLoc,
643 bool IsTemplateTypeArg) {
644 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
645
646 NestedNameSpecifier NNS = std::nullopt;
647 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
648 // If we weren't able to parse a default template argument, delay lookup
649 // until instantiation time by making a non-dependent DependentTypeName. We
650 // pretend we saw a NestedNameSpecifier referring to the current scope, and
651 // lookup is retried.
652 // FIXME: This hurts our diagnostic quality, since we get errors like "no
653 // type named 'Foo' in 'current_namespace'" when the user didn't write any
654 // name specifiers.
656 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
657 } else if (const CXXRecordDecl *RD =
659 // Build a DependentNameType that will perform lookup into RD at
660 // instantiation time.
661 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
662
663 // Diagnose that this identifier was undeclared, and retry the lookup during
664 // template instantiation.
665 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
666 << RD;
667 } else {
668 // This is not a situation that we should recover from.
669 return ParsedType();
670 }
671
672 QualType T =
673 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
674
675 // Build type location information. We synthesized the qualifier, so we have
676 // to build a fake NestedNameSpecifierLoc.
677 NestedNameSpecifierLocBuilder NNSLocBuilder;
678 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
679 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
680
681 TypeLocBuilder Builder;
682 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
683 DepTL.setNameLoc(NameLoc);
685 DepTL.setQualifierLoc(QualifierLoc);
686 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
687}
688
690 // Do a tag name lookup in this scope.
691 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
692 LookupName(R, S, false);
693 R.suppressDiagnostics();
694 if (R.getResultKind() == LookupResultKind::Found)
695 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
696 switch (TD->getTagKind()) {
702 return DeclSpec::TST_union;
704 return DeclSpec::TST_class;
706 return DeclSpec::TST_enum;
707 }
708 }
709
711}
712
714 if (!CurContext->isRecord())
715 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
716
717 switch (SS->getScopeRep().getKind()) {
719 return true;
721 QualType T(SS->getScopeRep().getAsType(), 0);
722 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
723 if (Context.hasSameUnqualifiedType(T, Base.getType()))
724 return true;
725 [[fallthrough]];
726 }
727 default:
728 return S->isFunctionPrototypeScope();
729 }
730}
731
733 SourceLocation IILoc,
734 Scope *S,
735 CXXScopeSpec *SS,
736 ParsedType &SuggestedType,
737 bool IsTemplateName) {
738 // Don't report typename errors for editor placeholders.
739 if (II->isEditorPlaceholder())
740 return;
741 // We don't have anything to suggest (yet).
742 SuggestedType = nullptr;
743
744 // There may have been a typo in the name of the type. Look up typo
745 // results, in case we have something that we can suggest.
746 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
747 /*AllowTemplates=*/IsTemplateName,
748 /*AllowNonTemplates=*/!IsTemplateName);
749 if (TypoCorrection Corrected =
752 // FIXME: Support error recovery for the template-name case.
753 bool CanRecover = !IsTemplateName;
754 if (Corrected.isKeyword()) {
755 // We corrected to a keyword.
756 diagnoseTypo(Corrected,
757 PDiag(IsTemplateName ? diag::err_no_template_suggest
758 : diag::err_unknown_typename_suggest)
759 << II);
760 II = Corrected.getCorrectionAsIdentifierInfo();
761 } else {
762 // We found a similarly-named type or interface; suggest that.
763 if (!SS || !SS->isSet()) {
764 diagnoseTypo(Corrected,
765 PDiag(IsTemplateName ? diag::err_no_template_suggest
766 : diag::err_unknown_typename_suggest)
767 << II, CanRecover);
768 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
769 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
770 bool DroppedSpecifier =
771 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
772 diagnoseTypo(Corrected,
773 PDiag(IsTemplateName
774 ? diag::err_no_member_template_suggest
775 : diag::err_unknown_nested_typename_suggest)
776 << II << DC << DroppedSpecifier << SS->getRange(),
777 CanRecover);
778 } else {
779 llvm_unreachable("could not have corrected a typo here");
780 }
781
782 if (!CanRecover)
783 return;
784
785 CXXScopeSpec tmpSS;
786 if (Corrected.getCorrectionSpecifier())
787 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
788 SourceRange(IILoc));
789 // FIXME: Support class template argument deduction here.
790 SuggestedType =
791 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
792 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
793 /*IsCtorOrDtorName=*/false,
794 /*WantNontrivialTypeSourceInfo=*/true);
795 }
796 return;
797 }
798
799 if (getLangOpts().CPlusPlus && !IsTemplateName) {
800 // See if II is a class template that the user forgot to pass arguments to.
801 UnqualifiedId Name;
802 Name.setIdentifier(II, IILoc);
803 CXXScopeSpec EmptySS;
804 TemplateTy TemplateResult;
805 bool MemberOfUnknownSpecialization;
806 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
807 Name, nullptr, true, TemplateResult,
808 MemberOfUnknownSpecialization) == TNK_Type_template) {
809 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
810 return;
811 }
812 }
813
814 // FIXME: Should we move the logic that tries to recover from a missing tag
815 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
816
817 if (!SS || (!SS->isSet() && !SS->isInvalid()))
818 Diag(IILoc, IsTemplateName ? diag::err_no_template
819 : diag::err_unknown_typename)
820 << II;
821 else if (DeclContext *DC = computeDeclContext(*SS, false))
822 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
823 : diag::err_typename_nested_not_found)
824 << II << DC << SS->getRange();
825 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
826 SuggestedType =
827 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
828 } else if (isDependentScopeSpecifier(*SS)) {
829 unsigned DiagID = diag::err_typename_missing;
830 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
831 DiagID = diag::ext_typename_missing;
832
833 SuggestedType =
834 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
835
836 Diag(SS->getRange().getBegin(), DiagID)
837 << GetTypeFromParser(SuggestedType)
838 << SourceRange(SS->getRange().getBegin(), IILoc)
839 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
840 } else {
841 assert(SS && SS->isInvalid() &&
842 "Invalid scope specifier has already been diagnosed");
843 }
844}
845
846/// Determine whether the given result set contains either a type name
847/// or
848static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
849 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
850 NextToken.is(tok::less);
851
852 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
854 return true;
855
856 if (CheckTemplate && isa<TemplateDecl>(*I))
857 return true;
858 }
859
860 return false;
861}
862
864 Scope *S, CXXScopeSpec &SS,
865 IdentifierInfo *&Name,
866 SourceLocation NameLoc) {
867 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
868 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
869 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
870 StringRef FixItTagName;
871 switch (Tag->getTagKind()) {
873 FixItTagName = "class ";
874 break;
875
877 FixItTagName = "enum ";
878 break;
879
881 FixItTagName = "struct ";
882 break;
883
885 FixItTagName = "__interface ";
886 break;
887
889 FixItTagName = "union ";
890 break;
891 }
892
893 StringRef TagName = FixItTagName.drop_back();
894 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
895 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
896 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
897
898 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
899 I != IEnd; ++I)
900 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
901 << Name << TagName;
902
903 // Replace lookup results with just the tag decl.
905 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
906 return true;
907 }
908
909 return false;
910}
911
913 IdentifierInfo *&Name,
914 SourceLocation NameLoc,
915 const Token &NextToken,
917 DeclarationNameInfo NameInfo(Name, NameLoc);
918 ObjCMethodDecl *CurMethod = getCurMethodDecl();
919
920 assert(NextToken.isNot(tok::coloncolon) &&
921 "parse nested name specifiers before calling ClassifyName");
922 if (getLangOpts().CPlusPlus && SS.isSet() &&
923 isCurrentClassName(*Name, S, &SS)) {
924 // Per [class.qual]p2, this names the constructors of SS, not the
925 // injected-class-name. We don't have a classification for that.
926 // There's not much point caching this result, since the parser
927 // will reject it later.
929 }
930
931 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
932 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
933 /*AllowBuiltinCreation=*/!CurMethod);
934
935 if (SS.isInvalid())
937
938 // For unqualified lookup in a class template in MSVC mode, look into
939 // dependent base classes where the primary class template is known.
940 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
941 if (ParsedType TypeInBase =
942 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
943 return TypeInBase;
944 }
945
946 // Perform lookup for Objective-C instance variables (including automatically
947 // synthesized instance variables), if we're in an Objective-C method.
948 // FIXME: This lookup really, really needs to be folded in to the normal
949 // unqualified lookup mechanism.
950 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
951 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
952 if (Ivar.isInvalid())
954 if (Ivar.isUsable())
956
957 // We defer builtin creation until after ivar lookup inside ObjC methods.
958 if (Result.empty())
960 }
961
962 bool SecondTry = false;
963 bool IsFilteredTemplateName = false;
964
965Corrected:
966 switch (Result.getResultKind()) {
968 // If an unqualified-id is followed by a '(', then we have a function
969 // call.
970 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
971 // In C++, this is an ADL-only call.
972 // FIXME: Reference?
975
976 // C90 6.3.2.2:
977 // If the expression that precedes the parenthesized argument list in a
978 // function call consists solely of an identifier, and if no
979 // declaration is visible for this identifier, the identifier is
980 // implicitly declared exactly as if, in the innermost block containing
981 // the function call, the declaration
982 //
983 // extern int identifier ();
984 //
985 // appeared.
986 //
987 // We also allow this in C99 as an extension. However, this is not
988 // allowed in all language modes as functions without prototypes may not
989 // be supported.
990 if (getLangOpts().implicitFunctionsAllowed()) {
991 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
993 }
994 }
995
996 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
997 // In C++20 onwards, this could be an ADL-only call to a function
998 // template, and we're required to assume that this is a template name.
999 //
1000 // FIXME: Find a way to still do typo correction in this case.
1002 Context.getAssumedTemplateName(NameInfo.getName());
1004 }
1005
1006 // In C, we first see whether there is a tag type by the same name, in
1007 // which case it's likely that the user just forgot to write "enum",
1008 // "struct", or "union".
1009 if (!getLangOpts().CPlusPlus && !SecondTry &&
1010 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1011 break;
1012 }
1013
1014 // Perform typo correction to determine if there is another name that is
1015 // close to this name.
1016 if (!SecondTry && CCC) {
1017 SecondTry = true;
1018 if (TypoCorrection Corrected =
1019 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1020 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1021 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1022 unsigned QualifiedDiag = diag::err_no_member_suggest;
1023
1024 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1025 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1026 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1027 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1028 UnqualifiedDiag = diag::err_no_template_suggest;
1029 QualifiedDiag = diag::err_no_member_template_suggest;
1030 } else if (UnderlyingFirstDecl &&
1031 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1032 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1033 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1034 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1035 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1036 }
1037
1038 if (SS.isEmpty()) {
1039 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1040 } else {// FIXME: is this even reachable? Test it.
1041 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1042 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1043 Name->getName() == CorrectedStr;
1044 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1045 << Name << computeDeclContext(SS, false)
1046 << DroppedSpecifier << SS.getRange());
1047 }
1048
1049 // Update the name, so that the caller has the new name.
1050 Name = Corrected.getCorrectionAsIdentifierInfo();
1051
1052 // Typo correction corrected to a keyword.
1053 if (Corrected.isKeyword())
1054 return Name;
1055
1056 // Also update the LookupResult...
1057 // FIXME: This should probably go away at some point
1058 Result.clear();
1059 Result.setLookupName(Corrected.getCorrection());
1060 if (FirstDecl)
1061 Result.addDecl(FirstDecl);
1062
1063 // If we found an Objective-C instance variable, let
1064 // LookupInObjCMethod build the appropriate expression to
1065 // reference the ivar.
1066 // FIXME: This is a gross hack.
1067 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1068 DeclResult R =
1069 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1070 if (R.isInvalid())
1072 if (R.isUsable())
1073 return NameClassification::NonType(Ivar);
1074 }
1075
1076 goto Corrected;
1077 }
1078 }
1079
1080 // We failed to correct; just fall through and let the parser deal with it.
1081 Result.suppressDiagnostics();
1083
1085 // We performed name lookup into the current instantiation, and there were
1086 // dependent bases, so we treat this result the same way as any other
1087 // dependent nested-name-specifier.
1088
1089 // C++ [temp.res]p2:
1090 // A name used in a template declaration or definition and that is
1091 // dependent on a template-parameter is assumed not to name a type
1092 // unless the applicable name lookup finds a type name or the name is
1093 // qualified by the keyword typename.
1094 //
1095 // FIXME: If the next token is '<', we might want to ask the parser to
1096 // perform some heroics to see if we actually have a
1097 // template-argument-list, which would indicate a missing 'template'
1098 // keyword here.
1100 }
1101
1105 break;
1106
1108 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1109 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1110 /*AllowDependent=*/false)) {
1111 // C++ [temp.local]p3:
1112 // A lookup that finds an injected-class-name (10.2) can result in an
1113 // ambiguity in certain cases (for example, if it is found in more than
1114 // one base class). If all of the injected-class-names that are found
1115 // refer to specializations of the same class template, and if the name
1116 // is followed by a template-argument-list, the reference refers to the
1117 // class template itself and not a specialization thereof, and is not
1118 // ambiguous.
1119 //
1120 // This filtering can make an ambiguous result into an unambiguous one,
1121 // so try again after filtering out template names.
1123 if (!Result.isAmbiguous()) {
1124 IsFilteredTemplateName = true;
1125 break;
1126 }
1127 }
1128
1129 // Diagnose the ambiguity and return an error.
1131 }
1132
1133 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1134 (IsFilteredTemplateName ||
1136 Result, /*AllowFunctionTemplates=*/true,
1137 /*AllowDependent=*/false,
1138 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1140 // C++ [temp.names]p3:
1141 // After name lookup (3.4) finds that a name is a template-name or that
1142 // an operator-function-id or a literal- operator-id refers to a set of
1143 // overloaded functions any member of which is a function template if
1144 // this is followed by a <, the < is always taken as the delimiter of a
1145 // template-argument-list and never as the less-than operator.
1146 // C++2a [temp.names]p2:
1147 // A name is also considered to refer to a template if it is an
1148 // unqualified-id followed by a < and name lookup finds either one
1149 // or more functions or finds nothing.
1150 if (!IsFilteredTemplateName)
1152
1153 bool IsFunctionTemplate;
1154 bool IsVarTemplate;
1156 if (Result.end() - Result.begin() > 1) {
1157 IsFunctionTemplate = true;
1158 Template = Context.getOverloadedTemplateName(Result.begin(),
1159 Result.end());
1160 } else if (!Result.empty()) {
1162 *Result.begin(), /*AllowFunctionTemplates=*/true,
1163 /*AllowDependent=*/false));
1164 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1165 IsVarTemplate = isa<VarTemplateDecl>(TD);
1166
1167 UsingShadowDecl *FoundUsingShadow =
1168 dyn_cast<UsingShadowDecl>(*Result.begin());
1169 assert(!FoundUsingShadow ||
1170 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1171 Template = Context.getQualifiedTemplateName(
1172 SS.getScopeRep(),
1173 /*TemplateKeyword=*/false,
1174 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1175 } else {
1176 // All results were non-template functions. This is a function template
1177 // name.
1178 IsFunctionTemplate = true;
1179 Template = Context.getAssumedTemplateName(NameInfo.getName());
1180 }
1181
1182 if (IsFunctionTemplate) {
1183 // Function templates always go through overload resolution, at which
1184 // point we'll perform the various checks (e.g., accessibility) we need
1185 // to based on which function we selected.
1186 Result.suppressDiagnostics();
1187
1189 }
1190
1191 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1193 }
1194
1195 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1196 QualType T;
1197 TypeLocBuilder TLB;
1198 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1199 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1200 USD);
1201 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1202 SS.getWithLocInContext(Context), NameLoc);
1203 } else {
1204 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1205 Type);
1206 if (isa<TagType>(T)) {
1207 auto TTL = TLB.push<TagTypeLoc>(T);
1209 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1210 TTL.setNameLoc(NameLoc);
1211 } else if (isa<TypedefType>(T)) {
1212 TLB.push<TypedefTypeLoc>(T).set(
1213 /*ElaboratedKeywordLoc=*/SourceLocation(),
1214 SS.getWithLocInContext(Context), NameLoc);
1215 } else if (isa<UnresolvedUsingType>(T)) {
1216 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1217 /*ElaboratedKeywordLoc=*/SourceLocation(),
1218 SS.getWithLocInContext(Context), NameLoc);
1219 } else {
1220 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1221 }
1222 }
1223 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
1224 };
1225
1226 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1227 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1228 DiagnoseUseOfDecl(Type, NameLoc);
1229 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1230 return BuildTypeFor(Type, *Result.begin());
1231 }
1232
1233 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1234 if (!Class) {
1235 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1236 if (ObjCCompatibleAliasDecl *Alias =
1237 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1238 Class = Alias->getClassInterface();
1239 }
1240
1241 if (Class) {
1242 DiagnoseUseOfDecl(Class, NameLoc);
1243
1244 if (NextToken.is(tok::period)) {
1245 // Interface. <something> is parsed as a property reference expression.
1246 // Just return "unknown" as a fall-through for now.
1247 Result.suppressDiagnostics();
1249 }
1250
1251 QualType T = Context.getObjCInterfaceType(Class);
1252 return ParsedType::make(T);
1253 }
1254
1256 // We want to preserve the UsingShadowDecl for concepts.
1257 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1261 }
1262
1263 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1264 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1266 }
1267
1268 // We can have a type template here if we're classifying a template argument.
1273
1274 // Check for a tag type hidden by a non-type decl in a few cases where it
1275 // seems likely a type is wanted instead of the non-type that was found.
1276 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1277 if ((NextToken.is(tok::identifier) ||
1278 (NextIsOp &&
1279 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1280 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1281 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1282 DiagnoseUseOfDecl(Type, NameLoc);
1283 return BuildTypeFor(Type, *Result.begin());
1284 }
1285
1286 // If we already know which single declaration is referenced, just annotate
1287 // that declaration directly. Defer resolving even non-overloaded class
1288 // member accesses, as we need to defer certain access checks until we know
1289 // the context.
1290 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1291 if (Result.isSingleResult() && !ADL &&
1292 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1293 return NameClassification::NonType(Result.getRepresentativeDecl());
1294
1295 // Otherwise, this is an overload set that we will need to resolve later.
1296 Result.suppressDiagnostics();
1298 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1299 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1300 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1301}
1302
1305 SourceLocation NameLoc) {
1306 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1307 CXXScopeSpec SS;
1308 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1309 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1310}
1311
1314 IdentifierInfo *Name,
1315 SourceLocation NameLoc,
1316 bool IsAddressOfOperand) {
1317 DeclarationNameInfo NameInfo(Name, NameLoc);
1318 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1319 NameInfo, IsAddressOfOperand,
1320 /*TemplateArgs=*/nullptr);
1321}
1322
1325 SourceLocation NameLoc,
1326 const Token &NextToken) {
1327 if (getCurMethodDecl() && SS.isEmpty())
1328 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1329 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1330
1331 // Reconstruct the lookup result.
1332 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1333 Result.addDecl(Found);
1334 Result.resolveKind();
1335
1336 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1337 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1338}
1339
1341 // For an implicit class member access, transform the result into a member
1342 // access expression if necessary.
1343 auto *ULE = cast<UnresolvedLookupExpr>(E);
1344 if ((*ULE->decls_begin())->isCXXClassMember()) {
1345 CXXScopeSpec SS;
1346 SS.Adopt(ULE->getQualifierLoc());
1347
1348 // Reconstruct the lookup result.
1349 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1351 Result.setNamingClass(ULE->getNamingClass());
1352 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1353 Result.addDecl(*I, I.getAccess());
1354 Result.resolveKind();
1356 nullptr, S);
1357 }
1358
1359 // Otherwise, this is already in the form we needed, and no further checks
1360 // are necessary.
1361 return ULE;
1362}
1363
1383
1385 assert(DC->getLexicalParent() == CurContext &&
1386 "The next DeclContext should be lexically contained in the current one.");
1387 CurContext = DC;
1388 S->setEntity(DC);
1389}
1390
1392 assert(CurContext && "DeclContext imbalance!");
1393
1394 CurContext = CurContext->getLexicalParent();
1395 assert(CurContext && "Popped translation unit!");
1396}
1397
1399 Decl *D) {
1400 // Unlike PushDeclContext, the context to which we return is not necessarily
1401 // the containing DC of TD, because the new context will be some pre-existing
1402 // TagDecl definition instead of a fresh one.
1403 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1404 CurContext = cast<TagDecl>(D)->getDefinition();
1405 assert(CurContext && "skipping definition of undefined tag");
1406 // Start lookups from the parent of the current context; we don't want to look
1407 // into the pre-existing complete definition.
1408 S->setEntity(CurContext->getLookupParent());
1409 return Result;
1410}
1411
1415
1417 // C++0x [basic.lookup.unqual]p13:
1418 // A name used in the definition of a static data member of class
1419 // X (after the qualified-id of the static member) is looked up as
1420 // if the name was used in a member function of X.
1421 // C++0x [basic.lookup.unqual]p14:
1422 // If a variable member of a namespace is defined outside of the
1423 // scope of its namespace then any name used in the definition of
1424 // the variable member (after the declarator-id) is looked up as
1425 // if the definition of the variable member occurred in its
1426 // namespace.
1427 // Both of these imply that we should push a scope whose context
1428 // is the semantic context of the declaration. We can't use
1429 // PushDeclContext here because that context is not necessarily
1430 // lexically contained in the current context. Fortunately,
1431 // the containing scope should have the appropriate information.
1432
1433 assert(!S->getEntity() && "scope already has entity");
1434
1435#ifndef NDEBUG
1436 Scope *Ancestor = S->getParent();
1437 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1438 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1439#endif
1440
1441 CurContext = DC;
1442 S->setEntity(DC);
1443
1444 if (S->getParent()->isTemplateParamScope()) {
1445 // Also set the corresponding entities for all immediately-enclosing
1446 // template parameter scopes.
1448 }
1449}
1450
1452 assert(S->getEntity() == CurContext && "Context imbalance!");
1453
1454 // Switch back to the lexical context. The safety of this is
1455 // enforced by an assert in EnterDeclaratorContext.
1456 Scope *Ancestor = S->getParent();
1457 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1458 CurContext = Ancestor->getEntity();
1459
1460 // We don't need to do anything with the scope, which is going to
1461 // disappear.
1462}
1463
1465 assert(S->isTemplateParamScope() &&
1466 "expected to be initializing a template parameter scope");
1467
1468 // C++20 [temp.local]p7:
1469 // In the definition of a member of a class template that appears outside
1470 // of the class template definition, the name of a member of the class
1471 // template hides the name of a template-parameter of any enclosing class
1472 // templates (but not a template-parameter of the member if the member is a
1473 // class or function template).
1474 // C++20 [temp.local]p9:
1475 // In the definition of a class template or in the definition of a member
1476 // of such a template that appears outside of the template definition, for
1477 // each non-dependent base class (13.8.2.1), if the name of the base class
1478 // or the name of a member of the base class is the same as the name of a
1479 // template-parameter, the base class name or member name hides the
1480 // template-parameter name (6.4.10).
1481 //
1482 // This means that a template parameter scope should be searched immediately
1483 // after searching the DeclContext for which it is a template parameter
1484 // scope. For example, for
1485 // template<typename T> template<typename U> template<typename V>
1486 // void N::A<T>::B<U>::f(...)
1487 // we search V then B<U> (and base classes) then U then A<T> (and base
1488 // classes) then T then N then ::.
1489 unsigned ScopeDepth = getTemplateDepth(S);
1490 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1491 DeclContext *SearchDCAfterScope = DC;
1492 for (; DC; DC = DC->getLookupParent()) {
1493 if (const TemplateParameterList *TPL =
1494 cast<Decl>(DC)->getDescribedTemplateParams()) {
1495 unsigned DCDepth = TPL->getDepth() + 1;
1496 if (DCDepth > ScopeDepth)
1497 continue;
1498 if (ScopeDepth == DCDepth)
1499 SearchDCAfterScope = DC = DC->getLookupParent();
1500 break;
1501 }
1502 }
1503 S->setLookupEntity(SearchDCAfterScope);
1504 }
1505}
1506
1508 // We assume that the caller has already called
1509 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1510 FunctionDecl *FD = D->getAsFunction();
1511 if (!FD)
1512 return;
1513
1514 // Same implementation as PushDeclContext, but enters the context
1515 // from the lexical parent, rather than the top-level class.
1516 assert(CurContext == FD->getLexicalParent() &&
1517 "The next DeclContext should be lexically contained in the current one.");
1518 CurContext = FD;
1520
1521 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1522 ParmVarDecl *Param = FD->getParamDecl(P);
1523 // If the parameter has an identifier, then add it to the scope
1524 if (Param->getIdentifier()) {
1525 S->AddDecl(Param);
1526 IdResolver.AddDecl(Param);
1527 }
1528 }
1529}
1530
1532 // Same implementation as PopDeclContext, but returns to the lexical parent,
1533 // rather than the top-level class.
1534 assert(CurContext && "DeclContext imbalance!");
1535 CurContext = CurContext->getLexicalParent();
1536 assert(CurContext && "Popped translation unit!");
1537}
1538
1539/// Determine whether overloading is allowed for a new function
1540/// declaration considering prior declarations of the same name.
1541///
1542/// This routine determines whether overloading is possible, not
1543/// whether a new declaration actually overloads a previous one.
1544/// It will return true in C++ (where overloads are always permitted)
1545/// or, as a C extension, when either the new declaration or a
1546/// previous one is declared with the 'overloadable' attribute.
1548 ASTContext &Context,
1549 const FunctionDecl *New) {
1550 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1551 return true;
1552
1553 // Multiversion function declarations are not overloads in the
1554 // usual sense of that term, but lookup will report that an
1555 // overload set was found if more than one multiversion function
1556 // declaration is present for the same name. It is therefore
1557 // inadequate to assume that some prior declaration(s) had
1558 // the overloadable attribute; checking is required. Since one
1559 // declaration is permitted to omit the attribute, it is necessary
1560 // to check at least two; hence the 'any_of' check below. Note that
1561 // the overloadable attribute is implicitly added to declarations
1562 // that were required to have it but did not.
1563 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1564 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1565 return ND->hasAttr<OverloadableAttr>();
1566 });
1567 } else if (Previous.getResultKind() == LookupResultKind::Found)
1568 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1569
1570 return false;
1571}
1572
1573void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1574 // Move up the scope chain until we find the nearest enclosing
1575 // non-transparent context. The declaration will be introduced into this
1576 // scope.
1577 while (S->getEntity() && S->getEntity()->isTransparentContext())
1578 S = S->getParent();
1579
1580 // Add scoped declarations into their context, so that they can be
1581 // found later. Declarations without a context won't be inserted
1582 // into any context.
1583 if (AddToContext)
1584 CurContext->addDecl(D);
1585
1586 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1587 // are function-local declarations.
1588 if (getLangOpts().CPlusPlus && D->isOutOfLine()) {
1589 if (!S->getFnParent())
1590 return;
1591
1592 // Even inside a function, an out-of-line definition of a type that is
1593 // nested inside a local class must not be pushed into the enclosing
1594 // function scope. For example:
1595 //
1596 // class A { public: class B; };
1597 // class A::B {}; // out-of-line definition inside the function
1598 // B b; // must fail - only A::B is valid
1599 // Wrapper{B{}} // must also fail
1600 //
1601 // Per C++ scoping rules only the qualified form A::B is accessible.
1602 // Without this guard, PushOnScopeChains would add B to the function's
1603 // local scope, making it findable via unqualified lookup, which is
1604 // incorrect. The condition targets TagDecls (class/struct/union/enum)
1605 // whose DeclContext is a CXXRecordDecl, i.e., types that are members
1606 // of a local class being defined out-of-line.
1608 return;
1609 }
1610
1611 // Template instantiations should also not be pushed into scope.
1612 if (isa<FunctionDecl>(D) &&
1613 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1614 return;
1615
1616 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1617 S->AddDecl(D);
1618 return;
1619 }
1620 // If this replaces anything in the current scope,
1622 IEnd = IdResolver.end();
1623 for (; I != IEnd; ++I) {
1624 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1625 S->RemoveDecl(*I);
1626 IdResolver.RemoveDecl(*I);
1627
1628 // Should only need to replace one decl.
1629 break;
1630 }
1631 }
1632
1633 S->AddDecl(D);
1634
1635 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1636 // Implicitly-generated labels may end up getting generated in an order that
1637 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1638 // the label at the appropriate place in the identifier chain.
1639 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1640 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1641 if (IDC == CurContext) {
1642 if (!S->isDeclScope(*I))
1643 continue;
1644 } else if (IDC->Encloses(CurContext))
1645 break;
1646 }
1647
1648 IdResolver.InsertDeclAfter(I, D);
1649 } else {
1650 IdResolver.AddDecl(D);
1651 }
1653}
1654
1656 bool AllowInlineNamespace) const {
1657 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1658}
1659
1661 DeclContext *TargetDC = DC->getPrimaryContext();
1662 do {
1663 if (DeclContext *ScopeDC = S->getEntity())
1664 if (ScopeDC->getPrimaryContext() == TargetDC)
1665 return S;
1666 } while ((S = S->getParent()));
1667
1668 return nullptr;
1669}
1670
1672 DeclContext*,
1673 ASTContext&);
1674
1676 bool ConsiderLinkage,
1677 bool AllowInlineNamespace) {
1678 LookupResult::Filter F = R.makeFilter();
1679 while (F.hasNext()) {
1680 NamedDecl *D = F.next();
1681
1682 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1683 continue;
1684
1685 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1686 continue;
1687
1688 F.erase();
1689 }
1690
1691 F.done();
1692}
1693
1695 if (auto *VD = dyn_cast<VarDecl>(D))
1696 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1697 if (auto *FD = dyn_cast<FunctionDecl>(D))
1698 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1699 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1700 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1701
1702 return false;
1703}
1704
1706 // [module.interface]p7:
1707 // A declaration is attached to a module as follows:
1708 // - If the declaration is a non-dependent friend declaration that nominates a
1709 // function with a declarator-id that is a qualified-id or template-id or that
1710 // nominates a class other than with an elaborated-type-specifier with neither
1711 // a nested-name-specifier nor a simple-template-id, it is attached to the
1712 // module to which the friend is attached ([basic.link]).
1713 if (New->getFriendObjectKind() &&
1714 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1715 New->setLocalOwningModule(Old->getOwningModule());
1717 return false;
1718 }
1719
1720 // Although we have questions for the module ownership of implicit
1721 // instantiations, it should be sure that we shouldn't diagnose the
1722 // redeclaration of incorrect module ownership for different implicit
1723 // instantiations in different modules. We will diagnose the redeclaration of
1724 // incorrect module ownership for the template itself.
1726 return false;
1727
1728 Module *NewM = New->getOwningModule();
1729 Module *OldM = Old->getOwningModule();
1730
1731 if (NewM && NewM->isPrivateModule())
1732 NewM = NewM->Parent;
1733 if (OldM && OldM->isPrivateModule())
1734 OldM = OldM->Parent;
1735
1736 if (NewM == OldM)
1737 return false;
1738
1739 if (NewM && OldM) {
1740 // A module implementation unit has visibility of the decls in its
1741 // implicitly imported interface.
1742 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1743 return false;
1744
1745 // Partitions are part of the module, but a partition could import another
1746 // module, so verify that the PMIs agree.
1747 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1748 getASTContext().isInSameModule(NewM, OldM))
1749 return false;
1750 }
1751
1752 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1753 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1754 if (NewIsModuleInterface || OldIsModuleInterface) {
1755 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1756 // if a declaration of D [...] appears in the purview of a module, all
1757 // other such declarations shall appear in the purview of the same module
1758 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1759 << New
1760 << NewIsModuleInterface
1761 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1762 << OldIsModuleInterface
1763 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1764 Diag(Old->getLocation(), diag::note_previous_declaration);
1765 New->setInvalidDecl();
1766 return true;
1767 }
1768
1769 return false;
1770}
1771
1773 // [module.interface]p1:
1774 // An export-declaration shall inhabit a namespace scope.
1775 //
1776 // So it is meaningless to talk about redeclaration which is not at namespace
1777 // scope.
1778 if (!New->getLexicalDeclContext()
1779 ->getNonTransparentContext()
1780 ->isFileContext() ||
1781 !Old->getLexicalDeclContext()
1783 ->isFileContext())
1784 return false;
1785
1786 bool IsNewExported = New->isInExportDeclContext();
1787 bool IsOldExported = Old->isInExportDeclContext();
1788
1789 // It should be irrevelant if both of them are not exported.
1790 if (!IsNewExported && !IsOldExported)
1791 return false;
1792
1793 if (IsOldExported)
1794 return false;
1795
1796 // If the Old declaration are not attached to named modules
1797 // and the New declaration are attached to global module.
1798 // It should be fine to allow the export since it doesn't change
1799 // the linkage of declarations. See
1800 // https://github.com/llvm/llvm-project/issues/98583 for details.
1801 if (!Old->isInNamedModule() && New->getOwningModule() &&
1802 New->getOwningModule()->isImplicitGlobalModule())
1803 return false;
1804
1805 assert(IsNewExported);
1806
1807 auto Lk = Old->getFormalLinkage();
1808 int S = 0;
1809 if (Lk == Linkage::Internal)
1810 S = 1;
1811 else if (Lk == Linkage::Module)
1812 S = 2;
1813 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1814 Diag(Old->getLocation(), diag::note_previous_declaration);
1815 return true;
1816}
1817
1820 return true;
1821
1823 return true;
1824
1825 return false;
1826}
1827
1829 const NamedDecl *Old) const {
1830 assert(getASTContext().isSameEntity(New, Old) &&
1831 "New and Old are not the same definition, we should diagnostic it "
1832 "immediately instead of checking it.");
1833 assert(const_cast<Sema *>(this)->isReachable(New) &&
1834 const_cast<Sema *>(this)->isReachable(Old) &&
1835 "We shouldn't see unreachable definitions here.");
1836
1837 Module *NewM = New->getOwningModule();
1838 Module *OldM = Old->getOwningModule();
1839
1840 // We only checks for named modules here. The header like modules is skipped.
1841 // FIXME: This is not right if we import the header like modules in the module
1842 // purview.
1843 //
1844 // For example, assuming "header.h" provides definition for `D`.
1845 // ```C++
1846 // //--- M.cppm
1847 // export module M;
1848 // import "header.h"; // or #include "header.h" but import it by clang modules
1849 // actually.
1850 //
1851 // //--- Use.cpp
1852 // import M;
1853 // import "header.h"; // or uses clang modules.
1854 // ```
1855 //
1856 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1857 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1858 // reject it. But the current implementation couldn't detect the case since we
1859 // don't record the information about the importee modules.
1860 //
1861 // But this might not be painful in practice. Since the design of C++20 Named
1862 // Modules suggests us to use headers in global module fragment instead of
1863 // module purview.
1864 if (NewM && NewM->isHeaderLikeModule())
1865 NewM = nullptr;
1866 if (OldM && OldM->isHeaderLikeModule())
1867 OldM = nullptr;
1868
1869 if (!NewM && !OldM)
1870 return true;
1871
1872 // [basic.def.odr]p14.3
1873 // Each such definition shall not be attached to a named module
1874 // ([module.unit]).
1875 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1876 return true;
1877
1878 // Then New and Old lives in the same TU if their share one same module unit.
1879 if (NewM)
1880 NewM = NewM->getTopLevelModule();
1881 if (OldM)
1882 OldM = OldM->getTopLevelModule();
1883 return OldM == NewM;
1884}
1885
1887 if (D->getDeclContext()->isFileContext())
1888 return false;
1889
1890 return isa<UsingShadowDecl>(D) ||
1893}
1894
1895/// Removes using shadow declarations not at class scope from the lookup
1896/// results.
1898 LookupResult::Filter F = R.makeFilter();
1899 while (F.hasNext())
1901 F.erase();
1902
1903 F.done();
1904}
1905
1906/// Check for this common pattern:
1907/// @code
1908/// class S {
1909/// S(const S&); // DO NOT IMPLEMENT
1910/// void operator=(const S&); // DO NOT IMPLEMENT
1911/// };
1912/// @endcode
1914 // FIXME: Should check for private access too but access is set after we get
1915 // the decl here.
1917 return false;
1918
1919 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1920 return CD->isCopyConstructor();
1921 return D->isCopyAssignmentOperator();
1922}
1923
1924bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1925 const DeclContext *DC = D->getDeclContext();
1926 while (!DC->isTranslationUnit()) {
1927 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1928 if (!RD->hasNameForLinkage())
1929 return true;
1930 }
1931 DC = DC->getParent();
1932 }
1933
1934 return !D->isExternallyVisible();
1935}
1936
1938 assert(D);
1939
1940 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1941 return false;
1942
1943 // Ignore all entities declared within templates, and out-of-line definitions
1944 // of members of class templates.
1945 if (D->getDeclContext()->isDependentContext() ||
1947 return false;
1948
1949 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1950 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1951 return false;
1952 // A non-out-of-line declaration of a member specialization was implicitly
1953 // instantiated; it's the out-of-line declaration that we're interested in.
1954 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1955 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1956 return false;
1957
1958 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1959 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1960 return false;
1961 } else {
1962 // 'static inline' functions are defined in headers; don't warn.
1963 if (FD->isInlined() && !isMainFileLoc(FD->getLocation()))
1964 return false;
1965 }
1966
1967 if (FD->doesThisDeclarationHaveABody() &&
1968 Context.DeclMustBeEmitted(FD))
1969 return false;
1970 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1971 // Constants and utility variables are defined in headers with internal
1972 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1973 // like "inline".)
1974 if (!isMainFileLoc(VD->getLocation()))
1975 return false;
1976
1977 if (Context.DeclMustBeEmitted(VD))
1978 return false;
1979
1980 if (VD->isStaticDataMember() &&
1981 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1982 return false;
1983 if (VD->isStaticDataMember() &&
1984 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1985 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1986 return false;
1987
1988 if (VD->isInline() && !isMainFileLoc(VD->getLocation()))
1989 return false;
1990 } else {
1991 return false;
1992 }
1993
1994 // Only warn for unused decls internal to the translation unit.
1995 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1996 // for inline functions defined in the main source file, for instance.
1997 return mightHaveNonExternalLinkage(D);
1998}
1999
2001 if (!D)
2002 return;
2003
2004 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2005 const FunctionDecl *First = FD->getFirstDecl();
2007 return; // First should already be in the vector.
2008 }
2009
2010 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2011 const VarDecl *First = VD->getFirstDecl();
2013 return; // First should already be in the vector.
2014 }
2015
2017 UnusedFileScopedDecls.push_back(D);
2018}
2019
2020static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2021 const NamedDecl *D) {
2022 if (D->isInvalidDecl())
2023 return false;
2024
2025 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
2026 // For a decomposition declaration, warn if none of the bindings are
2027 // referenced, instead of if the variable itself is referenced (which
2028 // it is, by the bindings' expressions).
2029 bool IsAllIgnored = true;
2030 for (const auto *BD : DD->bindings()) {
2031 if (BD->isReferenced())
2032 return false;
2033 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2034 BD->hasAttr<UnusedAttr>());
2035 }
2036 if (IsAllIgnored)
2037 return false;
2038 } else if (!D->getDeclName()) {
2039 return false;
2040 } else if (D->isReferenced() || D->isUsed()) {
2041 return false;
2042 }
2043
2044 if (D->isPlaceholderVar(LangOpts))
2045 return false;
2046
2047 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2048 D->hasAttr<CleanupAttr>())
2049 return false;
2050
2051 if (isa<LabelDecl>(D))
2052 return true;
2053
2054 // Except for labels, we only care about unused decls that are local to
2055 // functions.
2056 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2057 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2058 // For dependent types, the diagnostic is deferred.
2059 WithinFunction =
2060 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2061 if (!WithinFunction)
2062 return false;
2063
2064 if (isa<TypedefNameDecl>(D))
2065 return true;
2066
2067 // White-list anything that isn't a local variable.
2069 return false;
2070
2071 // Types of valid local variables should be complete, so this should succeed.
2072 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2073
2074 const Expr *Init = VD->getInit();
2075 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2076 Init = Cleanups->getSubExpr();
2077
2078 const auto *Ty = VD->getType().getTypePtr();
2079
2080 // Only look at the outermost level of typedef.
2081 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2082 // Allow anything marked with __attribute__((unused)).
2083 if (TT->getDecl()->hasAttr<UnusedAttr>())
2084 return false;
2085 }
2086
2087 // Warn for reference variables whose initializtion performs lifetime
2088 // extension.
2089 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2090 MTE && MTE->getExtendingDecl()) {
2091 Ty = VD->getType().getNonReferenceType().getTypePtr();
2092 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2093 }
2094
2095 // If we failed to complete the type for some reason, or if the type is
2096 // dependent, don't diagnose the variable.
2097 if (Ty->isIncompleteType() || Ty->isDependentType())
2098 return false;
2099
2100 // Look at the element type to ensure that the warning behaviour is
2101 // consistent for both scalars and arrays.
2102 Ty = Ty->getBaseElementTypeUnsafe();
2103
2104 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2105 if (Tag->hasAttr<UnusedAttr>())
2106 return false;
2107
2108 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2109 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2110 return false;
2111
2112 if (Init) {
2113 const auto *Construct =
2114 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2115 if (Construct && !Construct->isElidable()) {
2116 const CXXConstructorDecl *CD = Construct->getConstructor();
2117 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2118 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2119 return false;
2120 }
2121
2122 // Suppress the warning if we don't know how this is constructed, and
2123 // it could possibly be non-trivial constructor.
2124 if (Init->isTypeDependent()) {
2125 for (const CXXConstructorDecl *Ctor : RD->ctors())
2126 if (!Ctor->isTrivial())
2127 return false;
2128 }
2129
2130 // Suppress the warning if the constructor is unresolved because
2131 // its arguments are dependent.
2133 return false;
2134 }
2135 }
2136 }
2137
2138 // TODO: __attribute__((unused)) templates?
2139 }
2140
2141 return true;
2142}
2143
2145 FixItHint &Hint) {
2146 if (isa<LabelDecl>(D)) {
2148 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2149 /*SkipTrailingWhitespaceAndNewline=*/false);
2150 if (AfterColon.isInvalid())
2151 return;
2153 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2154 }
2155}
2156
2159 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2160}
2161
2163 DiagReceiverTy DiagReceiver) {
2164 if (D->isDependentType())
2165 return;
2166
2167 for (auto *TmpD : D->decls()) {
2168 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2169 DiagnoseUnusedDecl(T, DiagReceiver);
2170 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2171 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2172 }
2173}
2174
2177 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2178}
2179
2182 return;
2183
2184 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2185 // typedefs can be referenced later on, so the diagnostics are emitted
2186 // at end-of-translation-unit.
2188 return;
2189 }
2190
2191 FixItHint Hint;
2193
2194 unsigned DiagID;
2195 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2196 DiagID = diag::warn_unused_exception_param;
2197 else if (isa<LabelDecl>(D))
2198 DiagID = diag::warn_unused_label;
2199 else
2200 DiagID = diag::warn_unused_variable;
2201
2202 SourceLocation DiagLoc = D->getLocation();
2203 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2204}
2205
2207 DiagReceiverTy DiagReceiver) {
2208 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2209 // it's not really unused.
2210 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2211 return;
2212
2213 // In C++, `_` variables behave as if they were maybe_unused
2214 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2215 return;
2216
2217 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2218
2219 if (Ty->isReferenceType() || Ty->isDependentType())
2220 return;
2221
2222 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2223 if (Tag->hasAttr<UnusedAttr>())
2224 return;
2225 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2226 // mimic gcc's behavior.
2227 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2228 RD && !RD->hasAttr<WarnUnusedAttr>())
2229 return;
2230 }
2231
2232 // Don't warn on volatile file-scope variables. They are visible beyond their
2233 // declaring function and writes to them could be observable side effects.
2234 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2235 return;
2236
2237 // Don't warn about __block Objective-C pointer variables, as they might
2238 // be assigned in the block but not used elsewhere for the purpose of lifetime
2239 // extension.
2240 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2241 return;
2242
2243 // Don't warn about Objective-C pointer variables with precise lifetime
2244 // semantics; they can be used to ensure ARC releases the object at a known
2245 // time, which may mean assignment but no other references.
2246 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2247 return;
2248
2249 auto iter = RefsMinusAssignments.find(VD->getCanonicalDecl());
2250 if (iter == RefsMinusAssignments.end())
2251 return;
2252
2253 assert(iter->getSecond() >= 0 &&
2254 "Found a negative number of references to a VarDecl");
2255 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2256 // Assume the given VarDecl is "used" if its ref count stored in
2257 // `RefMinusAssignments` is positive, with one exception.
2258 //
2259 // For a C++ variable whose decl (with initializer) entirely consist the
2260 // condition expression of a if/while/for construct,
2261 // Clang creates a DeclRefExpr for the condition expression rather than a
2262 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2263 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2264 // used in the body of the if/while/for construct.
2265 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2266 if (!UnusedCXXCondDecl)
2267 return;
2268 }
2269
2270 unsigned DiagID;
2271 if (isa<ParmVarDecl>(VD))
2272 DiagID = diag::warn_unused_but_set_parameter;
2273 else if (VD->isFileVarDecl())
2274 DiagID = diag::warn_unused_but_set_global;
2275 else
2276 DiagID = diag::warn_unused_but_set_variable;
2277 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2278}
2279
2281 Sema::DiagReceiverTy DiagReceiver) {
2282 // Verify that we have no forward references left. If so, there was a goto
2283 // or address of a label taken, but no definition of it. Label fwd
2284 // definitions are indicated with a null substmt which is also not a resolved
2285 // MS inline assembly label name.
2286 bool Diagnose = false;
2287 if (L->isMSAsmLabel())
2288 Diagnose = !L->isResolvedMSAsmLabel();
2289 else
2290 Diagnose = L->getStmt() == nullptr;
2291 if (Diagnose)
2292 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2293 << L);
2294}
2295
2297 S->applyNRVO();
2298
2299 if (S->decl_empty()) return;
2301 "Scope shouldn't contain decls!");
2302
2303 /// We visit the decls in non-deterministic order, but we want diagnostics
2304 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2305 /// and sort the diagnostics before emitting them, after we visited all decls.
2306 struct LocAndDiag {
2307 SourceLocation Loc;
2308 std::optional<SourceLocation> PreviousDeclLoc;
2310 };
2312 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2313 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2314 };
2315 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2316 SourceLocation PreviousDeclLoc,
2317 PartialDiagnostic PD) {
2318 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2319 };
2320
2321 for (auto *TmpD : S->decls()) {
2322 assert(TmpD && "This decl didn't get pushed??");
2323
2324 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2325 NamedDecl *D = cast<NamedDecl>(TmpD);
2326
2327 // Diagnose unused variables in this scope.
2329 DiagnoseUnusedDecl(D, addDiag);
2330 if (const auto *RD = dyn_cast<RecordDecl>(D))
2331 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2332 // Wait until end of TU to diagnose internal linkage file vars.
2333 if (auto *VD = dyn_cast<VarDecl>(D);
2334 VD && !VD->isInternalLinkageFileVar()) {
2335 DiagnoseUnusedButSetDecl(VD, addDiag);
2336 RefsMinusAssignments.erase(VD->getCanonicalDecl());
2337 }
2338 }
2339
2340 if (!D->getDeclName()) continue;
2341
2342 // If this was a forward reference to a label, verify it was defined.
2343 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2344 CheckPoppedLabel(LD, *this, addDiag);
2345
2346 // Partial translation units that are created in incremental processing must
2347 // not clean up the IdResolver because PTUs should take into account the
2348 // declarations that came from previous PTUs.
2349 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2351 IdResolver.RemoveDecl(D);
2352
2353 // Warn on it if we are shadowing a declaration.
2354 auto ShadowI = ShadowingDecls.find(D);
2355 if (ShadowI != ShadowingDecls.end()) {
2356 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2357 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2358 PDiag(diag::warn_ctor_parm_shadows_field)
2359 << D << FD << FD->getParent());
2360 }
2361 ShadowingDecls.erase(ShadowI);
2362 }
2363 }
2364
2365 llvm::sort(DeclDiags,
2366 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2367 // The particular order for diagnostics is not important, as long
2368 // as the order is deterministic. Using the raw location is going
2369 // to generally be in source order unless there are macro
2370 // expansions involved.
2371 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2372 });
2373 for (const LocAndDiag &D : DeclDiags) {
2374 Diag(D.Loc, D.PD);
2375 if (D.PreviousDeclLoc)
2376 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2377 }
2378}
2379
2381 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2382 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2383 (S->isClassScope() && !getLangOpts().CPlusPlus))
2384 S = S->getParent();
2385 return S;
2386}
2387
2388static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2390 switch (Error) {
2392 return "";
2394 return BuiltinInfo.getHeaderName(ID);
2396 return "stdio.h";
2398 return "setjmp.h";
2400 return "ucontext.h";
2401 }
2402 llvm_unreachable("unhandled error kind");
2403}
2404
2406 unsigned ID, SourceLocation Loc) {
2407 DeclContext *Parent = Context.getTranslationUnitDecl();
2408
2409 if (getLangOpts().CPlusPlus) {
2411 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2412 CLinkageDecl->setImplicit();
2413 Parent->addDecl(CLinkageDecl);
2414 Parent = CLinkageDecl;
2415 }
2416
2418 if (Context.BuiltinInfo.isImmediate(ID)) {
2419 assert(getLangOpts().CPlusPlus20 &&
2420 "consteval builtins should only be available in C++20 mode");
2421 ConstexprKind = ConstexprSpecKind::Consteval;
2422 }
2423
2425 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2426 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2427 Type->isFunctionProtoType(), ConstexprKind);
2428 New->setImplicit();
2429 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2430
2431 // Create Decl objects for each parameter, adding them to the
2432 // FunctionDecl.
2433 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2435 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2437 Context, New, SourceLocation(), SourceLocation(), nullptr,
2438 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2439 parm->setScopeInfo(0, i);
2440 Params.push_back(parm);
2441 }
2442 New->setParams(Params);
2443 }
2444
2446 return New;
2447}
2448
2450 Scope *S, bool ForRedeclaration,
2451 SourceLocation Loc) {
2453
2455 QualType R = Context.GetBuiltinType(ID, Error);
2456 if (Error) {
2457 if (!ForRedeclaration)
2458 return nullptr;
2459
2460 // If we have a builtin without an associated type we should not emit a
2461 // warning when we were not able to find a type for it.
2463 Context.BuiltinInfo.allowTypeMismatch(ID))
2464 return nullptr;
2465
2466 // If we could not find a type for setjmp it is because the jmp_buf type was
2467 // not defined prior to the setjmp declaration.
2469 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2470 << Context.BuiltinInfo.getName(ID);
2471 return nullptr;
2472 }
2473
2474 // Generally, we emit a warning that the declaration requires the
2475 // appropriate header.
2476 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2477 << getHeaderName(Context.BuiltinInfo, ID, Error)
2478 << Context.BuiltinInfo.getName(ID);
2479 return nullptr;
2480 }
2481
2482 if (!ForRedeclaration &&
2483 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2484 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2485 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2486 : diag::ext_implicit_lib_function_decl)
2487 << Context.BuiltinInfo.getName(ID) << R;
2488 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2489 Diag(Loc, diag::note_include_header_or_declare)
2490 << Header << Context.BuiltinInfo.getName(ID);
2491 }
2492
2493 if (R.isNull())
2494 return nullptr;
2495
2496 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2498
2499 // TUScope is the translation-unit scope to insert this function into.
2500 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2501 // relate Scopes to DeclContexts, and probably eliminate CurContext
2502 // entirely, but we're not there yet.
2503 DeclContext *SavedContext = CurContext;
2504 CurContext = New->getDeclContext();
2506 CurContext = SavedContext;
2507 return New;
2508}
2509
2510/// Typedef declarations don't have linkage, but they still denote the same
2511/// entity if their types are the same.
2512/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2513/// isSameEntity.
2514static void
2517 // This is only interesting when modules are enabled.
2518 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2519 return;
2520
2521 // Empty sets are uninteresting.
2522 if (Previous.empty())
2523 return;
2524
2525 LookupResult::Filter Filter = Previous.makeFilter();
2526 while (Filter.hasNext()) {
2527 NamedDecl *Old = Filter.next();
2528
2529 // Non-hidden declarations are never ignored.
2530 if (S.isVisible(Old))
2531 continue;
2532
2533 // Declarations of the same entity are not ignored, even if they have
2534 // different linkages.
2535 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2536 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2537 Decl->getUnderlyingType()))
2538 continue;
2539
2540 // If both declarations give a tag declaration a typedef name for linkage
2541 // purposes, then they declare the same entity.
2542 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2543 Decl->getAnonDeclWithTypedefName())
2544 continue;
2545 }
2546
2547 Filter.erase();
2548 }
2549
2550 Filter.done();
2551}
2552
2554 QualType OldType;
2555 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2556 OldType = OldTypedef->getUnderlyingType();
2557 else
2558 OldType = Context.getTypeDeclType(Old);
2559 QualType NewType = New->getUnderlyingType();
2560
2561 if (NewType->isVariablyModifiedType()) {
2562 // Must not redefine a typedef with a variably-modified type.
2563 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2564 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2565 << Kind << NewType;
2566 if (Old->getLocation().isValid())
2567 notePreviousDefinition(Old, New->getLocation());
2568 New->setInvalidDecl();
2569 return true;
2570 }
2571
2572 if (OldType != NewType &&
2573 !OldType->isDependentType() &&
2574 !NewType->isDependentType() &&
2575 !Context.hasSameType(OldType, NewType)) {
2576 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2577 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2578 << Kind << NewType << OldType;
2579 if (Old->getLocation().isValid())
2580 notePreviousDefinition(Old, New->getLocation());
2581 New->setInvalidDecl();
2582 return true;
2583 }
2584 return false;
2585}
2586
2588 LookupResult &OldDecls) {
2589 // If the new decl is known invalid already, don't bother doing any
2590 // merging checks.
2591 if (New->isInvalidDecl()) return;
2592
2593 // Allow multiple definitions for ObjC built-in typedefs.
2594 // FIXME: Verify the underlying types are equivalent!
2595 if (getLangOpts().ObjC) {
2596 const IdentifierInfo *TypeID = New->getIdentifier();
2597 switch (TypeID->getLength()) {
2598 default: break;
2599 case 2:
2600 {
2601 if (!TypeID->isStr("id"))
2602 break;
2603 QualType T = New->getUnderlyingType();
2604 if (!T->isPointerType())
2605 break;
2606 if (!T->isVoidPointerType()) {
2608 if (!PT->isStructureType())
2609 break;
2610 }
2611 Context.setObjCIdRedefinitionType(T);
2612 // Install the built-in type for 'id', ignoring the current definition.
2613 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2614 Context.getObjCIdType());
2615 return;
2616 }
2617 case 5:
2618 if (!TypeID->isStr("Class"))
2619 break;
2620 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2621 // Install the built-in type for 'Class', ignoring the current definition.
2622 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2623 Context.getObjCClassType());
2624 return;
2625 case 3:
2626 if (!TypeID->isStr("SEL"))
2627 break;
2628 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2629 // Install the built-in type for 'SEL', ignoring the current definition.
2630 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2631 Context.getObjCSelType());
2632 return;
2633 }
2634 // Fall through - the typedef name was not a builtin type.
2635 }
2636
2637 // Verify the old decl was also a type.
2638 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2639 if (!Old) {
2640 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2641 << New->getDeclName();
2642
2643 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2644 if (OldD->getLocation().isValid())
2645 notePreviousDefinition(OldD, New->getLocation());
2646
2647 return New->setInvalidDecl();
2648 }
2649
2650 // If the old declaration is invalid, just give up here.
2651 if (Old->isInvalidDecl())
2652 return New->setInvalidDecl();
2653
2654 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2655 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2656 auto *NewTag = New->getAnonDeclWithTypedefName();
2657 NamedDecl *Hidden = nullptr;
2658 if (OldTag && NewTag &&
2659 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2660 !hasVisibleDefinition(OldTag, &Hidden)) {
2661 // There is a definition of this tag, but it is not visible. Use it
2662 // instead of our tag.
2663 if (OldTD->isModed())
2664 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2665 OldTD->getUnderlyingType());
2666 else
2667 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2668
2669 // Make the old tag definition visible.
2671
2673 }
2674 }
2675
2676 // If the typedef types are not identical, reject them in all languages and
2677 // with any extensions enabled.
2678 if (isIncompatibleTypedef(Old, New))
2679 return;
2680
2681 // The types match. Link up the redeclaration chain and merge attributes if
2682 // the old declaration was a typedef.
2683 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2684 New->setPreviousDecl(Typedef);
2686 }
2687
2688 if (getLangOpts().MicrosoftExt)
2689 return;
2690
2691 if (getLangOpts().CPlusPlus) {
2692 // C++ [dcl.typedef]p2:
2693 // In a given non-class scope, a typedef specifier can be used to
2694 // redefine the name of any type declared in that scope to refer
2695 // to the type to which it already refers.
2697 return;
2698
2699 // C++0x [dcl.typedef]p4:
2700 // In a given class scope, a typedef specifier can be used to redefine
2701 // any class-name declared in that scope that is not also a typedef-name
2702 // to refer to the type to which it already refers.
2703 //
2704 // This wording came in via DR424, which was a correction to the
2705 // wording in DR56, which accidentally banned code like:
2706 //
2707 // struct S {
2708 // typedef struct A { } A;
2709 // };
2710 //
2711 // in the C++03 standard. We implement the C++0x semantics, which
2712 // allow the above but disallow
2713 //
2714 // struct S {
2715 // typedef int I;
2716 // typedef int I;
2717 // };
2718 //
2719 // since that was the intent of DR56.
2720 if (!isa<TypedefNameDecl>(Old))
2721 return;
2722
2723 Diag(New->getLocation(), diag::err_redefinition)
2724 << New->getDeclName();
2725 notePreviousDefinition(Old, New->getLocation());
2726 return New->setInvalidDecl();
2727 }
2728
2729 // Modules always permit redefinition of typedefs, as does C11.
2730 if (getLangOpts().Modules || getLangOpts().C11)
2731 return;
2732
2733 // If we have a redefinition of a typedef in C, emit a warning. This warning
2734 // is normally mapped to an error, but can be controlled with
2735 // -Wtypedef-redefinition. If either the original or the redefinition is
2736 // in a system header, don't emit this for compatibility with GCC.
2737 if (getDiagnostics().getSuppressSystemWarnings() &&
2738 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2739 (Old->isImplicit() ||
2740 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2741 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2742 return;
2743
2744 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2745 << New->getDeclName();
2746 notePreviousDefinition(Old, New->getLocation());
2747}
2748
2750 // If this was an unscoped enumeration, yank all of its enumerators
2751 // out of the scope.
2752 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2753 Scope *EnumScope = getNonFieldDeclScope(S);
2754 for (auto *ECD : ED->enumerators()) {
2755 assert(EnumScope->isDeclScope(ECD));
2756 EnumScope->RemoveDecl(ECD);
2757 IdResolver.RemoveDecl(ECD);
2758 }
2759 }
2760}
2761
2762/// DeclhasAttr - returns true if decl Declaration already has the target
2763/// attribute.
2764static bool DeclHasAttr(const Decl *D, const Attr *A) {
2765 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2766 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2767 for (const auto *i : D->attrs())
2768 if (i->getKind() == A->getKind()) {
2769 if (Ann) {
2770 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2771 return true;
2772 continue;
2773 }
2774 // FIXME: Don't hardcode this check
2775 if (OA && isa<OwnershipAttr>(i))
2776 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2777 return true;
2778 }
2779
2780 return false;
2781}
2782
2784 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2785 return VD->isThisDeclarationADefinition();
2786 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2787 return TD->isCompleteDefinition() || TD->isBeingDefined();
2788 return true;
2789}
2790
2791/// Merge alignment attributes from \p Old to \p New, taking into account the
2792/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2793///
2794/// \return \c true if any attributes were added to \p New.
2795static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2796 // Look for alignas attributes on Old, and pick out whichever attribute
2797 // specifies the strictest alignment requirement.
2798 AlignedAttr *OldAlignasAttr = nullptr;
2799 AlignedAttr *OldStrictestAlignAttr = nullptr;
2800 unsigned OldAlign = 0;
2801 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2802 // FIXME: We have no way of representing inherited dependent alignments
2803 // in a case like:
2804 // template<int A, int B> struct alignas(A) X;
2805 // template<int A, int B> struct alignas(B) X {};
2806 // For now, we just ignore any alignas attributes which are not on the
2807 // definition in such a case.
2808 if (I->isAlignmentDependent())
2809 return false;
2810
2811 if (I->isAlignas())
2812 OldAlignasAttr = I;
2813
2814 unsigned Align = I->getAlignment(S.Context);
2815 if (Align > OldAlign) {
2816 OldAlign = Align;
2817 OldStrictestAlignAttr = I;
2818 }
2819 }
2820
2821 // Look for alignas attributes on New.
2822 AlignedAttr *NewAlignasAttr = nullptr;
2823 unsigned NewAlign = 0;
2824 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2825 if (I->isAlignmentDependent())
2826 return false;
2827
2828 if (I->isAlignas())
2829 NewAlignasAttr = I;
2830
2831 unsigned Align = I->getAlignment(S.Context);
2832 if (Align > NewAlign)
2833 NewAlign = Align;
2834 }
2835
2836 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2837 // Both declarations have 'alignas' attributes. We require them to match.
2838 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2839 // fall short. (If two declarations both have alignas, they must both match
2840 // every definition, and so must match each other if there is a definition.)
2841
2842 // If either declaration only contains 'alignas(0)' specifiers, then it
2843 // specifies the natural alignment for the type.
2844 if (OldAlign == 0 || NewAlign == 0) {
2845 QualType Ty;
2846 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2847 Ty = VD->getType();
2848 else
2850
2851 if (OldAlign == 0)
2852 OldAlign = S.Context.getTypeAlign(Ty);
2853 if (NewAlign == 0)
2854 NewAlign = S.Context.getTypeAlign(Ty);
2855 }
2856
2857 if (OldAlign != NewAlign) {
2858 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2861 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2862 }
2863 }
2864
2865 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2866 // C++11 [dcl.align]p6:
2867 // if any declaration of an entity has an alignment-specifier,
2868 // every defining declaration of that entity shall specify an
2869 // equivalent alignment.
2870 // C11 6.7.5/7:
2871 // If the definition of an object does not have an alignment
2872 // specifier, any other declaration of that object shall also
2873 // have no alignment specifier.
2874 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2875 << OldAlignasAttr;
2876 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2877 << OldAlignasAttr;
2878 }
2879
2880 bool AnyAdded = false;
2881
2882 // Ensure we have an attribute representing the strictest alignment.
2883 if (OldAlign > NewAlign) {
2884 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2885 Clone->setInherited(true);
2886 New->addAttr(Clone);
2887 AnyAdded = true;
2888 }
2889
2890 // Ensure we have an alignas attribute if the old declaration had one.
2891 if (OldAlignasAttr && !NewAlignasAttr &&
2892 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2893 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2894 Clone->setInherited(true);
2895 New->addAttr(Clone);
2896 AnyAdded = true;
2897 }
2898
2899 return AnyAdded;
2900}
2901
2902#define WANT_DECL_MERGE_LOGIC
2903#include "clang/Sema/AttrParsedAttrImpl.inc"
2904#undef WANT_DECL_MERGE_LOGIC
2905
2907 const InheritableAttr *Attr,
2909 // Diagnose any mutual exclusions between the attribute that we want to add
2910 // and attributes that already exist on the declaration.
2911 if (!DiagnoseMutualExclusions(S, D, Attr))
2912 return false;
2913
2914 // This function copies an attribute Attr from a previous declaration to the
2915 // new declaration D if the new declaration doesn't itself have that attribute
2916 // yet or if that attribute allows duplicates.
2917 // If you're adding a new attribute that requires logic different from
2918 // "use explicit attribute on decl if present, else use attribute from
2919 // previous decl", for example if the attribute needs to be consistent
2920 // between redeclarations, you need to call a custom merge function here.
2921 InheritableAttr *NewAttr = nullptr;
2922 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) {
2923 const IdentifierInfo *InferredPlatformII = nullptr;
2924 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2925 InferredPlatformII = Inf->getPlatform();
2927 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2928 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2929 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2930 AA->getPriority(), AA->getEnvironment(), InferredPlatformII);
2931 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2932 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2933 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2934 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2935 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2936 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2937 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2938 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2939 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2940 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2941 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2942 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2943 FA->getFirstArg());
2944 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2945 NewAttr = S.mergeFormatMatchesAttr(
2946 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2947 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Attr))
2948 NewAttr = S.mergeModularFormatAttr(
2949 D, *MFA, MFA->getModularImplFn(), MFA->getImplName(),
2950 MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2951 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2952 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2953 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2954 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2955 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2956 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2957 IA->getInheritanceModel());
2958 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2959 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2960 &S.Context.Idents.get(AA->getSpelling()));
2961 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2964 // CUDA target attributes are part of function signature for
2965 // overloading purposes and must not be merged.
2966 return false;
2967 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2968 NewAttr = S.mergeMinSizeAttr(D, *MA);
2969 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2970 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2971 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2972 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2973 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2974 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2975 else if (isa<AlignedAttr>(Attr))
2976 // AlignedAttrs are handled separately, because we need to handle all
2977 // such attributes on a declaration at the same time.
2978 NewAttr = nullptr;
2983 NewAttr = nullptr;
2984 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2985 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2986 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2987 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2988 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2989 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2990 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2991 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2992 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2993 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2994 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2995 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2996 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2997 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2998 NT->getZ());
2999 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
3000 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
3001 WS->getPreferred(),
3002 WS->getSpelledArgsCount());
3003 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
3004 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
3005 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
3006 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
3007 else if (isa<SuppressAttr>(Attr))
3008 // Do nothing. Each redeclaration should be suppressed separately.
3009 NewAttr = nullptr;
3010 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
3011 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
3012 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
3013 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
3014 else if (const auto *PA = dyn_cast<PersonalityAttr>(Attr))
3015 NewAttr = S.mergePersonalityAttr(D, PA->getRoutine(), *PA);
3016
3017 if (NewAttr) {
3018 NewAttr->setInherited(true);
3019 D->addAttr(NewAttr);
3020 if (isa<MSInheritanceAttr>(NewAttr))
3022 return true;
3023 }
3024
3025 return false;
3026}
3027
3028static const NamedDecl *getDefinition(const Decl *D) {
3029 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3030 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3031 return Def;
3032 return nullptr;
3033 }
3034 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3035 const VarDecl *Def = VD->getDefinition();
3036 if (Def)
3037 return Def;
3038 return VD->getActingDefinition();
3039 }
3040 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3041 const FunctionDecl *Def = nullptr;
3042 if (FD->isDefined(Def, true))
3043 return Def;
3044 }
3045 return nullptr;
3046}
3047
3048static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3049 for (const auto *Attribute : D->attrs())
3050 if (Attribute->getKind() == Kind)
3051 return true;
3052 return false;
3053}
3054
3055/// checkNewAttributesAfterDef - If we already have a definition, check that
3056/// there are no new attributes in this declaration.
3057static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3058 if (!New->hasAttrs())
3059 return;
3060
3061 const NamedDecl *Def = getDefinition(Old);
3062 if (!Def || Def == New)
3063 return;
3064
3065 AttrVec &NewAttributes = New->getAttrs();
3066 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3067 Attr *NewAttribute = NewAttributes[I];
3068
3069 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3070 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3071 SkipBodyInfo SkipBody;
3072 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3073
3074 // If we're skipping this definition, drop the "alias" attribute.
3075 if (SkipBody.ShouldSkip) {
3076 NewAttributes.erase(NewAttributes.begin() + I);
3077 --E;
3078 continue;
3079 }
3080 } else {
3081 VarDecl *VD = cast<VarDecl>(New);
3082 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3084 ? diag::err_alias_after_tentative
3085 : diag::err_redefinition;
3086 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3087 if (Diag == diag::err_redefinition)
3088 S.notePreviousDefinition(Def, VD->getLocation());
3089 else
3090 S.Diag(Def->getLocation(), diag::note_previous_definition);
3091 VD->setInvalidDecl();
3092 }
3093 ++I;
3094 continue;
3095 }
3096
3097 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3098 // Tentative definitions are only interesting for the alias check above.
3099 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3100 ++I;
3101 continue;
3102 }
3103 }
3104
3105 if (hasAttribute(Def, NewAttribute->getKind())) {
3106 ++I;
3107 continue; // regular attr merging will take care of validating this.
3108 }
3109
3110 if (isa<C11NoReturnAttr>(NewAttribute)) {
3111 // C's _Noreturn is allowed to be added to a function after it is defined.
3112 ++I;
3113 continue;
3114 } else if (isa<UuidAttr>(NewAttribute)) {
3115 // msvc will allow a subsequent definition to add an uuid to a class
3116 ++I;
3117 continue;
3119 NewAttribute) &&
3120 NewAttribute->isStandardAttributeSyntax()) {
3121 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3122 // deprecated attribute can later be re-declared with the attribute and
3123 // vice-versa.
3124 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3125 // maybe_unused attribute can later be redeclared with the attribute and
3126 // vice versa.
3127 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3128 // nodiscard attribute can later be redeclared with the attribute and
3129 // vice-versa.
3130 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3131 ++I;
3132 continue;
3133 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3134 if (AA->isAlignas()) {
3135 // C++11 [dcl.align]p6:
3136 // if any declaration of an entity has an alignment-specifier,
3137 // every defining declaration of that entity shall specify an
3138 // equivalent alignment.
3139 // C11 6.7.5/7:
3140 // If the definition of an object does not have an alignment
3141 // specifier, any other declaration of that object shall also
3142 // have no alignment specifier.
3143 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3144 << AA;
3145 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3146 << AA;
3147 NewAttributes.erase(NewAttributes.begin() + I);
3148 --E;
3149 continue;
3150 }
3151 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3152 // If there is a C definition followed by a redeclaration with this
3153 // attribute then there are two different definitions. In C++, prefer the
3154 // standard diagnostics.
3155 if (!S.getLangOpts().CPlusPlus) {
3156 S.Diag(NewAttribute->getLocation(),
3157 diag::err_loader_uninitialized_redeclaration);
3158 S.Diag(Def->getLocation(), diag::note_previous_definition);
3159 NewAttributes.erase(NewAttributes.begin() + I);
3160 --E;
3161 continue;
3162 }
3163 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3164 cast<VarDecl>(New)->isInline() &&
3165 !cast<VarDecl>(New)->isInlineSpecified()) {
3166 // Don't warn about applying selectany to implicitly inline variables.
3167 // Older compilers and language modes would require the use of selectany
3168 // to make such variables inline, and it would have no effect if we
3169 // honored it.
3170 ++I;
3171 continue;
3172 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3173 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3174 // declarations after definitions.
3175 ++I;
3176 continue;
3177 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3178 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3179 // error since the definition will have already been created without
3180 // the semantic effects of the attribute having been applied.
3181 S.Diag(NewAttribute->getLocation(),
3182 diag::err_sycl_entry_point_after_definition)
3183 << NewAttribute;
3184 S.Diag(Def->getLocation(), diag::note_previous_definition);
3185 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3186 ++I;
3187 continue;
3188 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3189 // SYCLExternalAttr may be added after a definition.
3190 ++I;
3191 continue;
3192 }
3193
3194 S.Diag(NewAttribute->getLocation(),
3195 diag::warn_attribute_precede_definition);
3196 S.Diag(Def->getLocation(), diag::note_previous_definition);
3197 NewAttributes.erase(NewAttributes.begin() + I);
3198 --E;
3199 }
3200}
3201
3202static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3203 const ConstInitAttr *CIAttr,
3204 bool AttrBeforeInit) {
3205 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3206
3207 // Figure out a good way to write this specifier on the old declaration.
3208 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3209 // enough of the attribute list spelling information to extract that without
3210 // heroics.
3211 std::string SuitableSpelling;
3212 if (S.getLangOpts().CPlusPlus20)
3213 SuitableSpelling = std::string(
3214 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3215 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3216 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3217 InsertLoc, {tok::l_square, tok::l_square,
3218 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3219 S.PP.getIdentifierInfo("require_constant_initialization"),
3220 tok::r_square, tok::r_square}));
3221 if (SuitableSpelling.empty())
3222 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3223 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3224 S.PP.getIdentifierInfo("require_constant_initialization"),
3225 tok::r_paren, tok::r_paren}));
3226 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3227 SuitableSpelling = "constinit";
3228 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3229 SuitableSpelling = "[[clang::require_constant_initialization]]";
3230 if (SuitableSpelling.empty())
3231 SuitableSpelling = "__attribute__((require_constant_initialization))";
3232 SuitableSpelling += " ";
3233
3234 if (AttrBeforeInit) {
3235 // extern constinit int a;
3236 // int a = 0; // error (missing 'constinit'), accepted as extension
3237 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3238 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3239 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3240 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3241 } else {
3242 // int a = 0;
3243 // constinit extern int a; // error (missing 'constinit')
3244 S.Diag(CIAttr->getLocation(),
3245 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3246 : diag::warn_require_const_init_added_too_late)
3247 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3248 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3249 << CIAttr->isConstinit()
3250 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3251 }
3252}
3253
3256 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3257 UsedAttr *NewAttr = OldAttr->clone(Context);
3258 NewAttr->setInherited(true);
3259 New->addAttr(NewAttr);
3260 }
3261 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3262 RetainAttr *NewAttr = OldAttr->clone(Context);
3263 NewAttr->setInherited(true);
3264 New->addAttr(NewAttr);
3265 }
3266
3267 if (!Old->hasAttrs() && !New->hasAttrs())
3268 return;
3269
3270 // [dcl.constinit]p1:
3271 // If the [constinit] specifier is applied to any declaration of a
3272 // variable, it shall be applied to the initializing declaration.
3273 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3274 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3275 if (bool(OldConstInit) != bool(NewConstInit)) {
3276 const auto *OldVD = cast<VarDecl>(Old);
3277 auto *NewVD = cast<VarDecl>(New);
3278
3279 // Find the initializing declaration. Note that we might not have linked
3280 // the new declaration into the redeclaration chain yet.
3281 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3282 if (!InitDecl &&
3283 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3284 InitDecl = NewVD;
3285
3286 if (InitDecl == NewVD) {
3287 // This is the initializing declaration. If it would inherit 'constinit',
3288 // that's ill-formed. (Note that we do not apply this to the attribute
3289 // form).
3290 if (OldConstInit && OldConstInit->isConstinit())
3291 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3292 /*AttrBeforeInit=*/true);
3293 } else if (NewConstInit) {
3294 // This is the first time we've been told that this declaration should
3295 // have a constant initializer. If we already saw the initializing
3296 // declaration, this is too late.
3297 if (InitDecl && InitDecl != NewVD) {
3298 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3299 /*AttrBeforeInit=*/false);
3300 NewVD->dropAttr<ConstInitAttr>();
3301 }
3302 }
3303 }
3304
3305 // Attributes declared post-definition are currently ignored.
3306 checkNewAttributesAfterDef(*this, New, Old);
3307
3308 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3309 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3310 if (!OldA->isEquivalent(NewA)) {
3311 // This redeclaration changes __asm__ label.
3312 Diag(New->getLocation(), diag::err_different_asm_label);
3313 Diag(OldA->getLocation(), diag::note_previous_declaration);
3314 }
3315 } else if (Old->isUsed()) {
3316 // This redeclaration adds an __asm__ label to a declaration that has
3317 // already been ODR-used.
3318 Diag(New->getLocation(), diag::err_late_asm_label_name)
3319 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3320 }
3321 }
3322
3323 // Re-declaration cannot add abi_tag's.
3324 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3325 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3326 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3327 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3328 Diag(NewAbiTagAttr->getLocation(),
3329 diag::err_new_abi_tag_on_redeclaration)
3330 << NewTag;
3331 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3332 }
3333 }
3334 } else {
3335 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3336 Diag(Old->getLocation(), diag::note_previous_declaration);
3337 }
3338 }
3339
3340 // This redeclaration adds a section attribute.
3341 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3342 if (auto *VD = dyn_cast<VarDecl>(New)) {
3343 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3344 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3345 Diag(Old->getLocation(), diag::note_previous_declaration);
3346 }
3347 }
3348 }
3349
3350 // Redeclaration adds code-seg attribute.
3351 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3352 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3353 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3354 Diag(New->getLocation(), diag::warn_mismatched_section)
3355 << 0 /*codeseg*/;
3356 Diag(Old->getLocation(), diag::note_previous_declaration);
3357 }
3358
3359 if (!Old->hasAttrs())
3360 return;
3361
3362 bool foundAny = New->hasAttrs();
3363
3364 // Ensure that any moving of objects within the allocated map is done before
3365 // we process them.
3366 if (!foundAny) New->setAttrs(AttrVec());
3367
3368 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3369 // Ignore deprecated/unavailable/availability attributes if requested.
3371 if (isa<DeprecatedAttr>(I) ||
3374 switch (AMK) {
3376 continue;
3377
3382 LocalAMK = AMK;
3383 break;
3384 }
3385 }
3386
3387 // Already handled.
3388 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3389 continue;
3390
3392 if (auto *FD = dyn_cast<FunctionDecl>(New);
3393 FD &&
3394 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3395 continue; // Don't propagate inferred noreturn attributes to explicit
3396 }
3397
3398 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3399 foundAny = true;
3400 }
3401
3402 if (mergeAlignedAttrs(*this, New, Old))
3403 foundAny = true;
3404
3405 if (!foundAny) New->dropAttrs();
3406}
3407
3409 for (const Attr *A : D->attrs())
3410 checkAttrIsTypeDependent(D, A);
3411}
3412
3413// Returns the number of added attributes.
3414template <class T>
3415static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3416 Sema &S) {
3417 unsigned found = 0;
3418 for (const auto *I : From->specific_attrs<T>()) {
3419 if (!DeclHasAttr(To, I)) {
3420 T *newAttr = cast<T>(I->clone(S.Context));
3421 newAttr->setInherited(true);
3422 To->addAttr(newAttr);
3423 ++found;
3424 }
3425 }
3426 return found;
3427}
3428
3429template <class F>
3430static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3431 F &&propagator) {
3432 if (!From->hasAttrs()) {
3433 return;
3434 }
3435
3436 bool foundAny = To->hasAttrs();
3437
3438 // Ensure that any moving of objects within the allocated map is
3439 // done before we process them.
3440 if (!foundAny)
3441 To->setAttrs(AttrVec());
3442
3443 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3444
3445 if (!foundAny)
3446 To->dropAttrs();
3447}
3448
3449/// mergeParamDeclAttributes - Copy attributes from the old parameter
3450/// to the new one.
3452 const ParmVarDecl *oldDecl,
3453 Sema &S) {
3454 // C++11 [dcl.attr.depend]p2:
3455 // The first declaration of a function shall specify the
3456 // carries_dependency attribute for its declarator-id if any declaration
3457 // of the function specifies the carries_dependency attribute.
3458 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3459 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3460 S.Diag(CDA->getLocation(),
3461 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3462 // Find the first declaration of the parameter.
3463 // FIXME: Should we build redeclaration chains for function parameters?
3464 const FunctionDecl *FirstFD =
3465 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3466 const ParmVarDecl *FirstVD =
3467 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3468 S.Diag(FirstVD->getLocation(),
3469 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3470 }
3471
3473 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3474 unsigned found = 0;
3475 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3476 // Propagate the lifetimebound attribute from parameters to the
3477 // most recent declaration. Note that this doesn't include the implicit
3478 // 'this' parameter, as the attribute is applied to the function type in
3479 // that case.
3480 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3481 return found;
3482 });
3483}
3484
3486 const ASTContext &Ctx) {
3487
3488 auto NoSizeInfo = [&Ctx](QualType Ty) {
3489 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3490 return true;
3491 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3492 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3493 return false;
3494 };
3495
3496 // `type[]` is equivalent to `type *` and `type[*]`.
3497 if (NoSizeInfo(Old) && NoSizeInfo(New))
3498 return true;
3499
3500 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3501 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3502 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3503 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3504 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3505 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3506 return false;
3507 return true;
3508 }
3509
3510 // Only compare size, ignore Size modifiers and CVR.
3511 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3512 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3514 }
3515
3516 // Don't try to compare dependent sized array
3517 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3518 return true;
3519 }
3520
3521 return Old == New;
3522}
3523
3524static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3525 const ParmVarDecl *OldParam,
3526 Sema &S) {
3527 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3528 if (auto Newnullability = NewParam->getType()->getNullability()) {
3529 if (*Oldnullability != *Newnullability) {
3530 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3532 *Newnullability,
3534 != 0))
3536 *Oldnullability,
3538 != 0));
3539 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3540 }
3541 } else {
3542 QualType NewT = NewParam->getType();
3543 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3544 NewParam->setType(NewT);
3545 }
3546 }
3547 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3548 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3549 if (OldParamDT && NewParamDT &&
3550 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3551 QualType OldParamOT = OldParamDT->getOriginalType();
3552 QualType NewParamOT = NewParamDT->getOriginalType();
3553 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3554 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3555 << NewParam << NewParamOT;
3556 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3557 << OldParamOT;
3558 }
3559 }
3560}
3561
3562namespace {
3563
3564/// Used in MergeFunctionDecl to keep track of function parameters in
3565/// C.
3566struct GNUCompatibleParamWarning {
3567 ParmVarDecl *OldParm;
3568 ParmVarDecl *NewParm;
3569 QualType PromotedType;
3570};
3571
3572} // end anonymous namespace
3573
3574// Determine whether the previous declaration was a definition, implicit
3575// declaration, or a declaration.
3576template <typename T>
3577static std::pair<diag::kind, SourceLocation>
3579 diag::kind PrevDiag;
3580 SourceLocation OldLocation = Old->getLocation();
3581 if (Old->isThisDeclarationADefinition())
3582 PrevDiag = diag::note_previous_definition;
3583 else if (Old->isImplicit()) {
3584 PrevDiag = diag::note_previous_implicit_declaration;
3585 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3586 if (FD->getBuiltinID())
3587 PrevDiag = diag::note_previous_builtin_declaration;
3588 }
3589 if (OldLocation.isInvalid())
3590 OldLocation = New->getLocation();
3591 } else
3592 PrevDiag = diag::note_previous_declaration;
3593 return std::make_pair(PrevDiag, OldLocation);
3594}
3595
3596/// canRedefineFunction - checks if a function can be redefined. Currently,
3597/// only extern inline functions can be redefined, and even then only in
3598/// GNU89 mode.
3599static bool canRedefineFunction(const FunctionDecl *FD,
3600 const LangOptions& LangOpts) {
3601 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3602 !LangOpts.CPlusPlus &&
3603 FD->isInlineSpecified() &&
3604 FD->getStorageClass() == SC_Extern);
3605}
3606
3607const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3608 const AttributedType *AT = T->getAs<AttributedType>();
3609 while (AT && !AT->isCallingConv())
3610 AT = AT->getModifiedType()->getAs<AttributedType>();
3611 return AT;
3612}
3613
3614template <typename T>
3615static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3616 const DeclContext *DC = Old->getDeclContext();
3617 if (DC->isRecord())
3618 return false;
3619
3620 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3621 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3622 return true;
3623 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3624 return true;
3625 return false;
3626}
3627
3628template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3629static bool isExternC(VarTemplateDecl *) { return false; }
3630static bool isExternC(FunctionTemplateDecl *) { return false; }
3631
3632/// Check whether a redeclaration of an entity introduced by a
3633/// using-declaration is valid, given that we know it's not an overload
3634/// (nor a hidden tag declaration).
3635template<typename ExpectedDecl>
3637 ExpectedDecl *New) {
3638 // C++11 [basic.scope.declarative]p4:
3639 // Given a set of declarations in a single declarative region, each of
3640 // which specifies the same unqualified name,
3641 // -- they shall all refer to the same entity, or all refer to functions
3642 // and function templates; or
3643 // -- exactly one declaration shall declare a class name or enumeration
3644 // name that is not a typedef name and the other declarations shall all
3645 // refer to the same variable or enumerator, or all refer to functions
3646 // and function templates; in this case the class name or enumeration
3647 // name is hidden (3.3.10).
3648
3649 // C++11 [namespace.udecl]p14:
3650 // If a function declaration in namespace scope or block scope has the
3651 // same name and the same parameter-type-list as a function introduced
3652 // by a using-declaration, and the declarations do not declare the same
3653 // function, the program is ill-formed.
3654
3655 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3656 if (Old &&
3657 !Old->getDeclContext()->getRedeclContext()->Equals(
3658 New->getDeclContext()->getRedeclContext()) &&
3659 !(isExternC(Old) && isExternC(New)))
3660 Old = nullptr;
3661
3662 if (!Old) {
3663 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3664 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3665 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3666 return true;
3667 }
3668 return false;
3669}
3670
3672 const FunctionDecl *B) {
3673 assert(A->getNumParams() == B->getNumParams());
3674
3675 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3676 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3677 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3678 if (AttrA == AttrB)
3679 return true;
3680 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3681 AttrA->isDynamic() == AttrB->isDynamic();
3682 };
3683
3684 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3685}
3686
3687/// If necessary, adjust the semantic declaration context for a qualified
3688/// declaration to name the correct inline namespace within the qualifier.
3690 DeclaratorDecl *OldD) {
3691 // The only case where we need to update the DeclContext is when
3692 // redeclaration lookup for a qualified name finds a declaration
3693 // in an inline namespace within the context named by the qualifier:
3694 //
3695 // inline namespace N { int f(); }
3696 // int ::f(); // Sema DC needs adjusting from :: to N::.
3697 //
3698 // For unqualified declarations, the semantic context *can* change
3699 // along the redeclaration chain (for local extern declarations,
3700 // extern "C" declarations, and friend declarations in particular).
3701 if (!NewD->getQualifier())
3702 return;
3703
3704 // NewD is probably already in the right context.
3705 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3706 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3707 if (NamedDC->Equals(SemaDC))
3708 return;
3709
3710 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3711 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3712 "unexpected context for redeclaration");
3713
3714 auto *LexDC = NewD->getLexicalDeclContext();
3715 auto FixSemaDC = [=](NamedDecl *D) {
3716 if (!D)
3717 return;
3718 D->setDeclContext(SemaDC);
3719 D->setLexicalDeclContext(LexDC);
3720 };
3721
3722 FixSemaDC(NewD);
3723 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3724 FixSemaDC(FD->getDescribedFunctionTemplate());
3725 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3726 FixSemaDC(VD->getDescribedVarTemplate());
3727}
3728
3730 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3731 // Verify the old decl was also a function.
3732 FunctionDecl *Old = OldD->getAsFunction();
3733 if (!Old) {
3734 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3735 // We don't need to check the using friend pattern from other module unit
3736 // since we should have diagnosed such cases in its unit already.
3737 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3738 Diag(New->getLocation(), diag::err_using_decl_friend);
3739 Diag(Shadow->getTargetDecl()->getLocation(),
3740 diag::note_using_decl_target);
3741 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3742 << 0;
3743 return true;
3744 }
3745
3746 // Check whether the two declarations might declare the same function or
3747 // function template.
3748 if (FunctionTemplateDecl *NewTemplate =
3749 New->getDescribedFunctionTemplate()) {
3751 NewTemplate))
3752 return true;
3753 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3754 ->getAsFunction();
3755 } else {
3756 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3757 return true;
3758 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3759 }
3760 } else {
3761 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3762 << New->getDeclName();
3763 notePreviousDefinition(OldD, New->getLocation());
3764 return true;
3765 }
3766 }
3767
3768 // If the old declaration was found in an inline namespace and the new
3769 // declaration was qualified, update the DeclContext to match.
3771
3772 // If the old declaration is invalid, just give up here.
3773 if (Old->isInvalidDecl())
3774 return true;
3775
3776 // Disallow redeclaration of some builtins.
3777 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3778 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3779 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3780 << Old << Old->getType();
3781 return true;
3782 }
3783
3784 diag::kind PrevDiag;
3785 SourceLocation OldLocation;
3786 std::tie(PrevDiag, OldLocation) =
3788
3789 // Don't complain about this if we're in GNU89 mode and the old function
3790 // is an extern inline function.
3791 // Don't complain about specializations. They are not supposed to have
3792 // storage classes.
3793 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3794 New->getStorageClass() == SC_Static &&
3795 Old->hasExternalFormalLinkage() &&
3796 !New->getTemplateSpecializationInfo() &&
3798 if (getLangOpts().MicrosoftExt) {
3799 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3800 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3801 } else {
3802 Diag(New->getLocation(), diag::err_static_non_static) << New;
3803 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3804 return true;
3805 }
3806 }
3807
3808 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3809 if (!Old->hasAttr<InternalLinkageAttr>()) {
3810 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3811 << ILA;
3812 Diag(Old->getLocation(), diag::note_previous_declaration);
3813 New->dropAttr<InternalLinkageAttr>();
3814 }
3815
3816 if (auto *EA = New->getAttr<ErrorAttr>()) {
3817 if (!Old->hasAttr<ErrorAttr>()) {
3818 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3819 Diag(Old->getLocation(), diag::note_previous_declaration);
3820 New->dropAttr<ErrorAttr>();
3821 }
3822 }
3823
3825 return true;
3826
3827 if (!getLangOpts().CPlusPlus) {
3828 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3829 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3830 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3831 << New << OldOvl;
3832
3833 // Try our best to find a decl that actually has the overloadable
3834 // attribute for the note. In most cases (e.g. programs with only one
3835 // broken declaration/definition), this won't matter.
3836 //
3837 // FIXME: We could do this if we juggled some extra state in
3838 // OverloadableAttr, rather than just removing it.
3839 const Decl *DiagOld = Old;
3840 if (OldOvl) {
3841 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3842 const auto *A = D->getAttr<OverloadableAttr>();
3843 return A && !A->isImplicit();
3844 });
3845 // If we've implicitly added *all* of the overloadable attrs to this
3846 // chain, emitting a "previous redecl" note is pointless.
3847 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3848 }
3849
3850 if (DiagOld)
3851 Diag(DiagOld->getLocation(),
3852 diag::note_attribute_overloadable_prev_overload)
3853 << OldOvl;
3854
3855 if (OldOvl)
3856 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3857 else
3858 New->dropAttr<OverloadableAttr>();
3859 }
3860 }
3861
3862 // It is not permitted to redeclare an SME function with different SME
3863 // attributes.
3864 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3865 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3866 << New->getType() << Old->getType();
3867 Diag(OldLocation, diag::note_previous_declaration);
3868 return true;
3869 }
3870
3871 // If a function is first declared with a calling convention, but is later
3872 // declared or defined without one, all following decls assume the calling
3873 // convention of the first.
3874 //
3875 // It's OK if a function is first declared without a calling convention,
3876 // but is later declared or defined with the default calling convention.
3877 //
3878 // To test if either decl has an explicit calling convention, we look for
3879 // AttributedType sugar nodes on the type as written. If they are missing or
3880 // were canonicalized away, we assume the calling convention was implicit.
3881 //
3882 // Note also that we DO NOT return at this point, because we still have
3883 // other tests to run.
3884 QualType OldQType = Context.getCanonicalType(Old->getType());
3885 QualType NewQType = Context.getCanonicalType(New->getType());
3886 const FunctionType *OldType = cast<FunctionType>(OldQType);
3887 const FunctionType *NewType = cast<FunctionType>(NewQType);
3888 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3889 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3890 bool RequiresAdjustment = false;
3891
3892 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3894 const FunctionType *FT =
3895 First->getType().getCanonicalType()->castAs<FunctionType>();
3897 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3898 if (!NewCCExplicit) {
3899 // Inherit the CC from the previous declaration if it was specified
3900 // there but not here.
3901 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3902 RequiresAdjustment = true;
3903 } else if (Old->getBuiltinID()) {
3904 // Builtin attribute isn't propagated to the new one yet at this point,
3905 // so we check if the old one is a builtin.
3906
3907 // Calling Conventions on a Builtin aren't really useful and setting a
3908 // default calling convention and cdecl'ing some builtin redeclarations is
3909 // common, so warn and ignore the calling convention on the redeclaration.
3910 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3911 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3913 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3914 RequiresAdjustment = true;
3915 } else {
3916 // Calling conventions aren't compatible, so complain.
3917 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3918 Diag(New->getLocation(), diag::err_cconv_change)
3919 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3920 << !FirstCCExplicit
3921 << (!FirstCCExplicit ? "" :
3923
3924 // Put the note on the first decl, since it is the one that matters.
3925 Diag(First->getLocation(), diag::note_previous_declaration);
3926 return true;
3927 }
3928 }
3929
3930 // FIXME: diagnose the other way around?
3931 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3932 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3933 RequiresAdjustment = true;
3934 }
3935
3936 // If the declaration is marked with cfi_unchecked_callee but the definition
3937 // isn't, the definition is also cfi_unchecked_callee.
3938 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3939 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3940 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3941 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3942
3943 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3944 EPI2.CFIUncheckedCallee = true;
3945 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3946 FPT2->getParamTypes(), EPI2);
3947 NewType = cast<FunctionType>(NewQType);
3948 New->setType(NewQType);
3949 }
3950 }
3951 }
3952
3953 // Merge regparm attribute.
3954 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3955 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3956 if (NewTypeInfo.getHasRegParm()) {
3957 Diag(New->getLocation(), diag::err_regparm_mismatch)
3958 << NewType->getRegParmType()
3959 << OldType->getRegParmType();
3960 Diag(OldLocation, diag::note_previous_declaration);
3961 return true;
3962 }
3963
3964 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3965 RequiresAdjustment = true;
3966 }
3967
3968 // Merge ns_returns_retained attribute.
3969 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3970 if (NewTypeInfo.getProducesResult()) {
3971 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3972 << "'ns_returns_retained'";
3973 Diag(OldLocation, diag::note_previous_declaration);
3974 return true;
3975 }
3976
3977 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3978 RequiresAdjustment = true;
3979 }
3980
3981 if (OldTypeInfo.getNoCallerSavedRegs() !=
3982 NewTypeInfo.getNoCallerSavedRegs()) {
3983 if (NewTypeInfo.getNoCallerSavedRegs()) {
3984 AnyX86NoCallerSavedRegistersAttr *Attr =
3985 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3986 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3987 Diag(OldLocation, diag::note_previous_declaration);
3988 return true;
3989 }
3990
3991 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3992 RequiresAdjustment = true;
3993 }
3994
3995 if (RequiresAdjustment) {
3996 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3997 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3998 New->setType(QualType(AdjustedType, 0));
3999 NewQType = Context.getCanonicalType(New->getType());
4000 }
4001
4002 // If this redeclaration makes the function inline, we may need to add it to
4003 // UndefinedButUsed.
4004 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
4005 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
4006 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
4007 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4008 SourceLocation()));
4009
4010 // If this redeclaration makes it newly gnu_inline, we don't want to warn
4011 // about it.
4012 if (New->hasAttr<GNUInlineAttr>() &&
4013 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
4014 UndefinedButUsed.erase(Old->getCanonicalDecl());
4015 }
4016
4017 // If pass_object_size params don't match up perfectly, this isn't a valid
4018 // redeclaration.
4019 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4021 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
4022 << New->getDeclName();
4023 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4024 return true;
4025 }
4026
4027 QualType OldQTypeForComparison = OldQType;
4028 if (Context.hasAnyFunctionEffects()) {
4029 const auto OldFX = Old->getFunctionEffects();
4030 const auto NewFX = New->getFunctionEffects();
4031 if (OldFX != NewFX) {
4032 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4033 for (const auto &Diff : Diffs) {
4034 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
4035 Diag(New->getLocation(),
4036 diag::warn_mismatched_func_effect_redeclaration)
4037 << Diff.effectName();
4038 Diag(Old->getLocation(), diag::note_previous_declaration);
4039 }
4040 }
4041 // Following a warning, we could skip merging effects from the previous
4042 // declaration, but that would trigger an additional "conflicting types"
4043 // error.
4044 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4046 FunctionEffectSet MergedFX =
4047 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
4048 if (!MergeErrs.empty())
4049 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
4050 Old->getLocation());
4051
4052 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4053 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4054 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
4055 NewFPT->getParamTypes(), EPI);
4056
4057 New->setType(ModQT);
4058 NewQType = New->getType();
4059
4060 // Revise OldQTForComparison to include the merged effects,
4061 // so as not to fail due to differences later.
4062 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4063 EPI = OldFPT->getExtProtoInfo();
4064 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4065 OldQTypeForComparison = Context.getFunctionType(
4066 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4067 }
4068 if (OldFX.empty()) {
4069 // A redeclaration may add the attribute to a previously seen function
4070 // body which needs to be verified.
4071 maybeAddDeclWithEffects(Old, MergedFX);
4072 }
4073 }
4074 }
4075 }
4076
4077 if (getLangOpts().CPlusPlus) {
4078 OldQType = Context.getCanonicalType(Old->getType());
4079 NewQType = Context.getCanonicalType(New->getType());
4080
4081 // Go back to the type source info to compare the declared return types,
4082 // per C++1y [dcl.type.auto]p13:
4083 // Redeclarations or specializations of a function or function template
4084 // with a declared return type that uses a placeholder type shall also
4085 // use that placeholder, not a deduced type.
4086 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4087 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4088 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4089 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4090 OldDeclaredReturnType)) {
4091 QualType ResQT;
4092 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4093 OldDeclaredReturnType->isObjCObjectPointerType())
4094 // FIXME: This does the wrong thing for a deduced return type.
4095 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4096 if (ResQT.isNull()) {
4097 if (New->isCXXClassMember() && New->isOutOfLine())
4098 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4099 << New << New->getReturnTypeSourceRange();
4100 else if (Old->isExternC() && New->isExternC() &&
4101 !Old->hasAttr<OverloadableAttr>() &&
4102 !New->hasAttr<OverloadableAttr>())
4103 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4104 else
4105 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4106 << New->getReturnTypeSourceRange();
4107 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4108 << Old->getReturnTypeSourceRange();
4109 return true;
4110 }
4111 else
4112 NewQType = ResQT;
4113 }
4114
4115 QualType OldReturnType = OldType->getReturnType();
4116 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4117 if (OldReturnType != NewReturnType) {
4118 // If this function has a deduced return type and has already been
4119 // defined, copy the deduced value from the old declaration.
4120 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4121 if (OldAT && OldAT->isDeduced()) {
4122 QualType DT = OldAT->getDeducedType();
4123 if (DT.isNull()) {
4124 New->setType(SubstAutoTypeDependent(New->getType()));
4125 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4126 } else {
4127 New->setType(SubstAutoType(New->getType(), DT));
4128 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4129 }
4130 }
4131 }
4132
4133 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4134 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4135 if (OldMethod && NewMethod) {
4136 // Preserve triviality.
4137 NewMethod->setTrivial(OldMethod->isTrivial());
4138
4139 // MSVC allows explicit template specialization at class scope:
4140 // 2 CXXMethodDecls referring to the same function will be injected.
4141 // We don't want a redeclaration error.
4142 bool IsClassScopeExplicitSpecialization =
4143 OldMethod->isFunctionTemplateSpecialization() &&
4145 bool isFriend = NewMethod->getFriendObjectKind();
4146
4147 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4148 !IsClassScopeExplicitSpecialization) {
4149 // -- Member function declarations with the same name and the
4150 // same parameter types cannot be overloaded if any of them
4151 // is a static member function declaration.
4152 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4153 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4154 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4155 return true;
4156 }
4157
4158 // C++ [class.mem]p1:
4159 // [...] A member shall not be declared twice in the
4160 // member-specification, except that a nested class or member
4161 // class template can be declared and then later defined.
4162 if (!inTemplateInstantiation()) {
4163 unsigned NewDiag;
4164 if (isa<CXXConstructorDecl>(OldMethod))
4165 NewDiag = diag::err_constructor_redeclared;
4166 else if (isa<CXXDestructorDecl>(NewMethod))
4167 NewDiag = diag::err_destructor_redeclared;
4168 else if (isa<CXXConversionDecl>(NewMethod))
4169 NewDiag = diag::err_conv_function_redeclared;
4170 else
4171 NewDiag = diag::err_member_redeclared;
4172
4173 Diag(New->getLocation(), NewDiag);
4174 } else {
4175 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4176 << New << New->getType();
4177 }
4178 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4179 return true;
4180
4181 // Complain if this is an explicit declaration of a special
4182 // member that was initially declared implicitly.
4183 //
4184 // As an exception, it's okay to befriend such methods in order
4185 // to permit the implicit constructor/destructor/operator calls.
4186 } else if (OldMethod->isImplicit()) {
4187 if (isFriend) {
4188 NewMethod->setImplicit();
4189 } else {
4190 Diag(NewMethod->getLocation(),
4191 diag::err_definition_of_implicitly_declared_member)
4192 << New << getSpecialMember(OldMethod);
4193 return true;
4194 }
4195 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4196 Diag(NewMethod->getLocation(),
4197 diag::err_definition_of_explicitly_defaulted_member)
4198 << getSpecialMember(OldMethod);
4199 return true;
4200 }
4201 }
4202
4203 // C++1z [over.load]p2
4204 // Certain function declarations cannot be overloaded:
4205 // -- Function declarations that differ only in the return type,
4206 // the exception specification, or both cannot be overloaded.
4207
4208 // Check the exception specifications match. This may recompute the type of
4209 // both Old and New if it resolved exception specifications, so grab the
4210 // types again after this. Because this updates the type, we do this before
4211 // any of the other checks below, which may update the "de facto" NewQType
4212 // but do not necessarily update the type of New.
4214 return true;
4215
4216 // C++11 [dcl.attr.noreturn]p1:
4217 // The first declaration of a function shall specify the noreturn
4218 // attribute if any declaration of that function specifies the noreturn
4219 // attribute.
4220 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4221 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4222 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4223 << NRA;
4224 Diag(Old->getLocation(), diag::note_previous_declaration);
4225 }
4226
4227 // C++11 [dcl.attr.depend]p2:
4228 // The first declaration of a function shall specify the
4229 // carries_dependency attribute for its declarator-id if any declaration
4230 // of the function specifies the carries_dependency attribute.
4231 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4232 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4233 Diag(CDA->getLocation(),
4234 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4235 Diag(Old->getFirstDecl()->getLocation(),
4236 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4237 }
4238
4239 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4240 // When a function is declared with SYCL_EXTERNAL, that macro must be
4241 // used on the first declaration of that function in the translation unit.
4242 // Redeclarations of the function in the same translation unit may
4243 // optionally use SYCL_EXTERNAL, but this is not required.
4244 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4245 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4246 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4247 << SEA;
4248 Diag(Old->getLocation(), diag::note_previous_declaration);
4249 }
4250
4251 // (C++98 8.3.5p3):
4252 // All declarations for a function shall agree exactly in both the
4253 // return type and the parameter-type-list.
4254 // We also want to respect all the extended bits except noreturn.
4255
4256 // noreturn should now match unless the old type info didn't have it.
4257 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4258 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4259 const FunctionType *OldTypeForComparison
4260 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4261 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4262 assert(OldQTypeForComparison.isCanonical());
4263 }
4264
4266 // As a special case, retain the language linkage from previous
4267 // declarations of a friend function as an extension.
4268 //
4269 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4270 // and is useful because there's otherwise no way to specify language
4271 // linkage within class scope.
4272 //
4273 // Check cautiously as the friend object kind isn't yet complete.
4274 if (New->getFriendObjectKind() != Decl::FOK_None) {
4275 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4276 Diag(OldLocation, PrevDiag);
4277 } else {
4278 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4279 Diag(OldLocation, PrevDiag);
4280 return true;
4281 }
4282 }
4283
4284 // HLSL check parameters for matching ABI specifications.
4285 if (getLangOpts().HLSL) {
4286 if (HLSL().CheckCompatibleParameterABI(New, Old))
4287 return true;
4288
4289 // If no errors are generated when checking parameter ABIs we can check if
4290 // the two declarations have the same type ignoring the ABIs and if so,
4291 // the declarations can be merged. This case for merging is only valid in
4292 // HLSL because there are no valid cases of merging mismatched parameter
4293 // ABIs except the HLSL implicit in and explicit in.
4294 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4295 NewQType))
4296 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4297 // Fall through for conflicting redeclarations and redefinitions.
4298 }
4299
4300 // If the function types are compatible, merge the declarations. Ignore the
4301 // exception specifier because it was already checked above in
4302 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4303 // about incompatible types under -fms-compatibility.
4304 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4305 NewQType))
4306 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4307
4308 // If the types are imprecise (due to dependent constructs in friends or
4309 // local extern declarations), it's OK if they differ. We'll check again
4310 // during instantiation.
4311 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4312 return false;
4313
4314 // Fall through for conflicting redeclarations and redefinitions.
4315 }
4316
4317 // C: Function types need to be compatible, not identical. This handles
4318 // duplicate function decls like "void f(int); void f(enum X);" properly.
4319 if (!getLangOpts().CPlusPlus) {
4320 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4321 // type is specified by a function definition that contains a (possibly
4322 // empty) identifier list, both shall agree in the number of parameters
4323 // and the type of each parameter shall be compatible with the type that
4324 // results from the application of default argument promotions to the
4325 // type of the corresponding identifier. ...
4326 // This cannot be handled by ASTContext::typesAreCompatible() because that
4327 // doesn't know whether the function type is for a definition or not when
4328 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4329 // we need to cover here is that the number of arguments agree as the
4330 // default argument promotion rules were already checked by
4331 // ASTContext::typesAreCompatible().
4332 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4333 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4334 if (Old->hasInheritedPrototype())
4335 Old = Old->getCanonicalDecl();
4336 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4337 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4338 return true;
4339 }
4340
4341 // If we are merging two functions where only one of them has a prototype,
4342 // we may have enough information to decide to issue a diagnostic that the
4343 // function without a prototype will change behavior in C23. This handles
4344 // cases like:
4345 // void i(); void i(int j);
4346 // void i(int j); void i();
4347 // void i(); void i(int j) {}
4348 // See ActOnFinishFunctionBody() for other cases of the behavior change
4349 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4350 // type without a prototype.
4351 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4352 !New->isImplicit() && !Old->isImplicit()) {
4353 const FunctionDecl *WithProto, *WithoutProto;
4354 if (New->hasWrittenPrototype()) {
4355 WithProto = New;
4356 WithoutProto = Old;
4357 } else {
4358 WithProto = Old;
4359 WithoutProto = New;
4360 }
4361
4362 if (WithProto->getNumParams() != 0) {
4363 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4364 // The one without the prototype will be changing behavior in C23, so
4365 // warn about that one so long as it's a user-visible declaration.
4366 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4367 if (WithoutProto == New)
4368 IsWithoutProtoADef = NewDeclIsDefn;
4369 else
4370 IsWithProtoADef = NewDeclIsDefn;
4371 Diag(WithoutProto->getLocation(),
4372 diag::warn_non_prototype_changes_behavior)
4373 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4374 << (WithoutProto == Old) << IsWithProtoADef;
4375
4376 // The reason the one without the prototype will be changing behavior
4377 // is because of the one with the prototype, so note that so long as
4378 // it's a user-visible declaration. There is one exception to this:
4379 // when the new declaration is a definition without a prototype, the
4380 // old declaration with a prototype is not the cause of the issue,
4381 // and that does not need to be noted because the one with a
4382 // prototype will not change behavior in C23.
4383 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4384 !IsWithoutProtoADef)
4385 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4386 }
4387 }
4388 }
4389
4390 if (Context.typesAreCompatible(OldQType, NewQType)) {
4391 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4392 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4393 const FunctionProtoType *OldProto = nullptr;
4394 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4395 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4396 // The old declaration provided a function prototype, but the
4397 // new declaration does not. Merge in the prototype.
4398 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4399 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4400 OldProto->getParamTypes(),
4401 OldProto->getExtProtoInfo());
4402 New->setType(NewQType);
4403 New->setHasInheritedPrototype();
4404
4405 // Synthesize parameters with the same types.
4407 for (const auto &ParamType : OldProto->param_types()) {
4409 Context, New, SourceLocation(), SourceLocation(), nullptr,
4410 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4411 Param->setScopeInfo(0, Params.size());
4412 Param->setImplicit();
4413 Params.push_back(Param);
4414 }
4415
4416 New->setParams(Params);
4417 }
4418
4419 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4420 }
4421 }
4422
4423 // Check if the function types are compatible when pointer size address
4424 // spaces are ignored.
4425 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4426 return false;
4427
4428 // GNU C permits a K&R definition to follow a prototype declaration
4429 // if the declared types of the parameters in the K&R definition
4430 // match the types in the prototype declaration, even when the
4431 // promoted types of the parameters from the K&R definition differ
4432 // from the types in the prototype. GCC then keeps the types from
4433 // the prototype.
4434 //
4435 // If a variadic prototype is followed by a non-variadic K&R definition,
4436 // the K&R definition becomes variadic. This is sort of an edge case, but
4437 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4438 // C99 6.9.1p8.
4439 if (!getLangOpts().CPlusPlus &&
4440 Old->hasPrototype() && !New->hasPrototype() &&
4441 New->getType()->getAs<FunctionProtoType>() &&
4442 Old->getNumParams() == New->getNumParams()) {
4445 const FunctionProtoType *OldProto
4446 = Old->getType()->getAs<FunctionProtoType>();
4447 const FunctionProtoType *NewProto
4448 = New->getType()->getAs<FunctionProtoType>();
4449
4450 // Determine whether this is the GNU C extension.
4451 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4452 NewProto->getReturnType());
4453 bool LooseCompatible = !MergedReturn.isNull();
4454 for (unsigned Idx = 0, End = Old->getNumParams();
4455 LooseCompatible && Idx != End; ++Idx) {
4456 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4457 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4458 if (Context.typesAreCompatible(OldParm->getType(),
4459 NewProto->getParamType(Idx))) {
4460 ArgTypes.push_back(NewParm->getType());
4461 } else if (Context.typesAreCompatible(OldParm->getType(),
4462 NewParm->getType(),
4463 /*CompareUnqualified=*/true)) {
4464 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4465 NewProto->getParamType(Idx) };
4466 Warnings.push_back(Warn);
4467 ArgTypes.push_back(NewParm->getType());
4468 } else
4469 LooseCompatible = false;
4470 }
4471
4472 if (LooseCompatible) {
4473 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4474 Diag(Warnings[Warn].NewParm->getLocation(),
4475 diag::ext_param_promoted_not_compatible_with_prototype)
4476 << Warnings[Warn].PromotedType
4477 << Warnings[Warn].OldParm->getType();
4478 if (Warnings[Warn].OldParm->getLocation().isValid())
4479 Diag(Warnings[Warn].OldParm->getLocation(),
4480 diag::note_previous_declaration);
4481 }
4482
4483 if (MergeTypeWithOld)
4484 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4485 OldProto->getExtProtoInfo()));
4486 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4487 }
4488
4489 // Fall through to diagnose conflicting types.
4490 }
4491
4492 // A function that has already been declared has been redeclared or
4493 // defined with a different type; show an appropriate diagnostic.
4494
4495 // If the previous declaration was an implicitly-generated builtin
4496 // declaration, then at the very least we should use a specialized note.
4497 unsigned BuiltinID;
4498 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4499 // If it's actually a library-defined builtin function like 'malloc'
4500 // or 'printf', just warn about the incompatible redeclaration.
4501 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4502 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4503 Diag(OldLocation, diag::note_previous_builtin_declaration)
4504 << Old << Old->getType();
4505 return false;
4506 }
4507
4508 PrevDiag = diag::note_previous_builtin_declaration;
4509 }
4510
4511 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4512 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4513 return true;
4514}
4515
4517 Scope *S, bool MergeTypeWithOld) {
4518 // Merge the attributes
4520
4521 // Merge "pure" flag.
4522 if (Old->isPureVirtual())
4523 New->setIsPureVirtual();
4524
4525 // Merge "used" flag.
4526 if (Old->getMostRecentDecl()->isUsed(false))
4527 New->setIsUsed();
4528
4529 // Merge attributes from the parameters. These can mismatch with K&R
4530 // declarations.
4531 if (New->getNumParams() == Old->getNumParams())
4532 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4533 ParmVarDecl *NewParam = New->getParamDecl(i);
4534 ParmVarDecl *OldParam = Old->getParamDecl(i);
4535 mergeParamDeclAttributes(NewParam, OldParam, *this);
4536 mergeParamDeclTypes(NewParam, OldParam, *this);
4537 }
4538
4539 if (getLangOpts().CPlusPlus)
4540 return MergeCXXFunctionDecl(New, Old, S);
4541
4542 // Merge the function types so the we get the composite types for the return
4543 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4544 // was visible.
4545 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4546 if (!Merged.isNull() && MergeTypeWithOld)
4547 New->setType(Merged);
4548
4549 return false;
4550}
4551
4553 ObjCMethodDecl *oldMethod) {
4554 // Merge the attributes, including deprecated/unavailable
4555 AvailabilityMergeKind MergeKind =
4557 ? (oldMethod->isOptional()
4560 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4563
4564 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4565
4566 // Merge attributes from the parameters.
4568 oe = oldMethod->param_end();
4570 ni = newMethod->param_begin(), ne = newMethod->param_end();
4571 ni != ne && oi != oe; ++ni, ++oi)
4572 mergeParamDeclAttributes(*ni, *oi, *this);
4573
4574 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4575}
4576
4578 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4579
4580 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4581 ? diag::err_redefinition_different_type
4582 : diag::err_redeclaration_different_type)
4583 << New->getDeclName() << New->getType() << Old->getType();
4584
4585 diag::kind PrevDiag;
4586 SourceLocation OldLocation;
4587 std::tie(PrevDiag, OldLocation)
4589 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4590 New->setInvalidDecl();
4591}
4592
4594 bool MergeTypeWithOld) {
4595 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4596 return;
4597
4598 QualType MergedT;
4599 if (getLangOpts().CPlusPlus) {
4600 if (New->getType()->isUndeducedType()) {
4601 // We don't know what the new type is until the initializer is attached.
4602 return;
4603 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4604 // These could still be something that needs exception specs checked.
4605 return MergeVarDeclExceptionSpecs(New, Old);
4606 }
4607 // C++ [basic.link]p10:
4608 // [...] the types specified by all declarations referring to a given
4609 // object or function shall be identical, except that declarations for an
4610 // array object can specify array types that differ by the presence or
4611 // absence of a major array bound (8.3.4).
4612 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4613 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4614 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4615
4616 // We are merging a variable declaration New into Old. If it has an array
4617 // bound, and that bound differs from Old's bound, we should diagnose the
4618 // mismatch.
4619 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4620 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4621 PrevVD = PrevVD->getPreviousDecl()) {
4622 QualType PrevVDTy = PrevVD->getType();
4623 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4624 continue;
4625
4626 if (!Context.hasSameType(New->getType(), PrevVDTy))
4627 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4628 }
4629 }
4630
4631 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4632 if (Context.hasSameType(OldArray->getElementType(),
4633 NewArray->getElementType()))
4634 MergedT = New->getType();
4635 }
4636 // FIXME: Check visibility. New is hidden but has a complete type. If New
4637 // has no array bound, it should not inherit one from Old, if Old is not
4638 // visible.
4639 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4640 if (Context.hasSameType(OldArray->getElementType(),
4641 NewArray->getElementType()))
4642 MergedT = Old->getType();
4643 }
4644 }
4645 else if (New->getType()->isObjCObjectPointerType() &&
4646 Old->getType()->isObjCObjectPointerType()) {
4647 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4648 Old->getType());
4649 }
4650 } else {
4651 // C 6.2.7p2:
4652 // All declarations that refer to the same object or function shall have
4653 // compatible type.
4654 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4655 }
4656 if (MergedT.isNull()) {
4657 // It's OK if we couldn't merge types if either type is dependent, for a
4658 // block-scope variable. In other cases (static data members of class
4659 // templates, variable templates, ...), we require the types to be
4660 // equivalent.
4661 // FIXME: The C++ standard doesn't say anything about this.
4662 if ((New->getType()->isDependentType() ||
4663 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4664 // If the old type was dependent, we can't merge with it, so the new type
4665 // becomes dependent for now. We'll reproduce the original type when we
4666 // instantiate the TypeSourceInfo for the variable.
4667 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4668 New->setType(Context.DependentTy);
4669 return;
4670 }
4671 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4672 }
4673
4674 // Don't actually update the type on the new declaration if the old
4675 // declaration was an extern declaration in a different scope.
4676 if (MergeTypeWithOld)
4677 New->setType(MergedT);
4678}
4679
4680static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4682 // C11 6.2.7p4:
4683 // For an identifier with internal or external linkage declared
4684 // in a scope in which a prior declaration of that identifier is
4685 // visible, if the prior declaration specifies internal or
4686 // external linkage, the type of the identifier at the later
4687 // declaration becomes the composite type.
4688 //
4689 // If the variable isn't visible, we do not merge with its type.
4690 if (Previous.isShadowed())
4691 return false;
4692
4693 if (S.getLangOpts().CPlusPlus) {
4694 // C++11 [dcl.array]p3:
4695 // If there is a preceding declaration of the entity in the same
4696 // scope in which the bound was specified, an omitted array bound
4697 // is taken to be the same as in that earlier declaration.
4698 return NewVD->isPreviousDeclInSameBlockScope() ||
4699 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4701 } else {
4702 // If the old declaration was function-local, don't merge with its
4703 // type unless we're in the same function.
4704 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4705 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4706 }
4707}
4708
4710 // If the new decl is already invalid, don't do any other checking.
4711 if (New->isInvalidDecl())
4712 return;
4713
4714 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4715 return;
4716
4717 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4718
4719 // Verify the old decl was also a variable or variable template.
4720 VarDecl *Old = nullptr;
4721 VarTemplateDecl *OldTemplate = nullptr;
4722 if (Previous.isSingleResult()) {
4723 if (NewTemplate) {
4724 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4725 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4726
4727 if (auto *Shadow =
4728 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4729 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4730 return New->setInvalidDecl();
4731 } else {
4732 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4733
4734 if (auto *Shadow =
4735 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4736 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4737 return New->setInvalidDecl();
4738 }
4739 }
4740 if (!Old) {
4741 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4742 << New->getDeclName();
4743 notePreviousDefinition(Previous.getRepresentativeDecl(),
4744 New->getLocation());
4745 return New->setInvalidDecl();
4746 }
4747
4748 // If the old declaration was found in an inline namespace and the new
4749 // declaration was qualified, update the DeclContext to match.
4751
4752 // Ensure the template parameters are compatible.
4753 if (NewTemplate &&
4755 OldTemplate->getTemplateParameters(),
4756 /*Complain=*/true, TPL_TemplateMatch))
4757 return New->setInvalidDecl();
4758
4759 // C++ [class.mem]p1:
4760 // A member shall not be declared twice in the member-specification [...]
4761 //
4762 // Here, we need only consider static data members.
4763 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4764 Diag(New->getLocation(), diag::err_duplicate_member)
4765 << New->getIdentifier();
4766 Diag(Old->getLocation(), diag::note_previous_declaration);
4767 New->setInvalidDecl();
4768 }
4769
4771 // Warn if an already-defined variable is made a weak_import in a subsequent
4772 // declaration
4773 if (New->hasAttr<WeakImportAttr>())
4774 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4775 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4776 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4777 Diag(D->getLocation(), diag::note_previous_definition);
4778 // Remove weak_import attribute on new declaration.
4779 New->dropAttr<WeakImportAttr>();
4780 break;
4781 }
4782 }
4783
4784 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4785 if (!Old->hasAttr<InternalLinkageAttr>()) {
4786 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4787 << ILA;
4788 Diag(Old->getLocation(), diag::note_previous_declaration);
4789 New->dropAttr<InternalLinkageAttr>();
4790 }
4791
4792 // Merge the types.
4793 VarDecl *MostRecent = Old->getMostRecentDecl();
4794 if (MostRecent != Old) {
4795 MergeVarDeclTypes(New, MostRecent,
4796 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4797 if (New->isInvalidDecl())
4798 return;
4799 }
4800
4802 if (New->isInvalidDecl())
4803 return;
4804
4805 diag::kind PrevDiag;
4806 SourceLocation OldLocation;
4807 std::tie(PrevDiag, OldLocation) =
4809
4810 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4811 if (New->getStorageClass() == SC_Static &&
4812 !New->isStaticDataMember() &&
4813 Old->hasExternalFormalLinkage()) {
4814 if (getLangOpts().MicrosoftExt) {
4815 Diag(New->getLocation(), diag::ext_static_non_static)
4816 << New->getDeclName();
4817 Diag(OldLocation, PrevDiag);
4818 } else {
4819 Diag(New->getLocation(), diag::err_static_non_static)
4820 << New->getDeclName();
4821 Diag(OldLocation, PrevDiag);
4822 return New->setInvalidDecl();
4823 }
4824 }
4825 // C99 6.2.2p4:
4826 // For an identifier declared with the storage-class specifier
4827 // extern in a scope in which a prior declaration of that
4828 // identifier is visible,23) if the prior declaration specifies
4829 // internal or external linkage, the linkage of the identifier at
4830 // the later declaration is the same as the linkage specified at
4831 // the prior declaration. If no prior declaration is visible, or
4832 // if the prior declaration specifies no linkage, then the
4833 // identifier has external linkage.
4834 if (New->hasExternalStorage() && Old->hasLinkage())
4835 /* Okay */;
4836 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4837 !New->isStaticDataMember() &&
4839 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4840 Diag(OldLocation, PrevDiag);
4841 return New->setInvalidDecl();
4842 }
4843
4844 // Check if extern is followed by non-extern and vice-versa.
4845 if (New->hasExternalStorage() &&
4846 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4847 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4848 Diag(OldLocation, PrevDiag);
4849 return New->setInvalidDecl();
4850 }
4851 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4852 !New->hasExternalStorage()) {
4853 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4854 Diag(OldLocation, PrevDiag);
4855 return New->setInvalidDecl();
4856 }
4857
4859 return;
4860
4861 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4862
4863 // FIXME: The test for external storage here seems wrong? We still
4864 // need to check for mismatches.
4865 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4866 // Don't complain about out-of-line definitions of static members.
4867 !(Old->getLexicalDeclContext()->isRecord() &&
4868 !New->getLexicalDeclContext()->isRecord())) {
4869 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4870 Diag(OldLocation, PrevDiag);
4871 return New->setInvalidDecl();
4872 }
4873
4874 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4875 if (VarDecl *Def = Old->getDefinition()) {
4876 // C++1z [dcl.fcn.spec]p4:
4877 // If the definition of a variable appears in a translation unit before
4878 // its first declaration as inline, the program is ill-formed.
4879 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4880 Diag(Def->getLocation(), diag::note_previous_definition);
4881 }
4882 }
4883
4884 // If this redeclaration makes the variable inline, we may need to add it to
4885 // UndefinedButUsed.
4886 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4887 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4888 !Old->isInAnotherModuleUnit())
4889 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4890 SourceLocation()));
4891
4892 if (New->getTLSKind() != Old->getTLSKind()) {
4893 if (!Old->getTLSKind()) {
4894 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4895 Diag(OldLocation, PrevDiag);
4896 } else if (!New->getTLSKind()) {
4897 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4898 Diag(OldLocation, PrevDiag);
4899 } else {
4900 // Do not allow redeclaration to change the variable between requiring
4901 // static and dynamic initialization.
4902 // FIXME: GCC allows this, but uses the TLS keyword on the first
4903 // declaration to determine the kind. Do we need to be compatible here?
4904 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4905 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4906 Diag(OldLocation, PrevDiag);
4907 }
4908 }
4909
4910 // C++ doesn't have tentative definitions, so go right ahead and check here.
4911 if (getLangOpts().CPlusPlus) {
4912 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4913 Old->getCanonicalDecl()->isConstexpr()) {
4914 // This definition won't be a definition any more once it's been merged.
4915 Diag(New->getLocation(),
4916 diag::warn_deprecated_redundant_constexpr_static_def);
4917 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4918 VarDecl *Def = Old->getDefinition();
4919 if (Def && checkVarDeclRedefinition(Def, New))
4920 return;
4921 if (Old->isInvalidDecl())
4922 New->setInvalidDecl();
4923 }
4924 } else {
4925 // C++ may not have a tentative definition rule, but it has a different
4926 // rule about what constitutes a definition in the first place. See
4927 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4928 // contains the extern specifier and doesn't have an initializer, it's fine
4929 // in C++.
4930 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4931 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4932 << New;
4933 Diag(Old->getLocation(), diag::note_previous_declaration);
4934 }
4935 }
4936
4938 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4939 Diag(OldLocation, PrevDiag);
4940 New->setInvalidDecl();
4941 return;
4942 }
4943
4944 // Merge "used" flag.
4945 if (Old->getMostRecentDecl()->isUsed(false))
4946 New->setIsUsed();
4947
4948 // Keep a chain of previous declarations.
4949 New->setPreviousDecl(Old);
4950 if (NewTemplate)
4951 NewTemplate->setPreviousDecl(OldTemplate);
4952
4953 // Inherit access appropriately.
4954 New->setAccess(Old->getAccess());
4955 if (NewTemplate)
4956 NewTemplate->setAccess(New->getAccess());
4957
4958 if (Old->isInline())
4959 New->setImplicitlyInline();
4960}
4961
4964 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4965 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4966 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4967 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4968 auto &HSI = PP.getHeaderSearchInfo();
4969 StringRef HdrFilename =
4970 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4971
4972 auto noteFromModuleOrInclude = [&](Module *Mod,
4973 SourceLocation IncLoc) -> bool {
4974 // Redefinition errors with modules are common with non modular mapped
4975 // headers, example: a non-modular header H in module A that also gets
4976 // included directly in a TU. Pointing twice to the same header/definition
4977 // is confusing, try to get better diagnostics when modules is on.
4978 if (IncLoc.isValid()) {
4979 if (Mod) {
4980 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4981 << HdrFilename.str() << Mod->getFullModuleName();
4982 if (!Mod->DefinitionLoc.isInvalid())
4983 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4984 << Mod->getFullModuleName();
4985 } else {
4986 Diag(IncLoc, diag::note_redefinition_include_same_file)
4987 << HdrFilename.str();
4988 }
4989 return true;
4990 }
4991
4992 return false;
4993 };
4994
4995 // Is it the same file and same offset? Provide more information on why
4996 // this leads to a redefinition error.
4997 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4998 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4999 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
5000 bool EmittedDiag =
5001 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
5002 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
5003
5004 // If the header has no guards, emit a note suggesting one.
5005 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
5006 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
5007
5008 if (EmittedDiag)
5009 return;
5010 }
5011
5012 // Redefinition coming from different files or couldn't do better above.
5013 if (Old->getLocation().isValid())
5014 Diag(Old->getLocation(), diag::note_previous_definition);
5015}
5016
5018 if (!hasVisibleDefinition(Old) &&
5019 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5021 New->getDescribedVarTemplate() ||
5022 !New->getTemplateParameterLists().empty() ||
5023 New->getDeclContext()->isDependentContext() ||
5024 New->hasAttr<SelectAnyAttr>())) {
5025 // The previous definition is hidden, and multiple definitions are
5026 // permitted (in separate TUs). Demote this to a declaration.
5027 New->demoteThisDefinitionToDeclaration();
5028
5029 // Make the canonical definition visible.
5030 if (auto *OldTD = Old->getDescribedVarTemplate())
5033 return false;
5034 } else {
5035 Diag(New->getLocation(), diag::err_redefinition) << New;
5036 notePreviousDefinition(Old, New->getLocation());
5037 New->setInvalidDecl();
5038 return true;
5039 }
5040}
5041
5043 DeclSpec &DS,
5044 const ParsedAttributesView &DeclAttrs,
5045 RecordDecl *&AnonRecord) {
5047 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
5048}
5049
5050// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5051// disambiguate entities defined in different scopes.
5052// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5053// compatibility.
5054// We will pick our mangling number depending on which version of MSVC is being
5055// targeted.
5056static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5060}
5061
5062void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5063 if (!Context.getLangOpts().CPlusPlus)
5064 return;
5065
5066 if (isa<CXXRecordDecl>(Tag->getParent())) {
5067 // If this tag is the direct child of a class, number it if
5068 // it is anonymous.
5069 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5070 return;
5072 Context.getManglingNumberContext(Tag->getParent());
5073 Context.setManglingNumber(
5074 Tag, MCtx.getManglingNumber(
5075 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5076 return;
5077 }
5078
5079 // If this tag isn't a direct child of a class, number it if it is local.
5081 Decl *ManglingContextDecl;
5082 std::tie(MCtx, ManglingContextDecl) =
5083 getCurrentMangleNumberContext(Tag->getDeclContext());
5084 if (MCtx) {
5085 Context.setManglingNumber(
5086 Tag, MCtx->getManglingNumber(
5087 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5088 }
5089}
5090
5091namespace {
5092struct NonCLikeKind {
5093 enum {
5094 None,
5095 BaseClass,
5096 DefaultMemberInit,
5097 Lambda,
5098 Friend,
5099 OtherMember,
5100 Invalid,
5101 } Kind = None;
5102 SourceRange Range;
5103
5104 explicit operator bool() { return Kind != None; }
5105};
5106}
5107
5108/// Determine whether a class is C-like, according to the rules of C++
5109/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5110static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5111 if (RD->isInvalidDecl())
5112 return {NonCLikeKind::Invalid, {}};
5113
5114 // C++ [dcl.typedef]p9: [P1766R1]
5115 // An unnamed class with a typedef name for linkage purposes shall not
5116 //
5117 // -- have any base classes
5118 if (RD->getNumBases())
5119 return {NonCLikeKind::BaseClass,
5121 RD->bases_end()[-1].getEndLoc())};
5122 bool Invalid = false;
5123 for (Decl *D : RD->decls()) {
5124 // Don't complain about things we already diagnosed.
5125 if (D->isInvalidDecl()) {
5126 Invalid = true;
5127 continue;
5128 }
5129
5130 // -- have any [...] default member initializers
5131 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5132 if (FD->hasInClassInitializer()) {
5133 auto *Init = FD->getInClassInitializer();
5134 return {NonCLikeKind::DefaultMemberInit,
5135 Init ? Init->getSourceRange() : D->getSourceRange()};
5136 }
5137 continue;
5138 }
5139
5140 // FIXME: We don't allow friend declarations. This violates the wording of
5141 // P1766, but not the intent.
5142 if (isa<FriendDecl>(D))
5143 return {NonCLikeKind::Friend, D->getSourceRange()};
5144
5145 // -- declare any members other than non-static data members, member
5146 // enumerations, or member classes,
5148 isa<EnumDecl>(D))
5149 continue;
5150 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5151 if (!MemberRD) {
5152 if (D->isImplicit())
5153 continue;
5154 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5155 }
5156
5157 // -- contain a lambda-expression,
5158 if (MemberRD->isLambda())
5159 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5160
5161 // and all member classes shall also satisfy these requirements
5162 // (recursively).
5163 if (MemberRD->isThisDeclarationADefinition()) {
5164 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5165 return Kind;
5166 }
5167 }
5168
5169 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5170}
5171
5173 TypedefNameDecl *NewTD) {
5174 if (TagFromDeclSpec->isInvalidDecl())
5175 return;
5176
5177 // Do nothing if the tag already has a name for linkage purposes.
5178 if (TagFromDeclSpec->hasNameForLinkage())
5179 return;
5180
5181 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5182 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5183
5184 // The type must match the tag exactly; no qualifiers allowed.
5185 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5186 Context.getCanonicalTagType(TagFromDeclSpec))) {
5187 if (getLangOpts().CPlusPlus)
5188 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5189 return;
5190 }
5191
5192 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5193 // An unnamed class with a typedef name for linkage purposes shall [be
5194 // C-like].
5195 //
5196 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5197 // shouldn't happen, but there are constructs that the language rule doesn't
5198 // disallow for which we can't reasonably avoid computing linkage early.
5199 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5200 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5201 : NonCLikeKind();
5202 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5203 if (NonCLike || ChangesLinkage) {
5204 if (NonCLike.Kind == NonCLikeKind::Invalid)
5205 return;
5206
5207 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5208 if (ChangesLinkage) {
5209 // If the linkage changes, we can't accept this as an extension.
5210 if (NonCLike.Kind == NonCLikeKind::None)
5211 DiagID = diag::err_typedef_changes_linkage;
5212 else
5213 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5214 }
5215
5216 SourceLocation FixitLoc =
5217 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5218 llvm::SmallString<40> TextToInsert;
5219 TextToInsert += ' ';
5220 TextToInsert += NewTD->getIdentifier()->getName();
5221
5222 Diag(FixitLoc, DiagID)
5223 << isa<TypeAliasDecl>(NewTD)
5224 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5225 if (NonCLike.Kind != NonCLikeKind::None) {
5226 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5227 << NonCLike.Kind - 1 << NonCLike.Range;
5228 }
5229 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5230 << NewTD << isa<TypeAliasDecl>(NewTD);
5231
5232 if (ChangesLinkage)
5233 return;
5234 }
5235
5236 // Otherwise, set this as the anon-decl typedef for the tag.
5237 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5238
5239 // Now that we have a name for the tag, process API notes again.
5240 ProcessAPINotes(TagFromDeclSpec);
5241}
5242
5243static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5245 switch (T) {
5247 return 0;
5249 return 1;
5251 return 2;
5253 return 3;
5254 case DeclSpec::TST_enum:
5255 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5256 if (ED->isScopedUsingClassTag())
5257 return 5;
5258 if (ED->isScoped())
5259 return 6;
5260 }
5261 return 4;
5262 default:
5263 llvm_unreachable("unexpected type specifier");
5264 }
5265}
5266
5268 DeclSpec &DS,
5269 const ParsedAttributesView &DeclAttrs,
5270 MultiTemplateParamsArg TemplateParams,
5271 bool IsExplicitInstantiation,
5272 RecordDecl *&AnonRecord,
5273 SourceLocation EllipsisLoc) {
5274 Decl *TagD = nullptr;
5275 TagDecl *Tag = nullptr;
5281 TagD = DS.getRepAsDecl();
5282
5283 if (!TagD) // We probably had an error
5284 return nullptr;
5285
5286 // Note that the above type specs guarantee that the
5287 // type rep is a Decl, whereas in many of the others
5288 // it's a Type.
5289 if (isa<TagDecl>(TagD))
5290 Tag = cast<TagDecl>(TagD);
5291 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5292 Tag = CTD->getTemplatedDecl();
5293 }
5294
5295 if (Tag) {
5296 handleTagNumbering(Tag, S);
5297 Tag->setFreeStanding();
5298 if (Tag->isInvalidDecl())
5299 return Tag;
5300 }
5301
5302 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5303 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5304 // or incomplete types shall not be restrict-qualified."
5305 if (TypeQuals & DeclSpec::TQ_restrict)
5307 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5308 << DS.getSourceRange();
5309 }
5310
5311 if (DS.isInlineSpecified())
5312 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5313 << getLangOpts().CPlusPlus17;
5314
5315 if (DS.hasConstexprSpecifier()) {
5316 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5317 // and definitions of functions and variables.
5318 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5319 // the declaration of a function or function template
5320 if (Tag)
5321 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5323 << static_cast<int>(DS.getConstexprSpecifier());
5324 else if (getLangOpts().C23)
5325 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5326 else
5327 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5328 << static_cast<int>(DS.getConstexprSpecifier());
5329 // Don't emit warnings after this error.
5330 return TagD;
5331 }
5332
5334
5335 if (DS.isFriendSpecified()) {
5336 // If we're dealing with a decl but not a TagDecl, assume that
5337 // whatever routines created it handled the friendship aspect.
5338 if (TagD && !Tag)
5339 return nullptr;
5340 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5341 }
5342
5343 assert(EllipsisLoc.isInvalid() &&
5344 "Friend ellipsis but not friend-specified?");
5345
5346 // Track whether this decl-specifier declares anything.
5347 bool DeclaresAnything = true;
5348
5349 // Handle anonymous struct definitions.
5350 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5351 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5353 if (getLangOpts().CPlusPlus ||
5354 Record->getDeclContext()->isRecord()) {
5355 // If CurContext is a DeclContext that can contain statements,
5356 // RecursiveASTVisitor won't visit the decls that
5357 // BuildAnonymousStructOrUnion() will put into CurContext.
5358 // Also store them here so that they can be part of the
5359 // DeclStmt that gets created in this case.
5360 // FIXME: Also return the IndirectFieldDecls created by
5361 // BuildAnonymousStructOr union, for the same reason?
5362 if (CurContext->isFunctionOrMethod())
5363 AnonRecord = Record;
5364 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5365 Context.getPrintingPolicy());
5366 }
5367
5368 DeclaresAnything = false;
5369 }
5370 }
5371
5372 // C11 6.7.2.1p2:
5373 // A struct-declaration that does not declare an anonymous structure or
5374 // anonymous union shall contain a struct-declarator-list.
5375 //
5376 // This rule also existed in C89 and C99; the grammar for struct-declaration
5377 // did not permit a struct-declaration without a struct-declarator-list.
5378 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5380 // Check for Microsoft C extension: anonymous struct/union member.
5381 // Handle 2 kinds of anonymous struct/union:
5382 // struct STRUCT;
5383 // union UNION;
5384 // and
5385 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5386 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5387 if ((Tag && Tag->getDeclName()) ||
5389 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5390 : DS.getRepAsType().get()->getAsRecordDecl();
5391 if (Record && getLangOpts().MSAnonymousStructs) {
5392 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5393 << Record->isUnion() << DS.getSourceRange();
5395 }
5396
5397 DeclaresAnything = false;
5398 }
5399 }
5400
5401 // Skip all the checks below if we have a type error.
5403 (TagD && TagD->isInvalidDecl()))
5404 return TagD;
5405
5406 if (getLangOpts().CPlusPlus &&
5408 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5409 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5410 !Enum->isInvalidDecl())
5411 DeclaresAnything = false;
5412
5413 if (!DS.isMissingDeclaratorOk()) {
5414 // Customize diagnostic for a typedef missing a name.
5416 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5417 << DS.getSourceRange();
5418 else
5419 DeclaresAnything = false;
5420 }
5421
5422 if (DS.isModulePrivateSpecified() &&
5423 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5424 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5425 << Tag->getTagKind()
5427
5429
5430 // C 6.7/2:
5431 // A declaration [...] shall declare at least a declarator [...], a tag,
5432 // or the members of an enumeration.
5433 // C++ [dcl.dcl]p3:
5434 // [If there are no declarators], and except for the declaration of an
5435 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5436 // names into the program, or shall redeclare a name introduced by a
5437 // previous declaration.
5438 if (!DeclaresAnything) {
5439 // In C, we allow this as a (popular) extension / bug. Don't bother
5440 // producing further diagnostics for redundant qualifiers after this.
5441 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5442 ? diag::err_no_declarators
5443 : diag::ext_no_declarators)
5444 << DS.getSourceRange();
5445 return TagD;
5446 }
5447
5448 // C++ [dcl.stc]p1:
5449 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5450 // init-declarator-list of the declaration shall not be empty.
5451 // C++ [dcl.fct.spec]p1:
5452 // If a cv-qualifier appears in a decl-specifier-seq, the
5453 // init-declarator-list of the declaration shall not be empty.
5454 //
5455 // Spurious qualifiers here appear to be valid in C.
5456 unsigned DiagID = diag::warn_standalone_specifier;
5457 if (getLangOpts().CPlusPlus)
5458 DiagID = diag::ext_standalone_specifier;
5459
5460 // Note that a linkage-specification sets a storage class, but
5461 // 'extern "C" struct foo;' is actually valid and not theoretically
5462 // useless.
5463 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5464 if (SCS == DeclSpec::SCS_mutable)
5465 // Since mutable is not a viable storage class specifier in C, there is
5466 // no reason to treat it as an extension. Instead, diagnose as an error.
5467 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5468 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5469 Diag(DS.getStorageClassSpecLoc(), DiagID)
5471 }
5472
5476 if (DS.getTypeQualifiers()) {
5478 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5480 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5481 // Restrict is covered above.
5483 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5485 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5486 }
5487
5488 // Warn about ignored type attributes, for example:
5489 // __attribute__((aligned)) struct A;
5490 // Attributes should be placed after tag to apply to type declaration.
5491 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5492 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5493 if (TypeSpecType == DeclSpec::TST_class ||
5494 TypeSpecType == DeclSpec::TST_struct ||
5495 TypeSpecType == DeclSpec::TST_interface ||
5496 TypeSpecType == DeclSpec::TST_union ||
5497 TypeSpecType == DeclSpec::TST_enum) {
5498
5499 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5500 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5501 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5502 DiagnosticId = diag::warn_attribute_ignored;
5503 else if (AL.isRegularKeywordAttribute())
5504 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5505 else
5506 DiagnosticId = diag::warn_declspec_attribute_ignored;
5507 Diag(AL.getLoc(), DiagnosticId)
5508 << AL << GetDiagnosticTypeSpecifierID(DS);
5509 };
5510
5511 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5512 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5513 }
5514 }
5515
5516 return TagD;
5517}
5518
5519/// We are trying to inject an anonymous member into the given scope;
5520/// check if there's an existing declaration that can't be overloaded.
5521///
5522/// \return true if this is a forbidden redeclaration
5523static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5524 DeclContext *Owner,
5525 DeclarationName Name,
5526 SourceLocation NameLoc, bool IsUnion,
5527 StorageClass SC) {
5528 LookupResult R(SemaRef, Name, NameLoc,
5532 if (!SemaRef.LookupName(R, S)) return false;
5533
5534 // Pick a representative declaration.
5535 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5536 assert(PrevDecl && "Expected a non-null Decl");
5537
5538 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5539 return false;
5540
5541 if (SC == StorageClass::SC_None &&
5542 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5543 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5544 if (!Owner->isRecord())
5545 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5546 return false;
5547 }
5548
5549 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5550 << IsUnion << Name;
5551 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5552
5553 return true;
5554}
5555
5557 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5559}
5560
5562 if (!getLangOpts().CPlusPlus)
5563 return;
5564
5565 // This function can be parsed before we have validated the
5566 // structure as an anonymous struct
5567 if (Record->isAnonymousStructOrUnion())
5568 return;
5569
5570 const NamedDecl *First = 0;
5571 for (const Decl *D : Record->decls()) {
5572 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5573 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5574 continue;
5575 if (!First)
5576 First = ND;
5577 else
5579 }
5580}
5581
5582/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5583/// anonymous struct or union AnonRecord into the owning context Owner
5584/// and scope S. This routine will be invoked just after we realize
5585/// that an unnamed union or struct is actually an anonymous union or
5586/// struct, e.g.,
5587///
5588/// @code
5589/// union {
5590/// int i;
5591/// float f;
5592/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5593/// // f into the surrounding scope.x
5594/// @endcode
5595///
5596/// This routine is recursive, injecting the names of nested anonymous
5597/// structs/unions into the owning context and scope as well.
5598static bool
5600 RecordDecl *AnonRecord, AccessSpecifier AS,
5601 StorageClass SC,
5602 SmallVectorImpl<NamedDecl *> &Chaining) {
5603 bool Invalid = false;
5604
5605 // Look every FieldDecl and IndirectFieldDecl with a name.
5606 for (auto *D : AnonRecord->decls()) {
5607 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5608 cast<NamedDecl>(D)->getDeclName()) {
5609 ValueDecl *VD = cast<ValueDecl>(D);
5610 // C++ [class.union]p2:
5611 // The names of the members of an anonymous union shall be
5612 // distinct from the names of any other entity in the
5613 // scope in which the anonymous union is declared.
5614
5615 bool FieldInvalid = CheckAnonMemberRedeclaration(
5616 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5617 AnonRecord->isUnion(), SC);
5618 if (FieldInvalid)
5619 Invalid = true;
5620
5621 // Inject the IndirectFieldDecl even if invalid, because later
5622 // diagnostics may depend on it being present, see findDefaultInitializer.
5623
5624 // C++ [class.union]p2:
5625 // For the purpose of name lookup, after the anonymous union
5626 // definition, the members of the anonymous union are
5627 // considered to have been defined in the scope in which the
5628 // anonymous union is declared.
5629 unsigned OldChainingSize = Chaining.size();
5630 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5631 Chaining.append(IF->chain_begin(), IF->chain_end());
5632 else
5633 Chaining.push_back(VD);
5634
5635 assert(Chaining.size() >= 2);
5636 NamedDecl **NamedChain =
5637 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5638 for (unsigned i = 0; i < Chaining.size(); i++)
5639 NamedChain[i] = Chaining[i];
5640
5642 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5643 VD->getType(), {NamedChain, Chaining.size()});
5644
5645 for (const auto *Attr : VD->attrs())
5646 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5647
5648 IndirectField->setAccess(AS);
5649 IndirectField->setImplicit();
5650 IndirectField->setInvalidDecl(FieldInvalid);
5651 SemaRef.PushOnScopeChains(IndirectField, S);
5652
5653 // That includes picking up the appropriate access specifier.
5654 if (AS != AS_none)
5655 IndirectField->setAccess(AS);
5656
5657 Chaining.resize(OldChainingSize);
5658 }
5659 }
5660
5661 return Invalid;
5662}
5663
5664/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5665/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5666/// illegal input values are mapped to SC_None.
5667static StorageClass
5669 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5670 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5671 "Parser allowed 'typedef' as storage class VarDecl.");
5672 switch (StorageClassSpec) {
5675 if (DS.isExternInLinkageSpec())
5676 return SC_None;
5677 return SC_Extern;
5678 case DeclSpec::SCS_static: return SC_Static;
5679 case DeclSpec::SCS_auto: return SC_Auto;
5682 // Illegal SCSs map to None: error reporting is up to the caller.
5683 case DeclSpec::SCS_mutable: // Fall through.
5684 case DeclSpec::SCS_typedef: return SC_None;
5685 }
5686 llvm_unreachable("unknown storage class specifier");
5687}
5688
5690 assert(Record->hasInClassInitializer());
5691
5692 for (const auto *I : Record->decls()) {
5693 const auto *FD = dyn_cast<FieldDecl>(I);
5694 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5695 FD = IFD->getAnonField();
5696 if (FD && FD->hasInClassInitializer())
5697 return FD->getLocation();
5698 }
5699
5700 llvm_unreachable("couldn't find in-class initializer");
5701}
5702
5704 SourceLocation DefaultInitLoc) {
5705 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5706 return;
5707
5708 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5709 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5710}
5711
5713 CXXRecordDecl *AnonUnion) {
5714 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5715 return;
5716
5718}
5719
5721 AccessSpecifier AS,
5723 const PrintingPolicy &Policy) {
5724 DeclContext *Owner = Record->getDeclContext();
5725
5726 // Diagnose whether this anonymous struct/union is an extension.
5727 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5728 Diag(Record->getLocation(), diag::ext_anonymous_union);
5729 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5730 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5731 else if (!Record->isUnion() && !getLangOpts().C11)
5732 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5733
5734 // C and C++ require different kinds of checks for anonymous
5735 // structs/unions.
5736 bool Invalid = false;
5737 if (getLangOpts().CPlusPlus) {
5738 const char *PrevSpec = nullptr;
5739 if (Record->isUnion()) {
5740 // C++ [class.union]p6:
5741 // C++17 [class.union.anon]p2:
5742 // Anonymous unions declared in a named namespace or in the
5743 // global namespace shall be declared static.
5744 unsigned DiagID;
5745 DeclContext *OwnerScope = Owner->getRedeclContext();
5747 (OwnerScope->isTranslationUnit() ||
5748 (OwnerScope->isNamespace() &&
5749 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5750 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5751 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5752
5753 // Recover by adding 'static'.
5755 PrevSpec, DiagID, Policy);
5756 }
5757 // C++ [class.union]p6:
5758 // A storage class is not allowed in a declaration of an
5759 // anonymous union in a class scope.
5761 isa<RecordDecl>(Owner)) {
5763 diag::err_anonymous_union_with_storage_spec)
5765
5766 // Recover by removing the storage specifier.
5769 PrevSpec, DiagID, Context.getPrintingPolicy());
5770 }
5771 }
5772
5773 // Ignore const/volatile/restrict qualifiers.
5774 if (DS.getTypeQualifiers()) {
5776 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5777 << Record->isUnion() << "const"
5781 diag::ext_anonymous_struct_union_qualified)
5782 << Record->isUnion() << "volatile"
5786 diag::ext_anonymous_struct_union_qualified)
5787 << Record->isUnion() << "restrict"
5791 diag::ext_anonymous_struct_union_qualified)
5792 << Record->isUnion() << "_Atomic"
5796 diag::ext_anonymous_struct_union_qualified)
5797 << Record->isUnion() << "__unaligned"
5799
5801 }
5802
5803 // C++ [class.union]p2:
5804 // The member-specification of an anonymous union shall only
5805 // define non-static data members. [Note: nested types and
5806 // functions cannot be declared within an anonymous union. ]
5807 for (auto *Mem : Record->decls()) {
5808 // Ignore invalid declarations; we already diagnosed them.
5809 if (Mem->isInvalidDecl())
5810 continue;
5811
5812 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5813 // C++ [class.union]p3:
5814 // An anonymous union shall not have private or protected
5815 // members (clause 11).
5816 assert(FD->getAccess() != AS_none);
5817 if (FD->getAccess() != AS_public) {
5818 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5819 << Record->isUnion() << (FD->getAccess() == AS_protected);
5820 Invalid = true;
5821 }
5822
5823 // C++ [class.union]p1
5824 // An object of a class with a non-trivial constructor, a non-trivial
5825 // copy constructor, a non-trivial destructor, or a non-trivial copy
5826 // assignment operator cannot be a member of a union, nor can an
5827 // array of such objects.
5828 if (CheckNontrivialField(FD))
5829 Invalid = true;
5830 } else if (Mem->isImplicit()) {
5831 // Any implicit members are fine.
5832 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5833 // This is a type that showed up in an
5834 // elaborated-type-specifier inside the anonymous struct or
5835 // union, but which actually declares a type outside of the
5836 // anonymous struct or union. It's okay.
5837 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5838 if (!MemRecord->isAnonymousStructOrUnion() &&
5839 MemRecord->getDeclName()) {
5840 // Visual C++ allows type definition in anonymous struct or union.
5841 if (getLangOpts().MicrosoftExt)
5842 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5843 << Record->isUnion();
5844 else {
5845 // This is a nested type declaration.
5846 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5847 << Record->isUnion();
5848 Invalid = true;
5849 }
5850 } else {
5851 // This is an anonymous type definition within another anonymous type.
5852 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5853 // not part of standard C++.
5854 Diag(MemRecord->getLocation(),
5855 diag::ext_anonymous_record_with_anonymous_type)
5856 << Record->isUnion();
5857 }
5858 } else if (isa<AccessSpecDecl>(Mem)) {
5859 // Any access specifier is fine.
5860 } else if (isa<StaticAssertDecl>(Mem)) {
5861 // In C++1z, static_assert declarations are also fine.
5862 } else {
5863 // We have something that isn't a non-static data
5864 // member. Complain about it.
5865 unsigned DK = diag::err_anonymous_record_bad_member;
5866 if (isa<TypeDecl>(Mem))
5867 DK = diag::err_anonymous_record_with_type;
5868 else if (isa<FunctionDecl>(Mem))
5869 DK = diag::err_anonymous_record_with_function;
5870 else if (isa<VarDecl>(Mem))
5871 DK = diag::err_anonymous_record_with_static;
5872
5873 // Visual C++ allows type definition in anonymous struct or union.
5874 if (getLangOpts().MicrosoftExt &&
5875 DK == diag::err_anonymous_record_with_type)
5876 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5877 << Record->isUnion();
5878 else {
5879 Diag(Mem->getLocation(), DK) << Record->isUnion();
5880 Invalid = true;
5881 }
5882 }
5883 }
5884
5885 // C++11 [class.union]p8 (DR1460):
5886 // At most one variant member of a union may have a
5887 // brace-or-equal-initializer.
5888 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5889 Owner->isRecord())
5892 }
5893
5894 if (!Record->isUnion() && !Owner->isRecord()) {
5895 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5896 << getLangOpts().CPlusPlus;
5897 Invalid = true;
5898 }
5899
5900 // C++ [dcl.dcl]p3:
5901 // [If there are no declarators], and except for the declaration of an
5902 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5903 // names into the program
5904 // C++ [class.mem]p2:
5905 // each such member-declaration shall either declare at least one member
5906 // name of the class or declare at least one unnamed bit-field
5907 //
5908 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5909 if (getLangOpts().CPlusPlus && Record->field_empty())
5910 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5911
5912 // Mock up a declarator.
5916 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5917
5918 // Create a declaration for this anonymous struct/union.
5919 NamedDecl *Anon = nullptr;
5920 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5921 Anon = FieldDecl::Create(
5922 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5923 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5924 /*BitWidth=*/nullptr, /*Mutable=*/false,
5925 /*InitStyle=*/ICIS_NoInit);
5926 Anon->setAccess(AS);
5927 ProcessDeclAttributes(S, Anon, Dc);
5928
5929 if (getLangOpts().CPlusPlus)
5930 FieldCollector->Add(cast<FieldDecl>(Anon));
5931 } else {
5932 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5933 if (SCSpec == DeclSpec::SCS_mutable) {
5934 // mutable can only appear on non-static class members, so it's always
5935 // an error here
5936 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5937 Invalid = true;
5938 SC = SC_None;
5939 }
5940
5941 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5942 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5943 Context.getCanonicalTagType(Record), TInfo, SC);
5944 if (Invalid)
5945 Anon->setInvalidDecl();
5946
5947 ProcessDeclAttributes(S, Anon, Dc);
5948
5949 // Default-initialize the implicit variable. This initialization will be
5950 // trivial in almost all cases, except if a union member has an in-class
5951 // initializer:
5952 // union { int n = 0; };
5954 }
5955 Anon->setImplicit();
5956
5957 // Mark this as an anonymous struct/union type.
5958 Record->setAnonymousStructOrUnion(true);
5959
5960 // Add the anonymous struct/union object to the current
5961 // context. We'll be referencing this object when we refer to one of
5962 // its members.
5963 Owner->addDecl(Anon);
5964
5965 // Inject the members of the anonymous struct/union into the owning
5966 // context and into the identifier resolver chain for name lookup
5967 // purposes.
5969 Chain.push_back(Anon);
5970
5971 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5972 Chain))
5973 Invalid = true;
5974
5975 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5976 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5978 Decl *ManglingContextDecl;
5979 std::tie(MCtx, ManglingContextDecl) =
5980 getCurrentMangleNumberContext(NewVD->getDeclContext());
5981 if (MCtx) {
5982 Context.setManglingNumber(
5983 NewVD, MCtx->getManglingNumber(
5984 NewVD, getMSManglingNumber(getLangOpts(), S)));
5985 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5986 }
5987 }
5988 }
5989
5990 if (Invalid)
5991 Anon->setInvalidDecl();
5992
5993 return Anon;
5994}
5995
5997 RecordDecl *Record) {
5998 assert(Record && "expected a record!");
5999
6000 // Mock up a declarator.
6003 assert(TInfo && "couldn't build declarator info for anonymous struct");
6004
6005 auto *ParentDecl = cast<RecordDecl>(CurContext);
6006 CanQualType RecTy = Context.getCanonicalTagType(Record);
6007
6008 // Create a declaration for this anonymous struct.
6009 NamedDecl *Anon =
6010 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
6011 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
6012 /*BitWidth=*/nullptr, /*Mutable=*/false,
6013 /*InitStyle=*/ICIS_NoInit);
6014 Anon->setImplicit();
6015
6016 // Add the anonymous struct object to the current context.
6017 CurContext->addDecl(Anon);
6018
6019 // Inject the members of the anonymous struct into the current
6020 // context and into the identifier resolver chain for name lookup
6021 // purposes.
6023 Chain.push_back(Anon);
6024
6025 RecordDecl *RecordDef = Record->getDefinition();
6026 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
6027 diag::err_field_incomplete_or_sizeless) ||
6029 *this, S, CurContext, RecordDef, AS_none,
6031 Anon->setInvalidDecl();
6032 ParentDecl->setInvalidDecl();
6033 }
6034
6035 return Anon;
6036}
6037
6041
6044 DeclarationNameInfo NameInfo;
6045 NameInfo.setLoc(Name.StartLocation);
6046
6047 switch (Name.getKind()) {
6048
6051 NameInfo.setName(Name.Identifier);
6052 return NameInfo;
6053
6055 // C++ [temp.deduct.guide]p3:
6056 // The simple-template-id shall name a class template specialization.
6057 // The template-name shall be the same identifier as the template-name
6058 // of the simple-template-id.
6059 // These together intend to imply that the template-name shall name a
6060 // class template.
6061 // FIXME: template<typename T> struct X {};
6062 // template<typename T> using Y = X<T>;
6063 // Y(int) -> Y<int>;
6064 // satisfies these rules but does not name a class template.
6065 TemplateName TN = Name.TemplateName.get().get();
6066 auto *Template = TN.getAsTemplateDecl();
6068 Diag(Name.StartLocation,
6069 diag::err_deduction_guide_name_not_class_template)
6070 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6071 if (Template)
6073 return DeclarationNameInfo();
6074 }
6075
6076 NameInfo.setName(
6077 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6078 return NameInfo;
6079 }
6080
6082 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6086 return NameInfo;
6087
6089 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6090 Name.Identifier));
6092 return NameInfo;
6093
6095 TypeSourceInfo *TInfo;
6097 if (Ty.isNull())
6098 return DeclarationNameInfo();
6099 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6100 Context.getCanonicalType(Ty)));
6101 NameInfo.setNamedTypeInfo(TInfo);
6102 return NameInfo;
6103 }
6104
6106 TypeSourceInfo *TInfo;
6107 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6108 if (Ty.isNull())
6109 return DeclarationNameInfo();
6110 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6111 Context.getCanonicalType(Ty)));
6112 NameInfo.setNamedTypeInfo(TInfo);
6113 return NameInfo;
6114 }
6115
6117 // In well-formed code, we can only have a constructor
6118 // template-id that refers to the current context, so go there
6119 // to find the actual type being constructed.
6120 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6121 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6122 return DeclarationNameInfo();
6123
6124 // Determine the type of the class being constructed.
6125 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6126
6127 // FIXME: Check two things: that the template-id names the same type as
6128 // CurClassType, and that the template-id does not occur when the name
6129 // was qualified.
6130
6131 NameInfo.setName(
6132 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6133 // FIXME: should we retrieve TypeSourceInfo?
6134 NameInfo.setNamedTypeInfo(nullptr);
6135 return NameInfo;
6136 }
6137
6139 TypeSourceInfo *TInfo;
6140 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6141 if (Ty.isNull())
6142 return DeclarationNameInfo();
6143 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6144 Context.getCanonicalType(Ty)));
6145 NameInfo.setNamedTypeInfo(TInfo);
6146 return NameInfo;
6147 }
6148
6150 TemplateName TName = Name.TemplateId->Template.get();
6151 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6152 return Context.getNameForTemplate(TName, TNameLoc);
6153 }
6154
6155 } // switch (Name.getKind())
6156
6157 llvm_unreachable("Unknown name kind");
6158}
6159
6161 do {
6162 if (Ty->isPointerOrReferenceType())
6163 Ty = Ty->getPointeeType();
6164 else if (Ty->isArrayType())
6166 else
6167 return Ty.withoutLocalFastQualifiers();
6168 } while (true);
6169}
6170
6171/// hasSimilarParameters - Determine whether the C++ functions Declaration
6172/// and Definition have "nearly" matching parameters. This heuristic is
6173/// used to improve diagnostics in the case where an out-of-line function
6174/// definition doesn't match any declaration within the class or namespace.
6175/// Also sets Params to the list of indices to the parameters that differ
6176/// between the declaration and the definition. If hasSimilarParameters
6177/// returns true and Params is empty, then all of the parameters match.
6181 SmallVectorImpl<unsigned> &Params) {
6182 Params.clear();
6183 if (Declaration->param_size() != Definition->param_size())
6184 return false;
6185 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6186 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6187 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6188
6189 // The parameter types are identical
6190 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6191 continue;
6192
6193 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6194 QualType DefParamBaseTy = getCoreType(DefParamTy);
6195 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6196 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6197
6198 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6199 (DeclTyName && DeclTyName == DefTyName))
6200 Params.push_back(Idx);
6201 else // The two parameters aren't even close
6202 return false;
6203 }
6204
6205 return true;
6206}
6207
6208/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6209/// declarator needs to be rebuilt in the current instantiation.
6210/// Any bits of declarator which appear before the name are valid for
6211/// consideration here. That's specifically the type in the decl spec
6212/// and the base type in any member-pointer chunks.
6214 DeclarationName Name) {
6215 // The types we specifically need to rebuild are:
6216 // - typenames, typeofs, and decltypes
6217 // - types which will become injected class names
6218 // Of course, we also need to rebuild any type referencing such a
6219 // type. It's safest to just say "dependent", but we call out a
6220 // few cases here.
6221
6222 DeclSpec &DS = D.getMutableDeclSpec();
6223 switch (DS.getTypeSpecType()) {
6227#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6228#include "clang/Basic/TransformTypeTraits.def"
6229 case DeclSpec::TST_atomic: {
6230 // Grab the type from the parser.
6231 TypeSourceInfo *TSI = nullptr;
6232 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6233 if (T.isNull() || !T->isInstantiationDependentType()) break;
6234
6235 // Make sure there's a type source info. This isn't really much
6236 // of a waste; most dependent types should have type source info
6237 // attached already.
6238 if (!TSI)
6240
6241 // Rebuild the type in the current instantiation.
6243 if (!TSI) return true;
6244
6245 // Store the new type back in the decl spec.
6246 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6247 DS.UpdateTypeRep(LocType);
6248 break;
6249 }
6250
6254 Expr *E = DS.getRepAsExpr();
6256 if (Result.isInvalid()) return true;
6257 DS.UpdateExprRep(Result.get());
6258 break;
6259 }
6260
6261 default:
6262 // Nothing to do for these decl specs.
6263 break;
6264 }
6265
6266 // It doesn't matter what order we do this in.
6267 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6268 DeclaratorChunk &Chunk = D.getTypeObject(I);
6269
6270 // The only type information in the declarator which can come
6271 // before the declaration name is the base type of a member
6272 // pointer.
6274 continue;
6275
6276 // Rebuild the scope specifier in-place.
6277 CXXScopeSpec &SS = Chunk.Mem.Scope();
6279 return true;
6280 }
6281
6282 return false;
6283}
6284
6285/// Returns true if the declaration is declared in a system header or from a
6286/// system macro.
6287static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6288 return SM.isInSystemHeader(D->getLocation()) ||
6289 SM.isInSystemMacro(D->getLocation());
6290}
6291
6293 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6294 // of system decl.
6295 if (D->getPreviousDecl() || D->isImplicit())
6296 return;
6299 !isFromSystemHeader(Context.getSourceManager(), D)) {
6300 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6301 << D << static_cast<int>(Status);
6302 }
6303}
6304
6307
6308 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6309 // declaration only if the `bind_to_declaration` extension is set.
6311 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6312 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6313 llvm::omp::TraitProperty::
6314 implementation_extension_bind_to_declaration))
6316 S, D, MultiTemplateParamsArg(), Bases);
6317
6319
6320 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6321 Dcl && Dcl->getDeclContext()->isFileContext())
6323
6324 if (!Bases.empty())
6326 Bases);
6327
6328 return Dcl;
6329}
6330
6332 DeclarationNameInfo NameInfo) {
6333 DeclarationName Name = NameInfo.getName();
6334
6335 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6336 while (Record && Record->isAnonymousStructOrUnion())
6337 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6338 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6339 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6340 return true;
6341 }
6342
6343 return false;
6344}
6345
6347 DeclarationName Name,
6348 SourceLocation Loc,
6349 TemplateIdAnnotation *TemplateId,
6350 bool IsMemberSpecialization) {
6351 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6352 "without nested-name-specifier");
6353 DeclContext *Cur = CurContext;
6354 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6355 Cur = Cur->getParent();
6356
6357 // If the user provided a superfluous scope specifier that refers back to the
6358 // class in which the entity is already declared, diagnose and ignore it.
6359 //
6360 // class X {
6361 // void X::f();
6362 // };
6363 //
6364 // Note, it was once ill-formed to give redundant qualification in all
6365 // contexts, but that rule was removed by DR482.
6366 if (Cur->Equals(DC)) {
6367 if (Cur->isRecord()) {
6368 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6369 : diag::err_member_extra_qualification)
6370 << Name << FixItHint::CreateRemoval(SS.getRange());
6371 SS.clear();
6372 } else {
6373 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6374 }
6375 return false;
6376 }
6377
6378 // Check whether the qualifying scope encloses the scope of the original
6379 // declaration. For a template-id, we perform the checks in
6380 // CheckTemplateSpecializationScope.
6381 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6382 if (Cur->isRecord())
6383 Diag(Loc, diag::err_member_qualification)
6384 << Name << SS.getRange();
6385 else if (isa<TranslationUnitDecl>(DC))
6386 Diag(Loc, diag::err_invalid_declarator_global_scope)
6387 << Name << SS.getRange();
6388 else if (isa<FunctionDecl>(Cur))
6389 Diag(Loc, diag::err_invalid_declarator_in_function)
6390 << Name << SS.getRange();
6391 else if (isa<BlockDecl>(Cur))
6392 Diag(Loc, diag::err_invalid_declarator_in_block)
6393 << Name << SS.getRange();
6394 else if (isa<ExportDecl>(Cur)) {
6395 if (!isa<NamespaceDecl>(DC))
6396 Diag(Loc, diag::err_export_non_namespace_scope_name)
6397 << Name << SS.getRange();
6398 else
6399 // The cases that DC is not NamespaceDecl should be handled in
6400 // CheckRedeclarationExported.
6401 return false;
6402 } else
6403 Diag(Loc, diag::err_invalid_declarator_scope)
6404 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6405
6406 return true;
6407 }
6408
6409 if (Cur->isRecord()) {
6410 // Cannot qualify members within a class.
6411 Diag(Loc, diag::err_member_qualification)
6412 << Name << SS.getRange();
6413 SS.clear();
6414
6415 // C++ constructors and destructors with incorrect scopes can break
6416 // our AST invariants by having the wrong underlying types. If
6417 // that's the case, then drop this declaration entirely.
6420 !Context.hasSameType(
6421 Name.getCXXNameType(),
6422 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6423 return true;
6424
6425 return false;
6426 }
6427
6428 // C++23 [temp.names]p5:
6429 // The keyword template shall not appear immediately after a declarative
6430 // nested-name-specifier.
6431 //
6432 // First check the template-id (if any), and then check each component of the
6433 // nested-name-specifier in reverse order.
6434 //
6435 // FIXME: nested-name-specifiers in friend declarations are declarative,
6436 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6437 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6438 Diag(Loc, diag::ext_template_after_declarative_nns)
6440
6442 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6443 TL = std::exchange(NextTL, TypeLoc())) {
6444 SourceLocation TemplateKeywordLoc;
6445 switch (TL.getTypeLocClass()) {
6446 case TypeLoc::TemplateSpecialization: {
6447 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6448 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6449 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6450 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6451 << TST.getLocalSourceRange();
6452 break;
6453 }
6454 case TypeLoc::Decltype:
6455 case TypeLoc::PackIndexing: {
6456 const Type *T = TL.getTypePtr();
6457 // C++23 [expr.prim.id.qual]p2:
6458 // [...] A declarative nested-name-specifier shall not have a
6459 // computed-type-specifier.
6460 //
6461 // CWG2858 changed this from 'decltype-specifier' to
6462 // 'computed-type-specifier'.
6463 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6464 << T->isDecltypeType() << TL.getSourceRange();
6465 break;
6466 }
6467 case TypeLoc::DependentName:
6468 NextTL =
6469 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6470 break;
6471 default:
6472 break;
6473 }
6474 if (TemplateKeywordLoc.isValid())
6475 Diag(Loc, diag::ext_template_after_declarative_nns)
6476 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6477 }
6478
6479 return false;
6480}
6481
6483 MultiTemplateParamsArg TemplateParamLists) {
6484 // TODO: consider using NameInfo for diagnostic.
6486 DeclarationName Name = NameInfo.getName();
6487
6488 // All of these full declarators require an identifier. If it doesn't have
6489 // one, the ParsedFreeStandingDeclSpec action should be used.
6490 if (D.isDecompositionDeclarator()) {
6491 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6492 } else if (!Name) {
6493 if (!D.isInvalidType()) // Reject this if we think it is valid.
6494 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6496 return nullptr;
6498 return nullptr;
6499
6500 DeclContext *DC = CurContext;
6501 if (D.getCXXScopeSpec().isInvalid())
6502 D.setInvalidType();
6503 else if (D.getCXXScopeSpec().isSet()) {
6506 return nullptr;
6507
6508 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6509 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6510 if (!DC || isa<EnumDecl>(DC)) {
6511 // If we could not compute the declaration context, it's because the
6512 // declaration context is dependent but does not refer to a class,
6513 // class template, or class template partial specialization. Complain
6514 // and return early, to avoid the coming semantic disaster.
6516 diag::err_template_qualified_declarator_no_match)
6518 << D.getCXXScopeSpec().getRange();
6519 return nullptr;
6520 }
6521 bool IsDependentContext = DC->isDependentContext();
6522
6523 if (!IsDependentContext &&
6525 return nullptr;
6526
6527 // If a class is incomplete, do not parse entities inside it.
6530 diag::err_member_def_undefined_record)
6531 << Name << DC << D.getCXXScopeSpec().getRange();
6532 return nullptr;
6533 }
6534 if (!D.getDeclSpec().isFriendSpecified()) {
6535 TemplateIdAnnotation *TemplateId =
6537 ? D.getName().TemplateId
6538 : nullptr;
6540 D.getIdentifierLoc(), TemplateId,
6541 /*IsMemberSpecialization=*/false)) {
6542 if (DC->isRecord())
6543 return nullptr;
6544
6545 D.setInvalidType();
6546 }
6547 }
6548
6549 // Check whether we need to rebuild the type of the given
6550 // declaration in the current instantiation.
6551 if (EnteringContext && IsDependentContext &&
6552 TemplateParamLists.size() != 0) {
6553 ContextRAII SavedContext(*this, DC);
6554 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6555 D.setInvalidType();
6556 }
6557 }
6558
6560 QualType R = TInfo->getType();
6561
6564 D.setInvalidType();
6565
6566 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6568
6569 // See if this is a redefinition of a variable in the same scope.
6570 if (!D.getCXXScopeSpec().isSet()) {
6571 bool IsLinkageLookup = false;
6572 bool CreateBuiltins = false;
6573
6574 // If the declaration we're planning to build will be a function
6575 // or object with linkage, then look for another declaration with
6576 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6577 //
6578 // If the declaration we're planning to build will be declared with
6579 // external linkage in the translation unit, create any builtin with
6580 // the same name.
6582 /* Do nothing*/;
6583 else if (CurContext->isFunctionOrMethod() &&
6585 R->isFunctionType())) {
6586 IsLinkageLookup = true;
6587 CreateBuiltins =
6588 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6589 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6591 CreateBuiltins = true;
6592
6593 if (IsLinkageLookup) {
6595 Previous.setRedeclarationKind(
6597 }
6598
6599 LookupName(Previous, S, CreateBuiltins);
6600 } else { // Something like "int foo::x;"
6602
6603 // C++ [dcl.meaning]p1:
6604 // When the declarator-id is qualified, the declaration shall refer to a
6605 // previously declared member of the class or namespace to which the
6606 // qualifier refers (or, in the case of a namespace, of an element of the
6607 // inline namespace set of that namespace (7.3.1)) or to a specialization
6608 // thereof; [...]
6609 //
6610 // Note that we already checked the context above, and that we do not have
6611 // enough information to make sure that Previous contains the declaration
6612 // we want to match. For example, given:
6613 //
6614 // class X {
6615 // void f();
6616 // void f(float);
6617 // };
6618 //
6619 // void X::f(int) { } // ill-formed
6620 //
6621 // In this case, Previous will point to the overload set
6622 // containing the two f's declared in X, but neither of them
6623 // matches.
6624
6626 }
6627
6628 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6629 TPD && TPD->isTemplateParameter()) {
6630 // Older versions of clang allowed the names of function/variable templates
6631 // to shadow the names of their template parameters. For the compatibility
6632 // purposes we detect such cases and issue a default-to-error warning that
6633 // can be disabled with -Wno-strict-primary-template-shadow.
6634 if (!D.isInvalidType()) {
6635 bool AllowForCompatibility = false;
6636 if (Scope *DeclParent = S->getDeclParent();
6637 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6638 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6639 TemplateParamParent->isDeclScope(TPD);
6640 }
6642 AllowForCompatibility);
6643 }
6644
6645 // Just pretend that we didn't see the previous declaration.
6646 Previous.clear();
6647 }
6648
6649 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6650 // Forget that the previous declaration is the injected-class-name.
6651 Previous.clear();
6652
6653 // In C++, the previous declaration we find might be a tag type
6654 // (class or enum). In this case, the new declaration will hide the
6655 // tag type. Note that this applies to functions, function templates, and
6656 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6657 if (Previous.isSingleTagDecl() &&
6659 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6660 Previous.clear();
6661
6662 // Check that there are no default arguments other than in the parameters
6663 // of a function declaration (C++ only).
6664 if (getLangOpts().CPlusPlus)
6666
6667 /// Get the innermost enclosing declaration scope.
6668 S = S->getDeclParent();
6669
6670 NamedDecl *New;
6671
6672 bool AddToScope = true;
6674 if (TemplateParamLists.size()) {
6675 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6676 return nullptr;
6677 }
6678
6679 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6680 } else if (R->isFunctionType()) {
6681 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6682 TemplateParamLists,
6683 AddToScope);
6684 } else {
6685 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6686 AddToScope);
6687 }
6688
6689 if (!New)
6690 return nullptr;
6691
6693
6694 // If this has an identifier and is not a function template specialization,
6695 // add it to the scope stack.
6696 if (New->getDeclName() && AddToScope)
6698
6699 if (OpenMP().isInOpenMPDeclareTargetContext())
6701
6702 return New;
6703}
6704
6705/// Helper method to turn variable array types into constant array
6706/// types in certain situations which would otherwise be errors (for
6707/// GCC compatibility).
6709 ASTContext &Context,
6710 bool &SizeIsNegative,
6711 llvm::APSInt &Oversized) {
6712 // This method tries to turn a variable array into a constant
6713 // array even when the size isn't an ICE. This is necessary
6714 // for compatibility with code that depends on gcc's buggy
6715 // constant expression folding, like struct {char x[(int)(char*)2];}
6716 SizeIsNegative = false;
6717 Oversized = 0;
6718
6719 if (T->isDependentType())
6720 return QualType();
6721
6723 const Type *Ty = Qs.strip(T);
6724
6725 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6726 QualType Pointee = PTy->getPointeeType();
6727 QualType FixedType =
6728 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6729 Oversized);
6730 if (FixedType.isNull()) return FixedType;
6731 FixedType = Context.getPointerType(FixedType);
6732 return Qs.apply(Context, FixedType);
6733 }
6734 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6735 QualType Inner = PTy->getInnerType();
6736 QualType FixedType =
6737 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6738 Oversized);
6739 if (FixedType.isNull()) return FixedType;
6740 FixedType = Context.getParenType(FixedType);
6741 return Qs.apply(Context, FixedType);
6742 }
6743
6744 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6745 if (!VLATy)
6746 return QualType();
6747
6748 QualType ElemTy = VLATy->getElementType();
6749 if (ElemTy->isVariablyModifiedType()) {
6750 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6751 SizeIsNegative, Oversized);
6752 if (ElemTy.isNull())
6753 return QualType();
6754 }
6755
6757 if (!VLATy->getSizeExpr() ||
6758 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6759 return QualType();
6760
6761 llvm::APSInt Res = Result.Val.getInt();
6762
6763 // Check whether the array size is negative.
6764 if (Res.isSigned() && Res.isNegative()) {
6765 SizeIsNegative = true;
6766 return QualType();
6767 }
6768
6769 // Check whether the array is too large to be addressed.
6770 unsigned ActiveSizeBits =
6771 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6772 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6773 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6774 : Res.getActiveBits();
6775 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6776 Oversized = std::move(Res);
6777 return QualType();
6778 }
6779
6780 QualType FoldedArrayType = Context.getConstantArrayType(
6781 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6782 return Qs.apply(Context, FoldedArrayType);
6783}
6784
6785static void
6787 SrcTL = SrcTL.getUnqualifiedLoc();
6788 DstTL = DstTL.getUnqualifiedLoc();
6789 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6790 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6791 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6792 DstPTL.getPointeeLoc());
6793 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6794 return;
6795 }
6796 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6797 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6798 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6799 DstPTL.getInnerLoc());
6800 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6801 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6802 return;
6803 }
6804 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6805 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6806 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6807 TypeLoc DstElemTL = DstATL.getElementLoc();
6808 if (VariableArrayTypeLoc SrcElemATL =
6809 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6810 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6811 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6812 } else {
6813 DstElemTL.initializeFullCopy(SrcElemTL);
6814 }
6815 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6816 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6817 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6818}
6819
6820/// Helper method to turn variable array types into constant array
6821/// types in certain situations which would otherwise be errors (for
6822/// GCC compatibility).
6823static TypeSourceInfo*
6825 ASTContext &Context,
6826 bool &SizeIsNegative,
6827 llvm::APSInt &Oversized) {
6828 QualType FixedTy
6829 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6830 SizeIsNegative, Oversized);
6831 if (FixedTy.isNull())
6832 return nullptr;
6833 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6835 FixedTInfo->getTypeLoc());
6836 return FixedTInfo;
6837}
6838
6840 QualType &T, SourceLocation Loc,
6841 unsigned FailedFoldDiagID) {
6842 bool SizeIsNegative;
6843 llvm::APSInt Oversized;
6845 TInfo, Context, SizeIsNegative, Oversized);
6846 if (FixedTInfo) {
6847 Diag(Loc, diag::ext_vla_folded_to_constant);
6848 TInfo = FixedTInfo;
6849 T = FixedTInfo->getType();
6850 return true;
6851 }
6852
6853 if (SizeIsNegative)
6854 Diag(Loc, diag::err_typecheck_negative_array_size);
6855 else if (Oversized.getBoolValue())
6856 Diag(Loc, diag::err_array_too_large) << toString(
6857 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6858 /*UpperCase=*/false, /*InsertSeparators=*/true);
6859 else if (FailedFoldDiagID)
6860 Diag(Loc, FailedFoldDiagID);
6861 return false;
6862}
6863
6864void
6866 if (!getLangOpts().CPlusPlus &&
6868 // Don't need to track declarations in the TU in C.
6869 return;
6870
6871 // Note that we have a locally-scoped external with this name.
6872 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6873}
6874
6876 // FIXME: We can have multiple results via __attribute__((overloadable)).
6877 auto Result = Context.getExternCContextDecl()->lookup(Name);
6878 return Result.empty() ? nullptr : *Result.begin();
6879}
6880
6882 // FIXME: We should probably indicate the identifier in question to avoid
6883 // confusion for constructs like "virtual int a(), b;"
6884 if (DS.isVirtualSpecified())
6886 diag::err_virtual_non_function);
6887
6888 if (DS.hasExplicitSpecifier())
6890 diag::err_explicit_non_function);
6891
6892 if (DS.isNoreturnSpecified())
6894 diag::err_noreturn_non_function);
6895}
6896
6897NamedDecl*
6900 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6901 if (D.getCXXScopeSpec().isSet()) {
6902 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6903 << D.getCXXScopeSpec().getRange();
6904 D.setInvalidType();
6905 // Pretend we didn't see the scope specifier.
6906 DC = CurContext;
6907 Previous.clear();
6908 }
6909
6911
6914 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6915 ? diag::warn_ms_inline_non_function
6916 : diag::err_inline_non_function)
6917 << getLangOpts().CPlusPlus17;
6919 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6920 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6921
6925 diag::err_deduction_guide_invalid_specifier)
6926 << "typedef";
6927 else
6928 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6929 << D.getName().getSourceRange();
6930 return nullptr;
6931 }
6932
6933 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6934 if (!NewTD) return nullptr;
6935
6936 // Handle attributes prior to checking for duplicates in MergeVarDecl
6937 ProcessDeclAttributes(S, NewTD, D);
6938
6940
6941 bool Redeclaration = D.isRedeclaration();
6944 return ND;
6945}
6946
6947void
6949 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6950 // then it shall have block scope.
6951 // Note that variably modified types must be fixed before merging the decl so
6952 // that redeclarations will match.
6953 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6954 QualType T = TInfo->getType();
6955 if (T->isVariablyModifiedType()) {
6957
6958 if (S->getFnParent() == nullptr) {
6959 bool SizeIsNegative;
6960 llvm::APSInt Oversized;
6961 TypeSourceInfo *FixedTInfo =
6963 SizeIsNegative,
6964 Oversized);
6965 if (FixedTInfo) {
6966 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6967 NewTD->setTypeSourceInfo(FixedTInfo);
6968 } else {
6969 if (SizeIsNegative)
6970 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6971 else if (T->isVariableArrayType())
6972 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6973 else if (Oversized.getBoolValue())
6974 Diag(NewTD->getLocation(), diag::err_array_too_large)
6975 << toString(Oversized, 10);
6976 else
6977 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6978 NewTD->setInvalidDecl();
6979 }
6980 }
6981 }
6982}
6983
6984NamedDecl*
6987
6988 // Find the shadowed declaration before filtering for scope.
6989 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6990
6991 // Merge the decl with the existing one if appropriate. If the decl is
6992 // in an outer scope, it isn't the same thing.
6993 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6994 /*AllowInlineNamespace*/false);
6996 if (!Previous.empty()) {
6997 Redeclaration = true;
6998 MergeTypedefNameDecl(S, NewTD, Previous);
6999 } else {
7001 }
7002
7003 if (ShadowedDecl && !Redeclaration)
7004 CheckShadow(NewTD, ShadowedDecl, Previous);
7005
7006 // If this is the C FILE type, notify the AST context.
7007 if (IdentifierInfo *II = NewTD->getIdentifier())
7008 if (!NewTD->isInvalidDecl() &&
7010 switch (II->getNotableIdentifierID()) {
7011 case tok::NotableIdentifierKind::FILE:
7012 Context.setFILEDecl(NewTD);
7013 break;
7014 case tok::NotableIdentifierKind::jmp_buf:
7015 Context.setjmp_bufDecl(NewTD);
7016 break;
7017 case tok::NotableIdentifierKind::sigjmp_buf:
7018 Context.setsigjmp_bufDecl(NewTD);
7019 break;
7020 case tok::NotableIdentifierKind::ucontext_t:
7021 Context.setucontext_tDecl(NewTD);
7022 break;
7023 case tok::NotableIdentifierKind::float_t:
7024 case tok::NotableIdentifierKind::double_t:
7025 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
7026 break;
7027 default:
7028 break;
7029 }
7030 }
7031
7032 return NewTD;
7033}
7034
7035/// Determines whether the given declaration is an out-of-scope
7036/// previous declaration.
7037///
7038/// This routine should be invoked when name lookup has found a
7039/// previous declaration (PrevDecl) that is not in the scope where a
7040/// new declaration by the same name is being introduced. If the new
7041/// declaration occurs in a local scope, previous declarations with
7042/// linkage may still be considered previous declarations (C99
7043/// 6.2.2p4-5, C++ [basic.link]p6).
7044///
7045/// \param PrevDecl the previous declaration found by name
7046/// lookup
7047///
7048/// \param DC the context in which the new declaration is being
7049/// declared.
7050///
7051/// \returns true if PrevDecl is an out-of-scope previous declaration
7052/// for a new delcaration with the same name.
7053static bool
7055 ASTContext &Context) {
7056 if (!PrevDecl)
7057 return false;
7058
7059 if (!PrevDecl->hasLinkage())
7060 return false;
7061
7062 if (Context.getLangOpts().CPlusPlus) {
7063 // C++ [basic.link]p6:
7064 // If there is a visible declaration of an entity with linkage
7065 // having the same name and type, ignoring entities declared
7066 // outside the innermost enclosing namespace scope, the block
7067 // scope declaration declares that same entity and receives the
7068 // linkage of the previous declaration.
7069 DeclContext *OuterContext = DC->getRedeclContext();
7070 if (!OuterContext->isFunctionOrMethod())
7071 // This rule only applies to block-scope declarations.
7072 return false;
7073
7074 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7075 if (PrevOuterContext->isRecord())
7076 // We found a member function: ignore it.
7077 return false;
7078
7079 // Find the innermost enclosing namespace for the new and
7080 // previous declarations.
7081 OuterContext = OuterContext->getEnclosingNamespaceContext();
7082 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7083
7084 // The previous declaration is in a different namespace, so it
7085 // isn't the same function.
7086 if (!OuterContext->Equals(PrevOuterContext))
7087 return false;
7088 }
7089
7090 return true;
7091}
7092
7094 CXXScopeSpec &SS = D.getCXXScopeSpec();
7095 if (!SS.isSet()) return;
7097}
7098
7101 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7102 // __opencl_c_program_scope_global_variables feature, the address space
7103 // for a variable at program scope or a static or extern variable inside
7104 // a function are inferred to be __global.
7105 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7106 Var->hasGlobalStorage())
7107 ImplAS = LangAS::opencl_global;
7108 Var->assignAddressSpace(Context, ImplAS);
7109}
7110
7111static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7112 // 'weak' only applies to declarations with external linkage.
7113 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7114 if (!ND.isExternallyVisible()) {
7115 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7116 ND.dropAttr<WeakAttr>();
7117 }
7118 }
7119}
7120
7121static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7122 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7123 if (ND.isExternallyVisible()) {
7124 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7125 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7126 }
7127 }
7128}
7129
7130static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7131 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7132 if (VD->hasInit()) {
7133 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7134 assert(VD->isThisDeclarationADefinition() &&
7135 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7136 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7137 VD->dropAttr<AliasAttr>();
7138 }
7139 }
7140 }
7141}
7142
7143static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7144 // 'selectany' only applies to externally visible variable declarations.
7145 // It does not apply to functions.
7146 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7147 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7148 S.Diag(Attr->getLocation(),
7149 diag::err_attribute_selectany_non_extern_data);
7150 ND.dropAttr<SelectAnyAttr>();
7151 }
7152 }
7153}
7154
7156 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7157 if (!ND.isExternallyVisible())
7158 S.Diag(Attr->getLocation(),
7159 diag::warn_attribute_hybrid_patchable_non_extern);
7160 }
7161}
7162
7164 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7165 auto *VD = dyn_cast<VarDecl>(&ND);
7166 bool IsAnonymousNS = false;
7167 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7168 if (VD) {
7169 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7170 while (NS && !IsAnonymousNS) {
7171 IsAnonymousNS = NS->isAnonymousNamespace();
7172 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7173 }
7174 }
7175 // dll attributes require external linkage. Static locals may have external
7176 // linkage but still cannot be explicitly imported or exported.
7177 // In Microsoft mode, a variable defined in anonymous namespace must have
7178 // external linkage in order to be exported.
7179 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7180 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7181 (!AnonNSInMicrosoftMode &&
7182 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7183 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7184 << &ND << Attr;
7185 ND.setInvalidDecl();
7186 }
7187 }
7188}
7189
7191 // Check the attributes on the function type and function params, if any.
7192 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7193 FD = FD->getMostRecentDecl();
7194 // Don't declare this variable in the second operand of the for-statement;
7195 // GCC miscompiles that by ending its lifetime before evaluating the
7196 // third operand. See gcc.gnu.org/PR86769.
7198 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7199 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7200 TL = ATL.getModifiedLoc()) {
7201 // The [[lifetimebound]] attribute can be applied to the implicit object
7202 // parameter of a non-static member function (other than a ctor or dtor)
7203 // by applying it to the function type.
7204 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7205 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7206 int NoImplicitObjectError = -1;
7207 if (!MD)
7208 NoImplicitObjectError = 0;
7209 else if (MD->isStatic())
7210 NoImplicitObjectError = 1;
7211 else if (MD->isExplicitObjectMemberFunction())
7212 NoImplicitObjectError = 2;
7213 if (NoImplicitObjectError != -1) {
7214 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7215 << NoImplicitObjectError << A->getRange();
7216 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7217 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7218 << isa<CXXDestructorDecl>(MD) << A->getRange();
7219 } else if (MD->getReturnType()->isVoidType()) {
7220 S.Diag(
7221 MD->getLocation(),
7222 diag::
7223 err_lifetimebound_implicit_object_parameter_void_return_type);
7224 }
7225 }
7226 }
7227
7228 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7229 const ParmVarDecl *P = FD->getParamDecl(I);
7230
7231 // The [[lifetimebound]] attribute can be applied to a function parameter
7232 // only if the function returns a value.
7233 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7234 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7235 S.Diag(A->getLocation(),
7236 diag::err_lifetimebound_parameter_void_return_type);
7237 }
7238 }
7239 }
7240 }
7241}
7242
7244 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7245 S.Diag(ND.getLocation(), diag::err_modular_format_attribute_no_format);
7246}
7247
7249 // Ensure that an auto decl is deduced otherwise the checks below might cache
7250 // the wrong linkage.
7251 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7252
7253 checkWeakAttr(S, ND);
7254 checkWeakRefAttr(S, ND);
7255 checkAliasAttr(S, ND);
7256 checkSelectAnyAttr(S, ND);
7258 checkInheritableAttr(S, ND);
7260}
7261
7263 NamedDecl *NewDecl,
7264 bool IsSpecialization,
7265 bool IsDefinition) {
7266 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7267 return;
7268
7269 bool IsTemplate = false;
7270 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7271 OldDecl = OldTD->getTemplatedDecl();
7272 IsTemplate = true;
7273 if (!IsSpecialization)
7274 IsDefinition = false;
7275 }
7276 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7277 NewDecl = NewTD->getTemplatedDecl();
7278 IsTemplate = true;
7279 }
7280
7281 if (!OldDecl || !NewDecl)
7282 return;
7283
7284 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7285 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7286 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7287 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7288
7289 // dllimport and dllexport are inheritable attributes so we have to exclude
7290 // inherited attribute instances.
7291 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7292 (NewExportAttr && !NewExportAttr->isInherited());
7293
7294 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7295 // the only exception being explicit specializations.
7296 // Implicitly generated declarations are also excluded for now because there
7297 // is no other way to switch these to use dllimport or dllexport.
7298 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7299
7300 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7301 // Allow with a warning for free functions and global variables.
7302 bool JustWarn = false;
7303 if (!OldDecl->isCXXClassMember()) {
7304 auto *VD = dyn_cast<VarDecl>(OldDecl);
7305 if (VD && !VD->getDescribedVarTemplate())
7306 JustWarn = true;
7307 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7308 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7309 JustWarn = true;
7310 }
7311
7312 // We cannot change a declaration that's been used because IR has already
7313 // been emitted. Dllimported functions will still work though (modulo
7314 // address equality) as they can use the thunk.
7315 if (OldDecl->isUsed())
7316 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7317 JustWarn = false;
7318
7319 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7320 : diag::err_attribute_dll_redeclaration;
7321 S.Diag(NewDecl->getLocation(), DiagID)
7322 << NewDecl
7323 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7324 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7325 if (!JustWarn) {
7326 NewDecl->setInvalidDecl();
7327 return;
7328 }
7329 }
7330
7331 // A redeclaration is not allowed to drop a dllimport attribute, the only
7332 // exceptions being inline function definitions (except for function
7333 // templates), local extern declarations, qualified friend declarations or
7334 // special MSVC extension: in the last case, the declaration is treated as if
7335 // it were marked dllexport.
7336 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7337 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7338 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7339 // Ignore static data because out-of-line definitions are diagnosed
7340 // separately.
7341 IsStaticDataMember = VD->isStaticDataMember();
7342 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7344 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7345 IsInline = FD->isInlined();
7346 IsQualifiedFriend = FD->getQualifier() &&
7347 FD->getFriendObjectKind() == Decl::FOK_Declared;
7348 }
7349
7350 if (OldImportAttr && !HasNewAttr &&
7351 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7352 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7353 if (IsMicrosoftABI && IsDefinition) {
7354 if (IsSpecialization) {
7355 S.Diag(
7356 NewDecl->getLocation(),
7357 diag::err_attribute_dllimport_function_specialization_definition);
7358 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7359 NewDecl->dropAttr<DLLImportAttr>();
7360 } else {
7361 S.Diag(NewDecl->getLocation(),
7362 diag::warn_redeclaration_without_import_attribute)
7363 << NewDecl;
7364 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7365 NewDecl->dropAttr<DLLImportAttr>();
7366 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7367 S.Context, NewImportAttr->getRange()));
7368 }
7369 } else if (IsMicrosoftABI && IsSpecialization) {
7370 assert(!IsDefinition);
7371 // MSVC allows this. Keep the inherited attribute.
7372 } else {
7373 S.Diag(NewDecl->getLocation(),
7374 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7375 << NewDecl << OldImportAttr;
7376 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7377 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7378 OldDecl->dropAttr<DLLImportAttr>();
7379 NewDecl->dropAttr<DLLImportAttr>();
7380 }
7381 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7382 // In MinGW, seeing a function declared inline drops the dllimport
7383 // attribute.
7384 OldDecl->dropAttr<DLLImportAttr>();
7385 NewDecl->dropAttr<DLLImportAttr>();
7386 S.Diag(NewDecl->getLocation(),
7387 diag::warn_dllimport_dropped_from_inline_function)
7388 << NewDecl << OldImportAttr;
7389 }
7390
7391 // A specialization of a class template member function is processed here
7392 // since it's a redeclaration. If the parent class is dllexport, the
7393 // specialization inherits that attribute. This doesn't happen automatically
7394 // since the parent class isn't instantiated until later.
7395 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7396 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7397 !NewImportAttr && !NewExportAttr) {
7398 if (const DLLExportAttr *ParentExportAttr =
7399 MD->getParent()->getAttr<DLLExportAttr>()) {
7400 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7401 NewAttr->setInherited(true);
7402 NewDecl->addAttr(NewAttr);
7403 }
7404 }
7405 }
7406}
7407
7408/// Given that we are within the definition of the given function,
7409/// will that definition behave like C99's 'inline', where the
7410/// definition is discarded except for optimization purposes?
7412 // Try to avoid calling GetGVALinkageForFunction.
7413
7414 // All cases of this require the 'inline' keyword.
7415 if (!FD->isInlined()) return false;
7416
7417 // This is only possible in C++ with the gnu_inline attribute.
7418 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7419 return false;
7420
7421 // Okay, go ahead and call the relatively-more-expensive function.
7423}
7424
7425/// Determine whether a variable is extern "C" prior to attaching
7426/// an initializer. We can't just call isExternC() here, because that
7427/// will also compute and cache whether the declaration is externally
7428/// visible, which might change when we attach the initializer.
7429///
7430/// This can only be used if the declaration is known to not be a
7431/// redeclaration of an internal linkage declaration.
7432///
7433/// For instance:
7434///
7435/// auto x = []{};
7436///
7437/// Attaching the initializer here makes this declaration not externally
7438/// visible, because its type has internal linkage.
7439///
7440/// FIXME: This is a hack.
7441template<typename T>
7442static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7443 if (S.getLangOpts().CPlusPlus) {
7444 // In C++, the overloadable attribute negates the effects of extern "C".
7445 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7446 return false;
7447
7448 // So do CUDA's host/device attributes.
7449 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7450 D->template hasAttr<CUDAHostAttr>()))
7451 return false;
7452 }
7453 return D->isExternC();
7454}
7455
7456static bool shouldConsiderLinkage(const VarDecl *VD) {
7457 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7460 return VD->hasExternalStorage();
7461 if (DC->isFileContext())
7462 return true;
7463 if (DC->isRecord())
7464 return false;
7465 if (DC->getDeclKind() == Decl::HLSLBuffer)
7466 return false;
7467
7469 return false;
7470 llvm_unreachable("Unexpected context");
7471}
7472
7473static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7474 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7475 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7477 return true;
7478 if (DC->isRecord())
7479 return false;
7480 llvm_unreachable("Unexpected context");
7481}
7482
7483static bool hasParsedAttr(Scope *S, const Declarator &PD,
7484 ParsedAttr::Kind Kind) {
7485 // Check decl attributes on the DeclSpec.
7486 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7487 return true;
7488
7489 // Walk the declarator structure, checking decl attributes that were in a type
7490 // position to the decl itself.
7491 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7492 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7493 return true;
7494 }
7495
7496 // Finally, check attributes on the decl itself.
7497 return PD.getAttributes().hasAttribute(Kind) ||
7499}
7500
7502 if (!DC->isFunctionOrMethod())
7503 return false;
7504
7505 // If this is a local extern function or variable declared within a function
7506 // template, don't add it into the enclosing namespace scope until it is
7507 // instantiated; it might have a dependent type right now.
7508 if (DC->isDependentContext())
7509 return true;
7510
7511 // C++11 [basic.link]p7:
7512 // When a block scope declaration of an entity with linkage is not found to
7513 // refer to some other declaration, then that entity is a member of the
7514 // innermost enclosing namespace.
7515 //
7516 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7517 // semantically-enclosing namespace, not a lexically-enclosing one.
7518 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7519 DC = DC->getParent();
7520 return true;
7521}
7522
7523/// Returns true if given declaration has external C language linkage.
7524static bool isDeclExternC(const Decl *D) {
7525 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7526 return FD->isExternC();
7527 if (const auto *VD = dyn_cast<VarDecl>(D))
7528 return VD->isExternC();
7529
7530 llvm_unreachable("Unknown type of decl!");
7531}
7532
7533/// Returns true if there hasn't been any invalid type diagnosed.
7534static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7535 DeclContext *DC = NewVD->getDeclContext();
7536 QualType R = NewVD->getType();
7537
7538 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7539 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7540 // argument.
7541 if (R->isImageType() || R->isPipeType()) {
7542 Se.Diag(NewVD->getLocation(),
7543 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7544 << R;
7545 NewVD->setInvalidDecl();
7546 return false;
7547 }
7548
7549 // OpenCL v1.2 s6.9.r:
7550 // The event type cannot be used to declare a program scope variable.
7551 // OpenCL v2.0 s6.9.q:
7552 // The clk_event_t and reserve_id_t types cannot be declared in program
7553 // scope.
7554 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7555 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7556 Se.Diag(NewVD->getLocation(),
7557 diag::err_invalid_type_for_program_scope_var)
7558 << R;
7559 NewVD->setInvalidDecl();
7560 return false;
7561 }
7562 }
7563
7564 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7565 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7566 Se.getLangOpts())) {
7567 QualType NR = R.getCanonicalType();
7568 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7569 NR->isReferenceType()) {
7572 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7573 << NR->isReferenceType();
7574 NewVD->setInvalidDecl();
7575 return false;
7576 }
7577 NR = NR->getPointeeType();
7578 }
7579 }
7580
7581 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7582 Se.getLangOpts())) {
7583 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7584 // half array type (unless the cl_khr_fp16 extension is enabled).
7585 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7586 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7587 NewVD->setInvalidDecl();
7588 return false;
7589 }
7590 }
7591
7592 // OpenCL v1.2 s6.9.r:
7593 // The event type cannot be used with the __local, __constant and __global
7594 // address space qualifiers.
7595 if (R->isEventT()) {
7596 if (R.getAddressSpace() != LangAS::opencl_private) {
7597 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7598 NewVD->setInvalidDecl();
7599 return false;
7600 }
7601 }
7602
7603 if (R->isSamplerT()) {
7604 // OpenCL v1.2 s6.9.b p4:
7605 // The sampler type cannot be used with the __local and __global address
7606 // space qualifiers.
7607 if (R.getAddressSpace() == LangAS::opencl_local ||
7608 R.getAddressSpace() == LangAS::opencl_global) {
7609 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7610 NewVD->setInvalidDecl();
7611 }
7612
7613 // OpenCL v1.2 s6.12.14.1:
7614 // A global sampler must be declared with either the constant address
7615 // space qualifier or with the const qualifier.
7616 if (DC->isTranslationUnit() &&
7617 !(R.getAddressSpace() == LangAS::opencl_constant ||
7618 R.isConstQualified())) {
7619 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7620 NewVD->setInvalidDecl();
7621 }
7622 if (NewVD->isInvalidDecl())
7623 return false;
7624 }
7625
7626 return true;
7627}
7628
7629template <typename AttrTy>
7630static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7631 const TypedefNameDecl *TND = TT->getDecl();
7632 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7633 AttrTy *Clone = Attribute->clone(S.Context);
7634 Clone->setInherited(true);
7635 D->addAttr(Clone);
7636 }
7637}
7638
7639// This function emits warning and a corresponding note based on the
7640// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7641// declarations of an annotated type must be const qualified.
7643 QualType VarType = VD->getType().getCanonicalType();
7644
7645 // Ignore local declarations (for now) and those with const qualification.
7646 // TODO: Local variables should not be allowed if their type declaration has
7647 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7648 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7649 return;
7650
7651 if (VarType->isArrayType()) {
7652 // Retrieve element type for array declarations.
7653 VarType = S.getASTContext().getBaseElementType(VarType);
7654 }
7655
7656 const RecordDecl *RD = VarType->getAsRecordDecl();
7657
7658 // Check if the record declaration is present and if it has any attributes.
7659 if (RD == nullptr)
7660 return;
7661
7662 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7663 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7664 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7665 return;
7666 }
7667}
7668
7670 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7671 "NewD is not a function or variable");
7672
7673 if (PendingExportedNames.empty())
7674 return;
7675 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(NewD)) {
7676 if (getLangOpts().CPlusPlus && !FD->isExternC())
7677 return;
7678 }
7679 IdentifierInfo *IdentName = NewD->getIdentifier();
7680 if (IdentName == nullptr)
7681 return;
7682 auto PendingName = PendingExportedNames.find(IdentName);
7683 if (PendingName != PendingExportedNames.end()) {
7684 auto &Label = PendingName->second;
7685 if (!Label.Used) {
7686 Label.Used = true;
7687 if (NewD->hasExternalFormalLinkage())
7688 mergeVisibilityType(NewD, Label.NameLoc, VisibilityAttr::Default);
7689 else
7690 Diag(Label.NameLoc, diag::warn_pragma_not_applied) << "export" << NewD;
7691 }
7692 }
7693}
7694
7695// Checks if VD is declared at global scope or with C language linkage.
7696static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7697 return Name.getAsIdentifierInfo() &&
7698 Name.getAsIdentifierInfo()->isStr("main") &&
7699 !VD->getDescribedVarTemplate() &&
7700 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7701 VD->isExternC());
7702}
7703
7704void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7705 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7706
7707 // Quickly return if the function does not have an `asm` attribute.
7708 if (E == nullptr)
7709 return;
7710
7711 // The parser guarantees this is a string.
7712 StringLiteral *SE = cast<StringLiteral>(E);
7713 StringRef Label = SE->getString();
7714 QualType R = TInfo->getType();
7715 if (S->getFnParent() != nullptr) {
7716 switch (SC) {
7717 case SC_None:
7718 case SC_Auto:
7719 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7720 break;
7721 case SC_Register:
7722 // Local Named register
7723 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7725 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7726 break;
7727 case SC_Static:
7728 case SC_Extern:
7729 case SC_PrivateExtern:
7730 break;
7731 }
7732 } else if (SC == SC_Register) {
7733 // Global Named register
7734 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7735 const auto &TI = Context.getTargetInfo();
7736 bool HasSizeMismatch;
7737
7738 if (!TI.isValidGCCRegisterName(Label))
7739 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7740 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),
7741 HasSizeMismatch))
7742 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7743 else if (HasSizeMismatch)
7744 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7745 }
7746
7747 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7748 Diag(TInfo->getTypeLoc().getBeginLoc(),
7749 diag::err_asm_unsupported_register_type)
7750 << TInfo->getTypeLoc().getSourceRange();
7751 NewVD->setInvalidDecl(true);
7752 }
7753 }
7754}
7755
7757 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7758 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7759 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7760 QualType R = TInfo->getType();
7762
7764 bool IsPlaceholderVariable = false;
7765
7766 if (D.isDecompositionDeclarator()) {
7767 // Take the name of the first declarator as our name for diagnostic
7768 // purposes.
7769 auto &Decomp = D.getDecompositionDeclarator();
7770 if (!Decomp.bindings().empty()) {
7771 II = Decomp.bindings()[0].Name;
7772 Name = II;
7773 }
7774 } else if (!II) {
7775 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7776 return nullptr;
7777 }
7778
7779
7782 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7783 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7784
7785 IsPlaceholderVariable = true;
7786
7787 if (!Previous.empty()) {
7788 NamedDecl *PrevDecl = *Previous.begin();
7789 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7790 DC->getRedeclContext());
7791 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7792 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7793 if (IsPlaceholderVariable)
7795 }
7796 }
7797 }
7798
7799 // dllimport globals without explicit storage class are treated as extern. We
7800 // have to change the storage class this early to get the right DeclContext.
7801 if (SC == SC_None && !DC->isRecord() &&
7802 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7803 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7804 SC = SC_Extern;
7805
7806 DeclContext *OriginalDC = DC;
7807 bool IsLocalExternDecl = SC == SC_Extern &&
7809
7810 if (SCSpec == DeclSpec::SCS_mutable) {
7811 // mutable can only appear on non-static class members, so it's always
7812 // an error here
7813 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7814 D.setInvalidType();
7815 SC = SC_None;
7816 }
7817
7818 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7819 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7821 // In C++11, the 'register' storage class specifier is deprecated.
7822 // Suppress the warning in system macros, it's used in macros in some
7823 // popular C system headers, such as in glibc's htonl() macro.
7825 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7826 : diag::warn_deprecated_register)
7828 }
7829
7831
7832 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7833 // C99 6.9p2: The storage-class specifiers auto and register shall not
7834 // appear in the declaration specifiers in an external declaration.
7835 // Global Register+Asm is a GNU extension we support.
7836 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7837 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7838 D.setInvalidType();
7839 }
7840 }
7841
7842 // If this variable has a VLA type and an initializer, try to
7843 // fold to a constant-sized type. This is otherwise invalid.
7844 if (D.hasInitializer() && R->isVariableArrayType())
7846 /*DiagID=*/0);
7847
7848 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7849 const AutoType *AT = TL.getTypePtr();
7850 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7851 }
7852
7853 bool IsMemberSpecialization = false;
7854 bool IsVariableTemplateSpecialization = false;
7855 bool IsPartialSpecialization = false;
7856 bool IsVariableTemplate = false;
7857 VarDecl *NewVD = nullptr;
7858 VarTemplateDecl *NewTemplate = nullptr;
7859 TemplateParameterList *TemplateParams = nullptr;
7860 if (!getLangOpts().CPlusPlus) {
7862 II, R, TInfo, SC);
7863
7864 if (R->getContainedDeducedType())
7865 ParsingInitForAutoVars.insert(NewVD);
7866
7867 if (D.isInvalidType())
7868 NewVD->setInvalidDecl();
7869
7871 NewVD->hasLocalStorage())
7872 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7874 } else {
7875 bool Invalid = false;
7876 // Match up the template parameter lists with the scope specifier, then
7877 // determine whether we have a template or a template specialization.
7880 D.getCXXScopeSpec(),
7882 ? D.getName().TemplateId
7883 : nullptr,
7884 TemplateParamLists,
7885 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7886
7887 if (TemplateParams) {
7888 if (DC->isDependentContext()) {
7889 ContextRAII SavedContext(*this, DC);
7891 Invalid = true;
7892 }
7893
7894 if (!TemplateParams->size() &&
7896 // There is an extraneous 'template<>' for this variable. Complain
7897 // about it, but allow the declaration of the variable.
7898 Diag(TemplateParams->getTemplateLoc(),
7899 diag::err_template_variable_noparams)
7900 << II
7901 << SourceRange(TemplateParams->getTemplateLoc(),
7902 TemplateParams->getRAngleLoc());
7903 TemplateParams = nullptr;
7904 } else {
7905 // Check that we can declare a template here.
7906 if (CheckTemplateDeclScope(S, TemplateParams))
7907 return nullptr;
7908
7910 // This is an explicit specialization or a partial specialization.
7911 IsVariableTemplateSpecialization = true;
7912 IsPartialSpecialization = TemplateParams->size() > 0;
7913 } else { // if (TemplateParams->size() > 0)
7914 // This is a template declaration.
7915 IsVariableTemplate = true;
7916
7917 // Only C++1y supports variable templates (N3651).
7918 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7919 }
7920 }
7921 } else {
7922 // Check that we can declare a member specialization here.
7923 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7924 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7925 return nullptr;
7926 assert((Invalid ||
7928 "should have a 'template<>' for this decl");
7929 }
7930
7931 bool IsExplicitSpecialization =
7932 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7933
7934 // C++ [temp.expl.spec]p2:
7935 // The declaration in an explicit-specialization shall not be an
7936 // export-declaration. An explicit specialization shall not use a
7937 // storage-class-specifier other than thread_local.
7938 //
7939 // We use the storage-class-specifier from DeclSpec because we may have
7940 // added implicit 'extern' for declarations with __declspec(dllimport)!
7941 if (SCSpec != DeclSpec::SCS_unspecified &&
7942 (IsExplicitSpecialization || IsMemberSpecialization)) {
7944 diag::ext_explicit_specialization_storage_class)
7946 }
7947
7948 if (CurContext->isRecord()) {
7949 if (SC == SC_Static) {
7950 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7951 // Walk up the enclosing DeclContexts to check for any that are
7952 // incompatible with static data members.
7953 const DeclContext *FunctionOrMethod = nullptr;
7954 const CXXRecordDecl *AnonStruct = nullptr;
7955 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7956 if (Ctxt->isFunctionOrMethod()) {
7957 FunctionOrMethod = Ctxt;
7958 break;
7959 }
7960 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7961 if (ParentDecl && !ParentDecl->getDeclName()) {
7962 AnonStruct = ParentDecl;
7963 break;
7964 }
7965 }
7966 if (FunctionOrMethod) {
7967 // C++ [class.static.data]p5: A local class shall not have static
7968 // data members.
7970 diag::err_static_data_member_not_allowed_in_local_class)
7971 << Name << RD->getDeclName() << RD->getTagKind();
7972 Invalid = true;
7973 } else if (AnonStruct) {
7974 // C++ [class.static.data]p4: Unnamed classes and classes contained
7975 // directly or indirectly within unnamed classes shall not contain
7976 // static data members.
7978 diag::err_static_data_member_not_allowed_in_anon_struct)
7979 << Name << AnonStruct->getTagKind();
7980 Invalid = true;
7981 } else if (RD->isUnion()) {
7982 // C++98 [class.union]p1: If a union contains a static data member,
7983 // the program is ill-formed. C++11 drops this restriction.
7985 diag_compat::static_data_member_in_union)
7986 << Name;
7987 }
7988 }
7989 } else if (IsVariableTemplate || IsPartialSpecialization) {
7990 // There is no such thing as a member field template.
7991 Diag(D.getIdentifierLoc(), diag::err_template_member)
7992 << II << TemplateParams->getSourceRange();
7993 // Recover by pretending this is a static data member template.
7994 SC = SC_Static;
7995 }
7996 } else if (DC->isRecord()) {
7997 // This is an out-of-line definition of a static data member.
7998 switch (SC) {
7999 case SC_None:
8000 break;
8001 case SC_Static:
8003 diag::err_static_out_of_line)
8006 break;
8007 case SC_Auto:
8008 case SC_Register:
8009 case SC_Extern:
8010 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8011 // to names of variables declared in a block or to function parameters.
8012 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8013 // of class members
8014
8016 diag::err_storage_class_for_static_member)
8019 break;
8020 case SC_PrivateExtern:
8021 llvm_unreachable("C storage class in c++!");
8022 }
8023 }
8024
8025 if (IsVariableTemplateSpecialization) {
8026 SourceLocation TemplateKWLoc =
8027 TemplateParamLists.size() > 0
8028 ? TemplateParamLists[0]->getTemplateLoc()
8029 : SourceLocation();
8031 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8033 if (Res.isInvalid())
8034 return nullptr;
8035 NewVD = cast<VarDecl>(Res.get());
8036 AddToScope = false;
8037 } else if (D.isDecompositionDeclarator()) {
8039 D.getIdentifierLoc(), R, TInfo, SC,
8040 Bindings);
8041 } else
8042 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
8043 D.getIdentifierLoc(), II, R, TInfo, SC);
8044
8045 // If this is supposed to be a variable template, create it as such.
8046 if (IsVariableTemplate) {
8047 NewTemplate =
8049 TemplateParams, NewVD);
8050 NewVD->setDescribedVarTemplate(NewTemplate);
8051 }
8052
8053 // If this decl has an auto type in need of deduction, make a note of the
8054 // Decl so we can diagnose uses of it in its own initializer.
8055 if (R->getContainedDeducedType())
8056 ParsingInitForAutoVars.insert(NewVD);
8057
8058 if (D.isInvalidType() || Invalid) {
8059 NewVD->setInvalidDecl();
8060 if (NewTemplate)
8061 NewTemplate->setInvalidDecl();
8062 }
8063
8064 SetNestedNameSpecifier(*this, NewVD, D);
8065
8066 // If we have any template parameter lists that don't directly belong to
8067 // the variable (matching the scope specifier), store them.
8068 // An explicit variable template specialization does not own any template
8069 // parameter lists.
8070 unsigned VDTemplateParamLists =
8071 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8072 if (TemplateParamLists.size() > VDTemplateParamLists)
8074 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
8075 }
8076
8077 if (D.getDeclSpec().isInlineSpecified()) {
8078 if (!getLangOpts().CPlusPlus) {
8079 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
8080 << 0;
8081 } else if (CurContext->isFunctionOrMethod()) {
8082 // 'inline' is not allowed on block scope variable declaration.
8084 diag::err_inline_declaration_block_scope) << Name
8086 } else {
8088 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8089 : diag::compat_pre_cxx17_inline_variable);
8090 NewVD->setInlineSpecified();
8091 }
8092 }
8093
8094 // Set the lexical context. If the declarator has a C++ scope specifier, the
8095 // lexical context will be different from the semantic context.
8097 if (NewTemplate)
8098 NewTemplate->setLexicalDeclContext(CurContext);
8099
8100 if (IsLocalExternDecl) {
8102 for (auto *B : Bindings)
8103 B->setLocalExternDecl();
8104 else
8105 NewVD->setLocalExternDecl();
8106 }
8107
8108 bool EmitTLSUnsupportedError = false;
8110 // C++11 [dcl.stc]p4:
8111 // When thread_local is applied to a variable of block scope the
8112 // storage-class-specifier static is implied if it does not appear
8113 // explicitly.
8114 // Core issue: 'static' is not implied if the variable is declared
8115 // 'extern'.
8116 if (NewVD->hasLocalStorage() &&
8117 (SCSpec != DeclSpec::SCS_unspecified ||
8119 !DC->isFunctionOrMethod()))
8121 diag::err_thread_non_global)
8123 else if (!Context.getTargetInfo().isTLSSupported()) {
8124 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8125 // Postpone error emission until we've collected attributes required to
8126 // figure out whether it's a host or device variable and whether the
8127 // error should be ignored.
8128 EmitTLSUnsupportedError = true;
8129 // We still need to mark the variable as TLS so it shows up in AST with
8130 // proper storage class for other tools to use even if we're not going
8131 // to emit any code for it.
8132 NewVD->setTSCSpec(TSCS);
8133 } else
8135 diag::err_thread_unsupported);
8136 } else
8137 NewVD->setTSCSpec(TSCS);
8138 }
8139
8140 switch (D.getDeclSpec().getConstexprSpecifier()) {
8142 break;
8143
8146 diag::err_constexpr_wrong_decl_kind)
8147 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8148 [[fallthrough]];
8149
8151 NewVD->setConstexpr(true);
8152 // C++1z [dcl.spec.constexpr]p1:
8153 // A static data member declared with the constexpr specifier is
8154 // implicitly an inline variable.
8155 if (NewVD->isStaticDataMember() &&
8157 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8158 NewVD->setImplicitlyInline();
8159 break;
8160
8162 if (!NewVD->hasGlobalStorage())
8164 diag::err_constinit_local_variable);
8165 else
8166 NewVD->addAttr(
8167 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8168 ConstInitAttr::Keyword_constinit));
8169 break;
8170 }
8171
8172 // C99 6.7.4p3
8173 // An inline definition of a function with external linkage shall
8174 // not contain a definition of a modifiable object with static or
8175 // thread storage duration...
8176 // We only apply this when the function is required to be defined
8177 // elsewhere, i.e. when the function is not 'extern inline'. Note
8178 // that a local variable with thread storage duration still has to
8179 // be marked 'static'. Also note that it's possible to get these
8180 // semantics in C++ using __attribute__((gnu_inline)).
8181 if (SC == SC_Static && S->getFnParent() != nullptr &&
8182 !NewVD->getType().isConstQualified()) {
8184 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8186 diag::warn_static_local_in_extern_inline);
8188 }
8189 }
8190
8192 if (IsVariableTemplateSpecialization)
8193 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8194 << (IsPartialSpecialization ? 1 : 0)
8197 else if (IsMemberSpecialization)
8198 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8199 << 2
8201 else if (NewVD->hasLocalStorage())
8202 Diag(NewVD->getLocation(), diag::err_module_private_local)
8203 << 0 << NewVD
8207 else {
8208 NewVD->setModulePrivate();
8209 if (NewTemplate)
8210 NewTemplate->setModulePrivate();
8211 for (auto *B : Bindings)
8212 B->setModulePrivate();
8213 }
8214 }
8215
8216 if (getLangOpts().OpenCL) {
8218
8220 if (TSC != TSCS_unspecified) {
8222 diag::err_opencl_unknown_type_specifier)
8224 << DeclSpec::getSpecifierName(TSC) << 1;
8225 NewVD->setInvalidDecl();
8226 }
8227 }
8228
8229 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8230 // address space if the table has local storage (semantic checks elsewhere
8231 // will produce an error anyway).
8232 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8233 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8234 !NewVD->hasLocalStorage()) {
8235 QualType Type = Context.getAddrSpaceQualType(
8236 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8237 NewVD->setType(Type);
8238 }
8239 }
8240
8242
8243 if (Expr *E = D.getAsmLabel()) {
8244 // The parser guarantees this is a string.
8246 StringRef Label = SE->getString();
8247
8248 // Insert the asm attribute.
8249 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8250 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8251 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8253 if (I != ExtnameUndeclaredIdentifiers.end()) {
8254 if (isDeclExternC(NewVD)) {
8255 NewVD->addAttr(I->second);
8257 } else if (NewVD->getDeclContext()
8260 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8261 << /*Variable*/ 1 << NewVD;
8262 }
8263 }
8264
8265 // Handle attributes prior to checking for duplicates in MergeVarDecl
8266 ProcessDeclAttributes(S, NewVD, D);
8267
8268 if (getLangOpts().HLSL)
8270
8271 if (getLangOpts().OpenACC)
8273
8274 // FIXME: This is probably the wrong location to be doing this and we should
8275 // probably be doing this for more attributes (especially for function
8276 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8277 // the code to copy attributes would be generated by TableGen.
8278 if (R->isFunctionPointerType())
8279 if (const auto *TT = R->getAs<TypedefType>())
8281
8282 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8283 if (EmitTLSUnsupportedError &&
8285 (getLangOpts().OpenMPIsTargetDevice &&
8286 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8288 diag::err_thread_unsupported);
8289
8290 if (EmitTLSUnsupportedError &&
8291 (LangOpts.SYCLIsDevice ||
8292 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8293 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8294 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8295 // storage [duration]."
8296 if (SC == SC_None && S->getFnParent() != nullptr &&
8297 (NewVD->hasAttr<CUDASharedAttr>() ||
8298 NewVD->hasAttr<CUDAConstantAttr>())) {
8299 NewVD->setStorageClass(SC_Static);
8300 }
8301 }
8302
8303 // Ensure that dllimport globals without explicit storage class are treated as
8304 // extern. The storage class is set above using parsed attributes. Now we can
8305 // check the VarDecl itself.
8306 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8307 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8308 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8309
8310 // In auto-retain/release, infer strong retension for variables of
8311 // retainable type.
8312 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8313 NewVD->setInvalidDecl();
8314
8315 // Check the ASM label here, as we need to know all other attributes of the
8316 // Decl first. Otherwise, we can't know if the asm label refers to the
8317 // host or device in a CUDA context. The device has other registers than
8318 // host and we must know where the function will be placed.
8319 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);
8320
8321 // Find the shadowed declaration before filtering for scope.
8322 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8324 : nullptr;
8325
8326 // Don't consider existing declarations that are in a different
8327 // scope and are out-of-semantic-context declarations (if the new
8328 // declaration has linkage).
8331 IsMemberSpecialization ||
8332 IsVariableTemplateSpecialization);
8333
8334 // Check whether the previous declaration is in the same block scope. This
8335 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8336 if (getLangOpts().CPlusPlus &&
8337 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8339 Previous.isSingleResult() && !Previous.isShadowed() &&
8340 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8341
8342 if (!getLangOpts().CPlusPlus) {
8344 } else {
8345 // If this is an explicit specialization of a static data member, check it.
8346 if (IsMemberSpecialization && !IsVariableTemplate &&
8347 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8349 NewVD->setInvalidDecl();
8350
8351 // Merge the decl with the existing one if appropriate.
8352 if (!Previous.empty()) {
8353 if (Previous.isSingleResult() &&
8354 isa<FieldDecl>(Previous.getFoundDecl()) &&
8355 D.getCXXScopeSpec().isSet()) {
8356 // The user tried to define a non-static data member
8357 // out-of-line (C++ [dcl.meaning]p1).
8358 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8359 << D.getCXXScopeSpec().getRange();
8360 Previous.clear();
8361 NewVD->setInvalidDecl();
8362 }
8363 } else if (D.getCXXScopeSpec().isSet() &&
8364 !IsVariableTemplateSpecialization) {
8365 // No previous declaration in the qualifying scope.
8366 Diag(D.getIdentifierLoc(), diag::err_no_member)
8367 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8368 << D.getCXXScopeSpec().getRange();
8369 NewVD->setInvalidDecl();
8370 }
8371
8372 if (!IsPlaceholderVariable)
8374
8375 // CheckVariableDeclaration will set NewVD as invalid if something is in
8376 // error like WebAssembly tables being declared as arrays with a non-zero
8377 // size, but then parsing continues and emits further errors on that line.
8378 // To avoid that we check here if it happened and return nullptr.
8379 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8380 return nullptr;
8381
8382 if (NewTemplate) {
8383 VarTemplateDecl *PrevVarTemplate =
8384 NewVD->getPreviousDecl()
8386 : nullptr;
8387
8388 // Check the template parameter list of this declaration, possibly
8389 // merging in the template parameter list from the previous variable
8390 // template declaration.
8392 TemplateParams,
8393 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8394 : nullptr,
8395 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8396 DC->isDependentContext())
8398 : TPC_Other))
8399 NewVD->setInvalidDecl();
8400 }
8401 }
8402
8403 if (IsMemberSpecialization) {
8404 if (NewTemplate && NewVD->getPreviousDecl()) {
8405 NewTemplate->setMemberSpecialization();
8406 } else if (IsPartialSpecialization) {
8408 ->setMemberSpecialization();
8409 }
8410 }
8411
8412 // Diagnose shadowed variables iff this isn't a redeclaration.
8413 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8414 CheckShadow(NewVD, ShadowedDecl, Previous);
8415
8416 ProcessPragmaWeak(S, NewVD);
8417 ProcessPragmaExport(NewVD);
8418
8419 // If this is the first declaration of an extern C variable, update
8420 // the map of such variables.
8421 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8422 isIncompleteDeclExternC(*this, NewVD))
8424
8425 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8427 Decl *ManglingContextDecl;
8428 std::tie(MCtx, ManglingContextDecl) =
8430 if (MCtx) {
8431 Context.setManglingNumber(
8432 NewVD, MCtx->getManglingNumber(
8433 NewVD, getMSManglingNumber(getLangOpts(), S)));
8434 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8435 }
8436 }
8437
8438 // Special handling of variable named 'main'.
8439 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8440 // C++ [basic.start.main]p3:
8441 // A program that declares
8442 // - a variable main at global scope, or
8443 // - an entity named main with C language linkage (in any namespace)
8444 // is ill-formed
8445 if (getLangOpts().CPlusPlus)
8446 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8447 << NewVD->isExternC();
8448
8449 // In C, and external-linkage variable named main results in undefined
8450 // behavior.
8451 else if (NewVD->hasExternalFormalLinkage())
8452 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8453 }
8454
8455 if (D.isRedeclaration() && !Previous.empty()) {
8456 NamedDecl *Prev = Previous.getRepresentativeDecl();
8457 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8459 }
8460
8461 if (NewTemplate) {
8462 if (NewVD->isInvalidDecl())
8463 NewTemplate->setInvalidDecl();
8464 ActOnDocumentableDecl(NewTemplate);
8465 return NewTemplate;
8466 }
8467
8468 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8470
8472
8473 return NewVD;
8474}
8475
8476/// Enum describing the %select options in diag::warn_decl_shadow.
8486
8487/// Determine what kind of declaration we're shadowing.
8489 const DeclContext *OldDC) {
8490 if (isa<TypeAliasDecl>(ShadowedDecl))
8491 return SDK_Using;
8492 else if (isa<TypedefDecl>(ShadowedDecl))
8493 return SDK_Typedef;
8494 else if (isa<BindingDecl>(ShadowedDecl))
8495 return SDK_StructuredBinding;
8496 else if (isa<RecordDecl>(OldDC))
8497 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8498
8499 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8500}
8501
8502/// Return the location of the capture if the given lambda captures the given
8503/// variable \p VD, or an invalid source location otherwise.
8505 const ValueDecl *VD) {
8506 for (const Capture &Capture : LSI->Captures) {
8508 return Capture.getLocation();
8509 }
8510 return SourceLocation();
8511}
8512
8514 const LookupResult &R) {
8515 // Only diagnose if we're shadowing an unambiguous field or variable.
8516 if (R.getResultKind() != LookupResultKind::Found)
8517 return false;
8518
8519 // Return false if warning is ignored.
8520 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8521}
8522
8524 const LookupResult &R) {
8526 return nullptr;
8527
8528 // Don't diagnose declarations at file scope.
8529 if (D->hasGlobalStorage() && !D->isStaticLocal())
8530 return nullptr;
8531
8532 NamedDecl *ShadowedDecl = R.getFoundDecl();
8533 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8534 : nullptr;
8535}
8536
8538 const LookupResult &R) {
8539 // Don't warn if typedef declaration is part of a class
8540 if (D->getDeclContext()->isRecord())
8541 return nullptr;
8542
8544 return nullptr;
8545
8546 NamedDecl *ShadowedDecl = R.getFoundDecl();
8547 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8548}
8549
8551 const LookupResult &R) {
8553 return nullptr;
8554
8555 NamedDecl *ShadowedDecl = R.getFoundDecl();
8556 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8557 : nullptr;
8558}
8559
8561 const LookupResult &R) {
8562 DeclContext *NewDC = D->getDeclContext();
8563
8564 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8565 if (const auto *MD =
8566 dyn_cast<CXXMethodDecl>(getFunctionLevelDeclContext())) {
8567 // Fields aren't shadowed in C++ static members or in member functions
8568 // with an explicit object parameter.
8569 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8570 return;
8571 }
8572 // Fields shadowed by constructor parameters are a special case. Usually
8573 // the constructor initializes the field with the parameter.
8574 if (isa<CXXConstructorDecl>(NewDC))
8575 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8576 // Remember that this was shadowed so we can either warn about its
8577 // modification or its existence depending on warning settings.
8578 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8579 return;
8580 }
8581 }
8582
8583 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8584 if (shadowedVar->isExternC()) {
8585 // For shadowing external vars, make sure that we point to the global
8586 // declaration, not a locally scoped extern declaration.
8587 for (auto *I : shadowedVar->redecls())
8588 if (I->isFileVarDecl()) {
8589 ShadowedDecl = I;
8590 break;
8591 }
8592 }
8593
8594 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8595
8596 unsigned WarningDiag = diag::warn_decl_shadow;
8597 SourceLocation CaptureLoc;
8598 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8599 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8600 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8601 // Handle both VarDecl and BindingDecl in lambda contexts
8602 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8603 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8604 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8605 if (RD->getLambdaCaptureDefault() == LCD_None) {
8606 // Try to avoid warnings for lambdas with an explicit capture
8607 // list. Warn only when the lambda captures the shadowed decl
8608 // explicitly.
8609 CaptureLoc = getCaptureLocation(LSI, VD);
8610 if (CaptureLoc.isInvalid())
8611 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8612 } else {
8613 // Remember that this was shadowed so we can avoid the warning if
8614 // the shadowed decl isn't captured and the warning settings allow
8615 // it.
8617 ->ShadowingDecls.push_back({D, VD});
8618 return;
8619 }
8620 }
8621 if (isa<FieldDecl>(ShadowedDecl)) {
8622 // If lambda can capture this, then emit default shadowing warning,
8623 // Otherwise it is not really a shadowing case since field is not
8624 // available in lambda's body.
8625 // At this point we don't know that lambda can capture this, so
8626 // remember that this was shadowed and delay until we know.
8628 ->ShadowingDecls.push_back({D, ShadowedDecl});
8629 return;
8630 }
8631 }
8632 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8633 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8634 bool HasLocalStorage = false;
8635 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8636 HasLocalStorage = VD->hasLocalStorage();
8637 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8638 HasLocalStorage =
8639 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8640
8641 if (HasLocalStorage) {
8642 // A variable can't shadow a local variable or binding in an enclosing
8643 // scope, if they are separated by a non-capturing declaration
8644 // context.
8645 for (DeclContext *ParentDC = NewDC;
8646 ParentDC && !ParentDC->Equals(OldDC);
8647 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8648 // Only block literals, captured statements, and lambda expressions
8649 // can capture; other scopes don't.
8650 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8651 !isLambdaCallOperator(ParentDC))
8652 return;
8653 }
8654 }
8655 }
8656 }
8657 }
8658
8659 // Never warn about shadowing a placeholder variable.
8660 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8661 return;
8662
8663 // Only warn about certain kinds of shadowing for class members.
8664 if (NewDC) {
8665 // In particular, don't warn about shadowing non-class members.
8666 if (NewDC->isRecord() && !OldDC->isRecord())
8667 return;
8668
8669 // Skip shadowing check if we're in a class scope, dealing with an enum
8670 // constant in a different context.
8671 DeclContext *ReDC = NewDC->getRedeclContext();
8672 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8673 return;
8674
8675 // TODO: should we warn about static data members shadowing
8676 // static data members from base classes?
8677
8678 // TODO: don't diagnose for inaccessible shadowed members.
8679 // This is hard to do perfectly because we might friend the
8680 // shadowing context, but that's just a false negative.
8681 }
8682
8683 DeclarationName Name = R.getLookupName();
8684
8685 // Emit warning and note.
8686 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8687 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8688 if (!CaptureLoc.isInvalid())
8689 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8690 << Name << /*explicitly*/ 1;
8691 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8692}
8693
8695 for (const auto &Shadow : LSI->ShadowingDecls) {
8696 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8697 // Try to avoid the warning when the shadowed decl isn't captured.
8698 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8699 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8700 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8701 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8702 Diag(Shadow.VD->getLocation(),
8703 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8704 : diag::warn_decl_shadow)
8705 << Shadow.VD->getDeclName()
8706 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8707 if (CaptureLoc.isValid())
8708 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8709 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8710 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8711 } else if (isa<FieldDecl>(ShadowedDecl)) {
8712 Diag(Shadow.VD->getLocation(),
8713 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8714 : diag::warn_decl_shadow_uncaptured_local)
8715 << Shadow.VD->getDeclName()
8716 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8717 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8718 }
8719 }
8720}
8721
8723 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8724 return;
8725
8726 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8729 LookupName(R, S);
8730 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8731 CheckShadow(D, ShadowedDecl, R);
8732}
8733
8734/// Check if 'E', which is an expression that is about to be modified, refers
8735/// to a constructor parameter that shadows a field.
8737 // Quickly ignore expressions that can't be shadowing ctor parameters.
8738 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8739 return;
8740 E = E->IgnoreParenImpCasts();
8741 auto *DRE = dyn_cast<DeclRefExpr>(E);
8742 if (!DRE)
8743 return;
8744 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8745 auto I = ShadowingDecls.find(D);
8746 if (I == ShadowingDecls.end())
8747 return;
8748 const NamedDecl *ShadowedDecl = I->second;
8749 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8750 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8751 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8752 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8753
8754 // Avoid issuing multiple warnings about the same decl.
8755 ShadowingDecls.erase(I);
8756}
8757
8758/// Check for conflict between this global or extern "C" declaration and
8759/// previous global or extern "C" declarations. This is only used in C++.
8760template<typename T>
8762 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8763 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8764 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8765
8766 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8767 // The common case: this global doesn't conflict with any extern "C"
8768 // declaration.
8769 return false;
8770 }
8771
8772 if (Prev) {
8773 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8774 // Both the old and new declarations have C language linkage. This is a
8775 // redeclaration.
8776 Previous.clear();
8777 Previous.addDecl(Prev);
8778 return true;
8779 }
8780
8781 // This is a global, non-extern "C" declaration, and there is a previous
8782 // non-global extern "C" declaration. Diagnose if this is a variable
8783 // declaration.
8784 if (!isa<VarDecl>(ND))
8785 return false;
8786 } else {
8787 // The declaration is extern "C". Check for any declaration in the
8788 // translation unit which might conflict.
8789 if (IsGlobal) {
8790 // We have already performed the lookup into the translation unit.
8791 IsGlobal = false;
8792 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8793 I != E; ++I) {
8794 if (isa<VarDecl>(*I)) {
8795 Prev = *I;
8796 break;
8797 }
8798 }
8799 } else {
8801 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8802 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8803 I != E; ++I) {
8804 if (isa<VarDecl>(*I)) {
8805 Prev = *I;
8806 break;
8807 }
8808 // FIXME: If we have any other entity with this name in global scope,
8809 // the declaration is ill-formed, but that is a defect: it breaks the
8810 // 'stat' hack, for instance. Only variables can have mangled name
8811 // clashes with extern "C" declarations, so only they deserve a
8812 // diagnostic.
8813 }
8814 }
8815
8816 if (!Prev)
8817 return false;
8818 }
8819
8820 // Use the first declaration's location to ensure we point at something which
8821 // is lexically inside an extern "C" linkage-spec.
8822 assert(Prev && "should have found a previous declaration to diagnose");
8823 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8824 Prev = FD->getFirstDecl();
8825 else
8826 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8827
8828 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8829 << IsGlobal << ND;
8830 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8831 << IsGlobal;
8832 return false;
8833}
8834
8835/// Apply special rules for handling extern "C" declarations. Returns \c true
8836/// if we have found that this is a redeclaration of some prior entity.
8837///
8838/// Per C++ [dcl.link]p6:
8839/// Two declarations [for a function or variable] with C language linkage
8840/// with the same name that appear in different scopes refer to the same
8841/// [entity]. An entity with C language linkage shall not be declared with
8842/// the same name as an entity in global scope.
8843template<typename T>
8846 if (!S.getLangOpts().CPlusPlus) {
8847 // In C, when declaring a global variable, look for a corresponding 'extern'
8848 // variable declared in function scope. We don't need this in C++, because
8849 // we find local extern decls in the surrounding file-scope DeclContext.
8850 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8851 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8852 Previous.clear();
8853 Previous.addDecl(Prev);
8854 return true;
8855 }
8856 }
8857 return false;
8858 }
8859
8860 // A declaration in the translation unit can conflict with an extern "C"
8861 // declaration.
8862 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8863 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8864
8865 // An extern "C" declaration can conflict with a declaration in the
8866 // translation unit or can be a redeclaration of an extern "C" declaration
8867 // in another scope.
8868 if (isIncompleteDeclExternC(S,ND))
8869 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8870
8871 // Neither global nor extern "C": nothing to do.
8872 return false;
8873}
8874
8875static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8876 QualType T) {
8877 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8878 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8879 // any of its members, even recursively, shall not have an atomic type, or a
8880 // variably modified type, or a type that is volatile or restrict qualified.
8881 if (CanonT->isVariablyModifiedType()) {
8882 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8883 return true;
8884 }
8885
8886 // Arrays are qualified by their element type, so get the base type (this
8887 // works on non-arrays as well).
8888 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8889
8890 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8891 CanonT.isRestrictQualified()) {
8892 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8893 return true;
8894 }
8895
8896 if (CanonT->isRecordType()) {
8897 const RecordDecl *RD = CanonT->getAsRecordDecl();
8898 if (!RD->isInvalidDecl() &&
8899 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8900 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8901 }))
8902 return true;
8903 }
8904
8905 return false;
8906}
8907
8909 // If the decl is already known invalid, don't check it.
8910 if (NewVD->isInvalidDecl())
8911 return;
8912
8913 QualType T = NewVD->getType();
8914
8915 // Defer checking an 'auto' type until its initializer is attached.
8916 if (T->isUndeducedType())
8917 return;
8918
8919 if (NewVD->hasAttrs())
8921
8922 if (T->isObjCObjectType()) {
8923 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8924 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8925 T = Context.getObjCObjectPointerType(T);
8926 NewVD->setType(T);
8927 }
8928
8929 // Emit an error if an address space was applied to decl with local storage.
8930 // This includes arrays of objects with address space qualifiers, but not
8931 // automatic variables that point to other address spaces.
8932 // ISO/IEC TR 18037 S5.1.2
8933 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8934 T.getAddressSpace() != LangAS::Default) {
8935 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8936 NewVD->setInvalidDecl();
8937 return;
8938 }
8939
8940 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8941 // scope.
8942 if (getLangOpts().OpenCLVersion == 120 &&
8943 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8944 getLangOpts()) &&
8945 NewVD->isStaticLocal()) {
8946 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8947 NewVD->setInvalidDecl();
8948 return;
8949 }
8950
8951 if (getLangOpts().OpenCL) {
8952 if (!diagnoseOpenCLTypes(*this, NewVD))
8953 return;
8954
8955 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8956 if (NewVD->hasAttr<BlocksAttr>()) {
8957 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8958 return;
8959 }
8960
8961 if (T->isBlockPointerType()) {
8962 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8963 // can't use 'extern' storage class.
8964 if (!T.isConstQualified()) {
8965 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8966 << 0 /*const*/;
8967 NewVD->setInvalidDecl();
8968 return;
8969 }
8970 if (NewVD->hasExternalStorage()) {
8971 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8972 NewVD->setInvalidDecl();
8973 return;
8974 }
8975 }
8976
8977 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8978 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8979 NewVD->hasExternalStorage()) {
8980 if (!T->isSamplerT() && !T->isDependentType() &&
8981 !(T.getAddressSpace() == LangAS::opencl_constant ||
8982 (T.getAddressSpace() == LangAS::opencl_global &&
8983 getOpenCLOptions().areProgramScopeVariablesSupported(
8984 getLangOpts())))) {
8985 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8986 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8987 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8988 << Scope << "global or constant";
8989 else
8990 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8991 << Scope << "constant";
8992 NewVD->setInvalidDecl();
8993 return;
8994 }
8995 } else {
8996 if (T.getAddressSpace() == LangAS::opencl_global) {
8997 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8998 << 1 /*is any function*/ << "global";
8999 NewVD->setInvalidDecl();
9000 return;
9001 }
9002 // When this extension is enabled, 'local' variables are permitted in
9003 // non-kernel functions and within nested scopes of kernel functions,
9004 // bypassing standard OpenCL address space restrictions.
9005 bool AllowFunctionScopeLocalVariables =
9006 T.getAddressSpace() == LangAS::opencl_local &&
9008 "__cl_clang_function_scope_local_variables", getLangOpts());
9009 if (AllowFunctionScopeLocalVariables) {
9010 // Direct pass: No further diagnostics needed for this specific case.
9011 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9012 T.getAddressSpace() == LangAS::opencl_local) {
9014 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9015 // in functions.
9016 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9017 if (T.getAddressSpace() == LangAS::opencl_constant)
9018 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9019 << 0 /*non-kernel only*/ << "constant";
9020 else
9021 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9022 << 0 /*non-kernel only*/ << "local";
9023 NewVD->setInvalidDecl();
9024 return;
9025 }
9026 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9027 // in the outermost scope of a kernel function.
9028 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9029 if (!getCurScope()->isFunctionScope()) {
9030 if (T.getAddressSpace() == LangAS::opencl_constant)
9031 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9032 << "constant";
9033 else
9034 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9035 << "local";
9036 NewVD->setInvalidDecl();
9037 return;
9038 }
9039 }
9040 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9041 // If we are parsing a template we didn't deduce an addr
9042 // space yet.
9043 T.getAddressSpace() != LangAS::Default) {
9044 // Do not allow other address spaces on automatic variable.
9045 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
9046 NewVD->setInvalidDecl();
9047 return;
9048 }
9049 }
9050 }
9051
9052 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9053 && !NewVD->hasAttr<BlocksAttr>()) {
9054 if (getLangOpts().getGC() != LangOptions::NonGC)
9055 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
9056 else {
9057 assert(!getLangOpts().ObjCAutoRefCount);
9058 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
9059 }
9060 }
9061
9062 // WebAssembly tables must be static with a zero length and can't be
9063 // declared within functions.
9064 if (T->isWebAssemblyTableType()) {
9065 if (getCurScope()->getParent()) { // Parent is null at top-level
9066 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
9067 NewVD->setInvalidDecl();
9068 return;
9069 }
9070 if (NewVD->getStorageClass() != SC_Static) {
9071 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
9072 NewVD->setInvalidDecl();
9073 return;
9074 }
9075 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
9076 if (!ATy || ATy->getZExtSize() != 0) {
9077 Diag(NewVD->getLocation(),
9078 diag::err_typecheck_wasm_table_must_have_zero_length);
9079 NewVD->setInvalidDecl();
9080 return;
9081 }
9082 }
9083
9084 // zero sized static arrays are not allowed in HIP device functions
9085 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9086 if (FunctionDecl *FD = getCurFunctionDecl();
9087 FD &&
9088 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9089 if (const ConstantArrayType *ArrayT =
9090 getASTContext().getAsConstantArrayType(T);
9091 ArrayT && ArrayT->isZeroSize()) {
9092 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
9093 }
9094 }
9095 }
9096
9097 bool isVM = T->isVariablyModifiedType();
9098 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9099 NewVD->hasAttr<BlocksAttr>())
9101
9102 if ((isVM && NewVD->hasLinkage()) ||
9103 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9104 bool SizeIsNegative;
9105 llvm::APSInt Oversized;
9107 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9108 QualType FixedT;
9109 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9110 FixedT = FixedTInfo->getType();
9111 else if (FixedTInfo) {
9112 // Type and type-as-written are canonically different. We need to fix up
9113 // both types separately.
9114 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9115 Oversized);
9116 }
9117 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9118 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9119 // FIXME: This won't give the correct result for
9120 // int a[10][n];
9121 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9122
9123 if (NewVD->isFileVarDecl())
9124 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9125 << SizeRange;
9126 else if (NewVD->isStaticLocal())
9127 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9128 << SizeRange;
9129 else
9130 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9131 << SizeRange;
9132 NewVD->setInvalidDecl();
9133 return;
9134 }
9135
9136 if (!FixedTInfo) {
9137 if (NewVD->isFileVarDecl())
9138 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9139 else
9140 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9141 NewVD->setInvalidDecl();
9142 return;
9143 }
9144
9145 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9146 NewVD->setType(FixedT);
9147 NewVD->setTypeSourceInfo(FixedTInfo);
9148 }
9149
9150 if (T->isVoidType()) {
9151 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9152 // of objects and functions.
9154 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9155 << T;
9156 NewVD->setInvalidDecl();
9157 return;
9158 }
9159 }
9160
9161 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9162 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9163 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9164 NewVD->setInvalidDecl();
9165 return;
9166 }
9167
9168 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9169 Diag(NewVD->getLocation(), diag::err_block_not_allowed_on)
9170 << diag::NotAllowedBlockVarReason::VariablyModifiedType;
9171 NewVD->setInvalidDecl();
9172 return;
9173 }
9174
9175 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9176 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9177 NewVD->setInvalidDecl();
9178 return;
9179 }
9180
9181 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9182 !T->isDependentType() &&
9183 RequireLiteralType(NewVD->getLocation(), T,
9184 diag::err_constexpr_var_non_literal)) {
9185 NewVD->setInvalidDecl();
9186 return;
9187 }
9188
9189 // PPC MMA non-pointer types are not allowed as non-local variable types.
9190 if (Context.getTargetInfo().getTriple().isPPC64() &&
9191 !NewVD->isLocalVarDecl() &&
9192 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9193 NewVD->setInvalidDecl();
9194 return;
9195 }
9196
9197 // Check that SVE types are only used in functions with SVE available.
9198 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9200 llvm::StringMap<bool> CallerFeatureMap;
9201 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9202 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,
9203 CallerFeatureMap)) {
9204 NewVD->setInvalidDecl();
9205 return;
9206 }
9207 }
9208
9209 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9211 llvm::StringMap<bool> CallerFeatureMap;
9212 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9214 CallerFeatureMap);
9215 }
9216
9217 if (T.hasAddressSpace() &&
9218 !CheckVarDeclSizeAddressSpace(NewVD, T.getAddressSpace())) {
9219 NewVD->setInvalidDecl();
9220 return;
9221 }
9222}
9223
9226
9227 // If the decl is already known invalid, don't check it.
9228 if (NewVD->isInvalidDecl())
9229 return false;
9230
9231 // If we did not find anything by this name, look for a non-visible
9232 // extern "C" declaration with the same name.
9233 if (Previous.empty() &&
9235 Previous.setShadowed();
9236
9237 if (!Previous.empty()) {
9238 MergeVarDecl(NewVD, Previous);
9239 return true;
9240 }
9241 return false;
9242}
9243
9246
9247 // Look for methods in base classes that this method might override.
9248 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9249 /*DetectVirtual=*/false);
9250 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9251 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9252 DeclarationName Name = MD->getDeclName();
9253
9255 // We really want to find the base class destructor here.
9256 Name = Context.DeclarationNames.getCXXDestructorName(
9257 Context.getCanonicalTagType(BaseRecord));
9258 }
9259
9260 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9261 CXXMethodDecl *BaseMD =
9262 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9263 if (!BaseMD || !BaseMD->isVirtual() ||
9264 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9265 /*ConsiderCudaAttrs=*/true))
9266 continue;
9267 if (!CheckExplicitObjectOverride(MD, BaseMD))
9268 continue;
9269 if (Overridden.insert(BaseMD).second) {
9270 MD->addOverriddenMethod(BaseMD);
9275 }
9276
9277 // A method can only override one function from each base class. We
9278 // don't track indirectly overridden methods from bases of bases.
9279 return true;
9280 }
9281
9282 return false;
9283 };
9284
9285 DC->lookupInBases(VisitBase, Paths);
9286 return !Overridden.empty();
9287}
9288
9289namespace {
9290 // Struct for holding all of the extra arguments needed by
9291 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9292 struct ActOnFDArgs {
9293 Scope *S;
9294 Declarator &D;
9295 MultiTemplateParamsArg TemplateParamLists;
9296 bool AddToScope;
9297 };
9298} // end anonymous namespace
9299
9300namespace {
9301
9302// Callback to only accept typo corrections that have a non-zero edit distance.
9303// Also only accept corrections that have the same parent decl.
9304class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9305 public:
9306 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9307 CXXRecordDecl *Parent)
9308 : Context(Context), OriginalFD(TypoFD),
9309 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9310
9311 bool ValidateCandidate(const TypoCorrection &candidate) override {
9312 if (candidate.getEditDistance() == 0)
9313 return false;
9314
9315 SmallVector<unsigned, 1> MismatchedParams;
9316 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9317 CDeclEnd = candidate.end();
9318 CDecl != CDeclEnd; ++CDecl) {
9319 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9320
9321 if (FD && !FD->hasBody() &&
9322 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9323 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9324 CXXRecordDecl *Parent = MD->getParent();
9325 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9326 return true;
9327 } else if (!ExpectedParent) {
9328 return true;
9329 }
9330 }
9331 }
9332
9333 return false;
9334 }
9335
9336 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9337 return std::make_unique<DifferentNameValidatorCCC>(*this);
9338 }
9339
9340 private:
9341 ASTContext &Context;
9342 FunctionDecl *OriginalFD;
9343 CXXRecordDecl *ExpectedParent;
9344};
9345
9346} // end anonymous namespace
9347
9351
9352/// Generate diagnostics for an invalid function redeclaration.
9353///
9354/// This routine handles generating the diagnostic messages for an invalid
9355/// function redeclaration, including finding possible similar declarations
9356/// or performing typo correction if there are no previous declarations with
9357/// the same name.
9358///
9359/// Returns a NamedDecl iff typo correction was performed and substituting in
9360/// the new declaration name does not cause new errors.
9362 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9363 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9364 DeclarationName Name = NewFD->getDeclName();
9365 DeclContext *NewDC = NewFD->getDeclContext();
9366 SmallVector<unsigned, 1> MismatchedParams;
9368 TypoCorrection Correction;
9369 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9370 unsigned DiagMsg =
9371 IsLocalFriend ? diag::err_no_matching_local_friend :
9372 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9373 diag::err_member_decl_does_not_match;
9374 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9375 IsLocalFriend ? Sema::LookupLocalFriendName
9378
9379 NewFD->setInvalidDecl();
9380 if (IsLocalFriend)
9381 SemaRef.LookupName(Prev, S);
9382 else
9383 SemaRef.LookupQualifiedName(Prev, NewDC);
9384 assert(!Prev.isAmbiguous() &&
9385 "Cannot have an ambiguity in previous-declaration lookup");
9386 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9387 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9388 MD ? MD->getParent() : nullptr);
9389 if (!Prev.empty()) {
9390 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9391 Func != FuncEnd; ++Func) {
9392 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9393 if (FD &&
9394 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9395 // Add 1 to the index so that 0 can mean the mismatch didn't
9396 // involve a parameter
9397 unsigned ParamNum =
9398 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9399 NearMatches.push_back(std::make_pair(FD, ParamNum));
9400 }
9401 }
9402 // If the qualified name lookup yielded nothing, try typo correction
9403 } else if ((Correction = SemaRef.CorrectTypo(
9404 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9405 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9407 IsLocalFriend ? nullptr : NewDC))) {
9408 // Set up everything for the call to ActOnFunctionDeclarator
9409 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9410 ExtraArgs.D.getIdentifierLoc());
9411 Previous.clear();
9412 Previous.setLookupName(Correction.getCorrection());
9413 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9414 CDeclEnd = Correction.end();
9415 CDecl != CDeclEnd; ++CDecl) {
9416 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9417 if (FD && !FD->hasBody() &&
9418 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9419 Previous.addDecl(FD);
9420 }
9421 }
9422 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9423
9425 // Retry building the function declaration with the new previous
9426 // declarations, and with errors suppressed.
9427 {
9428 // Trap errors.
9429 Sema::SFINAETrap Trap(SemaRef);
9430
9431 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9432 // pieces need to verify the typo-corrected C++ declaration and hopefully
9433 // eliminate the need for the parameter pack ExtraArgs.
9435 ExtraArgs.S, ExtraArgs.D,
9436 Correction.getCorrectionDecl()->getDeclContext(),
9437 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9438 ExtraArgs.AddToScope);
9439
9440 if (Trap.hasErrorOccurred())
9441 Result = nullptr;
9442 }
9443
9444 if (Result) {
9445 // Determine which correction we picked.
9446 Decl *Canonical = Result->getCanonicalDecl();
9447 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9448 I != E; ++I)
9449 if ((*I)->getCanonicalDecl() == Canonical)
9450 Correction.setCorrectionDecl(*I);
9451
9452 // Let Sema know about the correction.
9454 SemaRef.diagnoseTypo(
9455 Correction,
9456 SemaRef.PDiag(IsLocalFriend
9457 ? diag::err_no_matching_local_friend_suggest
9458 : diag::err_member_decl_does_not_match_suggest)
9459 << Name << NewDC << IsDefinition);
9460 return Result;
9461 }
9462
9463 // Pretend the typo correction never occurred
9464 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9465 ExtraArgs.D.getIdentifierLoc());
9466 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9467 Previous.clear();
9468 Previous.setLookupName(Name);
9469 }
9470
9471 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9472 << Name << NewDC << IsDefinition << NewFD->getLocation();
9473
9474 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9475 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9476 CXXRecordDecl *RD = NewMD->getParent();
9477 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9478 << RD->getName() << RD->getLocation();
9479 }
9480
9481 bool NewFDisConst = NewMD && NewMD->isConst();
9482
9483 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9484 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9485 NearMatch != NearMatchEnd; ++NearMatch) {
9486 FunctionDecl *FD = NearMatch->first;
9487 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9488 bool FDisConst = MD && MD->isConst();
9489 bool IsMember = MD || !IsLocalFriend;
9490
9491 // FIXME: These notes are poorly worded for the local friend case.
9492 if (unsigned Idx = NearMatch->second) {
9493 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9494 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9495 if (Loc.isInvalid()) Loc = FD->getLocation();
9496 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9497 : diag::note_local_decl_close_param_match)
9498 << Idx << FDParam->getType()
9499 << NewFD->getParamDecl(Idx - 1)->getType();
9500 } else if (FDisConst != NewFDisConst) {
9501 auto DB = SemaRef.Diag(FD->getLocation(),
9502 diag::note_member_def_close_const_match)
9503 << NewFDisConst << FD->getSourceRange().getEnd();
9504 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9505 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9506 " const");
9507 else if (FTI.hasMethodTypeQualifiers() &&
9508 FTI.getConstQualifierLoc().isValid())
9509 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9510 } else {
9511 SemaRef.Diag(FD->getLocation(),
9512 IsMember ? diag::note_member_def_close_match
9513 : diag::note_local_decl_close_match);
9514 }
9515 }
9516 return nullptr;
9517}
9518
9520 switch (D.getDeclSpec().getStorageClassSpec()) {
9521 default: llvm_unreachable("Unknown storage class!");
9522 case DeclSpec::SCS_auto:
9526 diag::err_typecheck_sclass_func);
9528 D.setInvalidType();
9529 break;
9530 case DeclSpec::SCS_unspecified: break;
9533 return SC_None;
9534 return SC_Extern;
9535 case DeclSpec::SCS_static: {
9537 // C99 6.7.1p5:
9538 // The declaration of an identifier for a function that has
9539 // block scope shall have no explicit storage-class specifier
9540 // other than extern
9541 // See also (C++ [dcl.stc]p4).
9543 diag::err_static_block_func);
9544 break;
9545 } else
9546 return SC_Static;
9547 }
9549 }
9550
9551 // No explicit storage class has already been returned
9552 return SC_None;
9553}
9554
9556 DeclContext *DC, QualType &R,
9557 TypeSourceInfo *TInfo,
9558 StorageClass SC,
9559 bool &IsVirtualOkay) {
9560 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9561 DeclarationName Name = NameInfo.getName();
9562
9563 FunctionDecl *NewFD = nullptr;
9564 bool isInline = D.getDeclSpec().isInlineSpecified();
9565
9567 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9568 (SemaRef.getLangOpts().C23 &&
9569 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9570
9571 if (SemaRef.getLangOpts().C23)
9572 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9573 diag::err_c23_constexpr_not_variable);
9574 else
9575 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9576 diag::err_constexpr_wrong_decl_kind)
9577 << static_cast<int>(ConstexprKind);
9578 ConstexprKind = ConstexprSpecKind::Unspecified;
9580 }
9581
9582 if (!SemaRef.getLangOpts().CPlusPlus) {
9583 // Determine whether the function was written with a prototype. This is
9584 // true when:
9585 // - there is a prototype in the declarator, or
9586 // - the type R of the function is some kind of typedef or other non-
9587 // attributed reference to a type name (which eventually refers to a
9588 // function type). Note, we can't always look at the adjusted type to
9589 // check this case because attributes may cause a non-function
9590 // declarator to still have a function type. e.g.,
9591 // typedef void func(int a);
9592 // __attribute__((noreturn)) func other_func; // This has a prototype
9593 bool HasPrototype =
9595 (D.getDeclSpec().isTypeRep() &&
9596 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9597 ->isFunctionProtoType()) ||
9598 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9599 assert(
9600 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9601 "Strict prototypes are required");
9602
9603 NewFD = FunctionDecl::Create(
9604 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9605 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9607 /*TrailingRequiresClause=*/{});
9608 if (D.isInvalidType())
9609 NewFD->setInvalidDecl();
9610
9611 return NewFD;
9612 }
9613
9615 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9616
9617 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9618
9620 // This is a C++ constructor declaration.
9621 assert(DC->isRecord() &&
9622 "Constructors can only be declared in a member context");
9623
9624 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9626 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9628 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9629 InheritedConstructor(), TrailingRequiresClause);
9630
9631 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9632 // This is a C++ destructor declaration.
9633 if (DC->isRecord()) {
9634 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9637 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9638 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9639 /*isImplicitlyDeclared=*/false, ConstexprKind,
9640 TrailingRequiresClause);
9641 // User defined destructors start as not selected if the class definition is still
9642 // not done.
9643 if (Record->isBeingDefined())
9644 NewDD->setIneligibleOrNotSelected(true);
9645
9646 // If the destructor needs an implicit exception specification, set it
9647 // now. FIXME: It'd be nice to be able to create the right type to start
9648 // with, but the type needs to reference the destructor declaration.
9649 if (SemaRef.getLangOpts().CPlusPlus11)
9650 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9651
9652 IsVirtualOkay = true;
9653 return NewDD;
9654
9655 } else {
9656 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9657 D.setInvalidType();
9658
9659 // Create a FunctionDecl to satisfy the function definition parsing
9660 // code path.
9661 return FunctionDecl::Create(
9662 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9663 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9664 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9665 }
9666
9668 if (!DC->isRecord()) {
9669 SemaRef.Diag(D.getIdentifierLoc(),
9670 diag::err_conv_function_not_member);
9671 return nullptr;
9672 }
9673
9674 SemaRef.CheckConversionDeclarator(D, R, SC);
9675 if (D.isInvalidType())
9676 return nullptr;
9677
9678 IsVirtualOkay = true;
9680 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9681 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9682 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9683 TrailingRequiresClause);
9684
9686 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9687 return nullptr;
9689 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9690 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9691 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9692 } else if (DC->isRecord()) {
9693 // If the name of the function is the same as the name of the record,
9694 // then this must be an invalid constructor that has a return type.
9695 // (The parser checks for a return type and makes the declarator a
9696 // constructor if it has no return type).
9697 if (Name.getAsIdentifierInfo() &&
9698 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9699 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9702 return nullptr;
9703 }
9704
9705 // This is a C++ method declaration.
9707 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9708 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9709 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9710 IsVirtualOkay = !Ret->isStatic();
9711 return Ret;
9712 } else {
9713 bool isFriend =
9714 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9715 if (!isFriend && SemaRef.CurContext->isRecord())
9716 return nullptr;
9717
9718 // Determine whether the function was written with a
9719 // prototype. This true when:
9720 // - we're in C++ (where every function has a prototype),
9721 return FunctionDecl::Create(
9722 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9723 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9724 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9725 }
9726}
9727
9736
9738 // Size dependent types are just typedefs to normal integer types
9739 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9740 // integers other than by their names.
9741 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9742
9743 // Remove typedefs one by one until we reach a typedef
9744 // for a size dependent type.
9745 QualType DesugaredTy = Ty;
9746 do {
9747 ArrayRef<StringRef> Names(SizeTypeNames);
9748 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9749 if (Names.end() != Match)
9750 return true;
9751
9752 Ty = DesugaredTy;
9753 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9754 } while (DesugaredTy != Ty);
9755
9756 return false;
9757}
9758
9760 if (PT->isDependentType())
9761 return InvalidKernelParam;
9762
9763 if (PT->isPointerOrReferenceType()) {
9764 QualType PointeeType = PT->getPointeeType();
9765 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9766 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9767 PointeeType.getAddressSpace() == LangAS::Default)
9769
9770 if (PointeeType->isPointerType()) {
9771 // This is a pointer to pointer parameter.
9772 // Recursively check inner type.
9773 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9774 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9775 ParamKind == InvalidKernelParam)
9776 return ParamKind;
9777
9778 // OpenCL v3.0 s6.11.a:
9779 // A restriction to pass pointers to pointers only applies to OpenCL C
9780 // v1.2 or below.
9782 return ValidKernelParam;
9783
9784 return PtrPtrKernelParam;
9785 }
9786
9787 // C++ for OpenCL v1.0 s2.4:
9788 // Moreover the types used in parameters of the kernel functions must be:
9789 // Standard layout types for pointer parameters. The same applies to
9790 // reference if an implementation supports them in kernel parameters.
9791 if (S.getLangOpts().OpenCLCPlusPlus &&
9793 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9794 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9795 bool IsStandardLayoutType = true;
9796 if (CXXRec) {
9797 // If template type is not ODR-used its definition is only available
9798 // in the template definition not its instantiation.
9799 // FIXME: This logic doesn't work for types that depend on template
9800 // parameter (PR58590).
9801 if (!CXXRec->hasDefinition())
9802 CXXRec = CXXRec->getTemplateInstantiationPattern();
9803 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9804 IsStandardLayoutType = false;
9805 }
9806 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9807 !IsStandardLayoutType)
9808 return InvalidKernelParam;
9809 }
9810
9811 // OpenCL v1.2 s6.9.p:
9812 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9814 return ValidKernelParam;
9815
9816 return PtrKernelParam;
9817 }
9818
9819 // OpenCL v1.2 s6.9.k:
9820 // Arguments to kernel functions in a program cannot be declared with the
9821 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9822 // uintptr_t or a struct and/or union that contain fields declared to be one
9823 // of these built-in scalar types.
9825 return InvalidKernelParam;
9826
9827 if (PT->isImageType())
9828 return PtrKernelParam;
9829
9830 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9831 return InvalidKernelParam;
9832
9833 // OpenCL extension spec v1.2 s9.5:
9834 // This extension adds support for half scalar and vector types as built-in
9835 // types that can be used for arithmetic operations, conversions etc.
9836 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9837 PT->isHalfType())
9838 return InvalidKernelParam;
9839
9840 // Look into an array argument to check if it has a forbidden type.
9841 if (PT->isArrayType()) {
9842 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9843 // Call ourself to check an underlying type of an array. Since the
9844 // getPointeeOrArrayElementType returns an innermost type which is not an
9845 // array, this recursive call only happens once.
9846 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9847 }
9848
9849 // C++ for OpenCL v1.0 s2.4:
9850 // Moreover the types used in parameters of the kernel functions must be:
9851 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9852 // types) for parameters passed by value;
9853 if (S.getLangOpts().OpenCLCPlusPlus &&
9855 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9856 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9857 return InvalidKernelParam;
9858
9859 if (PT->isRecordType())
9860 return RecordKernelParam;
9861
9862 return ValidKernelParam;
9863}
9864
9866 Sema &S,
9867 Declarator &D,
9868 ParmVarDecl *Param,
9869 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9870 QualType PT = Param->getType();
9871
9872 // Cache the valid types we encounter to avoid rechecking structs that are
9873 // used again
9874 if (ValidTypes.count(PT.getTypePtr()))
9875 return;
9876
9877 switch (getOpenCLKernelParameterType(S, PT)) {
9878 case PtrPtrKernelParam:
9879 // OpenCL v3.0 s6.11.a:
9880 // A kernel function argument cannot be declared as a pointer to a pointer
9881 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9882 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9883 D.setInvalidType();
9884 return;
9885
9887 // OpenCL v1.0 s6.5:
9888 // __kernel function arguments declared to be a pointer of a type can point
9889 // to one of the following address spaces only : __global, __local or
9890 // __constant.
9891 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9892 D.setInvalidType();
9893 return;
9894
9895 // OpenCL v1.2 s6.9.k:
9896 // Arguments to kernel functions in a program cannot be declared with the
9897 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9898 // uintptr_t or a struct and/or union that contain fields declared to be
9899 // one of these built-in scalar types.
9900
9901 case InvalidKernelParam:
9902 // OpenCL v1.2 s6.8 n:
9903 // A kernel function argument cannot be declared
9904 // of event_t type.
9905 // Do not diagnose half type since it is diagnosed as invalid argument
9906 // type for any function elsewhere.
9907 if (!PT->isHalfType()) {
9908 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9909
9910 // Explain what typedefs are involved.
9911 const TypedefType *Typedef = nullptr;
9912 while ((Typedef = PT->getAs<TypedefType>())) {
9913 SourceLocation Loc = Typedef->getDecl()->getLocation();
9914 // SourceLocation may be invalid for a built-in type.
9915 if (Loc.isValid())
9916 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9917 PT = Typedef->desugar();
9918 }
9919 }
9920
9921 D.setInvalidType();
9922 return;
9923
9924 case PtrKernelParam:
9925 case ValidKernelParam:
9926 ValidTypes.insert(PT.getTypePtr());
9927 return;
9928
9929 case RecordKernelParam:
9930 break;
9931 }
9932
9933 // Track nested structs we will inspect
9935
9936 // Track where we are in the nested structs. Items will migrate from
9937 // VisitStack to HistoryStack as we do the DFS for bad field.
9939 HistoryStack.push_back(nullptr);
9940
9941 // At this point we already handled everything except of a RecordType.
9942 assert(PT->isRecordType() && "Unexpected type.");
9943 const auto *PD = PT->castAsRecordDecl();
9944 VisitStack.push_back(PD);
9945 assert(VisitStack.back() && "First decl null?");
9946
9947 do {
9948 const Decl *Next = VisitStack.pop_back_val();
9949 if (!Next) {
9950 assert(!HistoryStack.empty());
9951 // Found a marker, we have gone up a level
9952 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9953 ValidTypes.insert(Hist->getType().getTypePtr());
9954
9955 continue;
9956 }
9957
9958 // Adds everything except the original parameter declaration (which is not a
9959 // field itself) to the history stack.
9960 const RecordDecl *RD;
9961 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9962 HistoryStack.push_back(Field);
9963
9964 QualType FieldTy = Field->getType();
9965 // Other field types (known to be valid or invalid) are handled while we
9966 // walk around RecordDecl::fields().
9967 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9968 "Unexpected type.");
9969 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9970
9971 RD = FieldRecTy->castAsRecordDecl();
9972 } else {
9973 RD = cast<RecordDecl>(Next);
9974 }
9975
9976 // Add a null marker so we know when we've gone back up a level
9977 VisitStack.push_back(nullptr);
9978
9979 for (const auto *FD : RD->fields()) {
9980 QualType QT = FD->getType();
9981
9982 if (ValidTypes.count(QT.getTypePtr()))
9983 continue;
9984
9986 if (ParamType == ValidKernelParam)
9987 continue;
9988
9989 if (ParamType == RecordKernelParam) {
9990 VisitStack.push_back(FD);
9991 continue;
9992 }
9993
9994 // OpenCL v1.2 s6.9.p:
9995 // Arguments to kernel functions that are declared to be a struct or union
9996 // do not allow OpenCL objects to be passed as elements of the struct or
9997 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9998 // of SVM.
9999 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10000 ParamType == InvalidAddrSpacePtrKernelParam) {
10001 S.Diag(Param->getLocation(),
10002 diag::err_record_with_pointers_kernel_param)
10003 << PT->isUnionType()
10004 << PT;
10005 } else {
10006 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
10007 }
10008
10009 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
10010 << PD->getDeclName();
10011
10012 // We have an error, now let's go back up through history and show where
10013 // the offending field came from
10015 I = HistoryStack.begin() + 1,
10016 E = HistoryStack.end();
10017 I != E; ++I) {
10018 const FieldDecl *OuterField = *I;
10019 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
10020 << OuterField->getType();
10021 }
10022
10023 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
10024 << QT->isPointerType()
10025 << QT;
10026 D.setInvalidType();
10027 return;
10028 }
10029 } while (!VisitStack.empty());
10030}
10031
10032/// Find the DeclContext in which a tag is implicitly declared if we see an
10033/// elaborated type specifier in the specified context, and lookup finds
10034/// nothing.
10036 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10037 DC = DC->getParent();
10038 return DC;
10039}
10040
10041/// Find the Scope in which a tag is implicitly declared if we see an
10042/// elaborated type specifier in the specified context, and lookup finds
10043/// nothing.
10044static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10045 while (S->isClassScope() ||
10046 (LangOpts.CPlusPlus &&
10048 ((S->getFlags() & Scope::DeclScope) == 0) ||
10049 (S->getEntity() && S->getEntity()->isTransparentContext()))
10050 S = S->getParent();
10051 return S;
10052}
10053
10054/// Determine whether a declaration matches a known function in namespace std.
10056 unsigned BuiltinID) {
10057 switch (BuiltinID) {
10058 case Builtin::BI__GetExceptionInfo:
10059 // No type checking whatsoever.
10060 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10061
10062 case Builtin::BIaddressof:
10063 case Builtin::BI__addressof:
10064 case Builtin::BIforward:
10065 case Builtin::BIforward_like:
10066 case Builtin::BImove:
10067 case Builtin::BImove_if_noexcept:
10068 case Builtin::BIas_const: {
10069 // Ensure that we don't treat the algorithm
10070 // OutputIt std::move(InputIt, InputIt, OutputIt)
10071 // as the builtin std::move.
10072 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10073 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10074 }
10075
10076 default:
10077 return false;
10078 }
10079}
10080
10081NamedDecl*
10084 MultiTemplateParamsArg TemplateParamListsRef,
10085 bool &AddToScope) {
10086 QualType R = TInfo->getType();
10087
10088 assert(R->isFunctionType());
10089 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10090 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10091
10092 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10093 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10095 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10096 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10097 TemplateParamLists.back() = Invented;
10098 else
10099 TemplateParamLists.push_back(Invented);
10100 }
10101
10102 // TODO: consider using NameInfo for diagnostic.
10104 DeclarationName Name = NameInfo.getName();
10106
10109 diag::err_invalid_thread)
10111
10116
10117 bool isFriend = false;
10119 bool isMemberSpecialization = false;
10120 bool isFunctionTemplateSpecialization = false;
10121
10122 bool HasExplicitTemplateArgs = false;
10123 TemplateArgumentListInfo TemplateArgs;
10124
10125 bool isVirtualOkay = false;
10126
10127 DeclContext *OriginalDC = DC;
10128 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10129
10130 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10131 isVirtualOkay);
10132 if (!NewFD) return nullptr;
10133
10134 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10136
10137 // Set the lexical context. If this is a function-scope declaration, or has a
10138 // C++ scope specifier, or is the object of a friend declaration, the lexical
10139 // context will be different from the semantic context.
10141
10142 if (IsLocalExternDecl)
10143 NewFD->setLocalExternDecl();
10144
10145 if (getLangOpts().CPlusPlus) {
10146 // The rules for implicit inlines changed in C++20 for methods and friends
10147 // with an in-class definition (when such a definition is not attached to
10148 // the global module). This does not affect declarations that are already
10149 // inline (whether explicitly or implicitly by being declared constexpr,
10150 // consteval, etc).
10151 // FIXME: We need a better way to separate C++ standard and clang modules.
10152 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10153 !NewFD->getOwningModule() ||
10154 NewFD->isFromGlobalModule() ||
10156 bool isInline = D.getDeclSpec().isInlineSpecified();
10157 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10158 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10159 isFriend = D.getDeclSpec().isFriendSpecified();
10160 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10161 // Pre-C++20 [class.friend]p5
10162 // A function can be defined in a friend declaration of a
10163 // class . . . . Such a function is implicitly inline.
10164 // Post C++20 [class.friend]p7
10165 // Such a function is implicitly an inline function if it is attached
10166 // to the global module.
10167 NewFD->setImplicitlyInline();
10168 }
10169
10170 // If this is a method defined in an __interface, and is not a constructor
10171 // or an overloaded operator, then set the pure flag (isVirtual will already
10172 // return true).
10173 if (const CXXRecordDecl *Parent =
10174 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10175 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10176 NewFD->setIsPureVirtual(true);
10177
10178 // C++ [class.union]p2
10179 // A union can have member functions, but not virtual functions.
10180 if (isVirtual && Parent->isUnion()) {
10181 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10182 NewFD->setInvalidDecl();
10183 }
10184 if ((Parent->isClass() || Parent->isStruct()) &&
10185 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10186 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10187 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10188 if (auto *Def = Parent->getDefinition())
10189 Def->setInitMethod(true);
10190 }
10191 }
10192
10193 SetNestedNameSpecifier(*this, NewFD, D);
10194 isMemberSpecialization = false;
10195 isFunctionTemplateSpecialization = false;
10196 if (D.isInvalidType())
10197 NewFD->setInvalidDecl();
10198
10199 // Match up the template parameter lists with the scope specifier, then
10200 // determine whether we have a template or a template specialization.
10201 bool Invalid = false;
10202 TemplateIdAnnotation *TemplateId =
10204 ? D.getName().TemplateId
10205 : nullptr;
10206 TemplateParameterList *TemplateParams =
10209 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10210 isMemberSpecialization, Invalid);
10211 if (TemplateParams) {
10212 // Check that we can declare a template here.
10213 if (CheckTemplateDeclScope(S, TemplateParams))
10214 NewFD->setInvalidDecl();
10215
10216 if (TemplateParams->size() > 0) {
10217 // This is a function template
10218
10219 // A destructor cannot be a template.
10221 Diag(NewFD->getLocation(), diag::err_destructor_template);
10222 NewFD->setInvalidDecl();
10223 // Function template with explicit template arguments.
10224 } else if (TemplateId) {
10225 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10226 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10227 NewFD->setInvalidDecl();
10228 }
10229
10230 // If we're adding a template to a dependent context, we may need to
10231 // rebuilding some of the types used within the template parameter list,
10232 // now that we know what the current instantiation is.
10233 if (DC->isDependentContext()) {
10234 ContextRAII SavedContext(*this, DC);
10236 Invalid = true;
10237 }
10238
10240 NewFD->getLocation(),
10241 Name, TemplateParams,
10242 NewFD);
10243 FunctionTemplate->setLexicalDeclContext(CurContext);
10245
10246 // For source fidelity, store the other template param lists.
10247 if (TemplateParamLists.size() > 1) {
10249 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10250 .drop_back(1));
10251 }
10252 } else {
10253 // This is a function template specialization.
10254 isFunctionTemplateSpecialization = true;
10255 // For source fidelity, store all the template param lists.
10256 if (TemplateParamLists.size() > 0)
10257 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10258
10259 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10260 if (isFriend) {
10261 // We want to remove the "template<>", found here.
10262 SourceRange RemoveRange = TemplateParams->getSourceRange();
10263
10264 // If we remove the template<> and the name is not a
10265 // template-id, we're actually silently creating a problem:
10266 // the friend declaration will refer to an untemplated decl,
10267 // and clearly the user wants a template specialization. So
10268 // we need to insert '<>' after the name.
10269 SourceLocation InsertLoc;
10271 InsertLoc = D.getName().getSourceRange().getEnd();
10272 InsertLoc = getLocForEndOfToken(InsertLoc);
10273 }
10274
10275 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10276 << Name << RemoveRange
10277 << FixItHint::CreateRemoval(RemoveRange)
10278 << FixItHint::CreateInsertion(InsertLoc, "<>");
10279 Invalid = true;
10280
10281 // Recover by faking up an empty template argument list.
10282 HasExplicitTemplateArgs = true;
10283 TemplateArgs.setLAngleLoc(InsertLoc);
10284 TemplateArgs.setRAngleLoc(InsertLoc);
10285 }
10286 }
10287 } else {
10288 // Check that we can declare a template here.
10289 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10290 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10291 NewFD->setInvalidDecl();
10292
10293 // All template param lists were matched against the scope specifier:
10294 // this is NOT (an explicit specialization of) a template.
10295 if (TemplateParamLists.size() > 0)
10296 // For source fidelity, store all the template param lists.
10297 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10298
10299 // "friend void foo<>(int);" is an implicit specialization decl.
10300 if (isFriend && TemplateId)
10301 isFunctionTemplateSpecialization = true;
10302 }
10303
10304 // If this is a function template specialization and the unqualified-id of
10305 // the declarator-id is a template-id, convert the template argument list
10306 // into our AST format and check for unexpanded packs.
10307 if (isFunctionTemplateSpecialization && TemplateId) {
10308 HasExplicitTemplateArgs = true;
10309
10310 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10311 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10312 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10313 TemplateId->NumArgs);
10314 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10315
10316 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10317 // declaration of a function template partial specialization? Should we
10318 // consider the unexpanded pack context to be a partial specialization?
10319 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10321 ArgLoc, isFriend ? UPPC_FriendDeclaration
10323 NewFD->setInvalidDecl();
10324 }
10325 }
10326
10327 if (Invalid) {
10328 NewFD->setInvalidDecl();
10329 if (FunctionTemplate)
10330 FunctionTemplate->setInvalidDecl();
10331 }
10332
10333 // C++ [dcl.fct.spec]p5:
10334 // The virtual specifier shall only be used in declarations of
10335 // nonstatic class member functions that appear within a
10336 // member-specification of a class declaration; see 10.3.
10337 //
10338 if (isVirtual && !NewFD->isInvalidDecl()) {
10339 if (!isVirtualOkay) {
10341 diag::err_virtual_non_function);
10342 } else if (!CurContext->isRecord()) {
10343 // 'virtual' was specified outside of the class.
10345 diag::err_virtual_out_of_class)
10347 } else if (NewFD->getDescribedFunctionTemplate()) {
10348 // C++ [temp.mem]p3:
10349 // A member function template shall not be virtual.
10351 diag::err_virtual_member_function_template)
10353 } else {
10354 // Okay: Add virtual to the method.
10355 NewFD->setVirtualAsWritten(true);
10356 }
10357
10358 if (getLangOpts().CPlusPlus14 &&
10359 NewFD->getReturnType()->isUndeducedType())
10360 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10361 }
10362
10363 // C++ [dcl.fct.spec]p3:
10364 // The inline specifier shall not appear on a block scope function
10365 // declaration.
10366 if (isInline && !NewFD->isInvalidDecl()) {
10367 if (CurContext->isFunctionOrMethod()) {
10368 // 'inline' is not allowed on block scope function declaration.
10370 diag::err_inline_declaration_block_scope) << Name
10372 }
10373 }
10374
10375 // C++ [dcl.fct.spec]p6:
10376 // The explicit specifier shall be used only in the declaration of a
10377 // constructor or conversion function within its class definition;
10378 // see 12.3.1 and 12.3.2.
10379 if (hasExplicit && !NewFD->isInvalidDecl() &&
10381 if (!CurContext->isRecord()) {
10382 // 'explicit' was specified outside of the class.
10384 diag::err_explicit_out_of_class)
10386 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10387 !isa<CXXConversionDecl>(NewFD)) {
10388 // 'explicit' was specified on a function that wasn't a constructor
10389 // or conversion function.
10391 diag::err_explicit_non_ctor_or_conv_function)
10393 }
10394 }
10395
10397 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10398 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10399 // are implicitly inline.
10400 NewFD->setImplicitlyInline();
10401
10402 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10403 // be either constructors or to return a literal type. Therefore,
10404 // destructors cannot be declared constexpr.
10405 if (isa<CXXDestructorDecl>(NewFD) &&
10407 ConstexprKind == ConstexprSpecKind::Consteval)) {
10408 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10409 << static_cast<int>(ConstexprKind);
10413 }
10414 // C++20 [dcl.constexpr]p2: An allocation function, or a
10415 // deallocation function shall not be declared with the consteval
10416 // specifier.
10417 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10420 diag::err_invalid_consteval_decl_kind)
10421 << NewFD;
10423 }
10424 }
10425
10426 // If __module_private__ was specified, mark the function accordingly.
10428 if (isFunctionTemplateSpecialization) {
10429 SourceLocation ModulePrivateLoc
10431 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10432 << 0
10433 << FixItHint::CreateRemoval(ModulePrivateLoc);
10434 } else {
10435 NewFD->setModulePrivate();
10436 if (FunctionTemplate)
10437 FunctionTemplate->setModulePrivate();
10438 }
10439 }
10440
10441 if (isFriend) {
10442 if (FunctionTemplate) {
10443 FunctionTemplate->setObjectOfFriendDecl();
10444 FunctionTemplate->setAccess(AS_public);
10445 }
10446 NewFD->setObjectOfFriendDecl();
10447 NewFD->setAccess(AS_public);
10448 }
10449
10450 // If a function is defined as defaulted or deleted, mark it as such now.
10451 // We'll do the relevant checks on defaulted / deleted functions later.
10452 switch (D.getFunctionDefinitionKind()) {
10455 break;
10456
10458 NewFD->setDefaulted();
10459 break;
10460
10462 NewFD->setDeletedAsWritten();
10463 break;
10464 }
10465
10466 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10468 // Pre C++20 [class.mfct]p2:
10469 // A member function may be defined (8.4) in its class definition, in
10470 // which case it is an inline member function (7.1.2)
10471 // Post C++20 [class.mfct]p1:
10472 // If a member function is attached to the global module and is defined
10473 // in its class definition, it is inline.
10474 NewFD->setImplicitlyInline();
10475 }
10476
10477 if (!isFriend && SC != SC_None) {
10478 // C++ [temp.expl.spec]p2:
10479 // The declaration in an explicit-specialization shall not be an
10480 // export-declaration. An explicit specialization shall not use a
10481 // storage-class-specifier other than thread_local.
10482 //
10483 // We diagnose friend declarations with storage-class-specifiers
10484 // elsewhere.
10485 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10487 diag::ext_explicit_specialization_storage_class)
10490 }
10491
10492 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10493 assert(isa<CXXMethodDecl>(NewFD) &&
10494 "Out-of-line member function should be a CXXMethodDecl");
10495 // C++ [class.static]p1:
10496 // A data or function member of a class may be declared static
10497 // in a class definition, in which case it is a static member of
10498 // the class.
10499
10500 // Complain about the 'static' specifier if it's on an out-of-line
10501 // member function definition.
10502
10503 // MSVC permits the use of a 'static' storage specifier on an
10504 // out-of-line member function template declaration and class member
10505 // template declaration (MSVC versions before 2015), warn about this.
10507 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10508 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10509 (getLangOpts().MSVCCompat &&
10511 ? diag::ext_static_out_of_line
10512 : diag::err_static_out_of_line)
10515 }
10516 }
10517
10518 // C++11 [except.spec]p15:
10519 // A deallocation function with no exception-specification is treated
10520 // as if it were specified with noexcept(true).
10521 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10522 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10523 !FPT->hasExceptionSpec())
10524 NewFD->setType(Context.getFunctionType(
10525 FPT->getReturnType(), FPT->getParamTypes(),
10527
10528 // C++20 [dcl.inline]/7
10529 // If an inline function or variable that is attached to a named module
10530 // is declared in a definition domain, it shall be defined in that
10531 // domain.
10532 // So, if the current declaration does not have a definition, we must
10533 // check at the end of the TU (or when the PMF starts) to see that we
10534 // have a definition at that point.
10535 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10536 NewFD->isInNamedModule()) {
10537 PendingInlineFuncDecls.insert(NewFD);
10538 }
10539 }
10540
10541 // Filter out previous declarations that don't match the scope.
10544 isMemberSpecialization ||
10545 isFunctionTemplateSpecialization);
10546
10548
10549 // Handle GNU asm-label extension (encoded as an attribute).
10550 if (Expr *E = D.getAsmLabel()) {
10551 // The parser guarantees this is a string.
10553 NewFD->addAttr(
10554 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10555 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10556 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10558 if (I != ExtnameUndeclaredIdentifiers.end()) {
10559 if (isDeclExternC(NewFD)) {
10560 NewFD->addAttr(I->second);
10562 } else if (NewFD->getDeclContext()
10565 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10566 << /*Variable*/0 << NewFD;
10567 }
10568 }
10569
10570 // Copy the parameter declarations from the declarator D to the function
10571 // declaration NewFD, if they are available. First scavenge them into Params.
10573 unsigned FTIIdx;
10574 if (D.isFunctionDeclarator(FTIIdx)) {
10576
10577 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10578 // function that takes no arguments, not a function that takes a
10579 // single void argument.
10580 // We let through "const void" here because Sema::GetTypeForDeclarator
10581 // already checks for that case.
10582 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10583 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10584 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10585 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10586 Param->setDeclContext(NewFD);
10587 Params.push_back(Param);
10588
10589 if (Param->isInvalidDecl())
10590 NewFD->setInvalidDecl();
10591 }
10592 }
10593
10594 if (!getLangOpts().CPlusPlus) {
10595 // In C, find all the tag declarations from the prototype and move them
10596 // into the function DeclContext. Remove them from the surrounding tag
10597 // injection context of the function, which is typically but not always
10598 // the TU.
10599 DeclContext *PrototypeTagContext =
10601 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10602 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10603
10604 // We don't want to reparent enumerators. Look at their parent enum
10605 // instead.
10606 if (!TD) {
10607 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10608 TD = cast<EnumDecl>(ECD->getDeclContext());
10609 }
10610 if (!TD)
10611 continue;
10612 DeclContext *TagDC = TD->getLexicalDeclContext();
10613 if (!TagDC->containsDecl(TD))
10614 continue;
10615 TagDC->removeDecl(TD);
10616 TD->setDeclContext(NewFD);
10617 NewFD->addDecl(TD);
10618
10619 // Preserve the lexical DeclContext if it is not the surrounding tag
10620 // injection context of the FD. In this example, the semantic context of
10621 // E will be f and the lexical context will be S, while both the
10622 // semantic and lexical contexts of S will be f:
10623 // void f(struct S { enum E { a } f; } s);
10624 if (TagDC != PrototypeTagContext)
10625 TD->setLexicalDeclContext(TagDC);
10626 }
10627 }
10628 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10629 // When we're declaring a function with a typedef, typeof, etc as in the
10630 // following example, we'll need to synthesize (unnamed)
10631 // parameters for use in the declaration.
10632 //
10633 // @code
10634 // typedef void fn(int);
10635 // fn f;
10636 // @endcode
10637
10638 // Synthesize a parameter for each argument type.
10639 for (const auto &AI : FT->param_types()) {
10640 ParmVarDecl *Param =
10642 Param->setScopeInfo(0, Params.size());
10643 Params.push_back(Param);
10644 }
10645 } else {
10646 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10647 "Should not need args for typedef of non-prototype fn");
10648 }
10649
10650 // Finally, we know we have the right number of parameters, install them.
10651 NewFD->setParams(Params);
10652
10653 // If this declarator is a declaration and not a definition, its parameters
10654 // will not be pushed onto a scope chain. That means we will not issue any
10655 // reserved identifier warnings for the declaration, but we will for the
10656 // definition. Handle those here.
10657 if (!D.isFunctionDefinition()) {
10658 for (const ParmVarDecl *PVD : Params)
10660 }
10661
10663 NewFD->addAttr(
10664 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10665
10666 // Functions returning a variably modified type violate C99 6.7.5.2p2
10667 // because all functions have linkage.
10668 if (!NewFD->isInvalidDecl() &&
10670 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10671 NewFD->setInvalidDecl();
10672 }
10673
10674 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10676 !NewFD->hasAttr<SectionAttr>())
10677 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10678 Context, PragmaClangTextSection.SectionName,
10679 PragmaClangTextSection.PragmaLocation));
10680
10681 // Apply an implicit SectionAttr if #pragma code_seg is active.
10682 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10683 !NewFD->hasAttr<SectionAttr>()) {
10684 NewFD->addAttr(SectionAttr::CreateImplicit(
10685 Context, CodeSegStack.CurrentValue->getString(),
10686 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10687 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10690 NewFD))
10691 NewFD->dropAttr<SectionAttr>();
10692 }
10693
10694 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10695 // active.
10696 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10697 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10698 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10699 Context, PragmaClangTextSection.PragmaLocation));
10700
10701 // Apply an implicit CodeSegAttr from class declspec or
10702 // apply an implicit SectionAttr from #pragma code_seg if active.
10703 if (!NewFD->hasAttr<CodeSegAttr>()) {
10705 D.isFunctionDefinition())) {
10706 NewFD->addAttr(SAttr);
10707 }
10708 }
10709
10710 // Handle attributes.
10711 ProcessDeclAttributes(S, NewFD, D);
10712 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10713 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10714 !NewTVA->isDefaultVersion() &&
10715 !Context.getTargetInfo().hasFeature("fmv")) {
10716 // Don't add to scope fmv functions declarations if fmv disabled
10717 AddToScope = false;
10718 return NewFD;
10719 }
10720
10721 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10722 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10723 // type.
10724 //
10725 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10726 // type declaration will generate a compilation error.
10727 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10728 if (AddressSpace != LangAS::Default) {
10729 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10730 NewFD->setInvalidDecl();
10731 }
10732 }
10733
10734 if (!getLangOpts().CPlusPlus) {
10735 // Perform semantic checking on the function declaration.
10736 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10737 CheckMain(NewFD, D.getDeclSpec());
10738
10739 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10740 CheckMSVCRTEntryPoint(NewFD);
10741
10742 if (!NewFD->isInvalidDecl())
10744 isMemberSpecialization,
10746 else if (!Previous.empty())
10747 // Recover gracefully from an invalid redeclaration.
10748 D.setRedeclaration(true);
10749 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10750 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10751 "previous declaration set still overloaded");
10752
10753 // Diagnose no-prototype function declarations with calling conventions that
10754 // don't support variadic calls. Only do this in C and do it after merging
10755 // possibly prototyped redeclarations.
10756 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10758 CallingConv CC = FT->getExtInfo().getCC();
10759 if (!supportsVariadicCall(CC)) {
10760 // Windows system headers sometimes accidentally use stdcall without
10761 // (void) parameters, so we relax this to a warning.
10762 int DiagID =
10763 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10764 Diag(NewFD->getLocation(), DiagID)
10766 }
10767 }
10768
10772 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10774 } else {
10775 // C++11 [replacement.functions]p3:
10776 // The program's definitions shall not be specified as inline.
10777 //
10778 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10779 //
10780 // Suppress the diagnostic if the function is __attribute__((used)), since
10781 // that forces an external definition to be emitted.
10782 if (D.getDeclSpec().isInlineSpecified() &&
10784 !NewFD->hasAttr<UsedAttr>())
10786 diag::ext_operator_new_delete_declared_inline)
10787 << NewFD->getDeclName();
10788
10789 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10790 // C++20 [dcl.decl.general]p4:
10791 // The optional requires-clause in an init-declarator or
10792 // member-declarator shall be present only if the declarator declares a
10793 // templated function.
10794 //
10795 // C++20 [temp.pre]p8:
10796 // An entity is templated if it is
10797 // - a template,
10798 // - an entity defined or created in a templated entity,
10799 // - a member of a templated entity,
10800 // - an enumerator for an enumeration that is a templated entity, or
10801 // - the closure type of a lambda-expression appearing in the
10802 // declaration of a templated entity.
10803 //
10804 // [Note 6: A local class, a local or block variable, or a friend
10805 // function defined in a templated entity is a templated entity.
10806 // — end note]
10807 //
10808 // A templated function is a function template or a function that is
10809 // templated. A templated class is a class template or a class that is
10810 // templated. A templated variable is a variable template or a variable
10811 // that is templated.
10812 if (!FunctionTemplate) {
10813 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10814 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10815 // An explicit specialization shall not have a trailing
10816 // requires-clause unless it declares a function template.
10817 //
10818 // Since a friend function template specialization cannot be
10819 // definition, and since a non-template friend declaration with a
10820 // trailing requires-clause must be a definition, we diagnose
10821 // friend function template specializations with trailing
10822 // requires-clauses on the same path as explicit specializations
10823 // even though they aren't necessarily prohibited by the same
10824 // language rule.
10825 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10826 << isFriend;
10827 } else if (isFriend && NewFD->isTemplated() &&
10828 !D.isFunctionDefinition()) {
10829 // C++ [temp.friend]p9:
10830 // A non-template friend declaration with a requires-clause shall be
10831 // a definition.
10832 Diag(NewFD->getBeginLoc(),
10833 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10834 NewFD->setInvalidDecl();
10835 } else if (!NewFD->isTemplated() ||
10836 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10837 Diag(TRC->getBeginLoc(),
10838 diag::err_constrained_non_templated_function);
10839 }
10840 }
10841 }
10842
10843 // We do not add HD attributes to specializations here because
10844 // they may have different constexpr-ness compared to their
10845 // templates and, after maybeAddHostDeviceAttrs() is applied,
10846 // may end up with different effective targets. Instead, a
10847 // specialization inherits its target attributes from its template
10848 // in the CheckFunctionTemplateSpecialization() call below.
10849 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10851
10852 // Handle explicit specializations of function templates
10853 // and friend function declarations with an explicit
10854 // template argument list.
10855 if (isFunctionTemplateSpecialization) {
10856 bool isDependentSpecialization = false;
10857 if (isFriend) {
10858 // For friend function specializations, this is a dependent
10859 // specialization if its semantic context is dependent, its
10860 // type is dependent, or if its template-id is dependent.
10861 isDependentSpecialization =
10862 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10863 (HasExplicitTemplateArgs &&
10864 TemplateSpecializationType::
10865 anyInstantiationDependentTemplateArguments(
10866 TemplateArgs.arguments()));
10867 assert((!isDependentSpecialization ||
10868 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10869 "dependent friend function specialization without template "
10870 "args");
10871 } else {
10872 // For class-scope explicit specializations of function templates,
10873 // if the lexical context is dependent, then the specialization
10874 // is dependent.
10875 isDependentSpecialization =
10876 CurContext->isRecord() && CurContext->isDependentContext();
10877 }
10878
10879 TemplateArgumentListInfo *ExplicitTemplateArgs =
10880 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10881 if (isDependentSpecialization) {
10882 // If it's a dependent specialization, it may not be possible
10883 // to determine the primary template (for explicit specializations)
10884 // or befriended declaration (for friends) until the enclosing
10885 // template is instantiated. In such cases, we store the declarations
10886 // found by name lookup and defer resolution until instantiation.
10888 NewFD, ExplicitTemplateArgs, Previous))
10889 NewFD->setInvalidDecl();
10890 } else if (!NewFD->isInvalidDecl()) {
10891 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10892 Previous))
10893 NewFD->setInvalidDecl();
10894 }
10895 } else if (isMemberSpecialization && !FunctionTemplate) {
10897 NewFD->setInvalidDecl();
10898 }
10899
10900 // Perform semantic checking on the function declaration.
10901 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10902 CheckMain(NewFD, D.getDeclSpec());
10903
10904 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10905 CheckMSVCRTEntryPoint(NewFD);
10906
10907 if (!NewFD->isInvalidDecl())
10909 isMemberSpecialization,
10911 else if (!Previous.empty())
10912 // Recover gracefully from an invalid redeclaration.
10913 D.setRedeclaration(true);
10914
10915 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10916 !D.isRedeclaration() ||
10917 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10918 "previous declaration set still overloaded");
10919
10920 NamedDecl *PrincipalDecl = (FunctionTemplate
10922 : NewFD);
10923
10924 if (isFriend && NewFD->getPreviousDecl()) {
10925 AccessSpecifier Access = AS_public;
10926 if (!NewFD->isInvalidDecl())
10927 Access = NewFD->getPreviousDecl()->getAccess();
10928
10929 NewFD->setAccess(Access);
10930 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10931 }
10932
10933 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10935 PrincipalDecl->setNonMemberOperator();
10936
10937 // If we have a function template, check the template parameter
10938 // list. This will check and merge default template arguments.
10939 if (FunctionTemplate) {
10940 FunctionTemplateDecl *PrevTemplate =
10941 FunctionTemplate->getPreviousDecl();
10942 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10943 PrevTemplate ? PrevTemplate->getTemplateParameters()
10944 : nullptr,
10949 : (D.getCXXScopeSpec().isSet() &&
10950 DC && DC->isRecord() &&
10951 DC->isDependentContext())
10954 }
10955
10956 if (NewFD->isInvalidDecl()) {
10957 // Ignore all the rest of this.
10958 } else if (!D.isRedeclaration()) {
10959 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10960 AddToScope };
10961 // Fake up an access specifier if it's supposed to be a class member.
10962 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10963 NewFD->setAccess(AS_public);
10964
10965 // Qualified decls generally require a previous declaration.
10966 if (D.getCXXScopeSpec().isSet()) {
10967 // ...with the major exception of templated-scope or
10968 // dependent-scope friend declarations.
10969
10970 // TODO: we currently also suppress this check in dependent
10971 // contexts because (1) the parameter depth will be off when
10972 // matching friend templates and (2) we might actually be
10973 // selecting a friend based on a dependent factor. But there
10974 // are situations where these conditions don't apply and we
10975 // can actually do this check immediately.
10976 //
10977 // Unless the scope is dependent, it's always an error if qualified
10978 // redeclaration lookup found nothing at all. Diagnose that now;
10979 // nothing will diagnose that error later.
10980 if (isFriend &&
10982 (!Previous.empty() && CurContext->isDependentContext()))) {
10983 // ignore these
10984 } else if (NewFD->isCPUDispatchMultiVersion() ||
10985 NewFD->isCPUSpecificMultiVersion()) {
10986 // ignore this, we allow the redeclaration behavior here to create new
10987 // versions of the function.
10988 } else {
10989 // The user tried to provide an out-of-line definition for a
10990 // function that is a member of a class or namespace, but there
10991 // was no such member function declared (C++ [class.mfct]p2,
10992 // C++ [namespace.memdef]p2). For example:
10993 //
10994 // class X {
10995 // void f() const;
10996 // };
10997 //
10998 // void X::f() { } // ill-formed
10999 //
11000 // Complain about this problem, and attempt to suggest close
11001 // matches (e.g., those that differ only in cv-qualifiers and
11002 // whether the parameter types are references).
11003
11005 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
11006 AddToScope = ExtraArgs.AddToScope;
11007 return Result;
11008 }
11009 }
11010
11011 // Unqualified local friend declarations are required to resolve
11012 // to something.
11013 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
11015 *this, Previous, NewFD, ExtraArgs, true, S)) {
11016 AddToScope = ExtraArgs.AddToScope;
11017 return Result;
11018 }
11019 }
11020 } else if (!D.isFunctionDefinition() &&
11021 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
11022 !isFriend && !isFunctionTemplateSpecialization &&
11023 !isMemberSpecialization) {
11024 // An out-of-line member function declaration must also be a
11025 // definition (C++ [class.mfct]p2).
11026 // Note that this is not the case for explicit specializations of
11027 // function templates or member functions of class templates, per
11028 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11029 // extension for compatibility with old SWIG code which likes to
11030 // generate them.
11031 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
11032 << D.getCXXScopeSpec().getRange();
11033 }
11034 }
11035
11036 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11037 // Any top level function could potentially be specified as an entry.
11038 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11039 HLSL().ActOnTopLevelFunction(NewFD);
11040
11041 if (NewFD->hasAttr<HLSLShaderAttr>())
11042 HLSL().CheckEntryPoint(NewFD);
11043 }
11044
11045 // If this is the first declaration of a library builtin function, add
11046 // attributes as appropriate.
11047 if (!D.isRedeclaration()) {
11048 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11049 if (unsigned BuiltinID = II->getBuiltinID()) {
11050 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
11051 if (!InStdNamespace &&
11053 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11054 // Validate the type matches unless this builtin is specified as
11055 // matching regardless of its declared type.
11056 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
11057 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11058 } else {
11060 LookupNecessaryTypesForBuiltin(S, BuiltinID);
11061 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
11062
11063 if (!Error && !BuiltinType.isNull() &&
11064 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11065 NewFD->getType(), BuiltinType))
11066 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11067 }
11068 }
11069 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11070 isStdBuiltin(Context, NewFD, BuiltinID)) {
11071 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11072 }
11073 }
11074 }
11075 }
11076
11077 ProcessPragmaWeak(S, NewFD);
11078 ProcessPragmaExport(NewFD);
11079 checkAttributesAfterMerging(*this, *NewFD);
11080
11082 // The above can add the format attribute for known builtin/library functions
11083 // which is required by the modular_format attribute, thus
11084 // validate modular_format now after those attributes have been added.
11085 checkModularFormatAttr(*this, *NewFD);
11086
11087 if (NewFD->hasAttr<OverloadableAttr>() &&
11088 !NewFD->getType()->getAs<FunctionProtoType>()) {
11089 Diag(NewFD->getLocation(),
11090 diag::err_attribute_overloadable_no_prototype)
11091 << NewFD;
11092 NewFD->dropAttr<OverloadableAttr>();
11093 }
11094
11095 // If there's a #pragma GCC visibility in scope, and this isn't a class
11096 // member, set the visibility of this function.
11097 if (!DC->isRecord() && NewFD->isExternallyVisible())
11099
11100 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11101 // marking the function.
11102 ObjC().AddCFAuditedAttribute(NewFD);
11103
11104 // If this is a function definition, check if we have to apply any
11105 // attributes (i.e. optnone and no_builtin) due to a pragma.
11106 if (D.isFunctionDefinition()) {
11107 AddRangeBasedOptnone(NewFD);
11109 AddSectionMSAllocText(NewFD);
11111 }
11112
11113 // If this is the first declaration of an extern C variable, update
11114 // the map of such variables.
11115 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11116 isIncompleteDeclExternC(*this, NewFD))
11118
11119 // Set this FunctionDecl's range up to the right paren.
11120 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11121
11122 if (D.isRedeclaration() && !Previous.empty()) {
11123 NamedDecl *Prev = Previous.getRepresentativeDecl();
11124 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11125 isMemberSpecialization ||
11126 isFunctionTemplateSpecialization,
11128 }
11129
11130 if (getLangOpts().CUDA) {
11131 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11132 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11134 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11135 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11137 Context.setcudaConfigureCallDecl(NewFD);
11138 }
11139 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&
11140 !NewFD->isInvalidDecl() &&
11142 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11143 Diag(NewFD->getLocation(), diag::err_config_pointer_return)
11145 Context.setcudaGetParameterBufferDecl(NewFD);
11146 }
11147 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&
11148 !NewFD->isInvalidDecl() &&
11150 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11151 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11153 Context.setcudaLaunchDeviceDecl(NewFD);
11154 }
11155 }
11156 }
11157
11159
11160 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11161 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11162 if (SC == SC_Static) {
11163 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11164 D.setInvalidType();
11165 }
11166
11167 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11168 if (!NewFD->getReturnType()->isVoidType()) {
11169 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11170 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11171 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11172 : FixItHint());
11173 D.setInvalidType();
11174 }
11175
11177 for (auto *Param : NewFD->parameters())
11178 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11179
11180 if (getLangOpts().OpenCLCPlusPlus) {
11181 if (DC->isRecord()) {
11182 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11183 D.setInvalidType();
11184 }
11185 if (FunctionTemplate) {
11186 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11187 D.setInvalidType();
11188 }
11189 }
11190 }
11191
11192 if (getLangOpts().CPlusPlus) {
11193 // Precalculate whether this is a friend function template with a constraint
11194 // that depends on an enclosing template, per [temp.friend]p9.
11195 if (isFriend && FunctionTemplate &&
11198
11199 // C++ [temp.friend]p9:
11200 // A friend function template with a constraint that depends on a
11201 // template parameter from an enclosing template shall be a definition.
11202 if (!D.isFunctionDefinition()) {
11203 Diag(NewFD->getBeginLoc(),
11204 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11205 NewFD->setInvalidDecl();
11206 }
11207 }
11208
11209 if (FunctionTemplate) {
11210 if (NewFD->isInvalidDecl())
11211 FunctionTemplate->setInvalidDecl();
11212 return FunctionTemplate;
11213 }
11214
11215 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11217 }
11218
11219 for (const ParmVarDecl *Param : NewFD->parameters()) {
11220 QualType PT = Param->getType();
11221
11222 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11223 // types.
11224 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11225 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11226 QualType ElemTy = PipeTy->getElementType();
11227 if (ElemTy->isPointerOrReferenceType()) {
11228 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11229 D.setInvalidType();
11230 }
11231 }
11232 }
11233 // WebAssembly tables can't be used as function parameters.
11234 if (Context.getTargetInfo().getTriple().isWasm()) {
11236 Diag(Param->getTypeSpecStartLoc(),
11237 diag::err_wasm_table_as_function_parameter);
11238 D.setInvalidType();
11239 }
11240 }
11241 }
11242
11243 // Diagnose availability attributes. Availability cannot be used on functions
11244 // that are run during load/unload.
11245 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11246 if (NewFD->hasAttr<ConstructorAttr>()) {
11247 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11248 << 1;
11249 NewFD->dropAttr<AvailabilityAttr>();
11250 }
11251 if (NewFD->hasAttr<DestructorAttr>()) {
11252 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11253 << 2;
11254 NewFD->dropAttr<AvailabilityAttr>();
11255 }
11256 }
11257
11258 // Diagnose no_builtin attribute on function declaration that are not a
11259 // definition.
11260 // FIXME: We should really be doing this in
11261 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11262 // the FunctionDecl and at this point of the code
11263 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11264 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11265 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11266 switch (D.getFunctionDefinitionKind()) {
11269 Diag(NBA->getLocation(),
11270 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11271 << NBA->getSpelling();
11272 break;
11274 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11275 << NBA->getSpelling();
11276 break;
11278 break;
11279 }
11280
11281 // Similar to no_builtin logic above, at this point of the code
11282 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11283 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11284 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11285 !NewFD->isInvalidDecl() &&
11287 ExternalDeclarations.push_back(NewFD);
11288
11289 // Used for a warning on the 'next' declaration when used with a
11290 // `routine(name)`.
11291 if (getLangOpts().OpenACC)
11293
11294 return NewFD;
11295}
11296
11297/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11298/// when __declspec(code_seg) "is applied to a class, all member functions of
11299/// the class and nested classes -- this includes compiler-generated special
11300/// member functions -- are put in the specified segment."
11301/// The actual behavior is a little more complicated. The Microsoft compiler
11302/// won't check outer classes if there is an active value from #pragma code_seg.
11303/// The CodeSeg is always applied from the direct parent but only from outer
11304/// classes when the #pragma code_seg stack is empty. See:
11305/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11306/// available since MS has removed the page.
11308 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11309 if (!Method)
11310 return nullptr;
11311 const CXXRecordDecl *Parent = Method->getParent();
11312 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11313 Attr *NewAttr = SAttr->clone(S.getASTContext());
11314 NewAttr->setImplicit(true);
11315 return NewAttr;
11316 }
11317
11318 // The Microsoft compiler won't check outer classes for the CodeSeg
11319 // when the #pragma code_seg stack is active.
11320 if (S.CodeSegStack.CurrentValue)
11321 return nullptr;
11322
11323 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11324 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11325 Attr *NewAttr = SAttr->clone(S.getASTContext());
11326 NewAttr->setImplicit(true);
11327 return NewAttr;
11328 }
11329 }
11330 return nullptr;
11331}
11332
11334 bool IsDefinition) {
11335 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11336 return A;
11337 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11338 CodeSegStack.CurrentValue)
11339 return SectionAttr::CreateImplicit(
11340 getASTContext(), CodeSegStack.CurrentValue->getString(),
11341 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11342 return nullptr;
11343}
11344
11346 QualType NewT, QualType OldT) {
11348 return true;
11349
11350 // For dependently-typed local extern declarations and friends, we can't
11351 // perform a correct type check in general until instantiation:
11352 //
11353 // int f();
11354 // template<typename T> void g() { T f(); }
11355 //
11356 // (valid if g() is only instantiated with T = int).
11357 if (NewT->isDependentType() &&
11358 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11359 return false;
11360
11361 // Similarly, if the previous declaration was a dependent local extern
11362 // declaration, we don't really know its type yet.
11363 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11364 return false;
11365
11366 return true;
11367}
11368
11371 return true;
11372
11373 // Don't chain dependent friend function definitions until instantiation, to
11374 // permit cases like
11375 //
11376 // void func();
11377 // template<typename T> class C1 { friend void func() {} };
11378 // template<typename T> class C2 { friend void func() {} };
11379 //
11380 // ... which is valid if only one of C1 and C2 is ever instantiated.
11381 //
11382 // FIXME: This need only apply to function definitions. For now, we proxy
11383 // this by checking for a file-scope function. We do not want this to apply
11384 // to friend declarations nominating member functions, because that gets in
11385 // the way of access checks.
11387 return false;
11388
11389 auto *VD = dyn_cast<ValueDecl>(D);
11390 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11391 return !VD || !PrevVD ||
11392 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11393 PrevVD->getType());
11394}
11395
11396/// Check the target or target_version attribute of the function for
11397/// MultiVersion validity.
11398///
11399/// Returns true if there was an error, false otherwise.
11400static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11401 const auto *TA = FD->getAttr<TargetAttr>();
11402 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11403
11404 assert((TA || TVA) && "Expecting target or target_version attribute");
11405
11407 enum ErrType { Feature = 0, Architecture = 1 };
11408
11409 if (TA) {
11410 ParsedTargetAttr ParseInfo =
11411 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11412 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11413 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11414 << Architecture << ParseInfo.CPU;
11415 return true;
11416 }
11417 for (const auto &Feat : ParseInfo.Features) {
11418 auto BareFeat = StringRef{Feat}.substr(1);
11419 if (Feat[0] == '-') {
11420 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11421 << Feature << ("no-" + BareFeat);
11422 return true;
11423 }
11424
11425 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11426 !TargetInfo.isValidFeatureName(BareFeat) ||
11427 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11428 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11429 << Feature << BareFeat;
11430 return true;
11431 }
11432 }
11433 }
11434
11435 if (TVA) {
11437 ParsedTargetAttr ParseInfo;
11438 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11439 ParseInfo =
11440 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11441 for (auto &Feat : ParseInfo.Features)
11442 Feats.push_back(StringRef{Feat}.substr(1));
11443 } else {
11444 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11445 TVA->getFeatures(Feats);
11446 }
11447 for (const auto &Feat : Feats) {
11448 if (!TargetInfo.validateCpuSupports(Feat)) {
11449 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11450 << Feature << Feat;
11451 return true;
11452 }
11453 }
11454 }
11455 return false;
11456}
11457
11458// Provide a white-list of attributes that are allowed to be combined with
11459// multiversion functions.
11461 MultiVersionKind MVKind) {
11462 // Note: this list/diagnosis must match the list in
11463 // checkMultiversionAttributesAllSame.
11464 switch (Kind) {
11465 default:
11466 return false;
11467 case attr::ArmLocallyStreaming:
11468 return MVKind == MultiVersionKind::TargetVersion ||
11470 case attr::Used:
11471 return MVKind == MultiVersionKind::Target;
11472 case attr::NonNull:
11473 case attr::NoThrow:
11474 return true;
11475 }
11476}
11477
11479 const FunctionDecl *FD,
11480 const FunctionDecl *CausedFD,
11481 MultiVersionKind MVKind) {
11482 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11483 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11484 << static_cast<unsigned>(MVKind) << A;
11485 if (CausedFD)
11486 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11487 return true;
11488 };
11489
11490 for (const Attr *A : FD->attrs()) {
11491 switch (A->getKind()) {
11492 case attr::CPUDispatch:
11493 case attr::CPUSpecific:
11494 if (MVKind != MultiVersionKind::CPUDispatch &&
11496 return Diagnose(S, A);
11497 break;
11498 case attr::Target:
11499 if (MVKind != MultiVersionKind::Target)
11500 return Diagnose(S, A);
11501 break;
11502 case attr::TargetVersion:
11503 if (MVKind != MultiVersionKind::TargetVersion &&
11505 return Diagnose(S, A);
11506 break;
11507 case attr::TargetClones:
11508 if (MVKind != MultiVersionKind::TargetClones &&
11510 return Diagnose(S, A);
11511 break;
11512 default:
11513 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11514 return Diagnose(S, A);
11515 break;
11516 }
11517 }
11518 return false;
11519}
11520
11522 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11523 const PartialDiagnostic &NoProtoDiagID,
11524 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11525 const PartialDiagnosticAt &NoSupportDiagIDAt,
11526 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11527 bool ConstexprSupported, bool CLinkageMayDiffer) {
11528 enum DoesntSupport {
11529 FuncTemplates = 0,
11530 VirtFuncs = 1,
11531 DeducedReturn = 2,
11532 Constructors = 3,
11533 Destructors = 4,
11534 DeletedFuncs = 5,
11535 DefaultedFuncs = 6,
11536 ConstexprFuncs = 7,
11537 ConstevalFuncs = 8,
11538 Lambda = 9,
11539 };
11540 enum Different {
11541 CallingConv = 0,
11542 ReturnType = 1,
11543 ConstexprSpec = 2,
11544 InlineSpec = 3,
11545 Linkage = 4,
11546 LanguageLinkage = 5,
11547 };
11548
11549 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11550 !OldFD->getType()->getAs<FunctionProtoType>()) {
11551 Diag(OldFD->getLocation(), NoProtoDiagID);
11552 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11553 return true;
11554 }
11555
11556 if (NoProtoDiagID.getDiagID() != 0 &&
11557 !NewFD->getType()->getAs<FunctionProtoType>())
11558 return Diag(NewFD->getLocation(), NoProtoDiagID);
11559
11560 if (!TemplatesSupported &&
11562 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11563 << FuncTemplates;
11564
11565 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11566 if (NewCXXFD->isVirtual())
11567 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11568 << VirtFuncs;
11569
11570 if (isa<CXXConstructorDecl>(NewCXXFD))
11571 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11572 << Constructors;
11573
11574 if (isa<CXXDestructorDecl>(NewCXXFD))
11575 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11576 << Destructors;
11577 }
11578
11579 if (NewFD->isDeleted())
11580 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11581 << DeletedFuncs;
11582
11583 if (NewFD->isDefaulted())
11584 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11585 << DefaultedFuncs;
11586
11587 if (!ConstexprSupported && NewFD->isConstexpr())
11588 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11589 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11590
11591 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11592 const auto *NewType = cast<FunctionType>(NewQType);
11593 QualType NewReturnType = NewType->getReturnType();
11594
11595 if (NewReturnType->isUndeducedType())
11596 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11597 << DeducedReturn;
11598
11599 // Ensure the return type is identical.
11600 if (OldFD) {
11601 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11602 const auto *OldType = cast<FunctionType>(OldQType);
11603 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11604 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11605
11606 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11607 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11608
11609 bool ArmStreamingCCMismatched = false;
11610 if (OldFPT && NewFPT) {
11611 unsigned Diff =
11612 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11613 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11614 // cannot be mixed.
11617 ArmStreamingCCMismatched = true;
11618 }
11619
11620 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11621 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11622
11623 QualType OldReturnType = OldType->getReturnType();
11624
11625 if (OldReturnType != NewReturnType)
11626 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11627
11628 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11629 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11630
11631 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11632 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11633
11634 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11635 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11636
11637 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11638 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11639
11640 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11641 NewFD->getLocation()))
11642 return true;
11643 }
11644 return false;
11645}
11646
11648 const FunctionDecl *NewFD,
11649 bool CausesMV,
11650 MultiVersionKind MVKind) {
11652 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11653 if (OldFD)
11654 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11655 return true;
11656 }
11657
11658 bool IsCPUSpecificCPUDispatchMVKind =
11661
11662 if (CausesMV && OldFD &&
11663 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11664 return true;
11665
11666 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11667 return true;
11668
11669 // Only allow transition to MultiVersion if it hasn't been used.
11670 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11671 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11672 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11673 return true;
11674 }
11675
11677 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11679 S.PDiag(diag::note_multiversioning_caused_here)),
11681 S.PDiag(diag::err_multiversion_doesnt_support)
11682 << static_cast<unsigned>(MVKind)),
11684 S.PDiag(diag::err_multiversion_diff)),
11685 /*TemplatesSupported=*/false,
11686 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11687 /*CLinkageMayDiffer=*/false);
11688}
11689
11690/// Check the validity of a multiversion function declaration that is the
11691/// first of its kind. Also sets the multiversion'ness' of the function itself.
11692///
11693/// This sets NewFD->isInvalidDecl() to true if there was an error.
11694///
11695/// Returns true if there was an error, false otherwise.
11698 assert(MVKind != MultiVersionKind::None &&
11699 "Function lacks multiversion attribute");
11700 const auto *TA = FD->getAttr<TargetAttr>();
11701 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11702 // The target attribute only causes MV if this declaration is the default,
11703 // otherwise it is treated as a normal function.
11704 if (TA && !TA->isDefaultVersion())
11705 return false;
11706
11707 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11708 FD->setInvalidDecl();
11709 return true;
11710 }
11711
11712 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11713 FD->setInvalidDecl();
11714 return true;
11715 }
11716
11717 FD->setIsMultiVersion();
11718 return false;
11719}
11720
11722 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11724 return true;
11725 }
11726
11727 return false;
11728}
11729
11731 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11732 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11733 return;
11734
11735 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11736 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11737
11738 if (MVKindTo == MultiVersionKind::None &&
11739 (MVKindFrom == MultiVersionKind::TargetVersion ||
11740 MVKindFrom == MultiVersionKind::TargetClones))
11741 To->addAttr(TargetVersionAttr::CreateImplicit(
11742 To->getASTContext(), "default", To->getSourceRange()));
11743}
11744
11746 FunctionDecl *NewFD,
11747 bool &Redeclaration,
11748 NamedDecl *&OldDecl,
11750 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11751
11752 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11753 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11754 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11755 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11756
11757 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11758
11759 // The definitions should be allowed in any order. If we have discovered
11760 // a new target version and the preceeding was the default, then add the
11761 // corresponding attribute to it.
11762 patchDefaultTargetVersion(NewFD, OldFD);
11763
11764 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11765 // to change, this is a simple redeclaration.
11766 if (NewTA && !NewTA->isDefaultVersion() &&
11767 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11768 return false;
11769
11770 // Otherwise, this decl causes MultiVersioning.
11771 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11774 NewFD->setInvalidDecl();
11775 return true;
11776 }
11777
11778 if (CheckMultiVersionValue(S, NewFD)) {
11779 NewFD->setInvalidDecl();
11780 return true;
11781 }
11782
11783 // If this is 'default', permit the forward declaration.
11784 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11785 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11786 Redeclaration = true;
11787 OldDecl = OldFD;
11788 OldFD->setIsMultiVersion();
11789 NewFD->setIsMultiVersion();
11790 return false;
11791 }
11792
11793 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11794 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11795 NewFD->setInvalidDecl();
11796 return true;
11797 }
11798
11799 if (NewTA) {
11800 ParsedTargetAttr OldParsed =
11802 OldTA->getFeaturesStr());
11803 llvm::sort(OldParsed.Features);
11804 ParsedTargetAttr NewParsed =
11806 NewTA->getFeaturesStr());
11807 // Sort order doesn't matter, it just needs to be consistent.
11808 llvm::sort(NewParsed.Features);
11809 if (OldParsed == NewParsed) {
11810 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11811 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11812 NewFD->setInvalidDecl();
11813 return true;
11814 }
11815 }
11816
11817 for (const auto *FD : OldFD->redecls()) {
11818 const auto *CurTA = FD->getAttr<TargetAttr>();
11819 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11820 // We allow forward declarations before ANY multiversioning attributes, but
11821 // nothing after the fact.
11823 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11824 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11825 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11826 << (NewTA ? 0 : 2);
11827 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11828 NewFD->setInvalidDecl();
11829 return true;
11830 }
11831 }
11832
11833 OldFD->setIsMultiVersion();
11834 NewFD->setIsMultiVersion();
11835 Redeclaration = false;
11836 OldDecl = nullptr;
11837 Previous.clear();
11838 return false;
11839}
11840
11842 MultiVersionKind OldKind = Old->getMultiVersionKind();
11843 MultiVersionKind NewKind = New->getMultiVersionKind();
11844
11845 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11846 NewKind == MultiVersionKind::None)
11847 return true;
11848
11849 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11850 switch (OldKind) {
11852 return NewKind == MultiVersionKind::TargetClones;
11854 return NewKind == MultiVersionKind::TargetVersion;
11855 default:
11856 return false;
11857 }
11858 } else {
11859 switch (OldKind) {
11861 return NewKind == MultiVersionKind::CPUSpecific;
11863 return NewKind == MultiVersionKind::CPUDispatch;
11864 default:
11865 return false;
11866 }
11867 }
11868}
11869
11870/// Check the validity of a new function declaration being added to an existing
11871/// multiversioned declaration collection.
11873 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11874 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11875 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11877
11878 // Disallow mixing of multiversioning types.
11879 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11880 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11881 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11882 NewFD->setInvalidDecl();
11883 return true;
11884 }
11885
11886 // Add the default target_version attribute if it's missing.
11887 patchDefaultTargetVersion(OldFD, NewFD);
11888 patchDefaultTargetVersion(NewFD, OldFD);
11889
11890 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11891 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11892 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11893 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11894
11895 ParsedTargetAttr NewParsed;
11896 if (NewTA) {
11898 NewTA->getFeaturesStr());
11899 llvm::sort(NewParsed.Features);
11900 }
11902 if (NewTVA) {
11903 NewTVA->getFeatures(NewFeats);
11904 llvm::sort(NewFeats);
11905 }
11906
11907 bool UseMemberUsingDeclRules =
11908 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11909
11910 bool MayNeedOverloadableChecks =
11912
11913 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11914 // of a previous member of the MultiVersion set.
11915 for (NamedDecl *ND : Previous) {
11916 FunctionDecl *CurFD = ND->getAsFunction();
11917 if (!CurFD || CurFD->isInvalidDecl())
11918 continue;
11919 if (MayNeedOverloadableChecks &&
11920 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11921 continue;
11922
11923 switch (NewMVKind) {
11925 assert(OldMVKind == MultiVersionKind::TargetClones &&
11926 "Only target_clones can be omitted in subsequent declarations");
11927 break;
11929 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11930 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11931 NewFD->setIsMultiVersion();
11932 Redeclaration = true;
11933 OldDecl = ND;
11934 return false;
11935 }
11936
11937 ParsedTargetAttr CurParsed =
11939 CurTA->getFeaturesStr());
11940 llvm::sort(CurParsed.Features);
11941 if (CurParsed == NewParsed) {
11942 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11943 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11944 NewFD->setInvalidDecl();
11945 return true;
11946 }
11947 break;
11948 }
11950 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11951 if (CurTVA->getName() == NewTVA->getName()) {
11952 NewFD->setIsMultiVersion();
11953 Redeclaration = true;
11954 OldDecl = ND;
11955 return false;
11956 }
11958 CurTVA->getFeatures(CurFeats);
11959 llvm::sort(CurFeats);
11960
11961 if (CurFeats == NewFeats) {
11962 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11963 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11964 NewFD->setInvalidDecl();
11965 return true;
11966 }
11967 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11968 // Default
11969 if (NewFeats.empty())
11970 break;
11971
11972 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11974 CurClones->getFeatures(CurFeats, I);
11975 llvm::sort(CurFeats);
11976
11977 if (CurFeats == NewFeats) {
11978 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11979 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11980 NewFD->setInvalidDecl();
11981 return true;
11982 }
11983 }
11984 }
11985 break;
11986 }
11988 assert(NewClones && "MultiVersionKind does not match attribute type");
11989 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11990 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11991 !std::equal(CurClones->featuresStrs_begin(),
11992 CurClones->featuresStrs_end(),
11993 NewClones->featuresStrs_begin())) {
11994 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11995 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11996 NewFD->setInvalidDecl();
11997 return true;
11998 }
11999 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12001 CurTVA->getFeatures(CurFeats);
12002 llvm::sort(CurFeats);
12003
12004 // Default
12005 if (CurFeats.empty())
12006 break;
12007
12008 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12009 NewFeats.clear();
12010 NewClones->getFeatures(NewFeats, I);
12011 llvm::sort(NewFeats);
12012
12013 if (CurFeats == NewFeats) {
12014 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12015 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12016 NewFD->setInvalidDecl();
12017 return true;
12018 }
12019 }
12020 break;
12021 }
12022 Redeclaration = true;
12023 OldDecl = CurFD;
12024 NewFD->setIsMultiVersion();
12025 return false;
12026 }
12029 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12030 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12031 // Handle CPUDispatch/CPUSpecific versions.
12032 // Only 1 CPUDispatch function is allowed, this will make it go through
12033 // the redeclaration errors.
12034 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12035 CurFD->hasAttr<CPUDispatchAttr>()) {
12036 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12037 std::equal(
12038 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
12039 NewCPUDisp->cpus_begin(),
12040 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12041 return Cur->getName() == New->getName();
12042 })) {
12043 NewFD->setIsMultiVersion();
12044 Redeclaration = true;
12045 OldDecl = ND;
12046 return false;
12047 }
12048
12049 // If the declarations don't match, this is an error condition.
12050 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
12051 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12052 NewFD->setInvalidDecl();
12053 return true;
12054 }
12055 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12056 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12057 std::equal(
12058 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
12059 NewCPUSpec->cpus_begin(),
12060 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12061 return Cur->getName() == New->getName();
12062 })) {
12063 NewFD->setIsMultiVersion();
12064 Redeclaration = true;
12065 OldDecl = ND;
12066 return false;
12067 }
12068
12069 // Only 1 version of CPUSpecific is allowed for each CPU.
12070 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12071 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12072 if (CurII == NewII) {
12073 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
12074 << NewII;
12075 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12076 NewFD->setInvalidDecl();
12077 return true;
12078 }
12079 }
12080 }
12081 }
12082 break;
12083 }
12084 }
12085 }
12086
12087 // Redeclarations of a target_clones function may omit the attribute, in which
12088 // case it will be inherited during declaration merging.
12089 if (NewMVKind == MultiVersionKind::None &&
12090 OldMVKind == MultiVersionKind::TargetClones) {
12091 NewFD->setIsMultiVersion();
12092 Redeclaration = true;
12093 OldDecl = OldFD;
12094 return false;
12095 }
12096
12097 // Else, this is simply a non-redecl case. Checking the 'value' is only
12098 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12099 // handled in the attribute adding step.
12100 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
12101 NewFD->setInvalidDecl();
12102 return true;
12103 }
12104
12105 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12106 !OldFD->isMultiVersion(), NewMVKind)) {
12107 NewFD->setInvalidDecl();
12108 return true;
12109 }
12110
12111 // Permit forward declarations in the case where these two are compatible.
12112 if (!OldFD->isMultiVersion()) {
12113 OldFD->setIsMultiVersion();
12114 NewFD->setIsMultiVersion();
12115 Redeclaration = true;
12116 OldDecl = OldFD;
12117 return false;
12118 }
12119
12120 NewFD->setIsMultiVersion();
12121 Redeclaration = false;
12122 OldDecl = nullptr;
12123 Previous.clear();
12124 return false;
12125}
12126
12127/// Check the validity of a mulitversion function declaration.
12128/// Also sets the multiversion'ness' of the function itself.
12129///
12130/// This sets NewFD->isInvalidDecl() to true if there was an error.
12131///
12132/// Returns true if there was an error, false otherwise.
12134 bool &Redeclaration, NamedDecl *&OldDecl,
12136 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12137
12138 // Check if FMV is disabled.
12139 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12140 return false;
12141
12142 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12143 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12144 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12145 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12146 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12147 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12148
12149 // Main isn't allowed to become a multiversion function, however it IS
12150 // permitted to have 'main' be marked with the 'target' optimization hint,
12151 // for 'target_version' only default is allowed.
12152 if (NewFD->isMain()) {
12153 if (MVKind != MultiVersionKind::None &&
12154 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12155 !(MVKind == MultiVersionKind::TargetVersion &&
12156 NewTVA->isDefaultVersion())) {
12157 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12158 NewFD->setInvalidDecl();
12159 return true;
12160 }
12161 return false;
12162 }
12163
12164 // Target attribute on AArch64 is not used for multiversioning
12165 if (NewTA && TI.getTriple().isAArch64())
12166 return false;
12167
12168 // Target attribute on RISCV is not used for multiversioning
12169 if (NewTA && TI.getTriple().isRISCV())
12170 return false;
12171
12172 if (!OldDecl || !OldDecl->getAsFunction() ||
12173 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12174 NewFD->getDeclContext()->getRedeclContext())) {
12175 // If there's no previous declaration, AND this isn't attempting to cause
12176 // multiversioning, this isn't an error condition.
12177 if (MVKind == MultiVersionKind::None)
12178 return false;
12179 return CheckMultiVersionFirstFunction(S, NewFD);
12180 }
12181
12182 FunctionDecl *OldFD = OldDecl->getAsFunction();
12183
12184 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12185 return false;
12186
12187 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12188 // for target_clones and target_version.
12189 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12192 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12194 NewFD->setInvalidDecl();
12195 return true;
12196 }
12197
12198 if (!OldFD->isMultiVersion()) {
12199 switch (MVKind) {
12203 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12205 if (OldFD->isUsed(false)) {
12206 NewFD->setInvalidDecl();
12207 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12208 }
12209 OldFD->setIsMultiVersion();
12210 break;
12211
12215 break;
12216 }
12217 }
12218
12219 // At this point, we have a multiversion function decl (in OldFD) AND an
12220 // appropriate attribute in the current function decl (unless it's allowed to
12221 // omit the attribute). Resolve that these are still compatible with previous
12222 // declarations.
12223 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12224 NewCPUSpec, NewClones, Redeclaration,
12225 OldDecl, Previous);
12226}
12227
12229 bool IsPure = NewFD->hasAttr<PureAttr>();
12230 bool IsConst = NewFD->hasAttr<ConstAttr>();
12231
12232 // If there are no pure or const attributes, there's nothing to check.
12233 if (!IsPure && !IsConst)
12234 return;
12235
12236 // If the function is marked both pure and const, we retain the const
12237 // attribute because it makes stronger guarantees than the pure attribute, and
12238 // we drop the pure attribute explicitly to prevent later confusion about
12239 // semantics.
12240 if (IsPure && IsConst) {
12241 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12242 NewFD->dropAttrs<PureAttr>();
12243 }
12244
12245 // Constructors and destructors are functions which return void, so are
12246 // handled here as well.
12247 if (NewFD->getReturnType()->isVoidType()) {
12248 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12249 << IsConst;
12250 NewFD->dropAttrs<PureAttr, ConstAttr>();
12251 }
12252}
12253
12256 bool IsMemberSpecialization,
12257 bool DeclIsDefn) {
12258 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12259 "Variably modified return types are not handled here");
12260
12261 // Determine whether the type of this function should be merged with
12262 // a previous visible declaration. This never happens for functions in C++,
12263 // and always happens in C if the previous declaration was visible.
12264 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12265 !Previous.isShadowed();
12266
12267 bool Redeclaration = false;
12268 NamedDecl *OldDecl = nullptr;
12269 bool MayNeedOverloadableChecks = false;
12270
12272 // Merge or overload the declaration with an existing declaration of
12273 // the same name, if appropriate.
12274 if (!Previous.empty()) {
12275 // Determine whether NewFD is an overload of PrevDecl or
12276 // a declaration that requires merging. If it's an overload,
12277 // there's no more work to do here; we'll just add the new
12278 // function to the scope.
12280 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12281 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12282 Redeclaration = true;
12283 OldDecl = Candidate;
12284 }
12285 } else {
12286 MayNeedOverloadableChecks = true;
12287 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12288 /*NewIsUsingDecl*/ false)) {
12290 Redeclaration = true;
12291 break;
12292
12294 Redeclaration = true;
12295 break;
12296
12298 Redeclaration = false;
12299 break;
12300 }
12301 }
12302 }
12303
12304 // Check for a previous extern "C" declaration with this name.
12305 if (!Redeclaration &&
12307 if (!Previous.empty()) {
12308 // This is an extern "C" declaration with the same name as a previous
12309 // declaration, and thus redeclares that entity...
12310 Redeclaration = true;
12311 OldDecl = Previous.getFoundDecl();
12312 MergeTypeWithPrevious = false;
12313
12314 // ... except in the presence of __attribute__((overloadable)).
12315 if (OldDecl->hasAttr<OverloadableAttr>() ||
12316 NewFD->hasAttr<OverloadableAttr>()) {
12317 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12318 MayNeedOverloadableChecks = true;
12319 Redeclaration = false;
12320 OldDecl = nullptr;
12321 }
12322 }
12323 }
12324 }
12325
12326 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12327 return Redeclaration;
12328
12329 // PPC MMA non-pointer types are not allowed as function return types.
12330 if (Context.getTargetInfo().getTriple().isPPC64() &&
12331 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12332 NewFD->setInvalidDecl();
12333 }
12334
12335 CheckConstPureAttributesUsage(*this, NewFD);
12336
12337 // C++ [dcl.spec.auto.general]p12:
12338 // Return type deduction for a templated function with a placeholder in its
12339 // declared type occurs when the definition is instantiated even if the
12340 // function body contains a return statement with a non-type-dependent
12341 // operand.
12342 //
12343 // C++ [temp.dep.expr]p3:
12344 // An id-expression is type-dependent if it is a template-id that is not a
12345 // concept-id and is dependent; or if its terminal name is:
12346 // - [...]
12347 // - associated by name lookup with one or more declarations of member
12348 // functions of a class that is the current instantiation declared with a
12349 // return type that contains a placeholder type,
12350 // - [...]
12351 //
12352 // If this is a templated function with a placeholder in its return type,
12353 // make the placeholder type dependent since it won't be deduced until the
12354 // definition is instantiated. We do this here because it needs to happen
12355 // for implicitly instantiated member functions/member function templates.
12356 if (getLangOpts().CPlusPlus14 &&
12357 (NewFD->isDependentContext() &&
12358 NewFD->getReturnType()->isUndeducedType())) {
12359 const FunctionProtoType *FPT =
12360 NewFD->getType()->castAs<FunctionProtoType>();
12361 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12362 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12363 FPT->getExtProtoInfo()));
12364 }
12365
12366 // C++11 [dcl.constexpr]p8:
12367 // A constexpr specifier for a non-static member function that is not
12368 // a constructor declares that member function to be const.
12369 //
12370 // This needs to be delayed until we know whether this is an out-of-line
12371 // definition of a static member function.
12372 //
12373 // This rule is not present in C++1y, so we produce a backwards
12374 // compatibility warning whenever it happens in C++11.
12375 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12376 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12377 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12379 CXXMethodDecl *OldMD = nullptr;
12380 if (OldDecl)
12381 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12382 if (!OldMD || !OldMD->isStatic()) {
12383 const FunctionProtoType *FPT =
12386 EPI.TypeQuals.addConst();
12387 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12388 FPT->getParamTypes(), EPI));
12389
12390 // Warn that we did this, if we're not performing template instantiation.
12391 // In that case, we'll have warned already when the template was defined.
12392 if (!inTemplateInstantiation()) {
12393 SourceLocation AddConstLoc;
12396 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12397
12398 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12399 << FixItHint::CreateInsertion(AddConstLoc, " const");
12400 }
12401 }
12402 }
12403
12404 if (Redeclaration) {
12405 // NewFD and OldDecl represent declarations that need to be
12406 // merged.
12407 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12408 DeclIsDefn)) {
12409 NewFD->setInvalidDecl();
12410 return Redeclaration;
12411 }
12412
12413 Previous.clear();
12414 Previous.addDecl(OldDecl);
12415
12416 if (FunctionTemplateDecl *OldTemplateDecl =
12417 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12418 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12419 FunctionTemplateDecl *NewTemplateDecl
12421 assert(NewTemplateDecl && "Template/non-template mismatch");
12422
12423 // The call to MergeFunctionDecl above may have created some state in
12424 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12425 // can add it as a redeclaration.
12426 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12427
12428 NewFD->setPreviousDeclaration(OldFD);
12429 if (NewFD->isCXXClassMember()) {
12430 NewFD->setAccess(OldTemplateDecl->getAccess());
12431 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12432 }
12433
12434 // If this is an explicit specialization of a member that is a function
12435 // template, mark it as a member specialization.
12436 if (IsMemberSpecialization &&
12437 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12438 NewTemplateDecl->setMemberSpecialization();
12439 assert(OldTemplateDecl->isMemberSpecialization());
12440 // Explicit specializations of a member template do not inherit deleted
12441 // status from the parent member template that they are specializing.
12442 if (OldFD->isDeleted()) {
12443 // FIXME: This assert will not hold in the presence of modules.
12444 assert(OldFD->getCanonicalDecl() == OldFD);
12445 // FIXME: We need an update record for this AST mutation.
12446 OldFD->setDeletedAsWritten(false);
12447 }
12448 }
12449
12450 } else {
12451 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12452 auto *OldFD = cast<FunctionDecl>(OldDecl);
12453 // This needs to happen first so that 'inline' propagates.
12454 NewFD->setPreviousDeclaration(OldFD);
12455 if (NewFD->isCXXClassMember())
12456 NewFD->setAccess(OldFD->getAccess());
12457 }
12458 }
12459 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12460 !NewFD->getAttr<OverloadableAttr>()) {
12461 assert((Previous.empty() ||
12462 llvm::any_of(Previous,
12463 [](const NamedDecl *ND) {
12464 return ND->hasAttr<OverloadableAttr>();
12465 })) &&
12466 "Non-redecls shouldn't happen without overloadable present");
12467
12468 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12469 const auto *FD = dyn_cast<FunctionDecl>(ND);
12470 return FD && !FD->hasAttr<OverloadableAttr>();
12471 });
12472
12473 if (OtherUnmarkedIter != Previous.end()) {
12474 Diag(NewFD->getLocation(),
12475 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12476 Diag((*OtherUnmarkedIter)->getLocation(),
12477 diag::note_attribute_overloadable_prev_overload)
12478 << false;
12479
12480 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12481 }
12482 }
12483
12484 if (LangOpts.OpenMP)
12486
12487 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12489
12490 if (NewFD->hasAttr<SYCLExternalAttr>())
12492
12493 // Semantic checking for this function declaration (in isolation).
12494
12495 if (getLangOpts().CPlusPlus) {
12496 // C++-specific checks.
12497 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12499 } else if (CXXDestructorDecl *Destructor =
12500 dyn_cast<CXXDestructorDecl>(NewFD)) {
12501 // We check here for invalid destructor names.
12502 // If we have a friend destructor declaration that is dependent, we can't
12503 // diagnose right away because cases like this are still valid:
12504 // template <class T> struct A { friend T::X::~Y(); };
12505 // struct B { struct Y { ~Y(); }; using X = Y; };
12506 // template struct A<B>;
12508 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12509 CanQualType ClassType =
12510 Context.getCanonicalTagType(Destructor->getParent());
12511
12512 DeclarationName Name =
12513 Context.DeclarationNames.getCXXDestructorName(ClassType);
12514 if (NewFD->getDeclName() != Name) {
12515 Diag(NewFD->getLocation(), diag::err_destructor_name);
12516 NewFD->setInvalidDecl();
12517 return Redeclaration;
12518 }
12519 }
12520 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12521 if (auto *TD = Guide->getDescribedFunctionTemplate())
12523
12524 // A deduction guide is not on the list of entities that can be
12525 // explicitly specialized.
12526 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12527 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12528 << /*explicit specialization*/ 1;
12529 }
12530
12531 // Find any virtual functions that this function overrides.
12532 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12533 if (!Method->isFunctionTemplateSpecialization() &&
12534 !Method->getDescribedFunctionTemplate() &&
12535 Method->isCanonicalDecl()) {
12536 AddOverriddenMethods(Method->getParent(), Method);
12537 }
12538 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12539 // C++2a [class.virtual]p6
12540 // A virtual method shall not have a requires-clause.
12542 diag::err_constrained_virtual_method);
12543
12544 if (Method->isStatic())
12546 }
12547
12548 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12549 ActOnConversionDeclarator(Conversion);
12550
12551 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12552 if (NewFD->isOverloadedOperator() &&
12554 NewFD->setInvalidDecl();
12555 return Redeclaration;
12556 }
12557
12558 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12559 if (NewFD->getLiteralIdentifier() &&
12561 NewFD->setInvalidDecl();
12562 return Redeclaration;
12563 }
12564
12565 // In C++, check default arguments now that we have merged decls. Unless
12566 // the lexical context is the class, because in this case this is done
12567 // during delayed parsing anyway.
12568 if (!CurContext->isRecord())
12570
12571 // If this function is declared as being extern "C", then check to see if
12572 // the function returns a UDT (class, struct, or union type) that is not C
12573 // compatible, and if it does, warn the user.
12574 // But, issue any diagnostic on the first declaration only.
12575 if (Previous.empty() && NewFD->isExternC()) {
12576 QualType R = NewFD->getReturnType();
12577 if (R->isIncompleteType() && !R->isVoidType())
12578 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12579 << NewFD << R;
12580 else if (!R.isPODType(Context) && !R->isVoidType() &&
12581 !R->isObjCObjectPointerType())
12582 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12583 }
12584
12585 // C++1z [dcl.fct]p6:
12586 // [...] whether the function has a non-throwing exception-specification
12587 // [is] part of the function type
12588 //
12589 // This results in an ABI break between C++14 and C++17 for functions whose
12590 // declared type includes an exception-specification in a parameter or
12591 // return type. (Exception specifications on the function itself are OK in
12592 // most cases, and exception specifications are not permitted in most other
12593 // contexts where they could make it into a mangling.)
12594 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12595 auto HasNoexcept = [&](QualType T) -> bool {
12596 // Strip off declarator chunks that could be between us and a function
12597 // type. We don't need to look far, exception specifications are very
12598 // restricted prior to C++17.
12599 if (auto *RT = T->getAs<ReferenceType>())
12600 T = RT->getPointeeType();
12601 else if (T->isAnyPointerType())
12602 T = T->getPointeeType();
12603 else if (auto *MPT = T->getAs<MemberPointerType>())
12604 T = MPT->getPointeeType();
12605 if (auto *FPT = T->getAs<FunctionProtoType>())
12606 if (FPT->isNothrow())
12607 return true;
12608 return false;
12609 };
12610
12611 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12612 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12613 for (QualType T : FPT->param_types())
12614 AnyNoexcept |= HasNoexcept(T);
12615 if (AnyNoexcept)
12616 Diag(NewFD->getLocation(),
12617 diag::warn_cxx17_compat_exception_spec_in_signature)
12618 << NewFD;
12619 }
12620
12621 if (!Redeclaration && LangOpts.CUDA) {
12622 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12623 for (auto *Parm : NewFD->parameters()) {
12624 if (!Parm->getType()->isDependentType() &&
12625 Parm->hasAttr<CUDAGridConstantAttr>() &&
12626 !(IsKernel && Parm->getType().isConstQualified()))
12627 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12628 diag::err_cuda_grid_constant_not_allowed);
12629 }
12631 }
12632 }
12633
12634 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12636
12637 return Redeclaration;
12638}
12639
12641 // [basic.start.main]p3
12642 // The main function shall not be declared with C linkage-specification.
12643 if (FD->isExternCContext())
12644 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12645
12646 // C++11 [basic.start.main]p3:
12647 // A program that [...] declares main to be inline, static or
12648 // constexpr is ill-formed.
12649 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12650 // appear in a declaration of main.
12651 // static main is not an error under C99, but we should warn about it.
12652 // We accept _Noreturn main as an extension.
12653 if (FD->getStorageClass() == SC_Static)
12655 ? diag::err_static_main : diag::warn_static_main)
12657 if (FD->isInlineSpecified())
12658 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12660 if (DS.isNoreturnSpecified()) {
12661 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12662 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12663 Diag(NoreturnLoc, diag::ext_noreturn_main);
12664 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12665 << FixItHint::CreateRemoval(NoreturnRange);
12666 }
12667 if (FD->isConstexpr()) {
12668 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12669 << FD->isConsteval()
12672 }
12673
12674 if (getLangOpts().OpenCL) {
12675 Diag(FD->getLocation(), diag::err_opencl_no_main)
12676 << FD->hasAttr<DeviceKernelAttr>();
12677 FD->setInvalidDecl();
12678 return;
12679 }
12680
12681 if (FD->hasAttr<SYCLExternalAttr>()) {
12682 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12683 << FD->getAttr<SYCLExternalAttr>();
12684 FD->setInvalidDecl();
12685 return;
12686 }
12687
12688 // Functions named main in hlsl are default entries, but don't have specific
12689 // signatures they are required to conform to.
12690 if (getLangOpts().HLSL)
12691 return;
12692
12693 QualType T = FD->getType();
12694 assert(T->isFunctionType() && "function decl is not of function type");
12695 const FunctionType* FT = T->castAs<FunctionType>();
12696
12697 // Set default calling convention for main()
12698 if (FT->getCallConv() != CC_C) {
12699 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12700 FD->setType(QualType(FT, 0));
12701 T = Context.getCanonicalType(FD->getType());
12702 }
12703
12705 // In C with GNU extensions we allow main() to have non-integer return
12706 // type, but we should warn about the extension, and we disable the
12707 // implicit-return-zero rule.
12708
12709 // GCC in C mode accepts qualified 'int'.
12710 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12711 FD->setHasImplicitReturnZero(true);
12712 else {
12713 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12714 SourceRange RTRange = FD->getReturnTypeSourceRange();
12715 if (RTRange.isValid())
12716 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12717 << FixItHint::CreateReplacement(RTRange, "int");
12718 }
12719 } else {
12720 // In C and C++, main magically returns 0 if you fall off the end;
12721 // set the flag which tells us that.
12722 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12723
12724 // All the standards say that main() should return 'int'.
12725 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12726 FD->setHasImplicitReturnZero(true);
12727 else {
12728 // Otherwise, this is just a flat-out error.
12729 SourceRange RTRange = FD->getReturnTypeSourceRange();
12730 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12731 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12732 : FixItHint());
12733 FD->setInvalidDecl(true);
12734 }
12735
12736 // [basic.start.main]p3:
12737 // A program that declares a function main that belongs to the global scope
12738 // and is attached to a named module is ill-formed.
12739 if (FD->isInNamedModule()) {
12740 const SourceLocation start = FD->getTypeSpecStartLoc();
12741 Diag(start, diag::warn_main_in_named_module)
12742 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12743 }
12744 }
12745
12746 // Treat protoless main() as nullary.
12747 if (isa<FunctionNoProtoType>(FT)) return;
12748
12750 unsigned nparams = FTP->getNumParams();
12751 assert(FD->getNumParams() == nparams);
12752
12753 bool HasExtraParameters = (nparams > 3);
12754
12755 if (FTP->isVariadic()) {
12756 Diag(FD->getLocation(), diag::ext_variadic_main);
12757 // FIXME: if we had information about the location of the ellipsis, we
12758 // could add a FixIt hint to remove it as a parameter.
12759 }
12760
12761 // Darwin passes an undocumented fourth argument of type char**. If
12762 // other platforms start sprouting these, the logic below will start
12763 // getting shifty.
12764 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12765 HasExtraParameters = false;
12766
12767 if (HasExtraParameters) {
12768 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12769 FD->setInvalidDecl(true);
12770 nparams = 3;
12771 }
12772
12773 // FIXME: a lot of the following diagnostics would be improved
12774 // if we had some location information about types.
12775
12776 QualType CharPP =
12777 Context.getPointerType(Context.getPointerType(Context.CharTy));
12778 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12779
12780 for (unsigned i = 0; i < nparams; ++i) {
12781 QualType AT = FTP->getParamType(i);
12782
12783 bool mismatch = true;
12784
12785 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12786 mismatch = false;
12787 else if (Expected[i] == CharPP) {
12788 // As an extension, the following forms are okay:
12789 // char const **
12790 // char const * const *
12791 // char * const *
12792
12794 const PointerType* PT;
12795 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12796 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12797 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12798 Context.CharTy)) {
12799 qs.removeConst();
12800 mismatch = !qs.empty();
12801 }
12802 }
12803
12804 if (mismatch) {
12805 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12806 // TODO: suggest replacing given type with expected type
12807 FD->setInvalidDecl(true);
12808 }
12809 }
12810
12811 if (nparams == 1 && !FD->isInvalidDecl()) {
12812 Diag(FD->getLocation(), diag::warn_main_one_arg);
12813 }
12814
12815 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12816 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12817 FD->setInvalidDecl();
12818 }
12819}
12820
12821static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12822
12823 // Default calling convention for main and wmain is __cdecl
12824 if (FD->getName() == "main" || FD->getName() == "wmain")
12825 return false;
12826
12827 // Default calling convention for MinGW and Cygwin is __cdecl
12828 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12829 if (T.isOSCygMing())
12830 return false;
12831
12832 // Default calling convention for WinMain, wWinMain and DllMain
12833 // is __stdcall on 32 bit Windows
12834 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12835 return true;
12836
12837 return false;
12838}
12839
12841 QualType T = FD->getType();
12842 assert(T->isFunctionType() && "function decl is not of function type");
12843 const FunctionType *FT = T->castAs<FunctionType>();
12844
12845 // Set an implicit return of 'zero' if the function can return some integral,
12846 // enumeration, pointer or nullptr type.
12850 // DllMain is exempt because a return value of zero means it failed.
12851 if (FD->getName() != "DllMain")
12852 FD->setHasImplicitReturnZero(true);
12853
12854 // Explicitly specified calling conventions are applied to MSVC entry points
12855 if (!hasExplicitCallingConv(T)) {
12856 if (isDefaultStdCall(FD, *this)) {
12857 if (FT->getCallConv() != CC_X86StdCall) {
12858 FT = Context.adjustFunctionType(
12860 FD->setType(QualType(FT, 0));
12861 }
12862 } else if (FT->getCallConv() != CC_C) {
12863 FT = Context.adjustFunctionType(FT,
12865 FD->setType(QualType(FT, 0));
12866 }
12867 }
12868
12869 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12870 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12871 FD->setInvalidDecl();
12872 }
12873}
12874
12876 // FIXME: Need strict checking. In C89, we need to check for
12877 // any assignment, increment, decrement, function-calls, or
12878 // commas outside of a sizeof. In C99, it's the same list,
12879 // except that the aforementioned are allowed in unevaluated
12880 // expressions. Everything else falls under the
12881 // "may accept other forms of constant expressions" exception.
12882 //
12883 // Regular C++ code will not end up here (exceptions: language extensions,
12884 // OpenCL C++ etc), so the constant expression rules there don't matter.
12885 if (Init->isValueDependent()) {
12886 assert(Init->containsErrors() &&
12887 "Dependent code should only occur in error-recovery path.");
12888 return true;
12889 }
12890 const Expr *Culprit;
12891 if (Init->isConstantInitializer(Context, /*ForRef=*/false, &Culprit))
12892 return false;
12893
12894 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
12895 if (getLangOpts().ObjCConstantLiterals && isa<ObjCObjectLiteral>(Culprit)) {
12896
12897 // For collection literals iterate the elements to highlight which one is
12898 // the offender.
12899 if (auto ALE = dyn_cast<ObjCArrayLiteral>(Init)) {
12900 for (auto *Elm : ALE->elements()) {
12901 if (!Elm->isConstantInitializer(Context)) {
12902 Diag(Elm->getExprLoc(),
12903 diag::err_objc_literal_nonconstant_at_file_scope)
12904 << ObjC().CheckLiteralKind(Init) << Elm->getSourceRange();
12905 return true;
12906 }
12907 }
12908 }
12909
12910 if (auto DLE = dyn_cast<ObjCDictionaryLiteral>(Init)) {
12911 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
12912 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(I);
12913
12914 // Check that the key is a string literal and is constant.
12915 if (!isa<ObjCStringLiteral>(Elm.Key) ||
12917 Diag(Elm.Key->getExprLoc(),
12918 diag::err_objc_literal_nonconstant_at_file_scope)
12920 return true;
12921 }
12922
12923 if (!Elm.Value->isConstantInitializer(Context)) {
12924 Diag(Elm.Value->getExprLoc(),
12925 diag::err_objc_literal_nonconstant_at_file_scope)
12927 return true;
12928 }
12929 }
12930 }
12931
12932 Diag(Culprit->getExprLoc(),
12933 diag::err_objc_literal_nonconstant_at_file_scope)
12934 << ObjC().CheckLiteralKind(Init) << Culprit->getSourceRange();
12935 return true;
12936 }
12937
12938 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12939 return true;
12940}
12941
12942namespace {
12943 // Visits an initialization expression to see if OrigDecl is evaluated in
12944 // its own initialization and throws a warning if it does.
12945 class SelfReferenceChecker
12946 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12947 Sema &S;
12948 Decl *OrigDecl;
12949 bool isRecordType;
12950 bool isPODType;
12951 bool isReferenceType;
12952 bool isInCXXOperatorCall;
12953
12954 bool isInitList;
12955 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12956
12957 public:
12959
12960 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12961 S(S), OrigDecl(OrigDecl) {
12962 isPODType = false;
12963 isRecordType = false;
12964 isReferenceType = false;
12965 isInCXXOperatorCall = false;
12966 isInitList = false;
12967 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12968 isPODType = VD->getType().isPODType(S.Context);
12969 isRecordType = VD->getType()->isRecordType();
12970 isReferenceType = VD->getType()->isReferenceType();
12971 }
12972 }
12973
12974 // For most expressions, just call the visitor. For initializer lists,
12975 // track the index of the field being initialized since fields are
12976 // initialized in order allowing use of previously initialized fields.
12977 void CheckExpr(Expr *E) {
12978 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12979 if (!InitList) {
12980 Visit(E);
12981 return;
12982 }
12983
12984 // Track and increment the index here.
12985 isInitList = true;
12986 InitFieldIndex.push_back(0);
12987 for (auto *Child : InitList->children()) {
12988 CheckExpr(cast<Expr>(Child));
12989 ++InitFieldIndex.back();
12990 }
12991 InitFieldIndex.pop_back();
12992 }
12993
12994 // Returns true if MemberExpr is checked and no further checking is needed.
12995 // Returns false if additional checking is required.
12996 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12997 llvm::SmallVector<FieldDecl*, 4> Fields;
12998 Expr *Base = E;
12999 bool ReferenceField = false;
13000
13001 // Get the field members used.
13002 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13003 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13004 if (!FD)
13005 return false;
13006 Fields.push_back(FD);
13007 if (FD->getType()->isReferenceType())
13008 ReferenceField = true;
13009 Base = ME->getBase()->IgnoreParenImpCasts();
13010 }
13011
13012 // Keep checking only if the base Decl is the same.
13013 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
13014 if (!DRE || DRE->getDecl() != OrigDecl)
13015 return false;
13016
13017 // A reference field can be bound to an unininitialized field.
13018 if (CheckReference && !ReferenceField)
13019 return true;
13020
13021 // Convert FieldDecls to their index number.
13022 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13023 for (const FieldDecl *I : llvm::reverse(Fields))
13024 UsedFieldIndex.push_back(I->getFieldIndex());
13025
13026 // See if a warning is needed by checking the first difference in index
13027 // numbers. If field being used has index less than the field being
13028 // initialized, then the use is safe.
13029 for (auto UsedIter = UsedFieldIndex.begin(),
13030 UsedEnd = UsedFieldIndex.end(),
13031 OrigIter = InitFieldIndex.begin(),
13032 OrigEnd = InitFieldIndex.end();
13033 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13034 if (*UsedIter < *OrigIter)
13035 return true;
13036 if (*UsedIter > *OrigIter)
13037 break;
13038 }
13039
13040 // TODO: Add a different warning which will print the field names.
13041 HandleDeclRefExpr(DRE);
13042 return true;
13043 }
13044
13045 // For most expressions, the cast is directly above the DeclRefExpr.
13046 // For conditional operators, the cast can be outside the conditional
13047 // operator if both expressions are DeclRefExpr's.
13048 void HandleValue(Expr *E) {
13049 E = E->IgnoreParens();
13050 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
13051 HandleDeclRefExpr(DRE);
13052 return;
13053 }
13054
13055 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
13056 Visit(CO->getCond());
13057 HandleValue(CO->getTrueExpr());
13058 HandleValue(CO->getFalseExpr());
13059 return;
13060 }
13061
13062 if (BinaryConditionalOperator *BCO =
13063 dyn_cast<BinaryConditionalOperator>(E)) {
13064 Visit(BCO->getCond());
13065 HandleValue(BCO->getFalseExpr());
13066 return;
13067 }
13068
13069 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
13070 if (Expr *SE = OVE->getSourceExpr())
13071 HandleValue(SE);
13072 return;
13073 }
13074
13075 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13076 if (BO->getOpcode() == BO_Comma) {
13077 Visit(BO->getLHS());
13078 HandleValue(BO->getRHS());
13079 return;
13080 }
13081 }
13082
13083 if (isa<MemberExpr>(E)) {
13084 if (isInitList) {
13085 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
13086 false /*CheckReference*/))
13087 return;
13088 }
13089
13090 Expr *Base = E->IgnoreParenImpCasts();
13091 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13092 // Check for static member variables and don't warn on them.
13093 if (!isa<FieldDecl>(ME->getMemberDecl()))
13094 return;
13095 Base = ME->getBase()->IgnoreParenImpCasts();
13096 }
13097 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
13098 HandleDeclRefExpr(DRE);
13099 return;
13100 }
13101
13102 Visit(E);
13103 }
13104
13105 // Reference types not handled in HandleValue are handled here since all
13106 // uses of references are bad, not just r-value uses.
13107 void VisitDeclRefExpr(DeclRefExpr *E) {
13108 if (isReferenceType)
13109 HandleDeclRefExpr(E);
13110 }
13111
13112 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13113 if (E->getCastKind() == CK_LValueToRValue) {
13114 HandleValue(E->getSubExpr());
13115 return;
13116 }
13117
13118 Inherited::VisitImplicitCastExpr(E);
13119 }
13120
13121 void VisitMemberExpr(MemberExpr *E) {
13122 if (isInitList) {
13123 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
13124 return;
13125 }
13126
13127 // Don't warn on arrays since they can be treated as pointers.
13128 if (E->getType()->canDecayToPointerType()) return;
13129
13130 // Warn when a non-static method call is followed by non-static member
13131 // field accesses, which is followed by a DeclRefExpr.
13132 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
13133 bool Warn = (MD && !MD->isStatic());
13134 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13135 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13136 if (!isa<FieldDecl>(ME->getMemberDecl()))
13137 Warn = false;
13138 Base = ME->getBase()->IgnoreParenImpCasts();
13139 }
13140
13141 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
13142 if (Warn)
13143 HandleDeclRefExpr(DRE);
13144 return;
13145 }
13146
13147 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13148 // Visit that expression.
13149 Visit(Base);
13150 }
13151
13152 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13153 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13154 Expr *Callee = E->getCallee();
13155
13156 if (isa<UnresolvedLookupExpr>(Callee))
13157 return Inherited::VisitCXXOperatorCallExpr(E);
13158
13159 Visit(Callee);
13160 for (auto Arg: E->arguments())
13161 HandleValue(Arg->IgnoreParenImpCasts());
13162 }
13163
13164 void VisitLambdaExpr(LambdaExpr *E) {
13165 if (!isInCXXOperatorCall) {
13166 Inherited::VisitLambdaExpr(E);
13167 return;
13168 }
13169
13170 for (Expr *Init : E->capture_inits())
13171 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13172 HandleDeclRefExpr(DRE);
13173 else if (Init)
13174 Visit(Init);
13175 }
13176
13177 void VisitUnaryOperator(UnaryOperator *E) {
13178 // For POD record types, addresses of its own members are well-defined.
13179 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13181 if (!isPODType)
13182 HandleValue(E->getSubExpr());
13183 return;
13184 }
13185
13186 if (E->isIncrementDecrementOp()) {
13187 HandleValue(E->getSubExpr());
13188 return;
13189 }
13190
13191 Inherited::VisitUnaryOperator(E);
13192 }
13193
13194 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13195
13196 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13197 if (E->getConstructor()->isCopyConstructor()) {
13198 Expr *ArgExpr = E->getArg(0);
13199 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13200 if (ILE->getNumInits() == 1)
13201 ArgExpr = ILE->getInit(0);
13202 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13203 if (ICE->getCastKind() == CK_NoOp)
13204 ArgExpr = ICE->getSubExpr();
13205 HandleValue(ArgExpr);
13206 return;
13207 }
13208 Inherited::VisitCXXConstructExpr(E);
13209 }
13210
13211 void VisitCallExpr(CallExpr *E) {
13212 // Treat std::move as a use.
13213 if (E->isCallToStdMove()) {
13214 HandleValue(E->getArg(0));
13215 return;
13216 }
13217
13218 Inherited::VisitCallExpr(E);
13219 }
13220
13221 void VisitBinaryOperator(BinaryOperator *E) {
13222 if (E->isCompoundAssignmentOp()) {
13223 HandleValue(E->getLHS());
13224 Visit(E->getRHS());
13225 return;
13226 }
13227
13228 Inherited::VisitBinaryOperator(E);
13229 }
13230
13231 // A custom visitor for BinaryConditionalOperator is needed because the
13232 // regular visitor would check the condition and true expression separately
13233 // but both point to the same place giving duplicate diagnostics.
13234 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13235 Visit(E->getCond());
13236 Visit(E->getFalseExpr());
13237 }
13238
13239 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13240 Decl* ReferenceDecl = DRE->getDecl();
13241 if (OrigDecl != ReferenceDecl) return;
13242 unsigned diag;
13243 if (isReferenceType) {
13244 diag = diag::warn_uninit_self_reference_in_reference_init;
13245 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13246 diag = diag::warn_static_self_reference_in_init;
13247 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13248 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13249 DRE->getDecl()->getType()->isRecordType()) {
13250 diag = diag::warn_uninit_self_reference_in_init;
13251 } else {
13252 // Local variables will be handled by the CFG analysis.
13253 return;
13254 }
13255
13256 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13257 S.PDiag(diag)
13258 << DRE->getDecl() << OrigDecl->getLocation()
13259 << DRE->getSourceRange());
13260 }
13261 };
13262
13263 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13264 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13265 bool DirectInit) {
13266 // Parameters arguments are occassionially constructed with itself,
13267 // for instance, in recursive functions. Skip them.
13268 if (isa<ParmVarDecl>(OrigDecl))
13269 return;
13270
13271 // Skip checking for file-scope constexpr variables - constant evaluation
13272 // will produce appropriate errors without needing runtime diagnostics.
13273 // Local constexpr should still emit runtime warnings.
13274 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);
13275 VD && VD->isConstexpr() && VD->isFileVarDecl())
13276 return;
13277
13278 E = E->IgnoreParens();
13279
13280 // Skip checking T a = a where T is not a record or reference type.
13281 // Doing so is a way to silence uninitialized warnings.
13282 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13283 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13284 if (ICE->getCastKind() == CK_LValueToRValue)
13285 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13286 if (DRE->getDecl() == OrigDecl)
13287 return;
13288
13289 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13290 }
13291} // end anonymous namespace
13292
13293namespace {
13294 // Simple wrapper to add the name of a variable or (if no variable is
13295 // available) a DeclarationName into a diagnostic.
13296 struct VarDeclOrName {
13297 VarDecl *VDecl;
13298 DeclarationName Name;
13299
13300 friend const Sema::SemaDiagnosticBuilder &
13301 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13302 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13303 }
13304 };
13305} // end anonymous namespace
13306
13309 TypeSourceInfo *TSI,
13310 SourceRange Range, bool DirectInit,
13311 Expr *Init) {
13312 bool IsInitCapture = !VDecl;
13313 assert((!VDecl || !VDecl->isInitCapture()) &&
13314 "init captures are expected to be deduced prior to initialization");
13315
13316 VarDeclOrName VN{VDecl, Name};
13317
13318 DeducedType *Deduced = Type->getContainedDeducedType();
13319 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13320
13321 // Diagnose auto array declarations in C23, unless it's a supported extension.
13322 if (getLangOpts().C23 && Type->isArrayType() &&
13323 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13324 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13325 << (int)Deduced->getContainedAutoType()->getKeyword()
13326 << /*in array decl*/ 23 << Range;
13327 return QualType();
13328 }
13329
13330 // C++11 [dcl.spec.auto]p3
13331 if (!Init) {
13332 assert(VDecl && "no init for init capture deduction?");
13333
13334 // Except for class argument deduction, and then for an initializing
13335 // declaration only, i.e. no static at class scope or extern.
13337 VDecl->hasExternalStorage() ||
13338 VDecl->isStaticDataMember()) {
13339 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13340 << VDecl->getDeclName() << Type;
13341 return QualType();
13342 }
13343 }
13344
13345 ArrayRef<Expr*> DeduceInits;
13346 if (Init)
13347 DeduceInits = Init;
13348
13349 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13350 if (DirectInit && PL)
13351 DeduceInits = PL->exprs();
13352
13354 assert(VDecl && "non-auto type for init capture deduction?");
13357 VDecl->getLocation(), DirectInit, Init);
13358 // FIXME: Initialization should not be taking a mutable list of inits.
13359 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13360 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13361 InitsCopy);
13362 }
13363
13364 if (DirectInit) {
13365 if (auto *IL = dyn_cast<InitListExpr>(Init))
13366 DeduceInits = IL->inits();
13367 }
13368
13369 // Deduction only works if we have exactly one source expression.
13370 if (DeduceInits.empty()) {
13371 // It isn't possible to write this directly, but it is possible to
13372 // end up in this situation with "auto x(some_pack...);"
13373 Diag(Init->getBeginLoc(), IsInitCapture
13374 ? diag::err_init_capture_no_expression
13375 : diag::err_auto_var_init_no_expression)
13376 << VN << Type << Range;
13377 return QualType();
13378 }
13379
13380 if (DeduceInits.size() > 1) {
13381 Diag(DeduceInits[1]->getBeginLoc(),
13382 IsInitCapture ? diag::err_init_capture_multiple_expressions
13383 : diag::err_auto_var_init_multiple_expressions)
13384 << VN << Type << Range;
13385 return QualType();
13386 }
13387
13388 Expr *DeduceInit = DeduceInits[0];
13389 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13390 Diag(Init->getBeginLoc(), IsInitCapture
13391 ? diag::err_init_capture_paren_braces
13392 : diag::err_auto_var_init_paren_braces)
13393 << isa<InitListExpr>(Init) << VN << Type << Range;
13394 return QualType();
13395 }
13396
13397 // Expressions default to 'id' when we're in a debugger.
13398 bool DefaultedAnyToId = false;
13399 if (getLangOpts().DebuggerCastResultToId &&
13400 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13402 if (Result.isInvalid()) {
13403 return QualType();
13404 }
13405 Init = Result.get();
13406 DefaultedAnyToId = true;
13407 }
13408
13409 // C++ [dcl.decomp]p1:
13410 // If the assignment-expression [...] has array type A and no ref-qualifier
13411 // is present, e has type cv A
13412 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13413 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13414 DeduceInit->getType()->isConstantArrayType())
13415 return Context.getQualifiedType(DeduceInit->getType(),
13416 Type.getQualifiers());
13417
13418 QualType DeducedType;
13419 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13421 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13424 if (!IsInitCapture)
13425 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13426 else if (isa<InitListExpr>(Init))
13427 Diag(Range.getBegin(),
13428 diag::err_init_capture_deduction_failure_from_init_list)
13429 << VN
13430 << (DeduceInit->getType().isNull() ? TSI->getType()
13431 : DeduceInit->getType())
13432 << DeduceInit->getSourceRange();
13433 else
13434 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13435 << VN << TSI->getType()
13436 << (DeduceInit->getType().isNull() ? TSI->getType()
13437 : DeduceInit->getType())
13438 << DeduceInit->getSourceRange();
13439 }
13440
13441 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13442 // 'id' instead of a specific object type prevents most of our usual
13443 // checks.
13444 // We only want to warn outside of template instantiations, though:
13445 // inside a template, the 'id' could have come from a parameter.
13446 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13447 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13448 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13449 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13450 }
13451
13452 return DeducedType;
13453}
13454
13456 Expr *Init) {
13457 assert(!Init || !Init->containsErrors());
13459 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13460 VDecl->getSourceRange(), DirectInit, Init);
13461 if (DeducedType.isNull()) {
13462 VDecl->setInvalidDecl();
13463 return true;
13464 }
13465
13466 VDecl->setType(DeducedType);
13467 assert(VDecl->isLinkageValid());
13468
13469 // In ARC, infer lifetime.
13470 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13471 VDecl->setInvalidDecl();
13472
13473 if (getLangOpts().OpenCL)
13475
13476 if (getLangOpts().HLSL)
13477 HLSL().deduceAddressSpace(VDecl);
13478
13479 // If this is a redeclaration, check that the type we just deduced matches
13480 // the previously declared type.
13481 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13482 // We never need to merge the type, because we cannot form an incomplete
13483 // array of auto, nor deduce such a type.
13484 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13485 }
13486
13487 // Check the deduced type is valid for a variable declaration.
13489 return VDecl->isInvalidDecl();
13490}
13491
13493 SourceLocation Loc) {
13494 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13495 Init = EWC->getSubExpr();
13496
13497 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13498 Init = CE->getSubExpr();
13499
13500 QualType InitType = Init->getType();
13503 "shouldn't be called if type doesn't have a non-trivial C struct");
13504 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13505 for (auto *I : ILE->inits()) {
13506 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13507 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13508 continue;
13509 SourceLocation SL = I->getExprLoc();
13510 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13511 }
13512 return;
13513 }
13514
13517 checkNonTrivialCUnion(InitType, Loc,
13519 NTCUK_Init);
13520 } else {
13521 // Assume all other explicit initializers involving copying some existing
13522 // object.
13523 // TODO: ignore any explicit initializers where we can guarantee
13524 // copy-elision.
13527 NTCUK_Copy);
13528 }
13529}
13530
13531namespace {
13532
13533bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13534 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13535 // in the source code or implicitly by the compiler if it is in a union
13536 // defined in a system header and has non-trivial ObjC ownership
13537 // qualifications. We don't want those fields to participate in determining
13538 // whether the containing union is non-trivial.
13539 return FD->hasAttr<UnavailableAttr>();
13540}
13541
13542struct DiagNonTrivalCUnionDefaultInitializeVisitor
13543 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13544 void> {
13545 using Super =
13546 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13547 void>;
13548
13549 DiagNonTrivalCUnionDefaultInitializeVisitor(
13550 QualType OrigTy, SourceLocation OrigLoc,
13551 NonTrivialCUnionContext UseContext, Sema &S)
13552 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13553
13554 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13555 const FieldDecl *FD, bool InNonTrivialUnion) {
13556 if (const auto *AT = S.Context.getAsArrayType(QT))
13557 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13558 InNonTrivialUnion);
13559 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13560 }
13561
13562 void visitARCStrong(QualType QT, const FieldDecl *FD,
13563 bool InNonTrivialUnion) {
13564 if (InNonTrivialUnion)
13565 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13566 << 1 << 0 << QT << FD->getName();
13567 }
13568
13569 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13570 if (InNonTrivialUnion)
13571 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13572 << 1 << 0 << QT << FD->getName();
13573 }
13574
13575 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13576 const auto *RD = QT->castAsRecordDecl();
13577 if (RD->isUnion()) {
13578 if (OrigLoc.isValid()) {
13579 bool IsUnion = false;
13580 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13581 IsUnion = OrigRD->isUnion();
13582 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13583 << 0 << OrigTy << IsUnion << UseContext;
13584 // Reset OrigLoc so that this diagnostic is emitted only once.
13585 OrigLoc = SourceLocation();
13586 }
13587 InNonTrivialUnion = true;
13588 }
13589
13590 if (InNonTrivialUnion)
13591 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13592 << 0 << 0 << QT.getUnqualifiedType() << "";
13593
13594 for (const FieldDecl *FD : RD->fields())
13595 if (!shouldIgnoreForRecordTriviality(FD))
13596 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13597 }
13598
13599 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13600
13601 // The non-trivial C union type or the struct/union type that contains a
13602 // non-trivial C union.
13603 QualType OrigTy;
13604 SourceLocation OrigLoc;
13605 NonTrivialCUnionContext UseContext;
13606 Sema &S;
13607};
13608
13609struct DiagNonTrivalCUnionDestructedTypeVisitor
13610 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13611 using Super =
13612 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13613
13614 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13615 SourceLocation OrigLoc,
13616 NonTrivialCUnionContext UseContext,
13617 Sema &S)
13618 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13619
13620 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13621 const FieldDecl *FD, bool InNonTrivialUnion) {
13622 if (const auto *AT = S.Context.getAsArrayType(QT))
13623 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13624 InNonTrivialUnion);
13625 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13626 }
13627
13628 void visitARCStrong(QualType QT, const FieldDecl *FD,
13629 bool InNonTrivialUnion) {
13630 if (InNonTrivialUnion)
13631 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13632 << 1 << 1 << QT << FD->getName();
13633 }
13634
13635 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13636 if (InNonTrivialUnion)
13637 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13638 << 1 << 1 << QT << FD->getName();
13639 }
13640
13641 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13642 const auto *RD = QT->castAsRecordDecl();
13643 if (RD->isUnion()) {
13644 if (OrigLoc.isValid()) {
13645 bool IsUnion = false;
13646 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13647 IsUnion = OrigRD->isUnion();
13648 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13649 << 1 << OrigTy << IsUnion << UseContext;
13650 // Reset OrigLoc so that this diagnostic is emitted only once.
13651 OrigLoc = SourceLocation();
13652 }
13653 InNonTrivialUnion = true;
13654 }
13655
13656 if (InNonTrivialUnion)
13657 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13658 << 0 << 1 << QT.getUnqualifiedType() << "";
13659
13660 for (const FieldDecl *FD : RD->fields())
13661 if (!shouldIgnoreForRecordTriviality(FD))
13662 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13663 }
13664
13665 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13666 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13667 bool InNonTrivialUnion) {}
13668
13669 // The non-trivial C union type or the struct/union type that contains a
13670 // non-trivial C union.
13671 QualType OrigTy;
13672 SourceLocation OrigLoc;
13673 NonTrivialCUnionContext UseContext;
13674 Sema &S;
13675};
13676
13677struct DiagNonTrivalCUnionCopyVisitor
13678 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13679 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13680
13681 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13682 NonTrivialCUnionContext UseContext, Sema &S)
13683 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13684
13685 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13686 const FieldDecl *FD, bool InNonTrivialUnion) {
13687 if (const auto *AT = S.Context.getAsArrayType(QT))
13688 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13689 InNonTrivialUnion);
13690 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13691 }
13692
13693 void visitARCStrong(QualType QT, const FieldDecl *FD,
13694 bool InNonTrivialUnion) {
13695 if (InNonTrivialUnion)
13696 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13697 << 1 << 2 << QT << FD->getName();
13698 }
13699
13700 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13701 if (InNonTrivialUnion)
13702 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13703 << 1 << 2 << QT << FD->getName();
13704 }
13705
13706 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13707 const auto *RD = QT->castAsRecordDecl();
13708 if (RD->isUnion()) {
13709 if (OrigLoc.isValid()) {
13710 bool IsUnion = false;
13711 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13712 IsUnion = OrigRD->isUnion();
13713 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13714 << 2 << OrigTy << IsUnion << UseContext;
13715 // Reset OrigLoc so that this diagnostic is emitted only once.
13716 OrigLoc = SourceLocation();
13717 }
13718 InNonTrivialUnion = true;
13719 }
13720
13721 if (InNonTrivialUnion)
13722 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13723 << 0 << 2 << QT.getUnqualifiedType() << "";
13724
13725 for (const FieldDecl *FD : RD->fields())
13726 if (!shouldIgnoreForRecordTriviality(FD))
13727 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13728 }
13729
13730 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13731 if (InNonTrivialUnion)
13732 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13733 << 1 << 2 << QT << FD->getName();
13734 }
13735
13736 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13737 const FieldDecl *FD, bool InNonTrivialUnion) {}
13738 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13739 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13740 bool InNonTrivialUnion) {}
13741
13742 // The non-trivial C union type or the struct/union type that contains a
13743 // non-trivial C union.
13744 QualType OrigTy;
13745 SourceLocation OrigLoc;
13746 NonTrivialCUnionContext UseContext;
13747 Sema &S;
13748};
13749
13750} // namespace
13751
13753 NonTrivialCUnionContext UseContext,
13754 unsigned NonTrivialKind) {
13758 "shouldn't be called if type doesn't have a non-trivial C union");
13759
13760 if ((NonTrivialKind & NTCUK_Init) &&
13762 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13763 .visit(QT, nullptr, false);
13764 if ((NonTrivialKind & NTCUK_Destruct) &&
13766 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13767 .visit(QT, nullptr, false);
13768 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13769 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13770 .visit(QT, nullptr, false);
13771}
13772
13774 const VarDecl *Dcl) {
13775 if (!getLangOpts().CPlusPlus)
13776 return false;
13777
13778 // We only need to warn if the definition is in a header file, so wait to
13779 // diagnose until we've seen the definition.
13780 if (!Dcl->isThisDeclarationADefinition())
13781 return false;
13782
13783 // If an object is defined in a source file, its definition can't get
13784 // duplicated since it will never appear in more than one TU.
13786 return false;
13787
13788 // If the variable we're looking at is a static local, then we actually care
13789 // about the properties of the function containing it.
13790 const ValueDecl *Target = Dcl;
13791 // VarDecls and FunctionDecls have different functions for checking
13792 // inline-ness, and whether they were originally templated, so we have to
13793 // call the appropriate functions manually.
13794 bool TargetIsInline = Dcl->isInline();
13795 bool TargetWasTemplated =
13797
13798 // Update the Target and TargetIsInline property if necessary
13799 if (Dcl->isStaticLocal()) {
13800 const DeclContext *Ctx = Dcl->getDeclContext();
13801 if (!Ctx)
13802 return false;
13803
13804 const FunctionDecl *FunDcl =
13805 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
13806 if (!FunDcl)
13807 return false;
13808
13809 Target = FunDcl;
13810 // IsInlined() checks for the C++ inline property
13811 TargetIsInline = FunDcl->isInlined();
13812 TargetWasTemplated =
13814 }
13815
13816 // Non-inline functions/variables can only legally appear in one TU
13817 // unless they were part of a template. Unfortunately, making complex
13818 // template instantiations visible is infeasible in practice, since
13819 // everything the template depends on also has to be visible. To avoid
13820 // giving impractical-to-fix warnings, don't warn if we're inside
13821 // something that was templated, even on inline stuff.
13822 if (!TargetIsInline || TargetWasTemplated)
13823 return false;
13824
13825 // If the object isn't hidden, the dynamic linker will prevent duplication.
13826 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13827
13828 // The target is "hidden" (from the dynamic linker) if:
13829 // 1. On posix, it has hidden visibility, or
13830 // 2. On windows, it has no import/export annotation, and neither does the
13831 // class which directly contains it.
13832 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13833 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13834 return false;
13835
13836 // If the variable isn't directly annotated, check to see if it's a member
13837 // of an annotated class.
13838 const CXXRecordDecl *Ctx =
13839 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
13840 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13841 return false;
13842
13843 } else if (Lnk.getVisibility() != HiddenVisibility) {
13844 // Posix case
13845 return false;
13846 }
13847
13848 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13850 return false;
13851
13852 return true;
13853}
13854
13855// Determine whether the object seems mutable for the purpose of diagnosing
13856// possible unique object duplication, i.e. non-const-qualified, and
13857// not an always-constant type like a function.
13858// Not perfect: doesn't account for mutable members, for example, or
13859// elements of container types.
13860// For nested pointers, any individual level being non-const is sufficient.
13861static bool looksMutable(QualType T, const ASTContext &Ctx) {
13862 T = T.getNonReferenceType();
13863 if (T->isFunctionType())
13864 return false;
13865 if (!T.isConstant(Ctx))
13866 return true;
13867 if (T->isPointerType())
13868 return looksMutable(T->getPointeeType(), Ctx);
13869 return false;
13870}
13871
13873 // If this object has external linkage and hidden visibility, it might be
13874 // duplicated when built into a shared library, which causes problems if it's
13875 // mutable (since the copies won't be in sync) or its initialization has side
13876 // effects (since it will run once per copy instead of once globally).
13877
13878 // Don't diagnose if we're inside a template, because it's not practical to
13879 // fix the warning in most cases.
13880 if (!VD->isTemplated() &&
13882
13883 QualType Type = VD->getType();
13884 if (looksMutable(Type, VD->getASTContext())) {
13885 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13886 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13887 }
13888
13889 // To keep false positives low, only warn if we're certain that the
13890 // initializer has side effects. Don't warn on operator new, since a mutable
13891 // pointer will trigger the previous warning, and an immutable pointer
13892 // getting duplicated just results in a little extra memory usage.
13893 const Expr *Init = VD->getAnyInitializer();
13894 if (Init &&
13895 Init->HasSideEffects(VD->getASTContext(),
13896 /*IncludePossibleEffects=*/false) &&
13897 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
13898 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13899 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13900 }
13901 }
13902}
13903
13905 llvm::scope_exit ResetDeclForInitializer([this]() {
13906 if (!this->ExprEvalContexts.empty())
13907 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13908 });
13909
13910 // If there is no declaration, there was an error parsing it. Just ignore
13911 // the initializer.
13912 if (!RealDecl) {
13913 return;
13914 }
13915
13916 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13917 if (!Method->isInvalidDecl()) {
13918 // Pure-specifiers are handled in ActOnPureSpecifier.
13919 Diag(Method->getLocation(), diag::err_member_function_initialization)
13920 << Method->getDeclName() << Init->getSourceRange();
13921 Method->setInvalidDecl();
13922 }
13923 return;
13924 }
13925
13926 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13927 if (!VDecl) {
13928 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13929 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13930 RealDecl->setInvalidDecl();
13931 return;
13932 }
13933
13934 if (VDecl->isInvalidDecl()) {
13935 ExprResult Recovery =
13936 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13937 if (Expr *E = Recovery.get())
13938 VDecl->setInit(E);
13939 return;
13940 }
13941
13942 // __amdgpu_feature_predicate_t cannot be initialised
13943 if (VDecl->getType().getDesugaredType(Context) ==
13944 Context.AMDGPUFeaturePredicateTy) {
13945 Diag(VDecl->getLocation(),
13946 diag::err_amdgcn_predicate_type_is_not_constructible)
13947 << VDecl;
13948 VDecl->setInvalidDecl();
13949 return;
13950 }
13951
13952 // WebAssembly tables can't be used to initialise a variable.
13953 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13954 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13955 VDecl->setInvalidDecl();
13956 return;
13957 }
13958
13959 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13960 if (VDecl->getType()->isUndeducedType()) {
13961 if (Init->containsErrors()) {
13962 // Invalidate the decl as we don't know the type for recovery-expr yet.
13963 RealDecl->setInvalidDecl();
13964 VDecl->setInit(Init);
13965 return;
13966 }
13967
13969 assert(VDecl->isInvalidDecl() &&
13970 "decl should be invalidated when deduce fails");
13971 if (auto *RecoveryExpr =
13972 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init})
13973 .get())
13974 VDecl->setInit(RecoveryExpr);
13975 return;
13976 }
13977 }
13978
13979 this->CheckAttributesOnDeducedType(RealDecl);
13980
13981 // we don't initialize groupshared variables so warn and return
13982 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
13983 Diag(VDecl->getLocation(), diag::warn_hlsl_groupshared_init);
13984 return;
13985 }
13986
13987 // dllimport cannot be used on variable definitions.
13988 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13989 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13990 VDecl->setInvalidDecl();
13991 return;
13992 }
13993
13994 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13995 // the identifier has external or internal linkage, the declaration shall
13996 // have no initializer for the identifier.
13997 // C++14 [dcl.init]p5 is the same restriction for C++.
13998 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13999 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
14000 VDecl->setInvalidDecl();
14001 return;
14002 }
14003
14004 if (!VDecl->getType()->isDependentType()) {
14005 // A definition must end up with a complete type, which means it must be
14006 // complete with the restriction that an array type might be completed by
14007 // the initializer; note that later code assumes this restriction.
14008 QualType BaseDeclType = VDecl->getType();
14009 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
14010 BaseDeclType = Array->getElementType();
14011 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
14012 diag::err_typecheck_decl_incomplete_type)) {
14013 RealDecl->setInvalidDecl();
14014 return;
14015 }
14016
14017 // The variable can not have an abstract class type.
14018 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
14019 diag::err_abstract_type_in_decl,
14021 VDecl->setInvalidDecl();
14022 }
14023
14024 // C++ [module.import/6]
14025 // ...
14026 // A header unit shall not contain a definition of a non-inline function or
14027 // variable whose name has external linkage.
14028 //
14029 // We choose to allow weak & selectany definitions, as they are common in
14030 // headers, and have semantics similar to inline definitions which are allowed
14031 // in header units.
14032 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14033 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14034 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14035 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
14037 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14038 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
14039 VDecl->setInvalidDecl();
14040 }
14041
14042 // If adding the initializer will turn this declaration into a definition,
14043 // and we already have a definition for this variable, diagnose or otherwise
14044 // handle the situation.
14045 if (VarDecl *Def = VDecl->getDefinition())
14046 if (Def != VDecl &&
14047 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14049 checkVarDeclRedefinition(Def, VDecl))
14050 return;
14051
14052 if (getLangOpts().CPlusPlus) {
14053 // C++ [class.static.data]p4
14054 // If a static data member is of const integral or const
14055 // enumeration type, its declaration in the class definition can
14056 // specify a constant-initializer which shall be an integral
14057 // constant expression (5.19). In that case, the member can appear
14058 // in integral constant expressions. The member shall still be
14059 // defined in a namespace scope if it is used in the program and the
14060 // namespace scope definition shall not contain an initializer.
14061 //
14062 // We already performed a redefinition check above, but for static
14063 // data members we also need to check whether there was an in-class
14064 // declaration with an initializer.
14065 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14066 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
14067 << VDecl->getDeclName();
14068 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14069 diag::note_previous_initializer)
14070 << 0;
14071 return;
14072 }
14073
14075 VDecl->setInvalidDecl();
14076 return;
14077 }
14078 }
14079
14080 // If the variable has an initializer and local storage, check whether
14081 // anything jumps over the initialization.
14082 if (VDecl->hasLocalStorage())
14084
14085 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14086 // a kernel function cannot be initialized."
14087 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14088 Diag(VDecl->getLocation(), diag::err_local_cant_init);
14089 VDecl->setInvalidDecl();
14090 return;
14091 }
14092
14093 // The LoaderUninitialized attribute acts as a definition (of undef).
14094 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14095 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
14096 VDecl->setInvalidDecl();
14097 return;
14098 }
14099
14100 if (getLangOpts().HLSL)
14101 if (!HLSL().handleInitialization(VDecl, Init))
14102 return;
14103
14104 // Get the decls type and save a reference for later, since
14105 // CheckInitializerTypes may change it.
14106 QualType DclT = VDecl->getType(), SavT = DclT;
14107
14108 // Expressions default to 'id' when we're in a debugger
14109 // and we are assigning it to a variable of Objective-C pointer type.
14110 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14111 Init->getType() == Context.UnknownAnyTy) {
14113 if (!Result.isUsable()) {
14114 VDecl->setInvalidDecl();
14115 return;
14116 }
14117 Init = Result.get();
14118 }
14119
14120 // Perform the initialization.
14121 bool InitializedFromParenListExpr = false;
14122 bool IsParenListInit = false;
14123 if (!VDecl->isInvalidDecl()) {
14126 VDecl->getLocation(), DirectInit, Init);
14127
14128 MultiExprArg Args = Init;
14129 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
14130 Args =
14131 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14132 InitializedFromParenListExpr = true;
14133 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
14134 Args = CXXDirectInit->getInitExprs();
14135 InitializedFromParenListExpr = true;
14136 }
14137
14138 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14139 /*TopLevelOfInitList=*/false,
14140 /*TreatUnavailableAsInvalid=*/false);
14141 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
14142 if (!Result.isUsable()) {
14143 // If the provided initializer fails to initialize the var decl,
14144 // we attach a recovery expr for better recovery.
14145 auto RecoveryExpr =
14146 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
14147 if (RecoveryExpr.get())
14148 VDecl->setInit(RecoveryExpr.get());
14149 // In general, for error recovery purposes, the initializer doesn't play
14150 // part in the valid bit of the declaration. There are a few exceptions:
14151 // 1) if the var decl has a deduced auto type, and the type cannot be
14152 // deduced by an invalid initializer;
14153 // 2) if the var decl is a decomposition decl with a non-deduced type,
14154 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14155 // Case 1) was already handled elsewhere.
14156 if (isa<DecompositionDecl>(VDecl)) // Case 2)
14157 VDecl->setInvalidDecl();
14158 return;
14159 }
14160
14161 Init = Result.getAs<Expr>();
14162 IsParenListInit = !InitSeq.steps().empty() &&
14163 InitSeq.step_begin()->Kind ==
14165 QualType VDeclType = VDecl->getType();
14166 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14167 !VDeclType->isDependentType() &&
14168 Context.getAsIncompleteArrayType(VDeclType) &&
14169 Context.getAsIncompleteArrayType(Init->getType())) {
14170 // Bail out if it is not possible to deduce array size from the
14171 // initializer.
14172 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
14173 << VDeclType;
14174 VDecl->setInvalidDecl();
14175 return;
14176 }
14177 }
14178
14179 // Check for self-references within variable initializers.
14180 // Variables declared within a function/method body (except for references)
14181 // are handled by a dataflow analysis.
14182 // This is undefined behavior in C++, but valid in C.
14183 if (getLangOpts().CPlusPlus)
14184 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14185 VDecl->getType()->isReferenceType())
14186 CheckSelfReference(*this, RealDecl, Init, DirectInit);
14187
14188 // If the type changed, it means we had an incomplete type that was
14189 // completed by the initializer. For example:
14190 // int ary[] = { 1, 3, 5 };
14191 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14192 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14193 VDecl->setType(DclT);
14194
14195 if (!VDecl->isInvalidDecl()) {
14196 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
14197
14198 if (VDecl->hasAttr<BlocksAttr>())
14199 ObjC().checkRetainCycles(VDecl, Init);
14200
14201 // It is safe to assign a weak reference into a strong variable.
14202 // Although this code can still have problems:
14203 // id x = self.weakProp;
14204 // id y = self.weakProp;
14205 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14206 // paths through the function. This should be revisited if
14207 // -Wrepeated-use-of-weak is made flow-sensitive.
14208 if (FunctionScopeInfo *FSI = getCurFunction())
14209 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14211 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14212 Init->getBeginLoc()))
14213 FSI->markSafeWeakUse(Init);
14214 }
14215
14216 // The initialization is usually a full-expression.
14217 //
14218 // FIXME: If this is a braced initialization of an aggregate, it is not
14219 // an expression, and each individual field initializer is a separate
14220 // full-expression. For instance, in:
14221 //
14222 // struct Temp { ~Temp(); };
14223 // struct S { S(Temp); };
14224 // struct T { S a, b; } t = { Temp(), Temp() }
14225 //
14226 // we should destroy the first Temp before constructing the second.
14227
14228 // Set context flag for OverflowBehaviorType initialization analysis
14230 true);
14233 /*DiscardedValue*/ false, VDecl->isConstexpr());
14234 if (!Result.isUsable()) {
14235 VDecl->setInvalidDecl();
14236 return;
14237 }
14238 Init = Result.get();
14239
14240 // Attach the initializer to the decl.
14241 VDecl->setInit(Init);
14242
14243 if (VDecl->isLocalVarDecl()) {
14244 // Don't check the initializer if the declaration is malformed.
14245 if (VDecl->isInvalidDecl()) {
14246 // do nothing
14247
14248 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14249 // This is true even in C++ for OpenCL.
14250 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14252
14253 // Otherwise, C++ does not restrict the initializer.
14254 } else if (getLangOpts().CPlusPlus) {
14255 // do nothing
14256
14257 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14258 // static storage duration shall be constant expressions or string literals.
14259 } else if (VDecl->getStorageClass() == SC_Static) {
14260 // Avoid evaluating the initializer twice for constexpr variables. It will
14261 // be evaluated later.
14262 if (!VDecl->isConstexpr())
14264
14265 // C89 is stricter than C99 for aggregate initializers.
14266 // C89 6.5.7p3: All the expressions [...] in an initializer list
14267 // for an object that has aggregate or union type shall be
14268 // constant expressions.
14269 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14271 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14272 }
14273
14274 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14275 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14276 if (VDecl->hasLocalStorage())
14277 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14278 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14279 VDecl->getLexicalDeclContext()->isRecord()) {
14280 // This is an in-class initialization for a static data member, e.g.,
14281 //
14282 // struct S {
14283 // static const int value = 17;
14284 // };
14285
14286 // C++ [class.mem]p4:
14287 // A member-declarator can contain a constant-initializer only
14288 // if it declares a static member (9.4) of const integral or
14289 // const enumeration type, see 9.4.2.
14290 //
14291 // C++11 [class.static.data]p3:
14292 // If a non-volatile non-inline const static data member is of integral
14293 // or enumeration type, its declaration in the class definition can
14294 // specify a brace-or-equal-initializer in which every initializer-clause
14295 // that is an assignment-expression is a constant expression. A static
14296 // data member of literal type can be declared in the class definition
14297 // with the constexpr specifier; if so, its declaration shall specify a
14298 // brace-or-equal-initializer in which every initializer-clause that is
14299 // an assignment-expression is a constant expression.
14300
14301 // Do nothing on dependent types.
14302 if (DclT->isDependentType()) {
14303
14304 // Allow any 'static constexpr' members, whether or not they are of literal
14305 // type. We separately check that every constexpr variable is of literal
14306 // type.
14307 } else if (VDecl->isConstexpr()) {
14308
14309 // Require constness.
14310 } else if (!DclT.isConstQualified()) {
14311 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14312 << Init->getSourceRange();
14313 VDecl->setInvalidDecl();
14314
14315 // We allow integer constant expressions in all cases.
14316 } else if (DclT->isIntegralOrEnumerationType()) {
14318 // In C++11, a non-constexpr const static data member with an
14319 // in-class initializer cannot be volatile.
14320 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14321
14322 // We allow foldable floating-point constants as an extension.
14323 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14324 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14325 // it anyway and provide a fixit to add the 'constexpr'.
14326 if (getLangOpts().CPlusPlus11) {
14327 Diag(VDecl->getLocation(),
14328 diag::ext_in_class_initializer_float_type_cxx11)
14329 << DclT << Init->getSourceRange();
14330 Diag(VDecl->getBeginLoc(),
14331 diag::note_in_class_initializer_float_type_cxx11)
14332 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14333 } else {
14334 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14335 << DclT << Init->getSourceRange();
14336
14337 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14338 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14339 << Init->getSourceRange();
14340 VDecl->setInvalidDecl();
14341 }
14342 }
14343
14344 // Suggest adding 'constexpr' in C++11 for literal types.
14345 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14346 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14347 << DclT << Init->getSourceRange()
14348 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14349 VDecl->setConstexpr(true);
14350
14351 } else {
14352 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14353 << DclT << Init->getSourceRange();
14354 VDecl->setInvalidDecl();
14355 }
14356 } else if (VDecl->isFileVarDecl()) {
14357 // In C, extern is typically used to avoid tentative definitions when
14358 // declaring variables in headers, but adding an initializer makes it a
14359 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14360 // In C++, extern is often used to give implicitly static const variables
14361 // external linkage, so don't warn in that case. If selectany is present,
14362 // this might be header code intended for C and C++ inclusion, so apply the
14363 // C++ rules.
14364 if (VDecl->getStorageClass() == SC_Extern &&
14365 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14366 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14367 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14369 Diag(VDecl->getLocation(), diag::warn_extern_init);
14370
14371 // In Microsoft C++ mode, a const variable defined in namespace scope has
14372 // external linkage by default if the variable is declared with
14373 // __declspec(dllexport).
14374 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14376 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14377 VDecl->setStorageClass(SC_Extern);
14378
14379 // C99 6.7.8p4. All file scoped initializers need to be constant.
14380 // Avoid duplicate diagnostics for constexpr variables.
14381 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14382 !VDecl->isConstexpr())
14384 }
14385
14386 QualType InitType = Init->getType();
14387 if (!InitType.isNull() &&
14391
14392 // We will represent direct-initialization similarly to copy-initialization:
14393 // int x(1); -as-> int x = 1;
14394 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14395 //
14396 // Clients that want to distinguish between the two forms, can check for
14397 // direct initializer using VarDecl::getInitStyle().
14398 // A major benefit is that clients that don't particularly care about which
14399 // exactly form was it (like the CodeGen) can handle both cases without
14400 // special case code.
14401
14402 // C++ 8.5p11:
14403 // The form of initialization (using parentheses or '=') matters
14404 // when the entity being initialized has class type.
14405 if (InitializedFromParenListExpr) {
14406 assert(DirectInit && "Call-style initializer must be direct init.");
14407 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14409 } else if (DirectInit) {
14410 // This must be list-initialization. No other way is direct-initialization.
14412 }
14413
14414 if (LangOpts.OpenMP &&
14415 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14416 VDecl->isFileVarDecl())
14417 DeclsToCheckForDeferredDiags.insert(VDecl);
14419
14420 if (LangOpts.OpenACC && !InitType.isNull())
14421 OpenACC().ActOnVariableInit(VDecl, InitType);
14422}
14423
14425 // Our main concern here is re-establishing invariants like "a
14426 // variable's type is either dependent or complete".
14427 if (!D || D->isInvalidDecl()) return;
14428
14429 VarDecl *VD = dyn_cast<VarDecl>(D);
14430 if (!VD) return;
14431
14432 // Bindings are not usable if we can't make sense of the initializer.
14433 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14434 for (auto *BD : DD->bindings())
14435 BD->setInvalidDecl();
14436
14437 // Auto types are meaningless if we can't make sense of the initializer.
14438 if (VD->getType()->isUndeducedType()) {
14439 D->setInvalidDecl();
14440 return;
14441 }
14442
14443 QualType Ty = VD->getType();
14444 if (Ty->isDependentType()) return;
14445
14446 // Require a complete type.
14448 Context.getBaseElementType(Ty),
14449 diag::err_typecheck_decl_incomplete_type)) {
14450 VD->setInvalidDecl();
14451 return;
14452 }
14453
14454 // Require a non-abstract type.
14455 if (RequireNonAbstractType(VD->getLocation(), Ty,
14456 diag::err_abstract_type_in_decl,
14458 VD->setInvalidDecl();
14459 return;
14460 }
14461
14462 // Don't bother complaining about constructors or destructors,
14463 // though.
14464}
14465
14467 // If there is no declaration, there was an error parsing it. Just ignore it.
14468 if (!RealDecl)
14469 return;
14470
14471 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14472 QualType Type = Var->getType();
14473
14474 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14475 Diag(Var->getLocation(),
14476 diag::err_amdgcn_predicate_type_is_not_constructible)
14477 << Var;
14478 Var->setInvalidDecl();
14479 return;
14480 }
14481 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14482 if (isa<DecompositionDecl>(RealDecl)) {
14483 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14484 Var->setInvalidDecl();
14485 return;
14486 }
14487
14488 if (Type->isUndeducedType() &&
14489 DeduceVariableDeclarationType(Var, false, nullptr))
14490 return;
14491
14492 this->CheckAttributesOnDeducedType(RealDecl);
14493
14494 // C++11 [class.static.data]p3: A static data member can be declared with
14495 // the constexpr specifier; if so, its declaration shall specify
14496 // a brace-or-equal-initializer.
14497 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14498 // the definition of a variable [...] or the declaration of a static data
14499 // member.
14500 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14501 !Var->isThisDeclarationADemotedDefinition()) {
14502 if (Var->isStaticDataMember()) {
14503 // C++1z removes the relevant rule; the in-class declaration is always
14504 // a definition there.
14505 if (!getLangOpts().CPlusPlus17 &&
14506 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14507 Diag(Var->getLocation(),
14508 diag::err_constexpr_static_mem_var_requires_init)
14509 << Var;
14510 Var->setInvalidDecl();
14511 return;
14512 }
14513 } else {
14514 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14515 Var->setInvalidDecl();
14516 return;
14517 }
14518 }
14519
14520 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14521 // be initialized.
14522 if (!Var->isInvalidDecl() &&
14523 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14524 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14525 bool HasConstExprDefaultConstructor = false;
14526 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14527 for (auto *Ctor : RD->ctors()) {
14528 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14529 Ctor->getMethodQualifiers().getAddressSpace() ==
14531 HasConstExprDefaultConstructor = true;
14532 }
14533 }
14534 }
14535 if (!HasConstExprDefaultConstructor) {
14536 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14537 Var->setInvalidDecl();
14538 return;
14539 }
14540 }
14541
14542 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14543 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14544 Diag(Var->getLocation(), diag::err_specialization_const);
14545 Var->setInvalidDecl();
14546 return;
14547 }
14548
14549 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14550 if (Var->getStorageClass() == SC_Extern) {
14551 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14552 << Var;
14553 Var->setInvalidDecl();
14554 return;
14555 }
14556 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14557 diag::err_typecheck_decl_incomplete_type)) {
14558 Var->setInvalidDecl();
14559 return;
14560 }
14561 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14562 if (!RD->hasTrivialDefaultConstructor()) {
14563 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14564 Var->setInvalidDecl();
14565 return;
14566 }
14567 }
14568 // The declaration is uninitialized, no need for further checks.
14569 return;
14570 }
14571
14572 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14573 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14574 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14575 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14577 NTCUK_Init);
14578
14579 switch (DefKind) {
14581 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14582 break;
14583
14584 // We have an out-of-line definition of a static data member
14585 // that has an in-class initializer, so we type-check this like
14586 // a declaration.
14587 //
14588 [[fallthrough]];
14589
14591 // It's only a declaration.
14592
14593 // Block scope. C99 6.7p7: If an identifier for an object is
14594 // declared with no linkage (C99 6.2.2p6), the type for the
14595 // object shall be complete.
14596 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14597 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14598 RequireCompleteType(Var->getLocation(), Type,
14599 diag::err_typecheck_decl_incomplete_type))
14600 Var->setInvalidDecl();
14601
14602 // Make sure that the type is not abstract.
14603 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14604 RequireNonAbstractType(Var->getLocation(), Type,
14605 diag::err_abstract_type_in_decl,
14607 Var->setInvalidDecl();
14608 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14609 Var->getStorageClass() == SC_PrivateExtern) {
14610 Diag(Var->getLocation(), diag::warn_private_extern);
14611 Diag(Var->getLocation(), diag::note_private_extern);
14612 }
14613
14614 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14615 !Var->isInvalidDecl())
14616 ExternalDeclarations.push_back(Var);
14617
14618 return;
14619
14621 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14622 // object that has file scope without an initializer, and without a
14623 // storage-class specifier or with the storage-class specifier "static",
14624 // constitutes a tentative definition. Note: A tentative definition with
14625 // external linkage is valid (C99 6.2.2p5).
14626 if (!Var->isInvalidDecl()) {
14627 if (const IncompleteArrayType *ArrayT
14628 = Context.getAsIncompleteArrayType(Type)) {
14630 Var->getLocation(), ArrayT->getElementType(),
14631 diag::err_array_incomplete_or_sizeless_type))
14632 Var->setInvalidDecl();
14633 }
14634 if (Var->getStorageClass() == SC_Static) {
14635 // C99 6.9.2p3: If the declaration of an identifier for an object is
14636 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14637 // declared type shall not be an incomplete type.
14638 // NOTE: code such as the following
14639 // static struct s;
14640 // struct s { int a; };
14641 // is accepted by gcc. Hence here we issue a warning instead of
14642 // an error and we do not invalidate the static declaration.
14643 // NOTE: to avoid multiple warnings, only check the first declaration.
14644 if (Var->isFirstDecl())
14645 RequireCompleteType(Var->getLocation(), Type,
14646 diag::ext_typecheck_decl_incomplete_type,
14647 Type->isArrayType());
14648 }
14649 }
14650
14651 // Record the tentative definition; we're done.
14652 if (!Var->isInvalidDecl())
14653 TentativeDefinitions.push_back(Var);
14654 return;
14655 }
14656
14657 // Provide a specific diagnostic for uninitialized variable definitions
14658 // with incomplete array type, unless it is a global unbounded HLSL resource
14659 // array.
14660 if (Type->isIncompleteArrayType() &&
14661 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14663 if (Var->isConstexpr())
14664 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14665 << Var;
14666 else
14667 Diag(Var->getLocation(),
14668 diag::err_typecheck_incomplete_array_needs_initializer);
14669 Var->setInvalidDecl();
14670 return;
14671 }
14672
14673 // Provide a specific diagnostic for uninitialized variable
14674 // definitions with reference type.
14675 if (Type->isReferenceType()) {
14676 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14677 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14678 return;
14679 }
14680
14681 // Do not attempt to type-check the default initializer for a
14682 // variable with dependent type.
14683 if (Type->isDependentType())
14684 return;
14685
14686 if (Var->isInvalidDecl())
14687 return;
14688
14689 if (!Var->hasAttr<AliasAttr>()) {
14690 if (RequireCompleteType(Var->getLocation(),
14691 Context.getBaseElementType(Type),
14692 diag::err_typecheck_decl_incomplete_type)) {
14693 Var->setInvalidDecl();
14694 return;
14695 }
14696 } else {
14697 return;
14698 }
14699
14700 // The variable can not have an abstract class type.
14701 if (RequireNonAbstractType(Var->getLocation(), Type,
14702 diag::err_abstract_type_in_decl,
14704 Var->setInvalidDecl();
14705 return;
14706 }
14707
14708 // In C, if the definition is const-qualified and has no initializer, it
14709 // is left uninitialized unless it has static or thread storage duration.
14710 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14711 unsigned DiagID = diag::warn_default_init_const_unsafe;
14712 if (Var->getStorageDuration() == SD_Static ||
14713 Var->getStorageDuration() == SD_Thread)
14714 DiagID = diag::warn_default_init_const;
14715
14716 bool EmitCppCompat = !Diags.isIgnored(
14717 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14718 Var->getLocation());
14719
14720 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14721 }
14722
14723 // Check for jumps past the implicit initializer. C++0x
14724 // clarifies that this applies to a "variable with automatic
14725 // storage duration", not a "local variable".
14726 // C++11 [stmt.dcl]p3
14727 // A program that jumps from a point where a variable with automatic
14728 // storage duration is not in scope to a point where it is in scope is
14729 // ill-formed unless the variable has scalar type, class type with a
14730 // trivial default constructor and a trivial destructor, a cv-qualified
14731 // version of one of these types, or an array of one of the preceding
14732 // types and is declared without an initializer.
14733 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14734 if (const auto *CXXRecord =
14735 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14736 // Mark the function (if we're in one) for further checking even if the
14737 // looser rules of C++11 do not require such checks, so that we can
14738 // diagnose incompatibilities with C++98.
14739 if (!CXXRecord->isPOD())
14741 }
14742 }
14743 // In OpenCL, we can't initialize objects in the __local address space,
14744 // even implicitly, so don't synthesize an implicit initializer.
14745 if (getLangOpts().OpenCL &&
14746 Var->getType().getAddressSpace() == LangAS::opencl_local)
14747 return;
14748
14749 // Handle HLSL uninitialized decls
14750 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14751 return;
14752
14753 // HLSL input & push-constant variables are expected to be externally
14754 // initialized, even when marked `static`.
14755 if (getLangOpts().HLSL &&
14756 hlsl::isInitializedByPipeline(Var->getType().getAddressSpace()))
14757 return;
14758
14759 // C++03 [dcl.init]p9:
14760 // If no initializer is specified for an object, and the
14761 // object is of (possibly cv-qualified) non-POD class type (or
14762 // array thereof), the object shall be default-initialized; if
14763 // the object is of const-qualified type, the underlying class
14764 // type shall have a user-declared default
14765 // constructor. Otherwise, if no initializer is specified for
14766 // a non- static object, the object and its subobjects, if
14767 // any, have an indeterminate initial value); if the object
14768 // or any of its subobjects are of const-qualified type, the
14769 // program is ill-formed.
14770 // C++0x [dcl.init]p11:
14771 // If no initializer is specified for an object, the object is
14772 // default-initialized; [...].
14775 = InitializationKind::CreateDefault(Var->getLocation());
14776
14777 InitializationSequence InitSeq(*this, Entity, Kind, {});
14778 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14779
14780 if (Init.get()) {
14781 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14782 // This is important for template substitution.
14783 Var->setInitStyle(VarDecl::CallInit);
14784 } else if (Init.isInvalid()) {
14785 // If default-init fails, attach a recovery-expr initializer to track
14786 // that initialization was attempted and failed.
14787 auto RecoveryExpr =
14788 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14789 if (RecoveryExpr.get())
14790 Var->setInit(RecoveryExpr.get());
14791 }
14792
14794 }
14795}
14796
14798 // If there is no declaration, there was an error parsing it. Ignore it.
14799 if (!D)
14800 return;
14801
14802 VarDecl *VD = dyn_cast<VarDecl>(D);
14803 if (!VD) {
14804 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14805 D->setInvalidDecl();
14806 return;
14807 }
14808
14809 VD->setCXXForRangeDecl(true);
14810
14811 // for-range-declaration cannot be given a storage class specifier.
14812 int Error = -1;
14813 switch (VD->getStorageClass()) {
14814 case SC_None:
14815 break;
14816 case SC_Extern:
14817 Error = 0;
14818 break;
14819 case SC_Static:
14820 Error = 1;
14821 break;
14822 case SC_PrivateExtern:
14823 Error = 2;
14824 break;
14825 case SC_Auto:
14826 Error = 3;
14827 break;
14828 case SC_Register:
14829 Error = 4;
14830 break;
14831 }
14832
14833 // for-range-declaration cannot be given a storage class specifier con't.
14834 switch (VD->getTSCSpec()) {
14835 case TSCS_thread_local:
14836 Error = 6;
14837 break;
14838 case TSCS___thread:
14839 case TSCS__Thread_local:
14840 case TSCS_unspecified:
14841 break;
14842 }
14843
14844 if (Error != -1) {
14845 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14846 << VD << Error;
14847 D->setInvalidDecl();
14848 }
14849}
14850
14852 IdentifierInfo *Ident,
14853 ParsedAttributes &Attrs) {
14854 // C++1y [stmt.iter]p1:
14855 // A range-based for statement of the form
14856 // for ( for-range-identifier : for-range-initializer ) statement
14857 // is equivalent to
14858 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14859 DeclSpec DS(Attrs.getPool().getFactory());
14860
14861 const char *PrevSpec;
14862 unsigned DiagID;
14863 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14865
14867 D.SetIdentifier(Ident, IdentLoc);
14868 D.takeAttributesAppending(Attrs);
14869
14870 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14871 IdentLoc);
14872 Decl *Var = ActOnDeclarator(S, D);
14873 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14875 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14876 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14877 : IdentLoc);
14878}
14879
14882 return;
14883 auto *Attr = LifetimeBoundAttr::CreateImplicit(Context, MD->getLocation());
14884 QualType MethodType = MD->getType();
14885 QualType AttributedType =
14886 Context.getAttributedType(Attr, MethodType, MethodType);
14887 TypeLocBuilder TLB;
14888 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
14889 TLB.pushFullCopy(TSI->getTypeLoc());
14890 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(AttributedType);
14891 TyLoc.setAttr(Attr);
14892 MD->setType(AttributedType);
14893 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, AttributedType));
14894}
14895
14897 if (var->isInvalidDecl()) return;
14898
14900
14901 if (getLangOpts().OpenCL) {
14902 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14903 // initialiser
14904 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14905 !var->hasInit()) {
14906 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14907 << 1 /*Init*/;
14908 var->setInvalidDecl();
14909 return;
14910 }
14911 }
14912
14913 // In Objective-C, don't allow jumps past the implicit initialization of a
14914 // local retaining variable.
14915 if (getLangOpts().ObjC &&
14916 var->hasLocalStorage()) {
14917 switch (var->getType().getObjCLifetime()) {
14921 break;
14922
14926 break;
14927 }
14928 }
14929
14930 if (var->hasLocalStorage() &&
14931 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14933
14934 // Warn about externally-visible variables being defined without a
14935 // prior declaration. We only want to do this for global
14936 // declarations, but we also specifically need to avoid doing it for
14937 // class members because the linkage of an anonymous class can
14938 // change if it's later given a typedef name.
14939 if (var->isThisDeclarationADefinition() &&
14940 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14941 var->isExternallyVisible() && var->hasLinkage() &&
14942 !var->isInline() && !var->getDescribedVarTemplate() &&
14943 var->getStorageClass() != SC_Register &&
14945 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14946 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14947 var->getLocation())) {
14948 // Find a previous declaration that's not a definition.
14949 VarDecl *prev = var->getPreviousDecl();
14950 while (prev && prev->isThisDeclarationADefinition())
14951 prev = prev->getPreviousDecl();
14952
14953 if (!prev) {
14954 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14955 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14956 << /* variable */ 0;
14957 }
14958 }
14959
14960 // Cache the result of checking for constant initialization.
14961 std::optional<bool> CacheHasConstInit;
14962 const Expr *CacheCulprit = nullptr;
14963 auto checkConstInit = [&]() mutable {
14964 const Expr *Init = var->getInit();
14965 if (Init->isInstantiationDependent())
14966 return true;
14967
14968 if (!CacheHasConstInit)
14969 CacheHasConstInit = var->getInit()->isConstantInitializer(
14970 Context, var->getType()->isReferenceType(), &CacheCulprit);
14971 return *CacheHasConstInit;
14972 };
14973
14974 if (var->getTLSKind() == VarDecl::TLS_Static) {
14975 if (var->getType().isDestructedType()) {
14976 // GNU C++98 edits for __thread, [basic.start.term]p3:
14977 // The type of an object with thread storage duration shall not
14978 // have a non-trivial destructor.
14979 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14981 Diag(var->getLocation(), diag::note_use_thread_local);
14982 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14983 if (!checkConstInit()) {
14984 // GNU C++98 edits for __thread, [basic.start.init]p4:
14985 // An object of thread storage duration shall not require dynamic
14986 // initialization.
14987 // FIXME: Need strict checking here.
14988 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14989 << CacheCulprit->getSourceRange();
14991 Diag(var->getLocation(), diag::note_use_thread_local);
14992 }
14993 }
14994 }
14995
14996
14997 if (!var->getType()->isStructureType() && var->hasInit() &&
14998 isa<InitListExpr>(var->getInit())) {
14999 const auto *ILE = cast<InitListExpr>(var->getInit());
15000 unsigned NumInits = ILE->getNumInits();
15001 if (NumInits > 2)
15002 for (unsigned I = 0; I < NumInits; ++I) {
15003 const auto *Init = ILE->getInit(I);
15004 if (!Init)
15005 break;
15006 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
15007 if (!SL)
15008 break;
15009
15010 unsigned NumConcat = SL->getNumConcatenated();
15011 // Diagnose missing comma in string array initialization.
15012 // Do not warn when all the elements in the initializer are concatenated
15013 // together. Do not warn for macros too.
15014 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15015 bool OnlyOneMissingComma = true;
15016 for (unsigned J = I + 1; J < NumInits; ++J) {
15017 const auto *Init = ILE->getInit(J);
15018 if (!Init)
15019 break;
15020 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
15021 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15022 OnlyOneMissingComma = false;
15023 break;
15024 }
15025 }
15026
15027 if (OnlyOneMissingComma) {
15029 for (unsigned i = 0; i < NumConcat - 1; ++i)
15030 Hints.push_back(FixItHint::CreateInsertion(
15031 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
15032
15033 Diag(SL->getStrTokenLoc(1),
15034 diag::warn_concatenated_literal_array_init)
15035 << Hints;
15036 Diag(SL->getBeginLoc(),
15037 diag::note_concatenated_string_literal_silence);
15038 }
15039 // In any case, stop now.
15040 break;
15041 }
15042 }
15043 }
15044
15045
15046 QualType type = var->getType();
15047
15048 if (var->hasAttr<BlocksAttr>())
15050
15051 Expr *Init = var->getInit();
15052 bool GlobalStorage = var->hasGlobalStorage();
15053 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15054 QualType baseType = Context.getBaseElementType(type);
15055 bool HasConstInit = true;
15056
15057 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15058 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
15059 << var;
15060
15061 // Check whether the initializer is sufficiently constant.
15062 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15063 !type->isDependentType() && Init && !Init->isValueDependent() &&
15064 (GlobalStorage || var->isConstexpr() ||
15065 var->mightBeUsableInConstantExpressions(Context))) {
15066 // If this variable might have a constant initializer or might be usable in
15067 // constant expressions, check whether or not it actually is now. We can't
15068 // do this lazily, because the result might depend on things that change
15069 // later, such as which constexpr functions happen to be defined.
15071 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15072 // Prior to C++11, in contexts where a constant initializer is required,
15073 // the set of valid constant initializers is described by syntactic rules
15074 // in [expr.const]p2-6.
15075 // FIXME: Stricter checking for these rules would be useful for constinit /
15076 // -Wglobal-constructors.
15077 HasConstInit = checkConstInit();
15078
15079 // Compute and cache the constant value, and remember that we have a
15080 // constant initializer.
15081 if (HasConstInit) {
15082 if (var->isStaticDataMember() && !var->isInline() &&
15083 var->getLexicalDeclContext()->isRecord() &&
15084 type->isIntegralOrEnumerationType()) {
15085 // In C++98, in-class initialization for a static data member must
15086 // be an integer constant expression.
15087 if (!Init->isIntegerConstantExpr(Context)) {
15088 Diag(Init->getExprLoc(),
15089 diag::ext_in_class_initializer_non_constant)
15090 << Init->getSourceRange();
15091 }
15092 }
15093 (void)var->checkForConstantInitialization(Notes);
15094 Notes.clear();
15095 } else if (CacheCulprit) {
15096 Notes.emplace_back(CacheCulprit->getExprLoc(),
15097 PDiag(diag::note_invalid_subexpr_in_const_expr));
15098 Notes.back().second << CacheCulprit->getSourceRange();
15099 }
15100 } else {
15101 // Evaluate the initializer to see if it's a constant initializer.
15102 HasConstInit = var->checkForConstantInitialization(Notes);
15103 }
15104
15105 if (HasConstInit) {
15106 // FIXME: Consider replacing the initializer with a ConstantExpr.
15107 } else if (var->isConstexpr()) {
15108 SourceLocation DiagLoc = var->getLocation();
15109 // If the note doesn't add any useful information other than a source
15110 // location, fold it into the primary diagnostic.
15111 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15112 diag::note_invalid_subexpr_in_const_expr) {
15113 DiagLoc = Notes[0].first;
15114 Notes.clear();
15115 }
15116 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
15117 << var << Init->getSourceRange();
15118 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15119 Diag(Notes[I].first, Notes[I].second);
15120 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15121 auto *Attr = var->getAttr<ConstInitAttr>();
15122 Diag(var->getLocation(), diag::err_require_constant_init_failed)
15123 << Init->getSourceRange();
15124 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
15125 << Attr->getRange() << Attr->isConstinit();
15126 for (auto &it : Notes)
15127 Diag(it.first, it.second);
15128 } else if (var->isStaticDataMember() && !var->isInline() &&
15129 var->getLexicalDeclContext()->isRecord()) {
15130 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
15131 << Init->getSourceRange();
15132 for (auto &it : Notes)
15133 Diag(it.first, it.second);
15134 var->setInvalidDecl();
15135 } else if (IsGlobal &&
15136 !getDiagnostics().isIgnored(diag::warn_global_constructor,
15137 var->getLocation())) {
15138 // Warn about globals which don't have a constant initializer. Don't
15139 // warn about globals with a non-trivial destructor because we already
15140 // warned about them.
15141 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15142 if (!(RD && !RD->hasTrivialDestructor())) {
15143 // checkConstInit() here permits trivial default initialization even in
15144 // C++11 onwards, where such an initializer is not a constant initializer
15145 // but nonetheless doesn't require a global constructor.
15146 if (!checkConstInit())
15147 Diag(var->getLocation(), diag::warn_global_constructor)
15148 << Init->getSourceRange();
15149 }
15150 }
15151 }
15152
15153 // Apply section attributes and pragmas to global variables.
15154 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15156 PragmaStack<StringLiteral *> *Stack = nullptr;
15157 int SectionFlags = ASTContext::PSF_Read;
15158 bool MSVCEnv =
15159 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15160 std::optional<QualType::NonConstantStorageReason> Reason;
15161 if (HasConstInit &&
15162 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
15163 Stack = &ConstSegStack;
15164 } else {
15165 SectionFlags |= ASTContext::PSF_Write;
15166 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15167 }
15168 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15169 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15170 SectionFlags |= ASTContext::PSF_Implicit;
15171 UnifySection(SA->getName(), SectionFlags, var);
15172 } else if (Stack->CurrentValue) {
15173 if (Stack != &ConstSegStack && MSVCEnv &&
15174 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15175 var->getType().isConstQualified()) {
15176 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15177 NonConstNonReferenceType) &&
15178 "This case should've already been handled elsewhere");
15179 Diag(var->getLocation(), diag::warn_section_msvc_compat)
15180 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15182 : *Reason);
15183 }
15184 SectionFlags |= ASTContext::PSF_Implicit;
15185 auto SectionName = Stack->CurrentValue->getString();
15186 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
15187 Stack->CurrentPragmaLocation,
15188 SectionAttr::Declspec_allocate));
15189 if (UnifySection(SectionName, SectionFlags, var))
15190 var->dropAttr<SectionAttr>();
15191 }
15192
15193 // Apply the init_seg attribute if this has an initializer. If the
15194 // initializer turns out to not be dynamic, we'll end up ignoring this
15195 // attribute.
15196 if (CurInitSeg && var->getInit())
15197 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
15198 CurInitSegLoc));
15199 }
15200
15201 // All the following checks are C++ only.
15202 if (!getLangOpts().CPlusPlus) {
15203 // If this variable must be emitted, add it as an initializer for the
15204 // current module.
15205 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15206 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15207 return;
15208 }
15209
15211
15212 // Require the destructor.
15213 if (!type->isDependentType())
15214 if (auto *RD = baseType->getAsCXXRecordDecl())
15216
15217 // If this variable must be emitted, add it as an initializer for the current
15218 // module.
15219 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty() &&
15220 (ModuleScopes.back().Module->isHeaderLikeModule() ||
15221 // For named modules, we may only emit non discardable variables.
15222 !isDiscardableGVALinkage(Context.GetGVALinkageForVariable(var))))
15223 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15224
15225 // Build the bindings if this is a structured binding declaration.
15226 if (auto *DD = dyn_cast<DecompositionDecl>(var))
15228}
15229
15231 assert(VD->isStaticLocal());
15232
15233 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15234
15235 // Find outermost function when VD is in lambda function.
15236 while (FD && !getDLLAttr(FD) &&
15237 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15238 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15239 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15240 }
15241
15242 if (!FD)
15243 return;
15244
15245 // Static locals inherit dll attributes from their function.
15246 if (Attr *A = getDLLAttr(FD)) {
15247 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15248 NewAttr->setInherited(true);
15249 VD->addAttr(NewAttr);
15250 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15251 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15252 NewAttr->setInherited(true);
15253 VD->addAttr(NewAttr);
15254
15255 // Export this function to enforce exporting this static variable even
15256 // if it is not used in this compilation unit.
15257 if (!FD->hasAttr<DLLExportAttr>())
15258 FD->addAttr(NewAttr);
15259
15260 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15261 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15262 NewAttr->setInherited(true);
15263 VD->addAttr(NewAttr);
15264 }
15265}
15266
15268 assert(VD->getTLSKind());
15269
15270 // Perform TLS alignment check here after attributes attached to the variable
15271 // which may affect the alignment have been processed. Only perform the check
15272 // if the target has a maximum TLS alignment (zero means no constraints).
15273 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15274 // Protect the check so that it's not performed on dependent types and
15275 // dependent alignments (we can't determine the alignment in that case).
15276 if (!VD->hasDependentAlignment()) {
15277 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15278 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15279 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15280 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15281 << (unsigned)MaxAlignChars.getQuantity();
15282 }
15283 }
15284 }
15285}
15286
15288 // Note that we are no longer parsing the initializer for this declaration.
15289 ParsingInitForAutoVars.erase(ThisDecl);
15290
15291 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15292 if (!VD)
15293 return;
15294
15295 // Emit any deferred warnings for the variable's initializer, even if the
15296 // variable is invalid
15297 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15298
15299 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15301 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15302 if (PragmaClangBSSSection.Valid)
15303 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15304 Context, PragmaClangBSSSection.SectionName,
15305 PragmaClangBSSSection.PragmaLocation));
15306 if (PragmaClangDataSection.Valid)
15307 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15308 Context, PragmaClangDataSection.SectionName,
15309 PragmaClangDataSection.PragmaLocation));
15310 if (PragmaClangRodataSection.Valid)
15311 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15312 Context, PragmaClangRodataSection.SectionName,
15313 PragmaClangRodataSection.PragmaLocation));
15314 if (PragmaClangRelroSection.Valid)
15315 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15316 Context, PragmaClangRelroSection.SectionName,
15317 PragmaClangRelroSection.PragmaLocation));
15318 }
15319
15320 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15321 for (auto *BD : DD->bindings()) {
15323 }
15324 }
15325
15326 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15328
15329 checkAttributesAfterMerging(*this, *VD);
15330
15331 if (VD->isStaticLocal())
15333
15334 if (VD->getTLSKind())
15336
15337 // Perform check for initializers of device-side global variables.
15338 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15339 // 7.5). We must also apply the same checks to all __shared__
15340 // variables whether they are local or not. CUDA also allows
15341 // constant initializers for __constant__ and __device__ variables.
15342 if (getLangOpts().CUDA)
15344
15345 // Grab the dllimport or dllexport attribute off of the VarDecl.
15346 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15347
15348 // Imported static data members cannot be defined out-of-line.
15349 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15350 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15352 // We allow definitions of dllimport class template static data members
15353 // with a warning.
15356 bool IsClassTemplateMember =
15358 Context->getDescribedClassTemplate();
15359
15360 Diag(VD->getLocation(),
15361 IsClassTemplateMember
15362 ? diag::warn_attribute_dllimport_static_field_definition
15363 : diag::err_attribute_dllimport_static_field_definition);
15364 Diag(IA->getLocation(), diag::note_attribute);
15365 if (!IsClassTemplateMember)
15366 VD->setInvalidDecl();
15367 }
15368 }
15369
15370 // dllimport/dllexport variables cannot be thread local, their TLS index
15371 // isn't exported with the variable.
15372 if (DLLAttr && VD->getTLSKind()) {
15373 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15374 if (F && getDLLAttr(F)) {
15375 assert(VD->isStaticLocal());
15376 // But if this is a static local in a dlimport/dllexport function, the
15377 // function will never be inlined, which means the var would never be
15378 // imported, so having it marked import/export is safe.
15379 } else {
15380 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15381 << DLLAttr;
15382 VD->setInvalidDecl();
15383 }
15384 }
15385
15386 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15387 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15388 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15389 << Attr;
15390 VD->dropAttr<UsedAttr>();
15391 }
15392 }
15393 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15394 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15395 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15396 << Attr;
15397 VD->dropAttr<RetainAttr>();
15398 }
15399 }
15400
15401 const DeclContext *DC = VD->getDeclContext();
15402 // If there's a #pragma GCC visibility in scope, and this isn't a class
15403 // member, set the visibility of this variable.
15406
15407 // FIXME: Warn on unused var template partial specializations.
15410
15411 // Now we have parsed the initializer and can update the table of magic
15412 // tag values.
15413 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15415 return;
15416
15417 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15418 const Expr *MagicValueExpr = VD->getInit();
15419 if (!MagicValueExpr) {
15420 continue;
15421 }
15422 std::optional<llvm::APSInt> MagicValueInt;
15423 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15424 Diag(I->getRange().getBegin(),
15425 diag::err_type_tag_for_datatype_not_ice)
15426 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15427 continue;
15428 }
15429 if (MagicValueInt->getActiveBits() > 64) {
15430 Diag(I->getRange().getBegin(),
15431 diag::err_type_tag_for_datatype_too_large)
15432 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15433 continue;
15434 }
15435 uint64_t MagicValue = MagicValueInt->getZExtValue();
15436 RegisterTypeTagForDatatype(I->getArgumentKind(),
15437 MagicValue,
15438 I->getMatchingCType(),
15439 I->getLayoutCompatible(),
15440 I->getMustBeNull());
15441 }
15442}
15443
15445 auto *VD = dyn_cast<VarDecl>(DD);
15446 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15447}
15448
15450 ArrayRef<Decl *> Group) {
15452
15453 if (DS.isTypeSpecOwned())
15454 Decls.push_back(DS.getRepAsDecl());
15455
15456 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15457 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15458 bool DiagnosedMultipleDecomps = false;
15459 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15460 bool DiagnosedNonDeducedAuto = false;
15461
15462 for (Decl *D : Group) {
15463 if (!D)
15464 continue;
15465 // Check if the Decl has been declared in '#pragma omp declare target'
15466 // directive and has static storage duration.
15467 if (auto *VD = dyn_cast<VarDecl>(D);
15468 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15469 VD->hasGlobalStorage())
15471 // For declarators, there are some additional syntactic-ish checks we need
15472 // to perform.
15473 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15474 if (!FirstDeclaratorInGroup)
15475 FirstDeclaratorInGroup = DD;
15476 if (!FirstDecompDeclaratorInGroup)
15477 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15478 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15479 !hasDeducedAuto(DD))
15480 FirstNonDeducedAutoInGroup = DD;
15481
15482 if (FirstDeclaratorInGroup != DD) {
15483 // A decomposition declaration cannot be combined with any other
15484 // declaration in the same group.
15485 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15486 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15487 diag::err_decomp_decl_not_alone)
15488 << FirstDeclaratorInGroup->getSourceRange()
15489 << DD->getSourceRange();
15490 DiagnosedMultipleDecomps = true;
15491 }
15492
15493 // A declarator that uses 'auto' in any way other than to declare a
15494 // variable with a deduced type cannot be combined with any other
15495 // declarator in the same group.
15496 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15497 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15498 diag::err_auto_non_deduced_not_alone)
15499 << FirstNonDeducedAutoInGroup->getType()
15501 << FirstDeclaratorInGroup->getSourceRange()
15502 << DD->getSourceRange();
15503 DiagnosedNonDeducedAuto = true;
15504 }
15505 }
15506 }
15507
15508 Decls.push_back(D);
15509 }
15510
15512 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15513 handleTagNumbering(Tag, S);
15514 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15516 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15517 }
15518 }
15519
15520 return BuildDeclaratorGroup(Decls);
15521}
15522
15525 // C++14 [dcl.spec.auto]p7: (DR1347)
15526 // If the type that replaces the placeholder type is not the same in each
15527 // deduction, the program is ill-formed.
15528 if (Group.size() > 1) {
15530 VarDecl *DeducedDecl = nullptr;
15531 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15532 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15533 if (!D || D->isInvalidDecl())
15534 break;
15535 DeducedType *DT = D->getType()->getContainedDeducedType();
15536 if (!DT || DT->getDeducedType().isNull())
15537 continue;
15538 if (Deduced.isNull()) {
15539 Deduced = DT->getDeducedType();
15540 DeducedDecl = D;
15541 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15542 auto *AT = dyn_cast<AutoType>(DT);
15543 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15544 diag::err_auto_different_deductions)
15545 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15546 << DeducedDecl->getDeclName() << DT->getDeducedType()
15547 << D->getDeclName();
15548 if (DeducedDecl->hasInit())
15549 Dia << DeducedDecl->getInit()->getSourceRange();
15550 if (D->getInit())
15551 Dia << D->getInit()->getSourceRange();
15552 D->setInvalidDecl();
15553 break;
15554 }
15555 }
15556 }
15557
15559
15560 return DeclGroupPtrTy::make(
15561 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15562}
15563
15567
15569 // Don't parse the comment if Doxygen diagnostics are ignored.
15570 if (Group.empty() || !Group[0])
15571 return;
15572
15573 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15574 Group[0]->getLocation()) &&
15575 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15576 Group[0]->getLocation()))
15577 return;
15578
15579 if (Group.size() >= 2) {
15580 // This is a decl group. Normally it will contain only declarations
15581 // produced from declarator list. But in case we have any definitions or
15582 // additional declaration references:
15583 // 'typedef struct S {} S;'
15584 // 'typedef struct S *S;'
15585 // 'struct S *pS;'
15586 // FinalizeDeclaratorGroup adds these as separate declarations.
15587 Decl *MaybeTagDecl = Group[0];
15588 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15589 Group = Group.slice(1);
15590 }
15591 }
15592
15593 // FIXME: We assume every Decl in the group is in the same file.
15594 // This is false when preprocessor constructs the group from decls in
15595 // different files (e. g. macros or #include).
15596 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15597}
15598
15600 // Check that there are no default arguments inside the type of this
15601 // parameter.
15602 if (getLangOpts().CPlusPlus)
15604
15605 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15606 if (D.getCXXScopeSpec().isSet()) {
15607 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15608 << D.getCXXScopeSpec().getRange();
15609 }
15610
15611 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15612 // simple identifier except [...irrelevant cases...].
15613 switch (D.getName().getKind()) {
15615 break;
15616
15624 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15626 break;
15627
15630 // GetNameForDeclarator would not produce a useful name in this case.
15631 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15632 break;
15633 }
15634}
15635
15637 // This only matters in C.
15638 if (getLangOpts().CPlusPlus)
15639 return;
15640
15641 // This only matters if the declaration has a type.
15642 const auto *VD = dyn_cast<ValueDecl>(D);
15643 if (!VD)
15644 return;
15645
15646 // Get the type, this only matters for tag types.
15647 QualType QT = VD->getType();
15648 const auto *TD = QT->getAsTagDecl();
15649 if (!TD)
15650 return;
15651
15652 // Check if the tag declaration is lexically declared somewhere different
15653 // from the lexical declaration of the given object, then it will be hidden
15654 // in C++ and we should warn on it.
15655 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15656 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15657 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15658 Diag(TD->getLocation(), diag::note_declared_at);
15659 }
15660}
15661
15663 SourceLocation ExplicitThisLoc) {
15664 if (!ExplicitThisLoc.isValid())
15665 return;
15666 assert(S.getLangOpts().CPlusPlus &&
15667 "explicit parameter in non-cplusplus mode");
15668 if (!S.getLangOpts().CPlusPlus23)
15669 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15670 << P->getSourceRange();
15671
15672 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15673 // parameter pack.
15674 if (P->isParameterPack()) {
15675 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15676 << P->getSourceRange();
15677 return;
15678 }
15679 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15680 if (LambdaScopeInfo *LSI = S.getCurLambda())
15681 LSI->ExplicitObjectParameter = P;
15682}
15683
15685 SourceLocation ExplicitThisLoc) {
15686 const DeclSpec &DS = D.getDeclSpec();
15687
15688 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15689 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15690 // except for the special case of a single unnamed parameter of type void
15691 // with no storage class specifier, no type qualifier, and no following
15692 // ellipsis terminator.
15693 // Clang applies the C2y rules for 'register void' in all C language modes,
15694 // same as GCC, because it's questionable what that could possibly mean.
15695
15696 // C++03 [dcl.stc]p2 also permits 'auto'.
15697 StorageClass SC = SC_None;
15699 SC = SC_Register;
15700 // In C++11, the 'register' storage class specifier is deprecated.
15701 // In C++17, it is not allowed, but we tolerate it as an extension.
15702 if (getLangOpts().CPlusPlus11) {
15704 ? diag::ext_register_storage_class
15705 : diag::warn_deprecated_register)
15707 } else if (!getLangOpts().CPlusPlus &&
15709 D.getNumTypeObjects() == 0) {
15711 diag::err_invalid_storage_class_in_func_decl)
15714 }
15715 } else if (getLangOpts().CPlusPlus &&
15717 SC = SC_Auto;
15720 diag::err_invalid_storage_class_in_func_decl);
15722 }
15723
15725 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15727 if (DS.isInlineSpecified())
15728 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15729 << getLangOpts().CPlusPlus17;
15730 if (DS.hasConstexprSpecifier())
15731 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15732 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15733
15735
15737
15739 QualType parmDeclType = TInfo->getType();
15740
15741 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15742 const IdentifierInfo *II = D.getIdentifier();
15743 if (II) {
15746 LookupName(R, S);
15747 if (!R.empty()) {
15748 NamedDecl *PrevDecl = *R.begin();
15749 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15750 // Maybe we will complain about the shadowed template parameter.
15752 // Just pretend that we didn't see the previous declaration.
15753 PrevDecl = nullptr;
15754 }
15755 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15756 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15757 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15758 // Recover by removing the name
15759 II = nullptr;
15760 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15761 D.setInvalidType(true);
15762 }
15763 }
15764 }
15765
15766 // Incomplete resource arrays are not allowed as function parameters in HLSL
15767 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15768 parmDeclType->isHLSLResourceRecordArray()) {
15770 diag::err_hlsl_incomplete_resource_array_in_function_param);
15771 D.setInvalidType(true);
15772 }
15773
15774 // Temporarily put parameter variables in the translation unit, not
15775 // the enclosing context. This prevents them from accidentally
15776 // looking like class members in C++.
15777 ParmVarDecl *New =
15778 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15779 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15780
15781 if (D.isInvalidType())
15782 New->setInvalidDecl();
15783
15784 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15785
15786 assert(S->isFunctionPrototypeScope());
15787 assert(S->getFunctionPrototypeDepth() >= 1);
15788 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15790
15792
15793 // Add the parameter declaration into this scope.
15794 S->AddDecl(New);
15795 if (II)
15796 IdResolver.AddDecl(New);
15797
15799
15801 Diag(New->getLocation(), diag::err_module_private_local)
15804
15805 if (New->hasAttr<BlocksAttr>())
15806 Diag(New->getLocation(), diag::err_block_not_allowed_on)
15807 << diag::NotAllowedBlockVarReason::NonlocalVariable;
15808
15809 New->deduceParmAddressSpace(Context);
15810
15811 return New;
15812}
15813
15815 SourceLocation Loc,
15816 QualType T) {
15817 /* FIXME: setting StartLoc == Loc.
15818 Would it be worth to modify callers so as to provide proper source
15819 location for the unnamed parameters, embedding the parameter's type? */
15820 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15821 T, Context.getTrivialTypeSourceInfo(T, Loc),
15822 SC_None, nullptr);
15823 Param->setImplicit();
15824 return Param;
15825}
15826
15828 // Don't diagnose unused-parameter errors in template instantiations; we
15829 // will already have done so in the template itself.
15831 return;
15832
15833 for (const ParmVarDecl *Parameter : Parameters) {
15834 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15835 !Parameter->hasAttr<UnusedAttr>() &&
15836 !Parameter->getIdentifier()->isPlaceholder()) {
15837 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15838 << Parameter->getDeclName();
15839 }
15840 }
15841}
15842
15844 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15845 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15846 return;
15847
15848 // Warn if the return value is pass-by-value and larger than the specified
15849 // threshold.
15850 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15851 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15852 if (Size > LangOpts.NumLargeByValueCopy)
15853 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15854 }
15855
15856 // Warn if any parameter is pass-by-value and larger than the specified
15857 // threshold.
15858 for (const ParmVarDecl *Parameter : Parameters) {
15859 QualType T = Parameter->getType();
15860 if (T->isDependentType() || !T.isPODType(Context))
15861 continue;
15862 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15863 if (Size > LangOpts.NumLargeByValueCopy)
15864 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15865 << Parameter << Size;
15866 }
15867}
15868
15870 SourceLocation NameLoc,
15871 const IdentifierInfo *Name, QualType T,
15872 TypeSourceInfo *TSInfo, StorageClass SC) {
15873 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15874 if (getLangOpts().ObjCAutoRefCount &&
15875 T.getObjCLifetime() == Qualifiers::OCL_None &&
15876 T->isObjCLifetimeType()) {
15877
15878 Qualifiers::ObjCLifetime lifetime;
15879
15880 // Special cases for arrays:
15881 // - if it's const, use __unsafe_unretained
15882 // - otherwise, it's an error
15883 if (T->isArrayType()) {
15884 if (!T.isConstQualified()) {
15888 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15889 else
15890 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15891 << TSInfo->getTypeLoc().getSourceRange();
15892 }
15894 } else {
15895 lifetime = T->getObjCARCImplicitLifetime();
15896 }
15897 T = Context.getLifetimeQualifiedType(T, lifetime);
15898 }
15899
15900 if (getLangOpts().OpenCL) {
15901 assert(!isa<DecayedType>(T));
15902 if (T->isArrayType() && !T.hasAddressSpace()) {
15903 QualType ET = Context.getAsArrayType(T)->getElementType();
15904 if (!ET.hasAddressSpace()) {
15905 // Add the private address space to the contents of the pointer when a
15906 // pointer parameter is declared as an array and not declared.
15908 T = Context.getAddrSpaceQualType(T, ImplAS);
15909 T = QualType(Context.getAsArrayType(T), 0);
15910 }
15911 }
15912 }
15913
15914 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15915 Context.getAdjustedParameterType(T),
15916 TSInfo, SC, nullptr);
15917
15918 // Make a note if we created a new pack in the scope of a lambda, so that
15919 // we know that references to that pack must also be expanded within the
15920 // lambda scope.
15921 if (New->isParameterPack())
15922 if (auto *CSI = getEnclosingLambdaOrBlock())
15923 CSI->LocalPacks.push_back(New);
15924
15925 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15926 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15927 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15930
15931 // Parameter declarators cannot be interface types. All ObjC objects are
15932 // passed by reference.
15933 if (T->isObjCObjectType()) {
15934 SourceLocation TypeEndLoc =
15936 Diag(NameLoc,
15937 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15938 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15939 T = Context.getObjCObjectPointerType(T);
15940 New->setType(T);
15941 }
15942
15943 // __ptrauth is forbidden on parameters.
15944 if (T.getPointerAuth()) {
15945 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
15946 New->setInvalidDecl();
15947 }
15948
15949 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15950 // duration shall not be qualified by an address-space qualifier."
15951 // Since all parameters have automatic store duration, they can not have
15952 // an address space.
15953 if (T.getAddressSpace() != LangAS::Default &&
15954 // OpenCL allows function arguments declared to be an array of a type
15955 // to be qualified with an address space.
15956 !(getLangOpts().OpenCL &&
15957 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15958 // WebAssembly allows reference types as parameters. Funcref in particular
15959 // lives in a different address space.
15960 !(T->isFunctionPointerType() &&
15961 T.getAddressSpace() == LangAS::wasm_funcref) &&
15962 // HLSL allows function arguments to be qualified with an address space
15963 // if the groupshared annotation is used.
15964 !(getLangOpts().HLSL &&
15965 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
15966 Diag(NameLoc, diag::err_arg_with_address_space);
15967 New->setInvalidDecl();
15968 }
15969
15970 // PPC MMA non-pointer types are not allowed as function argument types.
15971 if (Context.getTargetInfo().getTriple().isPPC64() &&
15972 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15973 New->setInvalidDecl();
15974 }
15975
15976 return New;
15977}
15978
15980 SourceLocation LocAfterDecls) {
15982
15983 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15984 // in the declaration list shall have at least one declarator, those
15985 // declarators shall only declare identifiers from the identifier list, and
15986 // every identifier in the identifier list shall be declared.
15987 //
15988 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15989 // identifiers it names shall be declared in the declaration list."
15990 //
15991 // This is why we only diagnose in C99 and later. Note, the other conditions
15992 // listed are checked elsewhere.
15993 if (!FTI.hasPrototype) {
15994 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15995 --i;
15996 if (FTI.Params[i].Param == nullptr) {
15997 if (getLangOpts().C99) {
15998 SmallString<256> Code;
15999 llvm::raw_svector_ostream(Code)
16000 << " int " << FTI.Params[i].Ident->getName() << ";\n";
16001 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
16002 << FTI.Params[i].Ident
16003 << FixItHint::CreateInsertion(LocAfterDecls, Code);
16004 }
16005
16006 // Implicitly declare the argument as type 'int' for lack of a better
16007 // type.
16008 AttributeFactory attrs;
16009 DeclSpec DS(attrs);
16010 const char* PrevSpec; // unused
16011 unsigned DiagID; // unused
16012 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
16013 DiagID, Context.getPrintingPolicy());
16014 // Use the identifier location for the type source range.
16015 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16016 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16019 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
16020 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
16021 }
16022 }
16023 }
16024}
16025
16026Decl *
16028 MultiTemplateParamsArg TemplateParameterLists,
16029 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16030 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16031 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16032 Scope *ParentScope = FnBodyScope->getParent();
16033
16034 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16035 // we define a non-templated function definition, we will create a declaration
16036 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16037 // The base function declaration will have the equivalent of an `omp declare
16038 // variant` annotation which specifies the mangled definition as a
16039 // specialization function under the OpenMP context defined as part of the
16040 // `omp begin declare variant`.
16042 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16044 ParentScope, D, TemplateParameterLists, Bases);
16045
16047 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
16048 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
16049
16050 if (!Bases.empty())
16052 Bases);
16053
16054 return Dcl;
16055}
16056
16058 Consumer.HandleInlineFunctionDefinition(D);
16059}
16060
16062 const FunctionDecl *&PossiblePrototype) {
16063 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16064 Prev = Prev->getPreviousDecl()) {
16065 // Ignore any declarations that occur in function or method
16066 // scope, because they aren't visible from the header.
16067 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16068 continue;
16069
16070 PossiblePrototype = Prev;
16071 return Prev->getType()->isFunctionProtoType();
16072 }
16073 return false;
16074}
16075
16076static bool
16078 const FunctionDecl *&PossiblePrototype) {
16079 // Don't warn about invalid declarations.
16080 if (FD->isInvalidDecl())
16081 return false;
16082
16083 // Or declarations that aren't global.
16084 if (!FD->isGlobal())
16085 return false;
16086
16087 // Don't warn about C++ member functions.
16088 if (isa<CXXMethodDecl>(FD))
16089 return false;
16090
16091 // Don't warn about 'main'.
16093 if (IdentifierInfo *II = FD->getIdentifier())
16094 if (II->isStr("main") || II->isStr("efi_main"))
16095 return false;
16096
16097 if (FD->isMSVCRTEntryPoint())
16098 return false;
16099
16100 // Don't warn about inline functions.
16101 if (FD->isInlined())
16102 return false;
16103
16104 // Don't warn about function templates.
16106 return false;
16107
16108 // Don't warn about function template specializations.
16110 return false;
16111
16112 // Don't warn for OpenCL kernels.
16113 if (FD->hasAttr<DeviceKernelAttr>())
16114 return false;
16115
16116 // Don't warn on explicitly deleted functions.
16117 if (FD->isDeleted())
16118 return false;
16119
16120 // Don't warn on implicitly local functions (such as having local-typed
16121 // parameters).
16122 if (!FD->isExternallyVisible())
16123 return false;
16124
16125 // If we were able to find a potential prototype, don't warn.
16126 if (FindPossiblePrototype(FD, PossiblePrototype))
16127 return false;
16128
16129 return true;
16130}
16131
16132void
16134 const FunctionDecl *EffectiveDefinition,
16135 SkipBodyInfo *SkipBody) {
16136 const FunctionDecl *Definition = EffectiveDefinition;
16137 if (!Definition &&
16138 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16139 return;
16140
16141 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16142 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16143 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16144 // A merged copy of the same function, instantiated as a member of
16145 // the same class, is OK.
16146 if (declaresSameEntity(OrigFD, OrigDef) &&
16147 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
16149 return;
16150 }
16151 }
16152 }
16153
16155 return;
16156
16157 // Don't emit an error when this is redefinition of a typo-corrected
16158 // definition.
16160 return;
16161
16162 bool DefinitionVisible = false;
16163 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&
16164 (Definition->getFormalLinkage() == Linkage::Internal ||
16165 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16166 !Definition->getTemplateParameterLists().empty())) {
16167 SkipBody->ShouldSkip = true;
16168 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16169 if (!DefinitionVisible) {
16170 if (auto *TD = Definition->getDescribedFunctionTemplate())
16173 }
16174 return;
16175 }
16176
16177 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16178 Definition->getStorageClass() == SC_Extern)
16179 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
16180 << FD << getLangOpts().CPlusPlus;
16181 else
16182 Diag(FD->getLocation(), diag::err_redefinition) << FD;
16183
16184 Diag(Definition->getLocation(), diag::note_previous_definition);
16185 FD->setInvalidDecl();
16186}
16187
16189 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16190
16192 LSI->CallOperator = CallOperator;
16193 LSI->Lambda = LambdaClass;
16194 LSI->ReturnType = CallOperator->getReturnType();
16195 // When this function is called in situation where the context of the call
16196 // operator is not entered, we set AfterParameterList to false, so that
16197 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16198 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16199 // where we would set the CurContext to the lambda operator before
16200 // substituting into it. In this case the flag needs to be true such that
16201 // tryCaptureVariable can correctly handle potential captures thereof.
16202 LSI->AfterParameterList = CurContext == CallOperator;
16203
16204 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16205 // used at the point of dealing with potential captures.
16206 //
16207 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16208 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16209 // associated. (Technically, we could recover that list from their
16210 // instantiation patterns, but for now, the GLTemplateParameterList seems
16211 // unnecessary in these cases.)
16212 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16213 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16214 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16215
16216 if (LCD == LCD_None)
16218 else if (LCD == LCD_ByCopy)
16220 else if (LCD == LCD_ByRef)
16222 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16223
16225 LSI->Mutable = !CallOperator->isConst();
16226 if (CallOperator->isExplicitObjectMemberFunction())
16227 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
16228
16229 // Add the captures to the LSI so they can be noted as already
16230 // captured within tryCaptureVar.
16231 auto I = LambdaClass->field_begin();
16232 for (const auto &C : LambdaClass->captures()) {
16233 if (C.capturesVariable()) {
16234 ValueDecl *VD = C.getCapturedVar();
16235 if (VD->isInitCapture())
16236 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
16237 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16238 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
16239 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
16240 /*EllipsisLoc*/C.isPackExpansion()
16241 ? C.getEllipsisLoc() : SourceLocation(),
16242 I->getType(), /*Invalid*/false);
16243
16244 } else if (C.capturesThis()) {
16245 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
16246 C.getCaptureKind() == LCK_StarThis);
16247 } else {
16248 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
16249 I->getType());
16250 }
16251 ++I;
16252 }
16253 return LSI;
16254}
16255
16257 SkipBodyInfo *SkipBody,
16258 FnBodyKind BodyKind) {
16259 if (!D) {
16260 // Parsing the function declaration failed in some way. Push on a fake scope
16261 // anyway so we can try to parse the function body.
16264 return D;
16265 }
16266
16267 FunctionDecl *FD = nullptr;
16268
16269 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16270 FD = FunTmpl->getTemplatedDecl();
16271 else
16272 FD = cast<FunctionDecl>(D);
16273
16274 // Do not push if it is a lambda because one is already pushed when building
16275 // the lambda in ActOnStartOfLambdaDefinition().
16276 if (!isLambdaCallOperator(FD))
16278 FD);
16279
16280 // Check for defining attributes before the check for redefinition.
16281 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16282 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16283 FD->dropAttr<AliasAttr>();
16284 FD->setInvalidDecl();
16285 }
16286 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16287 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16288 FD->dropAttr<IFuncAttr>();
16289 FD->setInvalidDecl();
16290 }
16291 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16292 if (Context.getTargetInfo().getTriple().isAArch64() &&
16293 !Context.getTargetInfo().hasFeature("fmv") &&
16294 !Attr->isDefaultVersion()) {
16295 // If function multi versioning disabled skip parsing function body
16296 // defined with non-default target_version attribute
16297 if (SkipBody)
16298 SkipBody->ShouldSkip = true;
16299 return nullptr;
16300 }
16301 }
16302
16303 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16304 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16305 Ctor->isDefaultConstructor() &&
16306 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16307 // If this is an MS ABI dllexport default constructor, instantiate any
16308 // default arguments.
16310 }
16311 }
16312
16313 // See if this is a redefinition. If 'will have body' (or similar) is already
16314 // set, then these checks were already performed when it was set.
16315 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16317 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16318
16319 // If we're skipping the body, we're done. Don't enter the scope.
16320 if (SkipBody && SkipBody->ShouldSkip)
16321 return D;
16322 }
16323
16324 // Mark this function as "will have a body eventually". This lets users to
16325 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16326 // this function.
16327 FD->setWillHaveBody();
16328
16329 // If we are instantiating a generic lambda call operator, push
16330 // a LambdaScopeInfo onto the function stack. But use the information
16331 // that's already been calculated (ActOnLambdaExpr) to prime the current
16332 // LambdaScopeInfo.
16333 // When the template operator is being specialized, the LambdaScopeInfo,
16334 // has to be properly restored so that tryCaptureVariable doesn't try
16335 // and capture any new variables. In addition when calculating potential
16336 // captures during transformation of nested lambdas, it is necessary to
16337 // have the LSI properly restored.
16339 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16340 // specialized.
16342 Diag(FD->getLocation(), diag::err_lambda_explicit_temp_spec)
16343 << /*specialization*/ 0;
16345 Diag(RD->getLocation(), diag::note_defined_here) << RD;
16346
16347 FD->setInvalidDecl();
16349 } else {
16350 assert(inTemplateInstantiation() &&
16351 "There should be an active template instantiation on the stack "
16352 "when instantiating a generic lambda!");
16354 }
16355 } else {
16356 // Enter a new function scope
16358 }
16359
16360 // Builtin functions cannot be defined.
16361 if (unsigned BuiltinID = FD->getBuiltinID()) {
16362 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16363 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16364 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16365 FD->setInvalidDecl();
16366 }
16367 }
16368
16369 // The return type of a function definition must be complete (C99 6.9.1p3).
16370 // C++23 [dcl.fct.def.general]/p2
16371 // The type of [...] the return for a function definition
16372 // shall not be a (possibly cv-qualified) class type that is incomplete
16373 // or abstract within the function body unless the function is deleted.
16374 QualType ResultType = FD->getReturnType();
16375 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16376 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16377 (RequireCompleteType(FD->getLocation(), ResultType,
16378 diag::err_func_def_incomplete_result) ||
16380 diag::err_abstract_type_in_decl,
16382 FD->setInvalidDecl();
16383
16384 if (FnBodyScope)
16385 PushDeclContext(FnBodyScope, FD);
16386
16387 // Check the validity of our function parameters
16388 if (BodyKind != FnBodyKind::Delete)
16390 /*CheckParameterNames=*/true);
16391
16392 // Add non-parameter declarations already in the function to the current
16393 // scope.
16394 if (FnBodyScope) {
16395 for (Decl *NPD : FD->decls()) {
16396 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16397 if (!NonParmDecl)
16398 continue;
16399 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16400 "parameters should not be in newly created FD yet");
16401
16402 // If the decl has a name, make it accessible in the current scope.
16403 if (NonParmDecl->getDeclName())
16404 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16405
16406 // Similarly, dive into enums and fish their constants out, making them
16407 // accessible in this scope.
16408 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16409 for (auto *EI : ED->enumerators())
16410 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16411 }
16412 }
16413 }
16414
16415 // Introduce our parameters into the function scope
16416 for (auto *Param : FD->parameters()) {
16417 Param->setOwningFunction(FD);
16418
16419 // If this has an identifier, add it to the scope stack.
16420 if (Param->getIdentifier() && FnBodyScope) {
16421 CheckShadow(FnBodyScope, Param);
16422
16423 PushOnScopeChains(Param, FnBodyScope);
16424 }
16425 }
16426
16427 // C++ [module.import/6]
16428 // ...
16429 // A header unit shall not contain a definition of a non-inline function or
16430 // variable whose name has external linkage.
16431 //
16432 // Deleted and Defaulted functions are implicitly inline (but the
16433 // inline state is not set at this point, so check the BodyKind explicitly).
16434 // We choose to allow weak & selectany definitions, as they are common in
16435 // headers, and have semantics similar to inline definitions which are allowed
16436 // in header units.
16437 // FIXME: Consider an alternate location for the test where the inlined()
16438 // state is complete.
16439 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16440 !FD->isInvalidDecl() && !FD->isInlined() &&
16441 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16442 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16443 !FD->isTemplateInstantiation() &&
16444 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16445 assert(FD->isThisDeclarationADefinition());
16446 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16447 FD->setInvalidDecl();
16448 }
16449
16450 // Ensure that the function's exception specification is instantiated.
16451 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16453
16454 // dllimport cannot be applied to non-inline function definitions.
16455 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16456 !FD->isTemplateInstantiation()) {
16457 assert(!FD->hasAttr<DLLExportAttr>());
16458 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16459 FD->setInvalidDecl();
16460 return D;
16461 }
16462
16463 // Some function attributes (like OptimizeNoneAttr) need actions before
16464 // parsing body started.
16466
16467 // We want to attach documentation to original Decl (which might be
16468 // a function template).
16470 if (getCurLexicalContext()->isObjCContainer() &&
16471 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16472 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16473 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16474
16476
16477 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16478 FnBodyScope) {
16479 // An implicit call expression is synthesized for functions declared with
16480 // the sycl_kernel_entry_point attribute. The call may resolve to a
16481 // function template, a member function template, or a call operator
16482 // of a variable template depending on the results of unqualified lookup
16483 // for 'sycl_kernel_launch' from the beginning of the function body.
16484 // Performing that lookup requires the stack of parsing scopes active
16485 // when the definition is parsed and is thus done here; the result is
16486 // cached in FunctionScopeInfo and used to synthesize the (possibly
16487 // unresolved) call expression after the function body has been parsed.
16488 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16489 if (!SKEPAttr->isInvalidAttr()) {
16490 ExprResult LaunchIdExpr =
16491 SYCL().BuildSYCLKernelLaunchIdExpr(FD, SKEPAttr->getKernelName());
16492 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16493 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16494 // treated as an error in the definition of 'FD'; treating it as an error
16495 // of the declaration would affect overload resolution which would
16496 // potentially result in additional errors. If construction of
16497 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16498 // a null pointer value below; that is expected.
16499 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16500 }
16501 }
16502
16503 return D;
16504}
16505
16507 if (!FD || FD->isInvalidDecl())
16508 return;
16509 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16510 FD = TD->getTemplatedDecl();
16511 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16514 CurFPFeatures.applyChanges(FPO);
16515 FpPragmaStack.CurrentValue =
16516 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16517 }
16518}
16519
16521 ReturnStmt **Returns = Scope->Returns.data();
16522
16523 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16524 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16525 if (!NRVOCandidate->isNRVOVariable()) {
16526 Diag(Returns[I]->getRetValue()->getExprLoc(),
16527 diag::warn_not_eliding_copy_on_return);
16528 Returns[I]->setNRVOCandidate(nullptr);
16529 }
16530 }
16531 }
16532}
16533
16535 // We can't delay parsing the body of a constexpr function template (yet).
16537 return false;
16538
16539 // We can't delay parsing the body of a function template with a deduced
16540 // return type (yet).
16541 if (D.getDeclSpec().hasAutoTypeSpec()) {
16542 // If the placeholder introduces a non-deduced trailing return type,
16543 // we can still delay parsing it.
16544 if (D.getNumTypeObjects()) {
16545 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16546 if (Outer.Kind == DeclaratorChunk::Function &&
16547 Outer.Fun.hasTrailingReturnType()) {
16548 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16549 return Ty.isNull() || !Ty->isUndeducedType();
16550 }
16551 }
16552 return false;
16553 }
16554
16555 return true;
16556}
16557
16559 // We cannot skip the body of a function (or function template) which is
16560 // constexpr, since we may need to evaluate its body in order to parse the
16561 // rest of the file.
16562 // We cannot skip the body of a function with an undeduced return type,
16563 // because any callers of that function need to know the type.
16564 if (const FunctionDecl *FD = D->getAsFunction()) {
16565 if (FD->isConstexpr())
16566 return false;
16567 // We can't simply call Type::isUndeducedType here, because inside template
16568 // auto can be deduced to a dependent type, which is not considered
16569 // "undeduced".
16570 if (FD->getReturnType()->getContainedDeducedType())
16571 return false;
16572 }
16573 return Consumer.shouldSkipFunctionBody(D);
16574}
16575
16577 if (!Decl)
16578 return nullptr;
16579 if (FunctionDecl *FD = Decl->getAsFunction())
16580 FD->setHasSkippedBody();
16581 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16582 MD->setHasSkippedBody();
16583 return Decl;
16584}
16585
16586/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16587/// body.
16589public:
16590 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16592 if (!IsLambda)
16593 S.PopExpressionEvaluationContext();
16594 }
16595
16596private:
16597 Sema &S;
16598 bool IsLambda = false;
16599};
16600
16602 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16603
16604 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16605 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16606 if (!Inserted)
16607 return It->second;
16608
16609 bool R = false;
16610 const BlockDecl *CurBD = BD;
16611
16612 do {
16613 R = !CurBD->doesNotEscape();
16614 if (R)
16615 break;
16616 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16617 } while (CurBD);
16618
16619 return It->second = R;
16620 };
16621
16622 // If the location where 'self' is implicitly retained is inside a escaping
16623 // block, emit a diagnostic.
16624 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16626 if (IsOrNestedInEscapingBlock(P.second))
16627 S.Diag(P.first, diag::warn_implicitly_retains_self)
16628 << FixItHint::CreateInsertion(P.first, "self->");
16629}
16630
16631static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16632 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16633 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16634}
16635
16637 return methodHasName(FD, "get_return_object");
16638}
16639
16641 return FD->isStatic() &&
16642 methodHasName(FD, "get_return_object_on_allocation_failure");
16643}
16644
16647 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16648 return;
16649 // Allow some_promise_type::get_return_object().
16651 return;
16652 if (!FD->hasAttr<CoroWrapperAttr>())
16653 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16654}
16655
16656Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16657 bool RetainFunctionScopeInfo) {
16659 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16660
16661 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16662 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16663
16664 SourceLocation AnalysisLoc;
16665 if (Body)
16666 AnalysisLoc = Body->getEndLoc();
16667 else if (FD)
16668 AnalysisLoc = FD->getEndLoc();
16670 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16671 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16672
16673 // If we skip function body, we can't tell if a function is a coroutine.
16674 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16675 if (FSI->isCoroutine())
16677 else
16679 }
16680
16681 // Diagnose invalid SYCL kernel entry point function declarations
16682 // and build SYCLKernelCallStmts for valid ones.
16683 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16684 SYCLKernelEntryPointAttr *SKEPAttr =
16685 FD->getAttr<SYCLKernelEntryPointAttr>();
16686 if (FD->isDefaulted()) {
16687 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16688 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16689 SKEPAttr->setInvalidAttr();
16690 } else if (FD->isDeleted()) {
16691 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16692 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16693 SKEPAttr->setInvalidAttr();
16694 } else if (FSI->isCoroutine()) {
16695 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16696 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16697 SKEPAttr->setInvalidAttr();
16698 } else if (Body && isa<CXXTryStmt>(Body)) {
16699 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16700 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16701 SKEPAttr->setInvalidAttr();
16702 }
16703
16704 // Build an unresolved SYCL kernel call statement for a function template,
16705 // validate that a SYCL kernel call statement was instantiated for an
16706 // (implicit or explicit) instantiation of a function template, or otherwise
16707 // build a (resolved) SYCL kernel call statement for a non-templated
16708 // function or an explicit specialization.
16709 if (Body && !SKEPAttr->isInvalidAttr()) {
16710 StmtResult SR;
16711 if (FD->isTemplateInstantiation()) {
16712 // The function body should already be a SYCLKernelCallStmt in this
16713 // case, but might not be if there were previous errors.
16714 SR = Body;
16715 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16716 // If name lookup for a template named sycl_kernel_launch failed
16717 // earlier, don't try to build a SYCL kernel call statement as that
16718 // would cause additional errors to be issued; just proceed with the
16719 // original function body.
16720 SR = Body;
16721 } else if (FD->isTemplated()) {
16723 cast<CompoundStmt>(Body), getCurFunction()->SYCLKernelLaunchIdExpr);
16724 } else {
16726 FD, cast<CompoundStmt>(Body),
16727 getCurFunction()->SYCLKernelLaunchIdExpr);
16728 }
16729 // If construction of the replacement body fails, just continue with the
16730 // original function body. An early error return here is not valid; the
16731 // current declaration context and function scopes must be popped before
16732 // returning.
16733 if (SR.isUsable())
16734 Body = SR.get();
16735 }
16736 }
16737
16738 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16739 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16740 if (FD->isDeletedAsWritten())
16741 Diag(SEAttr->getLocation(),
16742 diag::err_sycl_external_invalid_deleted_function)
16743 << SEAttr;
16744 }
16745
16746 {
16747 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16748 // one is already popped when finishing the lambda in BuildLambdaExpr().
16749 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16750 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16751 if (FD) {
16752 // The function body and the DefaultedOrDeletedInfo, if present, use
16753 // the same storage; don't overwrite the latter if the former is null
16754 // (the body is initialised to null anyway, so even if the latter isn't
16755 // present, this would still be a no-op).
16756 if (Body)
16757 FD->setBody(Body);
16758 FD->setWillHaveBody(false);
16759
16760 if (getLangOpts().CPlusPlus14) {
16761 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16762 FD->getReturnType()->isUndeducedType()) {
16763 // For a function with a deduced result type to return void,
16764 // the result type as written must be 'auto' or 'decltype(auto)',
16765 // possibly cv-qualified or constrained, but not ref-qualified.
16766 if (!FD->getReturnType()->getAs<AutoType>()) {
16767 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16768 << FD->getReturnType();
16769 FD->setInvalidDecl();
16770 } else {
16771 // Falling off the end of the function is the same as 'return;'.
16772 Expr *Dummy = nullptr;
16774 FD, dcl->getLocation(), Dummy,
16775 FD->getReturnType()->getAs<AutoType>()))
16776 FD->setInvalidDecl();
16777 }
16778 }
16779 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16780 // In C++11, we don't use 'auto' deduction rules for lambda call
16781 // operators because we don't support return type deduction.
16782 auto *LSI = getCurLambda();
16783 if (LSI->HasImplicitReturnType) {
16785
16786 // C++11 [expr.prim.lambda]p4:
16787 // [...] if there are no return statements in the compound-statement
16788 // [the deduced type is] the type void
16789 QualType RetType =
16790 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16791
16792 // Update the return type to the deduced type.
16793 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16794 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16795 Proto->getExtProtoInfo()));
16796 }
16797 }
16798
16799 // If the function implicitly returns zero (like 'main') or is naked,
16800 // don't complain about missing return statements.
16801 // Clang implicitly returns 0 in C89 mode, but that's considered an
16802 // extension. The check is necessary to ensure the expected extension
16803 // warning is emitted in C89 mode.
16804 if ((FD->hasImplicitReturnZero() &&
16805 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16806 FD->hasAttr<NakedAttr>())
16808
16809 // MSVC permits the use of pure specifier (=0) on function definition,
16810 // defined at class scope, warn about this non-standard construct.
16811 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16812 !FD->isOutOfLine())
16813 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16814
16815 if (!FD->isInvalidDecl()) {
16816 // Don't diagnose unused parameters of defaulted, deleted or naked
16817 // functions.
16818 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16819 !FD->hasAttr<NakedAttr>())
16822 FD->getReturnType(), FD);
16823
16824 // If this is a structor, we need a vtable.
16825 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16826 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16827 else if (CXXDestructorDecl *Destructor =
16828 dyn_cast<CXXDestructorDecl>(FD))
16829 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16830
16831 // Try to apply the named return value optimization. We have to check
16832 // if we can do this here because lambdas keep return statements around
16833 // to deduce an implicit return type.
16834 if (FD->getReturnType()->isRecordType() &&
16836 computeNRVO(Body, FSI);
16837 }
16838
16839 // GNU warning -Wmissing-prototypes:
16840 // Warn if a global function is defined without a previous
16841 // prototype declaration. This warning is issued even if the
16842 // definition itself provides a prototype. The aim is to detect
16843 // global functions that fail to be declared in header files.
16844 const FunctionDecl *PossiblePrototype = nullptr;
16845 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16846 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16847
16848 if (PossiblePrototype) {
16849 // We found a declaration that is not a prototype,
16850 // but that could be a zero-parameter prototype
16851 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16852 TypeLoc TL = TI->getTypeLoc();
16854 Diag(PossiblePrototype->getLocation(),
16855 diag::note_declaration_not_a_prototype)
16856 << (FD->getNumParams() != 0)
16858 FTL.getRParenLoc(), "void")
16859 : FixItHint{});
16860 }
16861 } else {
16862 // Returns true if the token beginning at this Loc is `const`.
16863 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16864 const LangOptions &LangOpts) {
16865 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16866 if (LocInfo.first.isInvalid())
16867 return false;
16868
16869 bool Invalid = false;
16870 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16871 if (Invalid)
16872 return false;
16873
16874 if (LocInfo.second > Buffer.size())
16875 return false;
16876
16877 const char *LexStart = Buffer.data() + LocInfo.second;
16878 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16879
16880 return StartTok.consume_front("const") &&
16881 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16882 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16883 };
16884
16885 auto findBeginLoc = [&]() {
16886 // If the return type has `const` qualifier, we want to insert
16887 // `static` before `const` (and not before the typename).
16888 if ((FD->getReturnType()->isAnyPointerType() &&
16891 // But only do this if we can determine where the `const` is.
16892
16893 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16894 getLangOpts()))
16895
16896 return FD->getBeginLoc();
16897 }
16898 return FD->getTypeSpecStartLoc();
16899 };
16901 diag::note_static_for_internal_linkage)
16902 << /* function */ 1
16903 << (FD->getStorageClass() == SC_None
16904 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16905 : FixItHint{});
16906 }
16907 }
16908
16909 // We might not have found a prototype because we didn't wish to warn on
16910 // the lack of a missing prototype. Try again without the checks for
16911 // whether we want to warn on the missing prototype.
16912 if (!PossiblePrototype)
16913 (void)FindPossiblePrototype(FD, PossiblePrototype);
16914
16915 // If the function being defined does not have a prototype, then we may
16916 // need to diagnose it as changing behavior in C23 because we now know
16917 // whether the function accepts arguments or not. This only handles the
16918 // case where the definition has no prototype but does have parameters
16919 // and either there is no previous potential prototype, or the previous
16920 // potential prototype also has no actual prototype. This handles cases
16921 // like:
16922 // void f(); void f(a) int a; {}
16923 // void g(a) int a; {}
16924 // See MergeFunctionDecl() for other cases of the behavior change
16925 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16926 // type without a prototype.
16927 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16928 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16929 !PossiblePrototype->isImplicit()))) {
16930 // The function definition has parameters, so this will change behavior
16931 // in C23. If there is a possible prototype, it comes before the
16932 // function definition.
16933 // FIXME: The declaration may have already been diagnosed as being
16934 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16935 // there's no way to test for the "changes behavior" condition in
16936 // SemaType.cpp when forming the declaration's function type. So, we do
16937 // this awkward dance instead.
16938 //
16939 // If we have a possible prototype and it declares a function with a
16940 // prototype, we don't want to diagnose it; if we have a possible
16941 // prototype and it has no prototype, it may have already been
16942 // diagnosed in SemaType.cpp as deprecated depending on whether
16943 // -Wstrict-prototypes is enabled. If we already warned about it being
16944 // deprecated, add a note that it also changes behavior. If we didn't
16945 // warn about it being deprecated (because the diagnostic is not
16946 // enabled), warn now that it is deprecated and changes behavior.
16947
16948 // This K&R C function definition definitely changes behavior in C23,
16949 // so diagnose it.
16950 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16951 << /*definition*/ 1 << /* not supported in C23 */ 0;
16952
16953 // If we have a possible prototype for the function which is a user-
16954 // visible declaration, we already tested that it has no prototype.
16955 // This will change behavior in C23. This gets a warning rather than a
16956 // note because it's the same behavior-changing problem as with the
16957 // definition.
16958 if (PossiblePrototype)
16959 Diag(PossiblePrototype->getLocation(),
16960 diag::warn_non_prototype_changes_behavior)
16961 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16962 << /*definition*/ 1;
16963 }
16964
16965 // Warn on CPUDispatch with an actual body.
16966 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16967 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16968 if (!CmpndBody->body_empty())
16969 Diag(CmpndBody->body_front()->getBeginLoc(),
16970 diag::warn_dispatch_body_ignored);
16971
16972 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16973 const CXXMethodDecl *KeyFunction;
16974 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16975 MD->isVirtual() &&
16976 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16977 MD == KeyFunction->getCanonicalDecl()) {
16978 // Update the key-function state if necessary for this ABI.
16979 if (FD->isInlined() &&
16980 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16981 Context.setNonKeyFunction(MD);
16982
16983 // If the newly-chosen key function is already defined, then we
16984 // need to mark the vtable as used retroactively.
16985 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16986 const FunctionDecl *Definition;
16987 if (KeyFunction && KeyFunction->isDefined(Definition))
16988 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16989 } else {
16990 // We just defined they key function; mark the vtable as used.
16991 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16992 }
16993 }
16994 }
16995
16996 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16997 "Function parsing confused");
16998 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16999 assert(MD == getCurMethodDecl() && "Method parsing confused");
17000 MD->setBody(Body);
17001 if (!MD->isInvalidDecl()) {
17003 MD->getReturnType(), MD);
17004
17005 if (Body)
17006 computeNRVO(Body, FSI);
17007 }
17008 if (FSI->ObjCShouldCallSuper) {
17009 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
17010 << MD->getSelector().getAsString();
17011 FSI->ObjCShouldCallSuper = false;
17012 }
17014 const ObjCMethodDecl *InitMethod = nullptr;
17015 bool isDesignated =
17016 MD->isDesignatedInitializerForTheInterface(&InitMethod);
17017 assert(isDesignated && InitMethod);
17018 (void)isDesignated;
17019
17020 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17021 auto IFace = MD->getClassInterface();
17022 if (!IFace)
17023 return false;
17024 auto SuperD = IFace->getSuperClass();
17025 if (!SuperD)
17026 return false;
17027 return SuperD->getIdentifier() ==
17028 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
17029 };
17030 // Don't issue this warning for unavailable inits or direct subclasses
17031 // of NSObject.
17032 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17033 Diag(MD->getLocation(),
17034 diag::warn_objc_designated_init_missing_super_call);
17035 Diag(InitMethod->getLocation(),
17036 diag::note_objc_designated_init_marked_here);
17037 }
17039 }
17040 if (FSI->ObjCWarnForNoInitDelegation) {
17041 // Don't issue this warning for unavailable inits.
17042 if (!MD->isUnavailable())
17043 Diag(MD->getLocation(),
17044 diag::warn_objc_secondary_init_missing_init_call);
17045 FSI->ObjCWarnForNoInitDelegation = false;
17046 }
17047
17049 } else {
17050 // Parsing the function declaration failed in some way. Pop the fake scope
17051 // we pushed on.
17052 PopFunctionScopeInfo(ActivePolicy, dcl);
17053 return nullptr;
17054 }
17055
17056 if (Body) {
17059 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17061 }
17062
17063 assert(!FSI->ObjCShouldCallSuper &&
17064 "This should only be set for ObjC methods, which should have been "
17065 "handled in the block above.");
17066
17067 // Verify and clean out per-function state.
17068 if (Body && (!FD || !FD->isDefaulted())) {
17069 // C++ constructors that have function-try-blocks can't have return
17070 // statements in the handlers of that block. (C++ [except.handle]p14)
17071 // Verify this.
17072 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
17074
17075 // Verify that gotos and switch cases don't jump into scopes illegally.
17076 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17078
17079 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
17080 if (!Destructor->getParent()->isDependentType())
17082
17084 Destructor->getParent());
17085 }
17086
17087 // If any errors have occurred, clear out any temporaries that may have
17088 // been leftover. This ensures that these temporaries won't be picked up
17089 // for deletion in some later function.
17092 getDiagnostics().getSuppressAllDiagnostics()) {
17094 }
17096 // Since the body is valid, issue any analysis-based warnings that are
17097 // enabled.
17098 ActivePolicy = &WP;
17099 }
17100
17101 if (!IsInstantiation && FD &&
17102 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17103 !FD->isInvalidDecl() &&
17105 FD->setInvalidDecl();
17106
17107 if (FD && FD->hasAttr<NakedAttr>()) {
17108 for (const Stmt *S : Body->children()) {
17109 // Allow local register variables without initializer as they don't
17110 // require prologue.
17111 bool RegisterVariables = false;
17112 if (auto *DS = dyn_cast<DeclStmt>(S)) {
17113 for (const auto *Decl : DS->decls()) {
17114 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
17115 RegisterVariables =
17116 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17117 if (!RegisterVariables)
17118 break;
17119 }
17120 }
17121 }
17122 if (RegisterVariables)
17123 continue;
17124 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
17125 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
17126 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
17127 FD->setInvalidDecl();
17128 break;
17129 }
17130 }
17131 }
17132
17133 assert(ExprCleanupObjects.size() ==
17134 ExprEvalContexts.back().NumCleanupObjects &&
17135 "Leftover temporaries in function");
17136 assert(!Cleanup.exprNeedsCleanups() &&
17137 "Unaccounted cleanups in function");
17138 assert(MaybeODRUseExprs.empty() &&
17139 "Leftover expressions for odr-use checking");
17140 }
17141 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17142 // the declaration context below. Otherwise, we're unable to transform
17143 // 'this' expressions when transforming immediate context functions.
17144
17145 if (FD)
17147
17148 if (!IsInstantiation)
17150
17151 if (!RetainFunctionScopeInfo)
17152 PopFunctionScopeInfo(ActivePolicy, dcl);
17153 // If any errors have occurred, clear out any temporaries that may have
17154 // been leftover. This ensures that these temporaries won't be picked up for
17155 // deletion in some later function.
17158 }
17159
17160 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17161 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17162 auto ES = getEmissionStatus(FD);
17166 }
17167
17168 if (FD && !FD->isDeleted())
17169 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
17170
17171 return dcl;
17172}
17173
17174/// When we finish delayed parsing of an attribute, we must attach it to the
17175/// relevant Decl.
17177 ParsedAttributes &Attrs) {
17178 // Always attach attributes to the underlying decl.
17179 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
17180 D = TD->getTemplatedDecl();
17181 ProcessDeclAttributeList(S, D, Attrs);
17182 ProcessAPINotes(D);
17183
17184 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
17185 if (Method->isStatic())
17187}
17188
17190 IdentifierInfo &II, Scope *S) {
17191 // It is not valid to implicitly define a function in C23.
17192 assert(LangOpts.implicitFunctionsAllowed() &&
17193 "Implicit function declarations aren't allowed in this language mode");
17194
17195 // Find the scope in which the identifier is injected and the corresponding
17196 // DeclContext.
17197 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17198 // In that case, we inject the declaration into the translation unit scope
17199 // instead.
17200 Scope *BlockScope = S;
17201 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17202 BlockScope = BlockScope->getParent();
17203
17204 // Loop until we find a DeclContext that is either a function/method or the
17205 // translation unit, which are the only two valid places to implicitly define
17206 // a function. This avoids accidentally defining the function within a tag
17207 // declaration, for example.
17208 Scope *ContextScope = BlockScope;
17209 while (!ContextScope->getEntity() ||
17210 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17211 !ContextScope->getEntity()->isTranslationUnit()))
17212 ContextScope = ContextScope->getParent();
17213 ContextRAII SavedContext(*this, ContextScope->getEntity());
17214
17215 // Before we produce a declaration for an implicitly defined
17216 // function, see whether there was a locally-scoped declaration of
17217 // this name as a function or variable. If so, use that
17218 // (non-visible) declaration, and complain about it.
17219 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
17220 if (ExternCPrev) {
17221 // We still need to inject the function into the enclosing block scope so
17222 // that later (non-call) uses can see it.
17223 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
17224
17225 // C89 footnote 38:
17226 // If in fact it is not defined as having type "function returning int",
17227 // the behavior is undefined.
17228 if (!isa<FunctionDecl>(ExternCPrev) ||
17229 !Context.typesAreCompatible(
17230 cast<FunctionDecl>(ExternCPrev)->getType(),
17231 Context.getFunctionNoProtoType(Context.IntTy))) {
17232 Diag(Loc, diag::ext_use_out_of_scope_declaration)
17233 << ExternCPrev << !getLangOpts().C99;
17234 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
17235 return ExternCPrev;
17236 }
17237 }
17238
17239 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17240 unsigned diag_id;
17241 if (II.getName().starts_with("__builtin_"))
17242 diag_id = diag::warn_builtin_unknown;
17243 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17244 else if (getLangOpts().C99)
17245 diag_id = diag::ext_implicit_function_decl_c99;
17246 else
17247 diag_id = diag::warn_implicit_function_decl;
17248
17249 TypoCorrection Corrected;
17250 // Because typo correction is expensive, only do it if the implicit
17251 // function declaration is going to be treated as an error.
17252 //
17253 // Perform the correction before issuing the main diagnostic, as some
17254 // consumers use typo-correction callbacks to enhance the main diagnostic.
17255 if (S && !ExternCPrev &&
17256 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
17258 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
17259 S, nullptr, CCC, CorrectTypoKind::NonError);
17260 }
17261
17262 Diag(Loc, diag_id) << &II;
17263 if (Corrected) {
17264 // If the correction is going to suggest an implicitly defined function,
17265 // skip the correction as not being a particularly good idea.
17266 bool Diagnose = true;
17267 if (const auto *D = Corrected.getCorrectionDecl())
17268 Diagnose = !D->isImplicit();
17269 if (Diagnose)
17270 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
17271 /*ErrorRecovery*/ false);
17272 }
17273
17274 // If we found a prior declaration of this function, don't bother building
17275 // another one. We've already pushed that one into scope, so there's nothing
17276 // more to do.
17277 if (ExternCPrev)
17278 return ExternCPrev;
17279
17280 // Set a Declarator for the implicit definition: int foo();
17281 const char *Dummy;
17282 AttributeFactory attrFactory;
17283 DeclSpec DS(attrFactory);
17284 unsigned DiagID;
17285 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
17286 Context.getPrintingPolicy());
17287 (void)Error; // Silence warning.
17288 assert(!Error && "Error setting up implicit decl!");
17289 SourceLocation NoLoc;
17291 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
17292 /*IsAmbiguous=*/false,
17293 /*LParenLoc=*/NoLoc,
17294 /*Params=*/nullptr,
17295 /*NumParams=*/0,
17296 /*EllipsisLoc=*/NoLoc,
17297 /*RParenLoc=*/NoLoc,
17298 /*RefQualifierIsLvalueRef=*/true,
17299 /*RefQualifierLoc=*/NoLoc,
17300 /*MutableLoc=*/NoLoc, EST_None,
17301 /*ESpecRange=*/SourceRange(),
17302 /*Exceptions=*/nullptr,
17303 /*ExceptionRanges=*/nullptr,
17304 /*NumExceptions=*/0,
17305 /*NoexceptExpr=*/nullptr,
17306 /*ExceptionSpecTokens=*/nullptr,
17307 /*DeclsInPrototype=*/{}, Loc, Loc,
17308 D),
17309 std::move(DS.getAttributes()), SourceLocation());
17310 D.SetIdentifier(&II, Loc);
17311
17312 // Insert this function into the enclosing block scope.
17313 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
17314 FD->setImplicit();
17315
17317
17318 return FD;
17319}
17320
17322 FunctionDecl *FD) {
17323 if (FD->isInvalidDecl())
17324 return;
17325
17326 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17327 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17328 return;
17329
17330 UnsignedOrNone AlignmentParam = std::nullopt;
17331 bool IsNothrow = false;
17332 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17333 return;
17334
17335 // C++2a [basic.stc.dynamic.allocation]p4:
17336 // An allocation function that has a non-throwing exception specification
17337 // indicates failure by returning a null pointer value. Any other allocation
17338 // function never returns a null pointer value and indicates failure only by
17339 // throwing an exception [...]
17340 //
17341 // However, -fcheck-new invalidates this possible assumption, so don't add
17342 // NonNull when that is enabled.
17343 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17344 !getLangOpts().CheckNew)
17345 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17346
17347 // C++2a [basic.stc.dynamic.allocation]p2:
17348 // An allocation function attempts to allocate the requested amount of
17349 // storage. [...] If the request succeeds, the value returned by a
17350 // replaceable allocation function is a [...] pointer value p0 different
17351 // from any previously returned value p1 [...]
17352 //
17353 // However, this particular information is being added in codegen,
17354 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17355
17356 // C++2a [basic.stc.dynamic.allocation]p2:
17357 // An allocation function attempts to allocate the requested amount of
17358 // storage. If it is successful, it returns the address of the start of a
17359 // block of storage whose length in bytes is at least as large as the
17360 // requested size.
17361 if (!FD->hasAttr<AllocSizeAttr>()) {
17362 FD->addAttr(AllocSizeAttr::CreateImplicit(
17363 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17364 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17365 }
17366
17367 // C++2a [basic.stc.dynamic.allocation]p3:
17368 // For an allocation function [...], the pointer returned on a successful
17369 // call shall represent the address of storage that is aligned as follows:
17370 // (3.1) If the allocation function takes an argument of type
17371 // std​::​align_­val_­t, the storage will have the alignment
17372 // specified by the value of this argument.
17373 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17374 FD->addAttr(AllocAlignAttr::CreateImplicit(
17375 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17376 }
17377
17378 // FIXME:
17379 // C++2a [basic.stc.dynamic.allocation]p3:
17380 // For an allocation function [...], the pointer returned on a successful
17381 // call shall represent the address of storage that is aligned as follows:
17382 // (3.2) Otherwise, if the allocation function is named operator new[],
17383 // the storage is aligned for any object that does not have
17384 // new-extended alignment ([basic.align]) and is no larger than the
17385 // requested size.
17386 // (3.3) Otherwise, the storage is aligned for any object that does not
17387 // have new-extended alignment and is of the requested size.
17388}
17389
17391 if (FD->isInvalidDecl())
17392 return;
17393
17394 // If this is a built-in function, map its builtin attributes to
17395 // actual attributes.
17396 if (unsigned BuiltinID = FD->getBuiltinID()) {
17397 // Handle printf-formatting attributes.
17398 unsigned FormatIdx;
17399 bool HasVAListArg;
17400 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17401 if (!FD->hasAttr<FormatAttr>()) {
17402 const char *fmt = "printf";
17403 unsigned int NumParams = FD->getNumParams();
17404 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17405 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17406 fmt = "NSString";
17407 FD->addAttr(FormatAttr::CreateImplicit(Context,
17408 &Context.Idents.get(fmt),
17409 FormatIdx+1,
17410 HasVAListArg ? 0 : FormatIdx+2,
17411 FD->getLocation()));
17412 }
17413 }
17414 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17415 HasVAListArg)) {
17416 if (!FD->hasAttr<FormatAttr>())
17417 FD->addAttr(FormatAttr::CreateImplicit(Context,
17418 &Context.Idents.get("scanf"),
17419 FormatIdx+1,
17420 HasVAListArg ? 0 : FormatIdx+2,
17421 FD->getLocation()));
17422 }
17423
17424 // Handle automatically recognized callbacks.
17425 SmallVector<int, 4> Encoding;
17426 if (!FD->hasAttr<CallbackAttr>() &&
17427 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17428 FD->addAttr(CallbackAttr::CreateImplicit(
17429 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17430
17431 // Mark const if we don't care about errno and/or floating point exceptions
17432 // that are the only thing preventing the function from being const. This
17433 // allows IRgen to use LLVM intrinsics for such functions.
17434 bool NoExceptions =
17436 bool ConstWithoutErrnoAndExceptions =
17437 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17438 bool ConstWithoutExceptions =
17439 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17440 if (!FD->hasAttr<ConstAttr>() &&
17441 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17442 (!ConstWithoutErrnoAndExceptions ||
17443 (!getLangOpts().MathErrno && NoExceptions)) &&
17444 (!ConstWithoutExceptions || NoExceptions))
17445 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17446
17447 // We make "fma" on GNU or Windows const because we know it does not set
17448 // errno in those environments even though it could set errno based on the
17449 // C standard.
17450 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17451 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17452 !FD->hasAttr<ConstAttr>()) {
17453 switch (BuiltinID) {
17454 case Builtin::BI__builtin_fma:
17455 case Builtin::BI__builtin_fmaf:
17456 case Builtin::BI__builtin_fmal:
17457 case Builtin::BIfma:
17458 case Builtin::BIfmaf:
17459 case Builtin::BIfmal:
17460 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17461 break;
17462 default:
17463 break;
17464 }
17465 }
17466
17467 SmallVector<int, 4> Indxs;
17469 if (Context.BuiltinInfo.isNonNull(BuiltinID, Indxs, OptMode) &&
17470 !FD->hasAttr<NonNullAttr>()) {
17472 for (int I : Indxs) {
17473 ParmVarDecl *PVD = FD->getParamDecl(I);
17474 QualType T = PVD->getType();
17475 T = Context.getAttributedType(attr::TypeNonNull, T, T);
17476 PVD->setType(T);
17477 }
17478 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17480 for (int I : Indxs)
17481 ParamIndxs.push_back(ParamIdx(I + 1, FD));
17482 FD->addAttr(NonNullAttr::CreateImplicit(Context, ParamIndxs.data(),
17483 ParamIndxs.size()));
17484 }
17485 }
17486 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17487 !FD->hasAttr<ReturnsTwiceAttr>())
17488 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17489 FD->getLocation()));
17490 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17491 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17492 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17493 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17494 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17495 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17496 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17497 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17498 // Add the appropriate attribute, depending on the CUDA compilation mode
17499 // and which target the builtin belongs to. For example, during host
17500 // compilation, aux builtins are __device__, while the rest are __host__.
17501 if (getLangOpts().CUDAIsDevice !=
17502 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17503 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17504 else
17505 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17506 }
17507
17508 // Add known guaranteed alignment for allocation functions.
17509 switch (BuiltinID) {
17510 case Builtin::BImemalign:
17511 case Builtin::BIaligned_alloc:
17512 if (!FD->hasAttr<AllocAlignAttr>())
17513 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17514 FD->getLocation()));
17515 break;
17516 default:
17517 break;
17518 }
17519
17520 // Add allocsize attribute for allocation functions.
17521 switch (BuiltinID) {
17522 case Builtin::BIcalloc:
17523 FD->addAttr(AllocSizeAttr::CreateImplicit(
17524 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17525 break;
17526 case Builtin::BImemalign:
17527 case Builtin::BIaligned_alloc:
17528 case Builtin::BIrealloc:
17529 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17530 ParamIdx(), FD->getLocation()));
17531 break;
17532 case Builtin::BImalloc:
17533 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17534 ParamIdx(), FD->getLocation()));
17535 break;
17536 default:
17537 break;
17538 }
17539 }
17540
17545
17546 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17547 // throw, add an implicit nothrow attribute to any extern "C" function we come
17548 // across.
17549 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17550 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17551 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17552 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17553 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17554 }
17555
17556 IdentifierInfo *Name = FD->getIdentifier();
17557 if (!Name)
17558 return;
17561 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17563 // Okay: this could be a libc/libm/Objective-C function we know
17564 // about.
17565 } else
17566 return;
17567
17568 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17569 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17570 // target-specific builtins, perhaps?
17571 if (!FD->hasAttr<FormatAttr>())
17572 FD->addAttr(FormatAttr::CreateImplicit(Context,
17573 &Context.Idents.get("printf"), 2,
17574 Name->isStr("vasprintf") ? 0 : 3,
17575 FD->getLocation()));
17576 }
17577
17578 if (Name->isStr("__CFStringMakeConstantString")) {
17579 // We already have a __builtin___CFStringMakeConstantString,
17580 // but builds that use -fno-constant-cfstrings don't go through that.
17581 if (!FD->hasAttr<FormatArgAttr>())
17582 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17583 FD->getLocation()));
17584 }
17585}
17586
17588 TypeSourceInfo *TInfo) {
17589 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17590 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17591
17592 if (!TInfo) {
17593 assert(D.isInvalidType() && "no declarator info for valid type");
17594 TInfo = Context.getTrivialTypeSourceInfo(T);
17595 }
17596
17597 // Scope manipulation handled by caller.
17598 TypedefDecl *NewTD =
17600 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17601
17602 // Bail out immediately if we have an invalid declaration.
17603 if (D.isInvalidType()) {
17604 NewTD->setInvalidDecl();
17605 return NewTD;
17606 }
17607
17609 if (CurContext->isFunctionOrMethod())
17610 Diag(NewTD->getLocation(), diag::err_module_private_local)
17611 << 2 << NewTD
17615 else
17616 NewTD->setModulePrivate();
17617 }
17618
17619 // C++ [dcl.typedef]p8:
17620 // If the typedef declaration defines an unnamed class (or
17621 // enum), the first typedef-name declared by the declaration
17622 // to be that class type (or enum type) is used to denote the
17623 // class type (or enum type) for linkage purposes only.
17624 // We need to check whether the type was declared in the declaration.
17625 switch (D.getDeclSpec().getTypeSpecType()) {
17626 case TST_enum:
17627 case TST_struct:
17628 case TST_interface:
17629 case TST_union:
17630 case TST_class: {
17631 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17632 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17633 break;
17634 }
17635
17636 default:
17637 break;
17638 }
17639
17640 return NewTD;
17641}
17642
17644 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17645 QualType T = TI->getType();
17646
17647 if (T->isDependentType())
17648 return false;
17649
17650 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17651 // integral type; any cv-qualification is ignored.
17652 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17653 // non-atomic version of the type specified by the type specifiers in the
17654 // specifier qualifier list.
17655 // Because of how odd C's rule is, we'll let the user know that operations
17656 // involving the enumeration type will be non-atomic.
17657 if (T->isAtomicType())
17658 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17659
17660 Qualifiers Q = T.getQualifiers();
17661 std::optional<unsigned> QualSelect;
17662 if (Q.hasConst() && Q.hasVolatile())
17663 QualSelect = diag::CVQualList::Both;
17664 else if (Q.hasConst())
17665 QualSelect = diag::CVQualList::Const;
17666 else if (Q.hasVolatile())
17667 QualSelect = diag::CVQualList::Volatile;
17668
17669 if (QualSelect)
17670 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17671
17672 T = T.getAtomicUnqualifiedType();
17673
17674 // This doesn't use 'isIntegralType' despite the error message mentioning
17675 // integral type because isIntegralType would also allow enum types in C.
17676 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17677 if (BT->isInteger())
17678 return false;
17679
17680 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17681 << T << T->isBitIntType();
17682}
17683
17685 QualType EnumUnderlyingTy, bool IsFixed,
17686 const EnumDecl *Prev) {
17687 if (IsScoped != Prev->isScoped()) {
17688 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17689 << Prev->isScoped();
17690 Diag(Prev->getLocation(), diag::note_previous_declaration);
17691 return true;
17692 }
17693
17694 if (IsFixed && Prev->isFixed()) {
17695 if (!EnumUnderlyingTy->isDependentType() &&
17696 !Prev->getIntegerType()->isDependentType() &&
17697 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17698 Prev->getIntegerType())) {
17699 // TODO: Highlight the underlying type of the redeclaration.
17700 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17701 << EnumUnderlyingTy << Prev->getIntegerType();
17702 Diag(Prev->getLocation(), diag::note_previous_declaration)
17703 << Prev->getIntegerTypeRange();
17704 return true;
17705 }
17706 } else if (IsFixed != Prev->isFixed()) {
17707 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17708 << Prev->isFixed();
17709 Diag(Prev->getLocation(), diag::note_previous_declaration);
17710 return true;
17711 }
17712
17713 return false;
17714}
17715
17716/// Get diagnostic %select index for tag kind for
17717/// redeclaration diagnostic message.
17718/// WARNING: Indexes apply to particular diagnostics only!
17719///
17720/// \returns diagnostic %select index.
17722 switch (Tag) {
17724 return 0;
17726 return 1;
17727 case TagTypeKind::Class:
17728 return 2;
17729 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17730 }
17731}
17732
17733/// Determine if tag kind is a class-key compatible with
17734/// class for redeclaration (class, struct, or __interface).
17735///
17736/// \returns true iff the tag kind is compatible.
17738{
17739 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17741}
17742
17744 if (isa<TypedefDecl>(PrevDecl))
17745 return NonTagKind::Typedef;
17746 else if (isa<TypeAliasDecl>(PrevDecl))
17747 return NonTagKind::TypeAlias;
17748 else if (isa<ClassTemplateDecl>(PrevDecl))
17749 return NonTagKind::Template;
17750 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17752 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17754 switch (TTK) {
17757 case TagTypeKind::Class:
17758 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17760 case TagTypeKind::Union:
17761 return NonTagKind::NonUnion;
17762 case TagTypeKind::Enum:
17763 return NonTagKind::NonEnum;
17764 }
17765 llvm_unreachable("invalid TTK");
17766}
17767
17769 TagTypeKind NewTag, bool isDefinition,
17770 SourceLocation NewTagLoc,
17771 const IdentifierInfo *Name) {
17772 // C++ [dcl.type.elab]p3:
17773 // The class-key or enum keyword present in the
17774 // elaborated-type-specifier shall agree in kind with the
17775 // declaration to which the name in the elaborated-type-specifier
17776 // refers. This rule also applies to the form of
17777 // elaborated-type-specifier that declares a class-name or
17778 // friend class since it can be construed as referring to the
17779 // definition of the class. Thus, in any
17780 // elaborated-type-specifier, the enum keyword shall be used to
17781 // refer to an enumeration (7.2), the union class-key shall be
17782 // used to refer to a union (clause 9), and either the class or
17783 // struct class-key shall be used to refer to a class (clause 9)
17784 // declared using the class or struct class-key.
17785 TagTypeKind OldTag = Previous->getTagKind();
17786 if (OldTag != NewTag &&
17788 return false;
17789
17790 // Tags are compatible, but we might still want to warn on mismatched tags.
17791 // Non-class tags can't be mismatched at this point.
17793 return true;
17794
17795 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17796 // by our warning analysis. We don't want to warn about mismatches with (eg)
17797 // declarations in system headers that are designed to be specialized, but if
17798 // a user asks us to warn, we should warn if their code contains mismatched
17799 // declarations.
17800 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17801 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17802 Loc);
17803 };
17804 if (IsIgnoredLoc(NewTagLoc))
17805 return true;
17806
17807 auto IsIgnored = [&](const TagDecl *Tag) {
17808 return IsIgnoredLoc(Tag->getLocation());
17809 };
17810 while (IsIgnored(Previous)) {
17811 Previous = Previous->getPreviousDecl();
17812 if (!Previous)
17813 return true;
17814 OldTag = Previous->getTagKind();
17815 }
17816
17817 bool isTemplate = false;
17818 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17819 isTemplate = Record->getDescribedClassTemplate();
17820
17822 if (OldTag != NewTag) {
17823 // In a template instantiation, do not offer fix-its for tag mismatches
17824 // since they usually mess up the template instead of fixing the problem.
17825 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17827 << getRedeclDiagFromTagKind(OldTag);
17828 // FIXME: Note previous location?
17829 }
17830 return true;
17831 }
17832
17833 if (isDefinition) {
17834 // On definitions, check all previous tags and issue a fix-it for each
17835 // one that doesn't match the current tag.
17836 if (Previous->getDefinition()) {
17837 // Don't suggest fix-its for redefinitions.
17838 return true;
17839 }
17840
17841 bool previousMismatch = false;
17842 for (const TagDecl *I : Previous->redecls()) {
17843 if (I->getTagKind() != NewTag) {
17844 // Ignore previous declarations for which the warning was disabled.
17845 if (IsIgnored(I))
17846 continue;
17847
17848 if (!previousMismatch) {
17849 previousMismatch = true;
17850 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17852 << getRedeclDiagFromTagKind(I->getTagKind());
17853 }
17854 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17856 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17858 }
17859 }
17860 return true;
17861 }
17862
17863 // Identify the prevailing tag kind: this is the kind of the definition (if
17864 // there is a non-ignored definition), or otherwise the kind of the prior
17865 // (non-ignored) declaration.
17866 const TagDecl *PrevDef = Previous->getDefinition();
17867 if (PrevDef && IsIgnored(PrevDef))
17868 PrevDef = nullptr;
17869 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17870 if (Redecl->getTagKind() != NewTag) {
17871 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17873 << getRedeclDiagFromTagKind(OldTag);
17874 Diag(Redecl->getLocation(), diag::note_previous_use);
17875
17876 // If there is a previous definition, suggest a fix-it.
17877 if (PrevDef) {
17878 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17882 }
17883 }
17884
17885 return true;
17886}
17887
17888/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17889/// from an outer enclosing namespace or file scope inside a friend declaration.
17890/// This should provide the commented out code in the following snippet:
17891/// namespace N {
17892/// struct X;
17893/// namespace M {
17894/// struct Y { friend struct /*N::*/ X; };
17895/// }
17896/// }
17898 SourceLocation NameLoc) {
17899 // While the decl is in a namespace, do repeated lookup of that name and see
17900 // if we get the same namespace back. If we do not, continue until
17901 // translation unit scope, at which point we have a fully qualified NNS.
17904 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17905 // This tag should be declared in a namespace, which can only be enclosed by
17906 // other namespaces. Bail if there's an anonymous namespace in the chain.
17907 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17908 if (!Namespace || Namespace->isAnonymousNamespace())
17909 return FixItHint();
17910 IdentifierInfo *II = Namespace->getIdentifier();
17911 Namespaces.push_back(II);
17912 NamedDecl *Lookup = SemaRef.LookupSingleName(
17913 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17914 if (Lookup == Namespace)
17915 break;
17916 }
17917
17918 // Once we have all the namespaces, reverse them to go outermost first, and
17919 // build an NNS.
17920 SmallString<64> Insertion;
17921 llvm::raw_svector_ostream OS(Insertion);
17922 if (DC->isTranslationUnit())
17923 OS << "::";
17924 std::reverse(Namespaces.begin(), Namespaces.end());
17925 for (auto *II : Namespaces)
17926 OS << II->getName() << "::";
17927 return FixItHint::CreateInsertion(NameLoc, Insertion);
17928}
17929
17930/// Determine whether a tag originally declared in context \p OldDC can
17931/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17932/// found a declaration in \p OldDC as a previous decl, perhaps through a
17933/// using-declaration).
17935 DeclContext *NewDC) {
17936 OldDC = OldDC->getRedeclContext();
17937 NewDC = NewDC->getRedeclContext();
17938
17939 if (OldDC->Equals(NewDC))
17940 return true;
17941
17942 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17943 // encloses the other).
17944 if (S.getLangOpts().MSVCCompat &&
17945 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17946 return true;
17947
17948 return false;
17949}
17950
17952Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17953 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17954 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17955 SourceLocation ModulePrivateLoc,
17956 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17957 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17958 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17959 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17960 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17961 // If this is not a definition, it must have a name.
17962 IdentifierInfo *OrigName = Name;
17963 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17964 "Nameless record must be a definition!");
17965 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17966
17967 OwnedDecl = false;
17969 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17970
17971 // FIXME: Check member specializations more carefully.
17972 bool isMemberSpecialization = false;
17973 bool IsInjectedClassName = false;
17974 bool Invalid = false;
17975
17976 // We only need to do this matching if we have template parameters
17977 // or a scope specifier, which also conveniently avoids this work
17978 // for non-C++ cases.
17979 if (TemplateParameterLists.size() > 0 ||
17980 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17981 TemplateParameterList *TemplateParams =
17983 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17984 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17985
17986 // C++23 [dcl.type.elab] p2:
17987 // If an elaborated-type-specifier is the sole constituent of a
17988 // declaration, the declaration is ill-formed unless it is an explicit
17989 // specialization, an explicit instantiation or it has one of the
17990 // following forms: [...]
17991 // C++23 [dcl.enum] p1:
17992 // If the enum-head-name of an opaque-enum-declaration contains a
17993 // nested-name-specifier, the declaration shall be an explicit
17994 // specialization.
17995 //
17996 // FIXME: Class template partial specializations can be forward declared
17997 // per CWG2213, but the resolution failed to allow qualified forward
17998 // declarations. This is almost certainly unintentional, so we allow them.
17999 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
18000 !isMemberSpecialization)
18001 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
18003
18004 if (TemplateParams) {
18005 if (Kind == TagTypeKind::Enum) {
18006 Diag(KWLoc, diag::err_enum_template);
18007 return true;
18008 }
18009
18010 if (TemplateParams->size() > 0) {
18011 // This is a declaration or definition of a class template (which may
18012 // be a member of another template).
18013
18014 if (Invalid)
18015 return true;
18016
18017 OwnedDecl = false;
18019 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
18020 AS, ModulePrivateLoc,
18021 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
18022 TemplateParameterLists.data(), isMemberSpecialization, SkipBody);
18023 return Result.get();
18024 } else {
18025 // The "template<>" header is extraneous.
18026 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18027 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18028 isMemberSpecialization = true;
18029 }
18030 }
18031
18032 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18033 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
18034 return true;
18035 }
18036
18037 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18038 // C++23 [dcl.type.elab]p4:
18039 // If an elaborated-type-specifier appears with the friend specifier as
18040 // an entire member-declaration, the member-declaration shall have one
18041 // of the following forms:
18042 // friend class-key nested-name-specifier(opt) identifier ;
18043 // friend class-key simple-template-id ;
18044 // friend class-key nested-name-specifier template(opt)
18045 // simple-template-id ;
18046 //
18047 // Since enum is not a class-key, so declarations like "friend enum E;"
18048 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18049 // invalid, most implementations accept so we issue a pedantic warning.
18050 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
18051 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18052 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18053 Diag(KWLoc, diag::note_enum_friend)
18054 << (ScopedEnum + ScopedEnumUsesClassTag);
18055 }
18056
18057 // Figure out the underlying type if this a enum declaration. We need to do
18058 // this early, because it's needed to detect if this is an incompatible
18059 // redeclaration.
18060 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18061 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18062
18063 if (Kind == TagTypeKind::Enum) {
18064 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18065 Invalid) {
18066 // No underlying type explicitly specified, or we failed to parse the
18067 // type, default to int.
18068 EnumUnderlying = Context.IntTy.getTypePtr();
18069 } else if (UnderlyingType.get()) {
18070 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18071 // integral type; any cv-qualification is ignored.
18072 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18073 // unqualified, non-atomic version of the type specified by the type
18074 // specifiers in the specifier qualifier list.
18075 TypeSourceInfo *TI = nullptr;
18076 GetTypeFromParser(UnderlyingType.get(), &TI);
18077 EnumUnderlying = TI;
18078
18080 // Recover by falling back to int.
18081 EnumUnderlying = Context.IntTy.getTypePtr();
18082
18085 EnumUnderlying = Context.IntTy.getTypePtr();
18086
18087 // If the underlying type is atomic, we need to adjust the type before
18088 // continuing. This only happens in the case we stored a TypeSourceInfo
18089 // into EnumUnderlying because the other cases are error recovery up to
18090 // this point. But because it's not possible to gin up a TypeSourceInfo
18091 // for a non-atomic type from an atomic one, we'll store into the Type
18092 // field instead. FIXME: it would be nice to have an easy way to get a
18093 // derived TypeSourceInfo which strips qualifiers including the weird
18094 // ones like _Atomic where it forms a different type.
18095 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
18096 TI && TI->getType()->isAtomicType())
18097 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18098
18099 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18100 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18101 // of 'int'. However, if this is an unfixed forward declaration, don't set
18102 // the underlying type unless the user enables -fms-compatibility. This
18103 // makes unfixed forward declared enums incomplete and is more conforming.
18104 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18105 EnumUnderlying = Context.IntTy.getTypePtr();
18106 }
18107 }
18108
18109 DeclContext *SearchDC = CurContext;
18110 DeclContext *DC = CurContext;
18111 bool isStdBadAlloc = false;
18112 bool isStdAlignValT = false;
18113
18115 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18117
18118 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18119 /// implemented asks for structural equivalence checking, the returned decl
18120 /// here is passed back to the parser, allowing the tag body to be parsed.
18121 auto createTagFromNewDecl = [&]() -> TagDecl * {
18122 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18123 // If there is an identifier, use the location of the identifier as the
18124 // location of the decl, otherwise use the location of the struct/union
18125 // keyword.
18126 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18127 TagDecl *New = nullptr;
18128
18129 if (Kind == TagTypeKind::Enum) {
18130 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
18131 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
18132 // If this is an undefined enum, bail.
18133 if (TUK != TagUseKind::Definition && !Invalid)
18134 return nullptr;
18135 if (EnumUnderlying) {
18137 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18139 else
18140 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18141 QualType EnumTy = ED->getIntegerType();
18142 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18143 ? Context.getPromotedIntegerType(EnumTy)
18144 : EnumTy);
18145 }
18146 } else { // struct/union
18147 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18148 nullptr);
18149 }
18150
18151 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18152 // Add alignment attributes if necessary; these attributes are checked
18153 // when the ASTContext lays out the structure.
18154 //
18155 // It is important for implementing the correct semantics that this
18156 // happen here (in ActOnTag). The #pragma pack stack is
18157 // maintained as a result of parser callbacks which can occur at
18158 // many points during the parsing of a struct declaration (because
18159 // the #pragma tokens are effectively skipped over during the
18160 // parsing of the struct).
18161 if (TUK == TagUseKind::Definition &&
18162 (!SkipBody || !SkipBody->ShouldSkip)) {
18163 if (LangOpts.HLSL)
18164 RD->addAttr(PackedAttr::CreateImplicit(Context));
18167 }
18168 }
18169 New->setLexicalDeclContext(CurContext);
18170 return New;
18171 };
18172
18173 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18174 if (Name && SS.isNotEmpty()) {
18175 // We have a nested-name tag ('struct foo::bar').
18176
18177 // Check for invalid 'foo::'.
18178 if (SS.isInvalid()) {
18179 Name = nullptr;
18180 goto CreateNewDecl;
18181 }
18182
18183 // If this is a friend or a reference to a class in a dependent
18184 // context, don't try to make a decl for it.
18185 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18186 DC = computeDeclContext(SS, false);
18187 if (!DC) {
18188 IsDependent = true;
18189 return true;
18190 }
18191 } else {
18192 DC = computeDeclContext(SS, true);
18193 if (!DC) {
18194 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
18195 << SS.getRange();
18196 return true;
18197 }
18198 }
18199
18200 if (RequireCompleteDeclContext(SS, DC))
18201 return true;
18202
18203 SearchDC = DC;
18204 // Look-up name inside 'foo::'.
18206
18207 if (Previous.isAmbiguous())
18208 return true;
18209
18210 if (Previous.empty()) {
18211 // Name lookup did not find anything. However, if the
18212 // nested-name-specifier refers to the current instantiation,
18213 // and that current instantiation has any dependent base
18214 // classes, we might find something at instantiation time: treat
18215 // this as a dependent elaborated-type-specifier.
18216 // But this only makes any sense for reference-like lookups.
18217 if (Previous.wasNotFoundInCurrentInstantiation() &&
18218 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18219 IsDependent = true;
18220 return true;
18221 }
18222
18223 // A tag 'foo::bar' must already exist.
18224 Diag(NameLoc, diag::err_not_tag_in_scope)
18225 << Kind << Name << DC << SS.getRange();
18226 Name = nullptr;
18227 Invalid = true;
18228 goto CreateNewDecl;
18229 }
18230 } else if (Name) {
18231 // C++14 [class.mem]p14:
18232 // If T is the name of a class, then each of the following shall have a
18233 // name different from T:
18234 // -- every member of class T that is itself a type
18235 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18236 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
18237 return true;
18238
18239 // If this is a named struct, check to see if there was a previous forward
18240 // declaration or definition.
18241 // FIXME: We're looking into outer scopes here, even when we
18242 // shouldn't be. Doing so can result in ambiguities that we
18243 // shouldn't be diagnosing.
18244 LookupName(Previous, S);
18245
18246 // When declaring or defining a tag, ignore ambiguities introduced
18247 // by types using'ed into this scope.
18248 if (Previous.isAmbiguous() &&
18250 LookupResult::Filter F = Previous.makeFilter();
18251 while (F.hasNext()) {
18252 NamedDecl *ND = F.next();
18253 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18254 SearchDC->getRedeclContext()))
18255 F.erase();
18256 }
18257 F.done();
18258 }
18259
18260 // C++11 [namespace.memdef]p3:
18261 // If the name in a friend declaration is neither qualified nor
18262 // a template-id and the declaration is a function or an
18263 // elaborated-type-specifier, the lookup to determine whether
18264 // the entity has been previously declared shall not consider
18265 // any scopes outside the innermost enclosing namespace.
18266 //
18267 // MSVC doesn't implement the above rule for types, so a friend tag
18268 // declaration may be a redeclaration of a type declared in an enclosing
18269 // scope. They do implement this rule for friend functions.
18270 //
18271 // Does it matter that this should be by scope instead of by
18272 // semantic context?
18273 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18274 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18275 LookupResult::Filter F = Previous.makeFilter();
18276 bool FriendSawTagOutsideEnclosingNamespace = false;
18277 while (F.hasNext()) {
18278 NamedDecl *ND = F.next();
18280 if (DC->isFileContext() &&
18281 !EnclosingNS->Encloses(ND->getDeclContext())) {
18282 if (getLangOpts().MSVCCompat)
18283 FriendSawTagOutsideEnclosingNamespace = true;
18284 else
18285 F.erase();
18286 }
18287 }
18288 F.done();
18289
18290 // Diagnose this MSVC extension in the easy case where lookup would have
18291 // unambiguously found something outside the enclosing namespace.
18292 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18293 NamedDecl *ND = Previous.getFoundDecl();
18294 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
18295 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
18296 }
18297 }
18298
18299 // Note: there used to be some attempt at recovery here.
18300 if (Previous.isAmbiguous())
18301 return true;
18302
18303 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18304 // FIXME: This makes sure that we ignore the contexts associated
18305 // with C structs, unions, and enums when looking for a matching
18306 // tag declaration or definition. See the similar lookup tweak
18307 // in Sema::LookupName; is there a better way to deal with this?
18309 SearchDC = SearchDC->getParent();
18310 } else if (getLangOpts().CPlusPlus) {
18311 // Inside ObjCContainer want to keep it as a lexical decl context but go
18312 // past it (most often to TranslationUnit) to find the semantic decl
18313 // context.
18314 while (isa<ObjCContainerDecl>(SearchDC))
18315 SearchDC = SearchDC->getParent();
18316 }
18317 } else if (getLangOpts().CPlusPlus) {
18318 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18319 // TagDecl the same way as we skip it for named TagDecl.
18320 while (isa<ObjCContainerDecl>(SearchDC))
18321 SearchDC = SearchDC->getParent();
18322 }
18323
18324 if (Previous.isSingleResult() &&
18325 Previous.getFoundDecl()->isTemplateParameter()) {
18326 // Maybe we will complain about the shadowed template parameter.
18327 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
18328 // Just pretend that we didn't see the previous declaration.
18329 Previous.clear();
18330 }
18331
18332 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18333 DC->Equals(getStdNamespace())) {
18334 if (Name->isStr("bad_alloc")) {
18335 // This is a declaration of or a reference to "std::bad_alloc".
18336 isStdBadAlloc = true;
18337
18338 // If std::bad_alloc has been implicitly declared (but made invisible to
18339 // name lookup), fill in this implicit declaration as the previous
18340 // declaration, so that the declarations get chained appropriately.
18341 if (Previous.empty() && StdBadAlloc)
18342 Previous.addDecl(getStdBadAlloc());
18343 } else if (Name->isStr("align_val_t")) {
18344 isStdAlignValT = true;
18345 if (Previous.empty() && StdAlignValT)
18346 Previous.addDecl(getStdAlignValT());
18347 }
18348 }
18349
18350 // If we didn't find a previous declaration, and this is a reference
18351 // (or friend reference), move to the correct scope. In C++, we
18352 // also need to do a redeclaration lookup there, just in case
18353 // there's a shadow friend decl.
18354 if (Name && Previous.empty() &&
18355 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18356 IsTemplateParamOrArg)) {
18357 if (Invalid) goto CreateNewDecl;
18358 assert(SS.isEmpty());
18359
18360 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18361 // C++ [basic.scope.pdecl]p5:
18362 // -- for an elaborated-type-specifier of the form
18363 //
18364 // class-key identifier
18365 //
18366 // if the elaborated-type-specifier is used in the
18367 // decl-specifier-seq or parameter-declaration-clause of a
18368 // function defined in namespace scope, the identifier is
18369 // declared as a class-name in the namespace that contains
18370 // the declaration; otherwise, except as a friend
18371 // declaration, the identifier is declared in the smallest
18372 // non-class, non-function-prototype scope that contains the
18373 // declaration.
18374 //
18375 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18376 // C structs and unions.
18377 //
18378 // It is an error in C++ to declare (rather than define) an enum
18379 // type, including via an elaborated type specifier. We'll
18380 // diagnose that later; for now, declare the enum in the same
18381 // scope as we would have picked for any other tag type.
18382 //
18383 // GNU C also supports this behavior as part of its incomplete
18384 // enum types extension, while GNU C++ does not.
18385 //
18386 // Find the context where we'll be declaring the tag.
18387 // FIXME: We would like to maintain the current DeclContext as the
18388 // lexical context,
18389 SearchDC = getTagInjectionContext(SearchDC);
18390
18391 // Find the scope where we'll be declaring the tag.
18393 } else {
18394 assert(TUK == TagUseKind::Friend);
18395 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18396
18397 // C++ [namespace.memdef]p3:
18398 // If a friend declaration in a non-local class first declares a
18399 // class or function, the friend class or function is a member of
18400 // the innermost enclosing namespace.
18401 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18402 : SearchDC->getEnclosingNamespaceContext();
18403 }
18404
18405 // In C++, we need to do a redeclaration lookup to properly
18406 // diagnose some problems.
18407 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18408 // hidden declaration so that we don't get ambiguity errors when using a
18409 // type declared by an elaborated-type-specifier. In C that is not correct
18410 // and we should instead merge compatible types found by lookup.
18411 if (getLangOpts().CPlusPlus) {
18412 // FIXME: This can perform qualified lookups into function contexts,
18413 // which are meaningless.
18414 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18415 LookupQualifiedName(Previous, SearchDC);
18416 } else {
18417 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18418 LookupName(Previous, S);
18419 }
18420 }
18421
18422 // If we have a known previous declaration to use, then use it.
18423 if (Previous.empty() && SkipBody && SkipBody->Previous)
18424 Previous.addDecl(SkipBody->Previous);
18425
18426 if (!Previous.empty()) {
18427 NamedDecl *PrevDecl = Previous.getFoundDecl();
18428 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18429
18430 // It's okay to have a tag decl in the same scope as a typedef
18431 // which hides a tag decl in the same scope. Finding this
18432 // with a redeclaration lookup can only actually happen in C++.
18433 //
18434 // This is also okay for elaborated-type-specifiers, which is
18435 // technically forbidden by the current standard but which is
18436 // okay according to the likely resolution of an open issue;
18437 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18438 if (getLangOpts().CPlusPlus) {
18439 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18440 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18441 if (Tag->getDeclName() == Name &&
18442 Tag->getDeclContext()->getRedeclContext()
18443 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18444 PrevDecl = Tag;
18445 Previous.clear();
18446 Previous.addDecl(Tag);
18447 Previous.resolveKind();
18448 }
18449 }
18450 } else if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18451 TUK == TagUseKind::Reference && RD &&
18452 RD->isInjectedClassName()) {
18453 // If lookup found the injected class name, the previous declaration is
18454 // the class being injected into.
18455 PrevDecl = cast<TagDecl>(RD->getDeclContext());
18456 Previous.clear();
18457 Previous.addDecl(PrevDecl);
18458 Previous.resolveKind();
18459 IsInjectedClassName = true;
18460 }
18461 }
18462
18463 // If this is a redeclaration of a using shadow declaration, it must
18464 // declare a tag in the same context. In MSVC mode, we allow a
18465 // redefinition if either context is within the other.
18466 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18467 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18468 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18469 TUK != TagUseKind::Friend &&
18470 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18471 !(OldTag && isAcceptableTagRedeclContext(
18472 *this, OldTag->getDeclContext(), SearchDC))) {
18473 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18474 Diag(Shadow->getTargetDecl()->getLocation(),
18475 diag::note_using_decl_target);
18476 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18477 << 0;
18478 // Recover by ignoring the old declaration.
18479 Previous.clear();
18480 goto CreateNewDecl;
18481 }
18482 }
18483
18484 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18485 // If this is a use of a previous tag, or if the tag is already declared
18486 // in the same scope (so that the definition/declaration completes or
18487 // rementions the tag), reuse the decl.
18488 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18489 isDeclInScope(DirectPrevDecl, SearchDC, S,
18490 SS.isNotEmpty() || isMemberSpecialization)) {
18491 // Make sure that this wasn't declared as an enum and now used as a
18492 // struct or something similar.
18493 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18494 TUK == TagUseKind::Definition, KWLoc,
18495 Name)) {
18496 bool SafeToContinue =
18497 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18498 Kind != TagTypeKind::Enum);
18499 if (SafeToContinue)
18500 Diag(KWLoc, diag::err_use_with_wrong_tag)
18501 << Name
18503 PrevTagDecl->getKindName());
18504 else
18505 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18506 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18507
18508 if (SafeToContinue)
18509 Kind = PrevTagDecl->getTagKind();
18510 else {
18511 // Recover by making this an anonymous redefinition.
18512 Name = nullptr;
18513 Previous.clear();
18514 Invalid = true;
18515 }
18516 }
18517
18518 if (Kind == TagTypeKind::Enum &&
18519 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18520 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18521 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18522 return PrevTagDecl;
18523
18524 QualType EnumUnderlyingTy;
18525 if (TypeSourceInfo *TI =
18526 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18527 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18528 else if (const Type *T =
18529 dyn_cast_if_present<const Type *>(EnumUnderlying))
18530 EnumUnderlyingTy = QualType(T, 0);
18531
18532 // All conflicts with previous declarations are recovered by
18533 // returning the previous declaration, unless this is a definition,
18534 // in which case we want the caller to bail out.
18535 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18536 ScopedEnum, EnumUnderlyingTy,
18537 IsFixed, PrevEnum))
18538 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18539 }
18540
18541 // C++11 [class.mem]p1:
18542 // A member shall not be declared twice in the member-specification,
18543 // except that a nested class or member class template can be declared
18544 // and then later defined.
18545 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18546 S->isDeclScope(PrevDecl)) {
18547 Diag(NameLoc, diag::ext_member_redeclared);
18548 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18549 }
18550
18551 // C++ [class.local]p3:
18552 // A class nested within a local class is a local class. A member of
18553 // a local class X shall be declared only in the definition of X or,
18554 // if the member is a nested class, in the nearest enclosing block
18555 // scope of X.
18556 if (TUK == TagUseKind::Definition && SS.isValid()) {
18557 if (const auto *OutermostClass = dyn_cast<CXXRecordDecl>(PrevDecl)) {
18558 while (const auto *ParentClass =
18559 dyn_cast<CXXRecordDecl>(OutermostClass->getParent()))
18560 OutermostClass = ParentClass;
18561
18562 if (OutermostClass->isLocalClass() &&
18563 !S->isDeclScope(OutermostClass)) {
18564 Diag(NameLoc, diag::err_local_nested_class_invalid_scope)
18565 << Name << OutermostClass;
18566 Diag(OutermostClass->getLocation(), diag::note_defined_here)
18567 << OutermostClass;
18568 }
18569 }
18570 }
18571
18572 if (!Invalid) {
18573 // If this is a use, just return the declaration we found, unless
18574 // we have attributes.
18575 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18576 if (!Attrs.empty()) {
18577 // FIXME: Diagnose these attributes. For now, we create a new
18578 // declaration to hold them.
18579 } else if (TUK == TagUseKind::Reference &&
18580 (PrevTagDecl->getFriendObjectKind() ==
18582 PrevDecl->getOwningModule() != getCurrentModule()) &&
18583 SS.isEmpty()) {
18584 // This declaration is a reference to an existing entity, but
18585 // has different visibility from that entity: it either makes
18586 // a friend visible or it makes a type visible in a new module.
18587 // In either case, create a new declaration. We only do this if
18588 // the declaration would have meant the same thing if no prior
18589 // declaration were found, that is, if it was found in the same
18590 // scope where we would have injected a declaration.
18591 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18592 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18593 return PrevTagDecl;
18594 // This is in the injected scope, create a new declaration in
18595 // that scope.
18597 } else {
18598 return PrevTagDecl;
18599 }
18600 }
18601
18602 // Diagnose attempts to redefine a tag.
18603 if (TUK == TagUseKind::Definition) {
18604 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18605 // If the type is currently being defined, complain
18606 // about a nested redefinition.
18607 if (Def->isBeingDefined()) {
18608 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18609 Diag(PrevTagDecl->getLocation(),
18610 diag::note_previous_definition);
18611 Name = nullptr;
18612 Previous.clear();
18613 Invalid = true;
18614 } else {
18615 // If we're defining a specialization and the previous
18616 // definition is from an implicit instantiation, don't emit an
18617 // error here; we'll catch this in the general case below.
18618 bool IsExplicitSpecializationAfterInstantiation = false;
18619 if (isMemberSpecialization) {
18620 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18621 IsExplicitSpecializationAfterInstantiation =
18622 RD->getTemplateSpecializationKind() !=
18624 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18625 IsExplicitSpecializationAfterInstantiation =
18626 ED->getTemplateSpecializationKind() !=
18628 }
18629
18630 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18631 // do not keep more that one definition around (merge them).
18632 // However, ensure the decl passes the structural compatibility
18633 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18634 NamedDecl *Hidden = nullptr;
18635 bool HiddenDefVisible = false;
18636 if (SkipBody &&
18637 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||
18638 getLangOpts().C23)) {
18639 // There is a definition of this tag, but it is not visible.
18640 // We explicitly make use of C++'s one definition rule here,
18641 // and assume that this definition is identical to the hidden
18642 // one we already have. Make the existing definition visible
18643 // and use it in place of this one.
18644 if (!getLangOpts().CPlusPlus) {
18645 // Postpone making the old definition visible until after we
18646 // complete parsing the new one and do the structural
18647 // comparison.
18648 SkipBody->CheckSameAsPrevious = true;
18649 SkipBody->New = createTagFromNewDecl();
18650 SkipBody->Previous = Def;
18651
18652 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18653 return Def;
18654 }
18655
18656 SkipBody->ShouldSkip = true;
18657 SkipBody->Previous = Def;
18658 if (!HiddenDefVisible && Hidden)
18660 // Carry on and handle it like a normal definition. We'll
18661 // skip starting the definition later.
18662
18663 } else if (!IsExplicitSpecializationAfterInstantiation) {
18664 // A redeclaration in function prototype scope in C isn't
18665 // visible elsewhere, so merely issue a warning.
18666 if (!getLangOpts().CPlusPlus &&
18668 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18669 << Name;
18670 else
18671 Diag(NameLoc, diag::err_redefinition) << Name;
18673 NameLoc.isValid() ? NameLoc : KWLoc);
18674 // If this is a redefinition, recover by making this
18675 // struct be anonymous, which will make any later
18676 // references get the previous definition.
18677 Name = nullptr;
18678 Previous.clear();
18679 Invalid = true;
18680 }
18681 }
18682 }
18683
18684 // Okay, this is definition of a previously declared or referenced
18685 // tag. We're going to create a new Decl for it.
18686 }
18687
18688 // Okay, we're going to make a redeclaration. If this is some kind
18689 // of reference, make sure we build the redeclaration in the same DC
18690 // as the original, and ignore the current access specifier.
18691 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18692 SearchDC = PrevTagDecl->getDeclContext();
18693 AS = AS_none;
18694 }
18695 }
18696 // If we get here we have (another) forward declaration or we
18697 // have a definition. Just create a new decl.
18698
18699 } else {
18700 // If we get here, this is a definition of a new tag type in a nested
18701 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18702 // new decl/type. We set PrevDecl to NULL so that the entities
18703 // have distinct types.
18704 Previous.clear();
18705 }
18706 // If we get here, we're going to create a new Decl. If PrevDecl
18707 // is non-NULL, it's a definition of the tag declared by
18708 // PrevDecl. If it's NULL, we have a new definition.
18709
18710 // Otherwise, PrevDecl is not a tag, but was found with tag
18711 // lookup. This is only actually possible in C++, where a few
18712 // things like templates still live in the tag namespace.
18713 } else {
18714 // Use a better diagnostic if an elaborated-type-specifier
18715 // found the wrong kind of type on the first
18716 // (non-redeclaration) lookup.
18717 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18718 !Previous.isForRedeclaration()) {
18719 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18720 Diag(NameLoc, diag::err_tag_reference_non_tag)
18721 << PrevDecl << NTK << Kind;
18722 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18723 Invalid = true;
18724
18725 // Otherwise, only diagnose if the declaration is in scope.
18726 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18727 SS.isNotEmpty() || isMemberSpecialization)) {
18728 // do nothing
18729
18730 // Diagnose implicit declarations introduced by elaborated types.
18731 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18732 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18733 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18734 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18735 Invalid = true;
18736
18737 // Otherwise it's a declaration. Call out a particularly common
18738 // case here.
18739 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18740 unsigned Kind = 0;
18741 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18742 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18743 << Name << Kind << TND->getUnderlyingType();
18744 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18745 Invalid = true;
18746
18747 // Otherwise, diagnose.
18748 } else {
18749 // The tag name clashes with something else in the target scope,
18750 // issue an error and recover by making this tag be anonymous.
18751 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18752 notePreviousDefinition(PrevDecl, NameLoc);
18753 Name = nullptr;
18754 Invalid = true;
18755 }
18756
18757 // The existing declaration isn't relevant to us; we're in a
18758 // new scope, so clear out the previous declaration.
18759 Previous.clear();
18760 }
18761 }
18762
18763CreateNewDecl:
18764
18765 TagDecl *PrevDecl = nullptr;
18766 if (Previous.isSingleResult())
18767 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18768
18769 // If there is an identifier, use the location of the identifier as the
18770 // location of the decl, otherwise use the location of the struct/union
18771 // keyword.
18772 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18773
18774 // Otherwise, create a new declaration. If there is a previous
18775 // declaration of the same entity, the two will be linked via
18776 // PrevDecl.
18777 TagDecl *New;
18778
18779 if (Kind == TagTypeKind::Enum) {
18780 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18781 // enum X { A, B, C } D; D should chain to X.
18782 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18783 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18784 ScopedEnumUsesClassTag, IsFixed);
18785
18788 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18789
18790 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18792
18793 // If this is an undefined enum, warn.
18794 if (TUK != TagUseKind::Definition && !Invalid) {
18795 TagDecl *Def;
18796 if (IsFixed && ED->isFixed()) {
18797 // C++0x: 7.2p2: opaque-enum-declaration.
18798 // Conflicts are diagnosed above. Do nothing.
18799 } else if (PrevDecl &&
18800 (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18801 Diag(Loc, diag::ext_forward_ref_enum_def)
18802 << New;
18803 Diag(Def->getLocation(), diag::note_previous_definition);
18804 } else {
18805 unsigned DiagID = diag::ext_forward_ref_enum;
18806 if (getLangOpts().MSVCCompat)
18807 DiagID = diag::ext_ms_forward_ref_enum;
18808 else if (getLangOpts().CPlusPlus)
18809 DiagID = diag::err_forward_ref_enum;
18810 Diag(Loc, DiagID);
18811 }
18812 }
18813
18814 if (EnumUnderlying) {
18816 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18818 else
18819 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18820 QualType EnumTy = ED->getIntegerType();
18821 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18822 ? Context.getPromotedIntegerType(EnumTy)
18823 : EnumTy);
18824 assert(ED->isComplete() && "enum with type should be complete");
18825 }
18826 } else {
18827 // struct/union/class
18828
18829 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18830 // struct X { int A; } D; D should chain to X.
18831 if (getLangOpts().CPlusPlus) {
18832 // FIXME: Look for a way to use RecordDecl for simple structs.
18833 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18834 cast_or_null<CXXRecordDecl>(PrevDecl));
18835
18836 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18838 } else
18839 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18840 cast_or_null<RecordDecl>(PrevDecl));
18841 }
18842
18843 // Only C23 and later allow defining new types in 'offsetof()'.
18844 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18846 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18847 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18848
18849 // C++11 [dcl.type]p3:
18850 // A type-specifier-seq shall not define a class or enumeration [...].
18851 if (!Invalid && getLangOpts().CPlusPlus &&
18852 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18853 TUK == TagUseKind::Definition) {
18854 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18855 << Context.getCanonicalTagType(New);
18856 Invalid = true;
18857 }
18858
18860 DC->getDeclKind() == Decl::Enum) {
18861 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18862 << Context.getCanonicalTagType(New);
18863 Invalid = true;
18864 }
18865
18866 // Maybe add qualifier info.
18867 if (SS.isNotEmpty()) {
18868 if (SS.isSet()) {
18869 // If this is either a declaration or a definition, check the
18870 // nested-name-specifier against the current context.
18871 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18872 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18873 /*TemplateId=*/nullptr,
18874 isMemberSpecialization))
18875 Invalid = true;
18876
18877 New->setQualifierInfo(SS.getWithLocInContext(Context));
18878 if (TemplateParameterLists.size() > 0) {
18879 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18880 }
18881 }
18882 else
18883 Invalid = true;
18884 }
18885
18886 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18887 // Add alignment attributes if necessary; these attributes are checked when
18888 // the ASTContext lays out the structure.
18889 //
18890 // It is important for implementing the correct semantics that this
18891 // happen here (in ActOnTag). The #pragma pack stack is
18892 // maintained as a result of parser callbacks which can occur at
18893 // many points during the parsing of a struct declaration (because
18894 // the #pragma tokens are effectively skipped over during the
18895 // parsing of the struct).
18896 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18897 if (LangOpts.HLSL)
18898 RD->addAttr(PackedAttr::CreateImplicit(Context));
18901 }
18902 }
18903
18904 if (ModulePrivateLoc.isValid()) {
18905 if (isMemberSpecialization)
18906 Diag(New->getLocation(), diag::err_module_private_specialization)
18907 << 2
18908 << FixItHint::CreateRemoval(ModulePrivateLoc);
18909 // __module_private__ does not apply to local classes. However, we only
18910 // diagnose this as an error when the declaration specifiers are
18911 // freestanding. Here, we just ignore the __module_private__.
18912 else if (!SearchDC->isFunctionOrMethod())
18913 New->setModulePrivate();
18914 }
18915
18916 // If this is a specialization of a member class (of a class template),
18917 // check the specialization.
18918 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18919 Invalid = true;
18920
18921 // If we're declaring or defining a tag in function prototype scope in C,
18922 // note that this type can only be used within the function and add it to
18923 // the list of decls to inject into the function definition scope. However,
18924 // in C23 and later, while the type is only visible within the function, the
18925 // function can be called with a compatible type defined in the same TU, so
18926 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18927 if ((Name || Kind == TagTypeKind::Enum) &&
18928 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18929 if (getLangOpts().CPlusPlus) {
18930 // C++ [dcl.fct]p6:
18931 // Types shall not be defined in return or parameter types.
18932 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18933 Diag(Loc, diag::err_type_defined_in_param_type)
18934 << Name;
18935 Invalid = true;
18936 }
18937 if (TUK == TagUseKind::Declaration)
18938 Invalid = true;
18939 } else if (!PrevDecl) {
18940 // In C23 mode, if the declaration is complete, we do not want to
18941 // diagnose.
18942 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18943 Diag(Loc, diag::warn_decl_in_param_list)
18944 << Context.getCanonicalTagType(New);
18945 }
18946 }
18947
18948 if (Invalid)
18949 New->setInvalidDecl();
18950
18951 // Set the lexical context. If the tag has a C++ scope specifier, the
18952 // lexical context will be different from the semantic context.
18953 New->setLexicalDeclContext(CurContext);
18954
18955 // Mark this as a friend decl if applicable.
18956 // In Microsoft mode, a friend declaration also acts as a forward
18957 // declaration so we always pass true to setObjectOfFriendDecl to make
18958 // the tag name visible.
18959 if (TUK == TagUseKind::Friend)
18960 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18961
18962 // Set the access specifier.
18963 if (!Invalid && SearchDC->isRecord())
18964 SetMemberAccessSpecifier(New, PrevDecl, AS);
18965
18966 if (PrevDecl)
18968
18969 if (TUK == TagUseKind::Definition) {
18970 if (!SkipBody || !SkipBody->ShouldSkip) {
18971 New->startDefinition();
18972 } else {
18973 New->setCompleteDefinition();
18974 New->demoteThisDefinitionToDeclaration();
18975 }
18976 }
18977
18978 ProcessDeclAttributeList(S, New, Attrs);
18980
18981 // If this has an identifier, add it to the scope stack.
18982 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18983 // We might be replacing an existing declaration in the lookup tables;
18984 // if so, borrow its access specifier.
18985 if (PrevDecl)
18986 New->setAccess(PrevDecl->getAccess());
18987
18988 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18990 if (Name) // can be null along some error paths
18991 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18992 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18993 } else if (Name) {
18994 S = getNonFieldDeclScope(S);
18995 PushOnScopeChains(New, S, true);
18996 } else {
18997 CurContext->addDecl(New);
18998 }
18999
19000 // If this is the C FILE type, notify the AST context.
19001 if (IdentifierInfo *II = New->getIdentifier())
19002 if (!New->isInvalidDecl() &&
19003 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
19004 II->isStr("FILE"))
19005 Context.setFILEDecl(New);
19006
19007 if (PrevDecl)
19008 mergeDeclAttributes(New, PrevDecl);
19009
19010 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
19013 }
19014
19015 // If there's a #pragma GCC visibility in scope, set the visibility of this
19016 // record.
19018
19019 // If this is not a definition, process API notes for it now.
19020 if (TUK != TagUseKind::Definition)
19022
19023 if (isMemberSpecialization && !New->isInvalidDecl())
19025
19026 OwnedDecl = true;
19027 // In C++, don't return an invalid declaration. We can't recover well from
19028 // the cases where we make the type anonymous.
19029 if (Invalid && getLangOpts().CPlusPlus) {
19030 if (New->isBeingDefined())
19031 if (auto RD = dyn_cast<RecordDecl>(New))
19032 RD->completeDefinition();
19033 return true;
19034 } else if (SkipBody && SkipBody->ShouldSkip) {
19035 return SkipBody->Previous;
19036 } else {
19037 return New;
19038 }
19039}
19040
19043 TagDecl *Tag = cast<TagDecl>(TagD);
19044
19045 // Enter the tag context.
19046 PushDeclContext(S, Tag);
19047
19049
19050 // If there's a #pragma GCC visibility in scope, set the visibility of this
19051 // record.
19053}
19054
19056 SkipBodyInfo &SkipBody) {
19057 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
19058 return false;
19059
19060 // Make the previous decl visible.
19062 CleanupMergedEnum(S, SkipBody.New);
19063 return true;
19064}
19065
19067 SourceLocation FinalLoc,
19068 bool IsFinalSpelledSealed,
19069 bool IsAbstract,
19070 SourceLocation LBraceLoc) {
19073
19074 FieldCollector->StartClass();
19075
19076 if (!Record->getIdentifier())
19077 return;
19078
19079 if (IsAbstract)
19080 Record->markAbstract();
19081
19082 if (FinalLoc.isValid()) {
19083 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
19084 IsFinalSpelledSealed
19085 ? FinalAttr::Keyword_sealed
19086 : FinalAttr::Keyword_final));
19087 }
19088
19089 // C++ [class]p2:
19090 // [...] The class-name is also inserted into the scope of the
19091 // class itself; this is known as the injected-class-name. For
19092 // purposes of access checking, the injected-class-name is treated
19093 // as if it were a public member name.
19094 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19095 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
19096 Record->getLocation(), Record->getIdentifier());
19097 InjectedClassName->setImplicit();
19098 InjectedClassName->setAccess(AS_public);
19099 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19100 InjectedClassName->setDescribedClassTemplate(Template);
19101
19102 PushOnScopeChains(InjectedClassName, S);
19103 assert(InjectedClassName->isInjectedClassName() &&
19104 "Broken injected-class-name");
19105}
19106
19108 SourceRange BraceRange) {
19110 TagDecl *Tag = cast<TagDecl>(TagD);
19111 Tag->setBraceRange(BraceRange);
19112
19113 // Make sure we "complete" the definition even it is invalid.
19114 if (Tag->isBeingDefined()) {
19115 assert(Tag->isInvalidDecl() && "We should already have completed it");
19116 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19117 RD->completeDefinition();
19118 }
19119
19120 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
19121 FieldCollector->FinishClass();
19122 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19123 auto *Def = RD->getDefinition();
19124 assert(Def && "The record is expected to have a completed definition");
19125 unsigned NumInitMethods = 0;
19126 for (auto *Method : Def->methods()) {
19127 if (!Method->getIdentifier())
19128 continue;
19129 if (Method->getName() == "__init")
19130 NumInitMethods++;
19131 }
19132 if (NumInitMethods > 1 || !Def->hasInitMethod())
19133 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
19134 }
19135
19136 // If we're defining a dynamic class in a module interface unit, we always
19137 // need to produce the vtable for it, even if the vtable is not used in the
19138 // current TU.
19139 //
19140 // The case where the current class is not dynamic is handled in
19141 // MarkVTableUsed.
19142 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19143 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
19144 }
19145
19146 // Exit this scope of this tag's definition.
19148
19149 if (getCurLexicalContext()->isObjCContainer() &&
19150 Tag->getDeclContext()->isFileContext())
19151 Tag->setTopLevelDeclInObjCContainer();
19152
19153 // Notify the consumer that we've defined a tag.
19154 if (!Tag->isInvalidDecl())
19155 Consumer.HandleTagDeclDefinition(Tag);
19156
19157 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19158 // from XLs and instead matches the XL #pragma pack(1) behavior.
19159 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19160 AlignPackStack.hasValue()) {
19161 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19162 // Only diagnose #pragma align(packed).
19163 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19164 return;
19165 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
19166 if (!RD)
19167 return;
19168 // Only warn if there is at least 1 bitfield member.
19169 if (llvm::any_of(RD->fields(),
19170 [](const FieldDecl *FD) { return FD->isBitField(); }))
19171 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
19172 }
19173}
19174
19177 TagDecl *Tag = cast<TagDecl>(TagD);
19178 Tag->setInvalidDecl();
19179
19180 // Make sure we "complete" the definition even it is invalid.
19181 if (Tag->isBeingDefined()) {
19182 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19183 RD->completeDefinition();
19184 }
19185
19186 // We're undoing ActOnTagStartDefinition here, not
19187 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19188 // the FieldCollector.
19189
19191}
19192
19193// Note that FieldName may be null for anonymous bitfields.
19195 const IdentifierInfo *FieldName,
19196 QualType FieldTy, bool IsMsStruct,
19197 Expr *BitWidth) {
19198 assert(BitWidth);
19199 if (BitWidth->containsErrors())
19200 return ExprError();
19201
19202 // C99 6.7.2.1p4 - verify the field type.
19203 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19204 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19205 // Handle incomplete and sizeless types with a specific error.
19206 if (RequireCompleteSizedType(FieldLoc, FieldTy,
19207 diag::err_field_incomplete_or_sizeless))
19208 return ExprError();
19209 if (FieldName)
19210 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
19211 << FieldName << FieldTy << BitWidth->getSourceRange();
19212 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
19213 << FieldTy << BitWidth->getSourceRange();
19215 return ExprError();
19216
19217 // If the bit-width is type- or value-dependent, don't try to check
19218 // it now.
19219 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19220 return BitWidth;
19221
19222 llvm::APSInt Value;
19223 ExprResult ICE =
19225 if (ICE.isInvalid())
19226 return ICE;
19227 BitWidth = ICE.get();
19228
19229 // Zero-width bitfield is ok for anonymous field.
19230 if (Value == 0 && FieldName)
19231 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
19232 << FieldName << BitWidth->getSourceRange();
19233
19234 if (Value.isSigned() && Value.isNegative()) {
19235 if (FieldName)
19236 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
19237 << FieldName << toString(Value, 10);
19238 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
19239 << toString(Value, 10);
19240 }
19241
19242 // The size of the bit-field must not exceed our maximum permitted object
19243 // size.
19244 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19245 return Diag(FieldLoc, diag::err_bitfield_too_wide)
19246 << !FieldName << FieldName << toString(Value, 10);
19247 }
19248
19249 if (!FieldTy->isDependentType()) {
19250 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
19251 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
19252 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
19253
19254 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19255 // ABI.
19256 bool CStdConstraintViolation =
19257 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19258 bool MSBitfieldViolation = Value.ugt(TypeStorageSize) && IsMsStruct;
19259 if (CStdConstraintViolation || MSBitfieldViolation) {
19260 unsigned DiagWidth =
19261 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19262 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
19263 << (bool)FieldName << FieldName << toString(Value, 10)
19264 << !CStdConstraintViolation << DiagWidth;
19265 }
19266
19267 // Warn on types where the user might conceivably expect to get all
19268 // specified bits as value bits: that's all integral types other than
19269 // 'bool'.
19270 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19271 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
19272 << FieldName << Value << (unsigned)TypeWidth;
19273 }
19274 }
19275
19276 if (isa<ConstantExpr>(BitWidth))
19277 return BitWidth;
19278 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
19279}
19280
19282 Declarator &D, Expr *BitfieldWidth) {
19283 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
19284 D, BitfieldWidth,
19285 /*InitStyle=*/ICIS_NoInit, AS_public);
19286 return Res;
19287}
19288
19290 SourceLocation DeclStart,
19291 Declarator &D, Expr *BitWidth,
19292 InClassInitStyle InitStyle,
19293 AccessSpecifier AS) {
19294 if (D.isDecompositionDeclarator()) {
19296 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
19297 << Decomp.getSourceRange();
19298 return nullptr;
19299 }
19300
19301 const IdentifierInfo *II = D.getIdentifier();
19302 SourceLocation Loc = DeclStart;
19303 if (II) Loc = D.getIdentifierLoc();
19304
19306 QualType T = TInfo->getType();
19307 if (getLangOpts().CPlusPlus) {
19309
19312 D.setInvalidType();
19313 T = Context.IntTy;
19314 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19315 }
19316 }
19317
19319
19321 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19322 << getLangOpts().CPlusPlus17;
19325 diag::err_invalid_thread)
19327
19328 // Check to see if this name was declared as a member previously
19329 NamedDecl *PrevDecl = nullptr;
19330 LookupResult Previous(*this, II, Loc, LookupMemberName,
19332 LookupName(Previous, S);
19333 switch (Previous.getResultKind()) {
19336 PrevDecl = Previous.getAsSingle<NamedDecl>();
19337 break;
19338
19340 PrevDecl = Previous.getRepresentativeDecl();
19341 break;
19342
19346 break;
19347 }
19348 Previous.suppressDiagnostics();
19349
19350 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19351 // Maybe we will complain about the shadowed template parameter.
19353 // Just pretend that we didn't see the previous declaration.
19354 PrevDecl = nullptr;
19355 }
19356
19357 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19358 PrevDecl = nullptr;
19359
19360 bool Mutable
19361 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19362 SourceLocation TSSL = D.getBeginLoc();
19363 FieldDecl *NewFD
19364 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
19365 TSSL, AS, PrevDecl, &D);
19366
19367 if (NewFD->isInvalidDecl())
19368 Record->setInvalidDecl();
19369
19371 NewFD->setModulePrivate();
19372
19373 if (NewFD->isInvalidDecl() && PrevDecl) {
19374 // Don't introduce NewFD into scope; there's already something
19375 // with the same name in the same scope.
19376 } else if (II) {
19377 PushOnScopeChains(NewFD, S);
19378 } else
19379 Record->addDecl(NewFD);
19380
19381 return NewFD;
19382}
19383
19385 TypeSourceInfo *TInfo,
19387 bool Mutable, Expr *BitWidth,
19388 InClassInitStyle InitStyle,
19389 SourceLocation TSSL,
19390 AccessSpecifier AS, NamedDecl *PrevDecl,
19391 Declarator *D) {
19392 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19393 bool InvalidDecl = false;
19394 if (D) InvalidDecl = D->isInvalidType();
19395
19396 // If we receive a broken type, recover by assuming 'int' and
19397 // marking this declaration as invalid.
19398 if (T.isNull() || T->containsErrors()) {
19399 InvalidDecl = true;
19400 T = Context.IntTy;
19401 }
19402
19403 QualType EltTy = Context.getBaseElementType(T);
19404 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19405 bool isIncomplete =
19406 LangOpts.HLSL // HLSL allows sizeless builtin types
19407 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19408 : RequireCompleteSizedType(Loc, EltTy,
19409 diag::err_field_incomplete_or_sizeless);
19410 if (isIncomplete) {
19411 // Fields of incomplete type force their record to be invalid.
19412 Record->setInvalidDecl();
19413 InvalidDecl = true;
19414 } else {
19415 NamedDecl *Def;
19416 EltTy->isIncompleteType(&Def);
19417 if (Def && Def->isInvalidDecl()) {
19418 Record->setInvalidDecl();
19419 InvalidDecl = true;
19420 }
19421 }
19422 }
19423
19424 // TR 18037 does not allow fields to be declared with address space
19425 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19426 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19427 Diag(Loc, diag::err_field_with_address_space);
19428 Record->setInvalidDecl();
19429 InvalidDecl = true;
19430 }
19431
19432 if (LangOpts.OpenCL) {
19433 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19434 // used as structure or union field: image, sampler, event or block types.
19435 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19436 T->isBlockPointerType()) {
19437 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19438 Record->setInvalidDecl();
19439 InvalidDecl = true;
19440 }
19441 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19442 // is enabled.
19443 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19444 "__cl_clang_bitfields", LangOpts)) {
19445 Diag(Loc, diag::err_opencl_bitfields);
19446 InvalidDecl = true;
19447 }
19448 }
19449
19450 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19451 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19452 T.hasQualifiers()) {
19453 InvalidDecl = true;
19454 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19455 }
19456
19457 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19458 // than a variably modified type.
19459 if (!InvalidDecl && T->isVariablyModifiedType()) {
19461 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19462 InvalidDecl = true;
19463 }
19464
19465 // Fields can not have abstract class types
19466 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19467 diag::err_abstract_type_in_decl,
19469 InvalidDecl = true;
19470
19471 if (InvalidDecl)
19472 BitWidth = nullptr;
19473 // If this is declared as a bit-field, check the bit-field.
19474 if (BitWidth) {
19475 BitWidth =
19476 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19477 if (!BitWidth) {
19478 InvalidDecl = true;
19479 BitWidth = nullptr;
19480 }
19481 }
19482
19483 // Check that 'mutable' is consistent with the type of the declaration.
19484 if (!InvalidDecl && Mutable) {
19485 unsigned DiagID = 0;
19486 if (T->isReferenceType())
19487 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19488 : diag::err_mutable_reference;
19489 else if (T.isConstQualified())
19490 DiagID = diag::err_mutable_const;
19491
19492 if (DiagID) {
19493 SourceLocation ErrLoc = Loc;
19494 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19495 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19496 Diag(ErrLoc, DiagID);
19497 if (DiagID != diag::ext_mutable_reference) {
19498 Mutable = false;
19499 InvalidDecl = true;
19500 }
19501 }
19502 }
19503
19504 // C++11 [class.union]p8 (DR1460):
19505 // At most one variant member of a union may have a
19506 // brace-or-equal-initializer.
19507 if (InitStyle != ICIS_NoInit)
19509
19510 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19511 BitWidth, Mutable, InitStyle);
19512 if (InvalidDecl)
19513 NewFD->setInvalidDecl();
19514
19515 if (!InvalidDecl)
19517
19518 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19519 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19520 Diag(Loc, diag::err_duplicate_member) << II;
19521 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19522 NewFD->setInvalidDecl();
19523 }
19524
19525 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19526 if (Record->isUnion()) {
19527 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19528 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19529
19530 // C++ [class.union]p1: An object of a class with a non-trivial
19531 // constructor, a non-trivial copy constructor, a non-trivial
19532 // destructor, or a non-trivial copy assignment operator
19533 // cannot be a member of a union, nor can an array of such
19534 // objects.
19535 if (CheckNontrivialField(NewFD))
19536 NewFD->setInvalidDecl();
19537 }
19538
19539 // C++ [class.union]p1: If a union contains a member of reference type,
19540 // the program is ill-formed, except when compiling with MSVC extensions
19541 // enabled.
19542 if (EltTy->isReferenceType()) {
19543 const bool HaveMSExt =
19544 getLangOpts().MicrosoftExt &&
19546
19547 Diag(NewFD->getLocation(),
19548 HaveMSExt ? diag::ext_union_member_of_reference_type
19549 : diag::err_union_member_of_reference_type)
19550 << NewFD->getDeclName() << EltTy;
19551 if (!HaveMSExt)
19552 NewFD->setInvalidDecl();
19553 }
19554 }
19555 }
19556
19557 // FIXME: We need to pass in the attributes given an AST
19558 // representation, not a parser representation.
19559 if (D) {
19560 // FIXME: The current scope is almost... but not entirely... correct here.
19561 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19562
19563 if (NewFD->hasAttrs())
19565 }
19566
19567 // In auto-retain/release, infer strong retension for fields of
19568 // retainable type.
19569 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19570 NewFD->setInvalidDecl();
19571
19572 if (T.isObjCGCWeak())
19573 Diag(Loc, diag::warn_attribute_weak_on_field);
19574
19575 // PPC MMA non-pointer types are not allowed as field types.
19576 if (Context.getTargetInfo().getTriple().isPPC64() &&
19577 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19578 NewFD->setInvalidDecl();
19579
19580 NewFD->setAccess(AS);
19581 return NewFD;
19582}
19583
19585 assert(FD);
19586 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19587
19588 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19589 return false;
19590
19591 QualType EltTy = Context.getBaseElementType(FD->getType());
19592 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19593 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19594 // We check for copy constructors before constructors
19595 // because otherwise we'll never get complaints about
19596 // copy constructors.
19597
19599 // We're required to check for any non-trivial constructors. Since the
19600 // implicit default constructor is suppressed if there are any
19601 // user-declared constructors, we just need to check that there is a
19602 // trivial default constructor and a trivial copy constructor. (We don't
19603 // worry about move constructors here, since this is a C++98 check.)
19604 if (RDecl->hasNonTrivialCopyConstructor())
19606 else if (!RDecl->hasTrivialDefaultConstructor())
19608 else if (RDecl->hasNonTrivialCopyAssignment())
19610 else if (RDecl->hasNonTrivialDestructor())
19612
19613 if (member != CXXSpecialMemberKind::Invalid) {
19614 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19615 RDecl->hasObjectMember()) {
19616 // Objective-C++ ARC: it is an error to have a non-trivial field of
19617 // a union. However, system headers in Objective-C programs
19618 // occasionally have Objective-C lifetime objects within unions,
19619 // and rather than cause the program to fail, we make those
19620 // members unavailable.
19621 SourceLocation Loc = FD->getLocation();
19622 if (getSourceManager().isInSystemHeader(Loc)) {
19623 if (!FD->hasAttr<UnavailableAttr>())
19624 FD->addAttr(UnavailableAttr::CreateImplicit(
19625 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19626 return false;
19627 }
19628 }
19629
19630 Diag(FD->getLocation(),
19632 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19633 : diag::err_illegal_union_or_anon_struct_member)
19634 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19635 DiagnoseNontrivial(RDecl, member);
19636 return !getLangOpts().CPlusPlus11;
19637 }
19638 }
19639
19640 return false;
19641}
19642
19644 SmallVectorImpl<Decl *> &AllIvarDecls) {
19645 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19646 return;
19647
19648 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19649 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19650
19651 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19652 return;
19653 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19654 if (!ID) {
19655 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19656 if (!CD->IsClassExtension())
19657 return;
19658 }
19659 // No need to add this to end of @implementation.
19660 else
19661 return;
19662 }
19663 // All conditions are met. Add a new bitfield to the tail end of ivars.
19664 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19665 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19666 Expr *BitWidth =
19667 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19668
19669 Ivar = ObjCIvarDecl::Create(
19670 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19671 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19672 ObjCIvarDecl::Private, BitWidth, true);
19673 AllIvarDecls.push_back(Ivar);
19674}
19675
19676/// [class.dtor]p4:
19677/// At the end of the definition of a class, overload resolution is
19678/// performed among the prospective destructors declared in that class with
19679/// an empty argument list to select the destructor for the class, also
19680/// known as the selected destructor.
19681///
19682/// We do the overload resolution here, then mark the selected constructor in the AST.
19683/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19685 if (!Record->hasUserDeclaredDestructor()) {
19686 return;
19687 }
19688
19689 SourceLocation Loc = Record->getLocation();
19691
19692 for (auto *Decl : Record->decls()) {
19693 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19694 if (DD->isInvalidDecl())
19695 continue;
19696 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19697 OCS);
19698 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19699 }
19700 }
19701
19702 if (OCS.empty()) {
19703 return;
19704 }
19706 unsigned Msg = 0;
19707 OverloadCandidateDisplayKind DisplayKind;
19708
19709 switch (OCS.BestViableFunction(S, Loc, Best)) {
19710 case OR_Success:
19711 case OR_Deleted:
19712 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19713 break;
19714
19715 case OR_Ambiguous:
19716 Msg = diag::err_ambiguous_destructor;
19717 DisplayKind = OCD_AmbiguousCandidates;
19718 break;
19719
19721 Msg = diag::err_no_viable_destructor;
19722 DisplayKind = OCD_AllCandidates;
19723 break;
19724 }
19725
19726 if (Msg) {
19727 // OpenCL have got their own thing going with destructors. It's slightly broken,
19728 // but we allow it.
19729 if (!S.LangOpts.OpenCL) {
19730 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19731 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19732 Record->setInvalidDecl();
19733 }
19734 // It's a bit hacky: At this point we've raised an error but we want the
19735 // rest of the compiler to continue somehow working. However almost
19736 // everything we'll try to do with the class will depend on there being a
19737 // destructor. So let's pretend the first one is selected and hope for the
19738 // best.
19739 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19740 }
19741}
19742
19743/// [class.mem.special]p5
19744/// Two special member functions are of the same kind if:
19745/// - they are both default constructors,
19746/// - they are both copy or move constructors with the same first parameter
19747/// type, or
19748/// - they are both copy or move assignment operators with the same first
19749/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19751 CXXMethodDecl *M1,
19752 CXXMethodDecl *M2,
19754 // We don't want to compare templates to non-templates: See
19755 // https://github.com/llvm/llvm-project/issues/59206
19757 return bool(M1->getDescribedFunctionTemplate()) ==
19759 // FIXME: better resolve CWG
19760 // https://cplusplus.github.io/CWG/issues/2787.html
19761 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19762 M2->getNonObjectParameter(0)->getType()))
19763 return false;
19764 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
19766 return false;
19767
19768 return true;
19769}
19770
19771/// [class.mem.special]p6:
19772/// An eligible special member function is a special member function for which:
19773/// - the function is not deleted,
19774/// - the associated constraints, if any, are satisfied, and
19775/// - no special member function of the same kind whose associated constraints
19776/// [CWG2595], if any, are satisfied is more constrained.
19780 SmallVector<bool, 4> SatisfactionStatus;
19781
19782 for (CXXMethodDecl *Method : Methods) {
19783 if (!Method->getTrailingRequiresClause())
19784 SatisfactionStatus.push_back(true);
19785 else {
19786 ConstraintSatisfaction Satisfaction;
19787 if (S.CheckFunctionConstraints(Method, Satisfaction))
19788 SatisfactionStatus.push_back(false);
19789 else
19790 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19791 }
19792 }
19793
19794 for (size_t i = 0; i < Methods.size(); i++) {
19795 if (!SatisfactionStatus[i])
19796 continue;
19797 CXXMethodDecl *Method = Methods[i];
19798 CXXMethodDecl *OrigMethod = Method;
19799 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19800 OrigMethod = cast<CXXMethodDecl>(MF);
19801
19803 bool AnotherMethodIsMoreConstrained = false;
19804 for (size_t j = 0; j < Methods.size(); j++) {
19805 if (i == j || !SatisfactionStatus[j])
19806 continue;
19807 CXXMethodDecl *OtherMethod = Methods[j];
19808 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19809 OtherMethod = cast<CXXMethodDecl>(MF);
19810
19811 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19812 CSM))
19813 continue;
19814
19816 if (!Other)
19817 continue;
19818 if (!Orig) {
19819 AnotherMethodIsMoreConstrained = true;
19820 break;
19821 }
19822 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
19823 AnotherMethodIsMoreConstrained)) {
19824 // There was an error with the constraints comparison. Exit the loop
19825 // and don't consider this function eligible.
19826 AnotherMethodIsMoreConstrained = true;
19827 }
19828 if (AnotherMethodIsMoreConstrained)
19829 break;
19830 }
19831 // FIXME: Do not consider deleted methods as eligible after implementing
19832 // DR1734 and DR1496.
19833 if (!AnotherMethodIsMoreConstrained) {
19834 Method->setIneligibleOrNotSelected(false);
19835 Record->addedEligibleSpecialMemberFunction(Method,
19836 1 << llvm::to_underlying(CSM));
19837 }
19838 }
19839}
19840
19843 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19844 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19845 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19846 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19847 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19848
19849 for (auto *Decl : Record->decls()) {
19850 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19851 if (!MD) {
19852 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19853 if (FTD)
19854 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19855 }
19856 if (!MD)
19857 continue;
19858 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19859 if (CD->isInvalidDecl())
19860 continue;
19861 if (CD->isDefaultConstructor())
19862 DefaultConstructors.push_back(MD);
19863 else if (CD->isCopyConstructor())
19864 CopyConstructors.push_back(MD);
19865 else if (CD->isMoveConstructor())
19866 MoveConstructors.push_back(MD);
19867 } else if (MD->isCopyAssignmentOperator()) {
19868 CopyAssignmentOperators.push_back(MD);
19869 } else if (MD->isMoveAssignmentOperator()) {
19870 MoveAssignmentOperators.push_back(MD);
19871 }
19872 }
19873
19874 SetEligibleMethods(S, Record, DefaultConstructors,
19876 SetEligibleMethods(S, Record, CopyConstructors,
19878 SetEligibleMethods(S, Record, MoveConstructors,
19880 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19882 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19884}
19885
19886bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19887 // Check to see if a FieldDecl is a pointer to a function.
19888 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19889 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19890 if (!FD) {
19891 // Check whether this is a forward declaration that was inserted by
19892 // Clang. This happens when a non-forward declared / defined type is
19893 // used, e.g.:
19894 //
19895 // struct foo {
19896 // struct bar *(*f)();
19897 // struct bar *(*g)();
19898 // };
19899 //
19900 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19901 // incomplete definition.
19902 if (const auto *TD = dyn_cast<TagDecl>(D))
19903 return !TD->isCompleteDefinition();
19904 return false;
19905 }
19906 QualType FieldType = FD->getType().getDesugaredType(Context);
19907 if (isa<PointerType>(FieldType)) {
19908 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19909 return PointeeType.getDesugaredType(Context)->isFunctionType();
19910 }
19911 // If a member is a struct entirely of function pointers, that counts too.
19912 if (const auto *Record = FieldType->getAsRecordDecl();
19913 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19914 return true;
19915 return false;
19916 };
19917
19918 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
19919}
19920
19921void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19922 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19923 SourceLocation RBrac,
19924 const ParsedAttributesView &Attrs) {
19925 assert(EnclosingDecl && "missing record or interface decl");
19926
19927 // If this is an Objective-C @implementation or category and we have
19928 // new fields here we should reset the layout of the interface since
19929 // it will now change.
19930 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19931 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19932 switch (DC->getKind()) {
19933 default: break;
19934 case Decl::ObjCCategory:
19935 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19936 break;
19937 case Decl::ObjCImplementation:
19938 Context.
19939 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19940 break;
19941 }
19942 }
19943
19944 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19945 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19946
19947 // Start counting up the number of named members; make sure to include
19948 // members of anonymous structs and unions in the total.
19949 unsigned NumNamedMembers = 0;
19950 if (Record) {
19951 for (const auto *I : Record->decls()) {
19952 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19953 if (IFD->getDeclName())
19954 ++NumNamedMembers;
19955 }
19956 }
19957
19958 // Verify that all the fields are okay.
19960 const FieldDecl *PreviousField = nullptr;
19961 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19962 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
19963 FieldDecl *FD = cast<FieldDecl>(*i);
19964
19965 // Get the type for the field.
19966 const Type *FDTy = FD->getType().getTypePtr();
19967
19968 if (!FD->isAnonymousStructOrUnion()) {
19969 // Remember all fields written by the user.
19970 RecFields.push_back(FD);
19971 }
19972
19973 // If the field is already invalid for some reason, don't emit more
19974 // diagnostics about it.
19975 if (FD->isInvalidDecl()) {
19976 EnclosingDecl->setInvalidDecl();
19977 continue;
19978 }
19979
19980 // C99 6.7.2.1p2:
19981 // A structure or union shall not contain a member with
19982 // incomplete or function type (hence, a structure shall not
19983 // contain an instance of itself, but may contain a pointer to
19984 // an instance of itself), except that the last member of a
19985 // structure with more than one named member may have incomplete
19986 // array type; such a structure (and any union containing,
19987 // possibly recursively, a member that is such a structure)
19988 // shall not be a member of a structure or an element of an
19989 // array.
19990 bool IsLastField = (i + 1 == Fields.end());
19991 if (FDTy->isFunctionType()) {
19992 // Field declared as a function.
19993 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19994 << FD->getDeclName();
19995 FD->setInvalidDecl();
19996 EnclosingDecl->setInvalidDecl();
19997 continue;
19998 } else if (FDTy->isIncompleteArrayType() &&
19999 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
20000 if (Record) {
20001 // Flexible array member.
20002 // Microsoft and g++ is more permissive regarding flexible array.
20003 // It will accept flexible array in union and also
20004 // as the sole element of a struct/class.
20005 unsigned DiagID = 0;
20006 if (!Record->isUnion() && !IsLastField) {
20007 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
20008 << FD->getDeclName() << FD->getType() << Record->getTagKind();
20009 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
20010 FD->setInvalidDecl();
20011 EnclosingDecl->setInvalidDecl();
20012 continue;
20013 } else if (Record->isUnion())
20014 DiagID = getLangOpts().MicrosoftExt
20015 ? diag::ext_flexible_array_union_ms
20016 : diag::ext_flexible_array_union_gnu;
20017 else if (NumNamedMembers < 1)
20018 DiagID = getLangOpts().MicrosoftExt
20019 ? diag::ext_flexible_array_empty_aggregate_ms
20020 : diag::ext_flexible_array_empty_aggregate_gnu;
20021
20022 if (DiagID)
20023 Diag(FD->getLocation(), DiagID)
20024 << FD->getDeclName() << Record->getTagKind();
20025 // While the layout of types that contain virtual bases is not specified
20026 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
20027 // virtual bases after the derived members. This would make a flexible
20028 // array member declared at the end of an object not adjacent to the end
20029 // of the type.
20030 if (CXXRecord && CXXRecord->getNumVBases() != 0)
20031 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
20032 << FD->getDeclName() << Record->getTagKind();
20033 if (!getLangOpts().C99)
20034 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
20035 << FD->getDeclName() << Record->getTagKind();
20036
20037 // If the element type has a non-trivial destructor, we would not
20038 // implicitly destroy the elements, so disallow it for now.
20039 //
20040 // FIXME: GCC allows this. We should probably either implicitly delete
20041 // the destructor of the containing class, or just allow this.
20042 QualType BaseElem = Context.getBaseElementType(FD->getType());
20043 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20044 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
20045 << FD->getDeclName() << FD->getType();
20046 FD->setInvalidDecl();
20047 EnclosingDecl->setInvalidDecl();
20048 continue;
20049 }
20050 // Okay, we have a legal flexible array member at the end of the struct.
20051 Record->setHasFlexibleArrayMember(true);
20052 } else {
20053 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20054 // unless they are followed by another ivar. That check is done
20055 // elsewhere, after synthesized ivars are known.
20056 }
20057 } else if (!FDTy->isDependentType() &&
20058 (LangOpts.HLSL // HLSL allows sizeless builtin types
20060 diag::err_incomplete_type)
20062 FD->getLocation(), FD->getType(),
20063 diag::err_field_incomplete_or_sizeless))) {
20064 // Incomplete type
20065 FD->setInvalidDecl();
20066 EnclosingDecl->setInvalidDecl();
20067 continue;
20068 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20069 if (Record && RD->hasFlexibleArrayMember()) {
20070 // A type which contains a flexible array member is considered to be a
20071 // flexible array member.
20072 Record->setHasFlexibleArrayMember(true);
20073 if (!Record->isUnion()) {
20074 // If this is a struct/class and this is not the last element, reject
20075 // it. Note that GCC supports variable sized arrays in the middle of
20076 // structures.
20077 if (!IsLastField)
20078 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
20079 << FD->getDeclName() << FD->getType();
20080 else {
20081 // We support flexible arrays at the end of structs in
20082 // other structs as an extension.
20083 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
20084 << FD->getDeclName();
20085 }
20086 }
20087 }
20088 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
20090 diag::err_abstract_type_in_decl,
20092 // Ivars can not have abstract class types
20093 FD->setInvalidDecl();
20094 }
20095 if (Record && RD->hasObjectMember())
20096 Record->setHasObjectMember(true);
20097 if (Record && RD->hasVolatileMember())
20098 Record->setHasVolatileMember(true);
20099 } else if (FDTy->isObjCObjectType()) {
20100 /// A field cannot be an Objective-c object
20101 Diag(FD->getLocation(), diag::err_statically_allocated_object)
20103 QualType T = Context.getObjCObjectPointerType(FD->getType());
20104 FD->setType(T);
20105 } else if (Record && Record->isUnion() &&
20107 getSourceManager().isInSystemHeader(FD->getLocation()) &&
20108 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20110 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
20111 // For backward compatibility, fields of C unions declared in system
20112 // headers that have non-trivial ObjC ownership qualifications are marked
20113 // as unavailable unless the qualifier is explicit and __strong. This can
20114 // break ABI compatibility between programs compiled with ARC and MRR, but
20115 // is a better option than rejecting programs using those unions under
20116 // ARC.
20117 FD->addAttr(UnavailableAttr::CreateImplicit(
20118 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
20119 FD->getLocation()));
20120 } else if (getLangOpts().ObjC &&
20121 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20122 !Record->hasObjectMember()) {
20123 if (FD->getType()->isObjCObjectPointerType() ||
20124 FD->getType().isObjCGCStrong())
20125 Record->setHasObjectMember(true);
20126 else if (Context.getAsArrayType(FD->getType())) {
20127 QualType BaseType = Context.getBaseElementType(FD->getType());
20128 if (const auto *RD = BaseType->getAsRecordDecl();
20129 RD && RD->hasObjectMember())
20130 Record->setHasObjectMember(true);
20131 else if (BaseType->isObjCObjectPointerType() ||
20132 BaseType.isObjCGCStrong())
20133 Record->setHasObjectMember(true);
20134 }
20135 }
20136
20137 if (Record && !getLangOpts().CPlusPlus &&
20138 !shouldIgnoreForRecordTriviality(FD)) {
20139 QualType FT = FD->getType();
20141 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20143 Record->isUnion())
20144 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20145 }
20148 Record->setNonTrivialToPrimitiveCopy(true);
20149 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20150 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20151 }
20152 if (FD->hasAttr<ExplicitInitAttr>())
20153 Record->setHasUninitializedExplicitInitFields(true);
20154 if (FT.isDestructedType()) {
20155 Record->setNonTrivialToPrimitiveDestroy(true);
20156 Record->setParamDestroyedInCallee(true);
20157 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20158 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20159 }
20160
20161 if (const auto *RD = FT->getAsRecordDecl()) {
20162 if (RD->getArgPassingRestrictions() ==
20164 Record->setArgPassingRestrictions(
20166 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20167 Record->setArgPassingRestrictions(
20169 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20170 Q && Q.isAddressDiscriminated()) {
20171 Record->setArgPassingRestrictions(
20173 Record->setNonTrivialToPrimitiveCopy(true);
20174 }
20175 }
20176
20177 if (Record && FD->getType().isVolatileQualified())
20178 Record->setHasVolatileMember(true);
20179 bool ReportMSBitfieldStoragePacking =
20180 Record && PreviousField &&
20181 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
20182 Record->getLocation());
20183 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20184 return FD->isBitField() && !FD->getType()->isDependentType();
20185 };
20186
20187 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20188 IsNonDependentBitField(PreviousField)) {
20189 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
20190 CharUnits PreviousFieldStorageSize =
20191 Context.getTypeSizeInChars(PreviousField->getType());
20192 if (FDStorageSize != PreviousFieldStorageSize) {
20193 Diag(FD->getLocation(),
20194 diag::warn_ms_bitfield_mismatched_storage_packing)
20195 << FD << FD->getType() << FDStorageSize.getQuantity()
20196 << PreviousFieldStorageSize.getQuantity();
20197 Diag(PreviousField->getLocation(),
20198 diag::note_ms_bitfield_mismatched_storage_size_previous)
20199 << PreviousField << PreviousField->getType();
20200 }
20201 }
20202 // Keep track of the number of named members.
20203 if (FD->getIdentifier())
20204 ++NumNamedMembers;
20205 }
20206
20207 // Okay, we successfully defined 'Record'.
20208 if (Record) {
20209 bool Completed = false;
20210 if (S) {
20211 Scope *Parent = S->getParent();
20212 if (Parent && Parent->isTypeAliasScope() &&
20213 Parent->isTemplateParamScope())
20214 Record->setInvalidDecl();
20215 }
20216
20217 if (CXXRecord) {
20218 if (!CXXRecord->isInvalidDecl()) {
20219 // Set access bits correctly on the directly-declared conversions.
20221 I = CXXRecord->conversion_begin(),
20222 E = CXXRecord->conversion_end(); I != E; ++I)
20223 I.setAccess((*I)->getAccess());
20224 }
20225
20226 // Add any implicitly-declared members to this class.
20228
20229 if (!CXXRecord->isDependentType()) {
20230 if (!CXXRecord->isInvalidDecl()) {
20231 // If we have virtual base classes, we may end up finding multiple
20232 // final overriders for a given virtual function. Check for this
20233 // problem now.
20234 if (CXXRecord->getNumVBases()) {
20235 CXXFinalOverriderMap FinalOverriders;
20236 CXXRecord->getFinalOverriders(FinalOverriders);
20237
20238 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20239 MEnd = FinalOverriders.end();
20240 M != MEnd; ++M) {
20241 for (OverridingMethods::iterator SO = M->second.begin(),
20242 SOEnd = M->second.end();
20243 SO != SOEnd; ++SO) {
20244 assert(SO->second.size() > 0 &&
20245 "Virtual function without overriding functions?");
20246 if (SO->second.size() == 1)
20247 continue;
20248
20249 // C++ [class.virtual]p2:
20250 // In a derived class, if a virtual member function of a base
20251 // class subobject has more than one final overrider the
20252 // program is ill-formed.
20253 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
20254 << (const NamedDecl *)M->first << Record;
20255 Diag(M->first->getLocation(),
20256 diag::note_overridden_virtual_function);
20258 OM = SO->second.begin(),
20259 OMEnd = SO->second.end();
20260 OM != OMEnd; ++OM)
20261 Diag(OM->Method->getLocation(), diag::note_final_overrider)
20262 << (const NamedDecl *)M->first << OM->Method->getParent();
20263
20264 Record->setInvalidDecl();
20265 }
20266 }
20267 CXXRecord->completeDefinition(&FinalOverriders);
20268 Completed = true;
20269 }
20270 }
20271 ComputeSelectedDestructor(*this, CXXRecord);
20273 }
20274 }
20275
20276 if (!Completed)
20277 Record->completeDefinition();
20278
20279 // Handle attributes before checking the layout.
20281
20282 // Maybe randomize the record's decls. We automatically randomize a record
20283 // of function pointers, unless it has the "no_randomize_layout" attribute.
20284 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20285 !Record->isRandomized() && !Record->isUnion() &&
20286 (Record->hasAttr<RandomizeLayoutAttr>() ||
20287 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20288 EntirelyFunctionPointers(Record)))) {
20289 SmallVector<Decl *, 32> NewDeclOrdering;
20291 NewDeclOrdering))
20292 Record->reorderDecls(NewDeclOrdering);
20293 }
20294
20295 // We may have deferred checking for a deleted destructor. Check now.
20296 if (CXXRecord) {
20297 auto *Dtor = CXXRecord->getDestructor();
20298 if (Dtor && Dtor->isImplicit() &&
20300 CXXRecord->setImplicitDestructorIsDeleted();
20301 SetDeclDeleted(Dtor, CXXRecord->getLocation());
20302 }
20303 }
20304
20305 if (Record->hasAttrs()) {
20307
20308 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20310 IA->getRange(), IA->getBestCase(),
20311 IA->getInheritanceModel());
20312 }
20313
20314 // Check if the structure/union declaration is a type that can have zero
20315 // size in C. For C this is a language extension, for C++ it may cause
20316 // compatibility problems.
20317 bool CheckForZeroSize;
20318 if (!getLangOpts().CPlusPlus) {
20319 CheckForZeroSize = true;
20320 } else {
20321 // For C++ filter out types that cannot be referenced in C code.
20323 CheckForZeroSize =
20324 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20325 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20326 CXXRecord->isCLike();
20327 }
20328 if (CheckForZeroSize) {
20329 bool ZeroSize = true;
20330 bool IsEmpty = true;
20331 unsigned NonBitFields = 0;
20332 for (RecordDecl::field_iterator I = Record->field_begin(),
20333 E = Record->field_end();
20334 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20335 IsEmpty = false;
20336 if (I->isUnnamedBitField()) {
20337 if (!I->isZeroLengthBitField())
20338 ZeroSize = false;
20339 } else {
20340 ++NonBitFields;
20341 QualType FieldType = I->getType();
20342 if (FieldType->isIncompleteType() ||
20343 !Context.getTypeSizeInChars(FieldType).isZero())
20344 ZeroSize = false;
20345 }
20346 }
20347
20348 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20349 // allowed in C++, but warn if its declaration is inside
20350 // extern "C" block.
20351 if (ZeroSize) {
20352 Diag(RecLoc, getLangOpts().CPlusPlus ?
20353 diag::warn_zero_size_struct_union_in_extern_c :
20354 diag::warn_zero_size_struct_union_compat)
20355 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20356 }
20357
20358 // Structs without named members are extension in C (C99 6.7.2.1p7),
20359 // but are accepted by GCC. In C2y, this became implementation-defined
20360 // (C2y 6.7.3.2p10).
20361 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20362 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
20363 : diag::ext_no_named_members_in_struct_union)
20364 << Record->isUnion();
20365 }
20366 }
20367 } else {
20368 ObjCIvarDecl **ClsFields =
20369 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20370 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
20371 ID->setEndOfDefinitionLoc(RBrac);
20372 // Add ivar's to class's DeclContext.
20373 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20374 ClsFields[i]->setLexicalDeclContext(ID);
20375 ID->addDecl(ClsFields[i]);
20376 }
20377 // Must enforce the rule that ivars in the base classes may not be
20378 // duplicates.
20379 if (ID->getSuperClass())
20380 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
20381 } else if (ObjCImplementationDecl *IMPDecl =
20382 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
20383 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20384 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20385 // Ivar declared in @implementation never belongs to the implementation.
20386 // Only it is in implementation's lexical context.
20387 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20388 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20389 RBrac);
20390 IMPDecl->setIvarLBraceLoc(LBrac);
20391 IMPDecl->setIvarRBraceLoc(RBrac);
20392 } else if (ObjCCategoryDecl *CDecl =
20393 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20394 // case of ivars in class extension; all other cases have been
20395 // reported as errors elsewhere.
20396 // FIXME. Class extension does not have a LocEnd field.
20397 // CDecl->setLocEnd(RBrac);
20398 // Add ivar's to class extension's DeclContext.
20399 // Diagnose redeclaration of private ivars.
20400 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20401 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20402 if (IDecl) {
20403 if (const ObjCIvarDecl *ClsIvar =
20404 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20405 Diag(ClsFields[i]->getLocation(),
20406 diag::err_duplicate_ivar_declaration);
20407 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20408 continue;
20409 }
20410 for (const auto *Ext : IDecl->known_extensions()) {
20411 if (const ObjCIvarDecl *ClsExtIvar
20412 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20413 Diag(ClsFields[i]->getLocation(),
20414 diag::err_duplicate_ivar_declaration);
20415 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20416 continue;
20417 }
20418 }
20419 }
20420 ClsFields[i]->setLexicalDeclContext(CDecl);
20421 CDecl->addDecl(ClsFields[i]);
20422 }
20423 CDecl->setIvarLBraceLoc(LBrac);
20424 CDecl->setIvarRBraceLoc(RBrac);
20425 }
20426 }
20429}
20430
20431// Given an integral type, return the next larger integral type
20432// (or a NULL type of no such type exists).
20434 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20435 // enum checking below.
20436 assert((T->isIntegralType(Context) ||
20437 T->isEnumeralType()) && "Integral type required!");
20438 const unsigned NumTypes = 4;
20439 QualType SignedIntegralTypes[NumTypes] = {
20440 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20441 };
20442 QualType UnsignedIntegralTypes[NumTypes] = {
20443 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20444 Context.UnsignedLongLongTy
20445 };
20446
20447 unsigned BitWidth = Context.getTypeSize(T);
20448 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20449 : UnsignedIntegralTypes;
20450 for (unsigned I = 0; I != NumTypes; ++I)
20451 if (Context.getTypeSize(Types[I]) > BitWidth)
20452 return Types[I];
20453
20454 return QualType();
20455}
20456
20458 EnumConstantDecl *LastEnumConst,
20459 SourceLocation IdLoc,
20460 IdentifierInfo *Id,
20461 Expr *Val) {
20462 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20463 llvm::APSInt EnumVal(IntWidth);
20464 QualType EltTy;
20465
20467 Val = nullptr;
20468
20469 if (Val)
20470 Val = DefaultLvalueConversion(Val).get();
20471
20472 if (Val) {
20473 if (Enum->isDependentType() || Val->isTypeDependent() ||
20474 Val->containsErrors())
20475 EltTy = Context.DependentTy;
20476 else {
20477 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20478 // underlying type, but do allow it in all other contexts.
20479 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20480 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20481 // constant-expression in the enumerator-definition shall be a converted
20482 // constant expression of the underlying type.
20483 EltTy = Enum->getIntegerType();
20485 Val, EltTy, EnumVal, CCEKind::Enumerator);
20486 if (Converted.isInvalid())
20487 Val = nullptr;
20488 else
20489 Val = Converted.get();
20490 } else if (!Val->isValueDependent() &&
20491 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20493 .get())) {
20494 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20495 } else {
20496 if (Enum->isComplete()) {
20497 EltTy = Enum->getIntegerType();
20498
20499 // In Obj-C and Microsoft mode, require the enumeration value to be
20500 // representable in the underlying type of the enumeration. In C++11,
20501 // we perform a non-narrowing conversion as part of converted constant
20502 // expression checking.
20503 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20504 if (Context.getTargetInfo()
20505 .getTriple()
20506 .isWindowsMSVCEnvironment()) {
20507 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20508 } else {
20509 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20510 }
20511 }
20512
20513 // Cast to the underlying type.
20514 Val = ImpCastExprToType(Val, EltTy,
20515 EltTy->isBooleanType() ? CK_IntegralToBoolean
20516 : CK_IntegralCast)
20517 .get();
20518 } else if (getLangOpts().CPlusPlus) {
20519 // C++11 [dcl.enum]p5:
20520 // If the underlying type is not fixed, the type of each enumerator
20521 // is the type of its initializing value:
20522 // - If an initializer is specified for an enumerator, the
20523 // initializing value has the same type as the expression.
20524 EltTy = Val->getType();
20525 } else {
20526 // C99 6.7.2.2p2:
20527 // The expression that defines the value of an enumeration constant
20528 // shall be an integer constant expression that has a value
20529 // representable as an int.
20530
20531 // Complain if the value is not representable in an int.
20532 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20533 Diag(IdLoc, getLangOpts().C23
20534 ? diag::warn_c17_compat_enum_value_not_int
20535 : diag::ext_c23_enum_value_not_int)
20536 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20537 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20538 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20539 // Force the type of the expression to 'int'.
20540 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20541 }
20542 EltTy = Val->getType();
20543 }
20544 }
20545 }
20546 }
20547
20548 if (!Val) {
20549 if (Enum->isDependentType())
20550 EltTy = Context.DependentTy;
20551 else if (!LastEnumConst) {
20552 // C++0x [dcl.enum]p5:
20553 // If the underlying type is not fixed, the type of each enumerator
20554 // is the type of its initializing value:
20555 // - If no initializer is specified for the first enumerator, the
20556 // initializing value has an unspecified integral type.
20557 //
20558 // GCC uses 'int' for its unspecified integral type, as does
20559 // C99 6.7.2.2p3.
20560 if (Enum->isFixed()) {
20561 EltTy = Enum->getIntegerType();
20562 }
20563 else {
20564 EltTy = Context.IntTy;
20565 }
20566 } else {
20567 // Assign the last value + 1.
20568 EnumVal = LastEnumConst->getInitVal();
20569 ++EnumVal;
20570 EltTy = LastEnumConst->getType();
20571
20572 // Check for overflow on increment.
20573 if (EnumVal < LastEnumConst->getInitVal()) {
20574 // C++0x [dcl.enum]p5:
20575 // If the underlying type is not fixed, the type of each enumerator
20576 // is the type of its initializing value:
20577 //
20578 // - Otherwise the type of the initializing value is the same as
20579 // the type of the initializing value of the preceding enumerator
20580 // unless the incremented value is not representable in that type,
20581 // in which case the type is an unspecified integral type
20582 // sufficient to contain the incremented value. If no such type
20583 // exists, the program is ill-formed.
20585 if (T.isNull() || Enum->isFixed()) {
20586 // There is no integral type larger enough to represent this
20587 // value. Complain, then allow the value to wrap around.
20588 EnumVal = LastEnumConst->getInitVal();
20589 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20590 ++EnumVal;
20591 if (Enum->isFixed())
20592 // When the underlying type is fixed, this is ill-formed.
20593 Diag(IdLoc, diag::err_enumerator_wrapped)
20594 << toString(EnumVal, 10)
20595 << EltTy;
20596 else
20597 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20598 << toString(EnumVal, 10);
20599 } else {
20600 EltTy = T;
20601 }
20602
20603 // Retrieve the last enumerator's value, extent that type to the
20604 // type that is supposed to be large enough to represent the incremented
20605 // value, then increment.
20606 EnumVal = LastEnumConst->getInitVal();
20607 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20608 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20609 ++EnumVal;
20610
20611 // If we're not in C++, diagnose the overflow of enumerator values,
20612 // which in C99 means that the enumerator value is not representable in
20613 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20614 // are representable in some larger integral type and we allow it in
20615 // older language modes as an extension.
20616 // Exclude fixed enumerators since they are diagnosed with an error for
20617 // this case.
20618 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20619 Diag(IdLoc, getLangOpts().C23
20620 ? diag::warn_c17_compat_enum_value_not_int
20621 : diag::ext_c23_enum_value_not_int)
20622 << 1 << toString(EnumVal, 10) << 1;
20623 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20624 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20625 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20626 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20627 : diag::ext_c23_enum_value_not_int)
20628 << 1 << toString(EnumVal, 10) << 1;
20629 }
20630 }
20631 }
20632
20633 if (!EltTy->isDependentType()) {
20634 // Make the enumerator value match the signedness and size of the
20635 // enumerator's type.
20636 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20637 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20638 }
20639
20640 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20641 Val, EnumVal);
20642}
20643
20645 SourceLocation IILoc) {
20646 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20648 return SkipBodyInfo();
20649
20650 // We have an anonymous enum definition. Look up the first enumerator to
20651 // determine if we should merge the definition with an existing one and
20652 // skip the body.
20653 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20655 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20656 if (!PrevECD)
20657 return SkipBodyInfo();
20658
20659 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20660 NamedDecl *Hidden;
20661 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20663 Skip.Previous = Hidden;
20664 return Skip;
20665 }
20666
20667 return SkipBodyInfo();
20668}
20669
20670Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20671 SourceLocation IdLoc, IdentifierInfo *Id,
20672 const ParsedAttributesView &Attrs,
20673 SourceLocation EqualLoc, Expr *Val,
20674 SkipBodyInfo *SkipBody) {
20675 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20676 EnumConstantDecl *LastEnumConst =
20677 cast_or_null<EnumConstantDecl>(lastEnumConst);
20678
20679 // The scope passed in may not be a decl scope. Zip up the scope tree until
20680 // we find one that is.
20681 S = getNonFieldDeclScope(S);
20682
20683 // Verify that there isn't already something declared with this name in this
20684 // scope.
20685 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20687 LookupName(R, S);
20688 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20689
20690 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20691 // Maybe we will complain about the shadowed template parameter.
20692 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20693 // Just pretend that we didn't see the previous declaration.
20694 PrevDecl = nullptr;
20695 }
20696
20697 // C++ [class.mem]p15:
20698 // If T is the name of a class, then each of the following shall have a name
20699 // different from T:
20700 // - every enumerator of every member of class T that is an unscoped
20701 // enumerated type
20702 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20704 DeclarationNameInfo(Id, IdLoc)))
20705 return nullptr;
20706
20708 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20709 if (!New)
20710 return nullptr;
20711
20712 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20713 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20714 // Check for other kinds of shadowing not already handled.
20715 CheckShadow(New, PrevDecl, R);
20716 }
20717
20718 // When in C++, we may get a TagDecl with the same name; in this case the
20719 // enum constant will 'hide' the tag.
20720 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20721 "Received TagDecl when not in C++!");
20722 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20723 if (isa<EnumConstantDecl>(PrevDecl))
20724 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20725 else
20726 Diag(IdLoc, diag::err_redefinition) << Id;
20727 notePreviousDefinition(PrevDecl, IdLoc);
20728 return nullptr;
20729 }
20730 }
20731
20732 // Process attributes.
20733 ProcessDeclAttributeList(S, New, Attrs);
20736
20737 // Register this decl in the current scope stack.
20738 New->setAccess(TheEnumDecl->getAccess());
20740
20742
20743 return New;
20744}
20745
20746// Returns true when the enum initial expression does not trigger the
20747// duplicate enum warning. A few common cases are exempted as follows:
20748// Element2 = Element1
20749// Element2 = Element1 + 1
20750// Element2 = Element1 - 1
20751// Where Element2 and Element1 are from the same enum.
20753 Expr *InitExpr = ECD->getInitExpr();
20754 if (!InitExpr)
20755 return true;
20756 InitExpr = InitExpr->IgnoreImpCasts();
20757
20758 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20759 if (!BO->isAdditiveOp())
20760 return true;
20761 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20762 if (!IL)
20763 return true;
20764 if (IL->getValue() != 1)
20765 return true;
20766
20767 InitExpr = BO->getLHS();
20768 }
20769
20770 // This checks if the elements are from the same enum.
20771 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20772 if (!DRE)
20773 return true;
20774
20775 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20776 if (!EnumConstant)
20777 return true;
20778
20780 Enum)
20781 return true;
20782
20783 return false;
20784}
20785
20786// Emits a warning when an element is implicitly set a value that
20787// a previous element has already been set to.
20789 EnumDecl *Enum, QualType EnumType) {
20790 // Avoid anonymous enums
20791 if (!Enum->getIdentifier())
20792 return;
20793
20794 // Only check for small enums.
20795 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20796 return;
20797
20798 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20799 return;
20800
20801 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20802 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20803
20804 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20805
20806 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20807 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20808
20809 // Use int64_t as a key to avoid needing special handling for map keys.
20810 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20811 llvm::APSInt Val = D->getInitVal();
20812 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20813 };
20814
20815 DuplicatesVector DupVector;
20816 ValueToVectorMap EnumMap;
20817
20818 // Populate the EnumMap with all values represented by enum constants without
20819 // an initializer.
20820 for (auto *Element : Elements) {
20821 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20822
20823 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20824 // this constant. Skip this enum since it may be ill-formed.
20825 if (!ECD) {
20826 return;
20827 }
20828
20829 // Constants with initializers are handled in the next loop.
20830 if (ECD->getInitExpr())
20831 continue;
20832
20833 // Duplicate values are handled in the next loop.
20834 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20835 }
20836
20837 if (EnumMap.size() == 0)
20838 return;
20839
20840 // Create vectors for any values that has duplicates.
20841 for (auto *Element : Elements) {
20842 // The last loop returned if any constant was null.
20844 if (!ValidDuplicateEnum(ECD, Enum))
20845 continue;
20846
20847 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20848 if (Iter == EnumMap.end())
20849 continue;
20850
20851 DeclOrVector& Entry = Iter->second;
20852 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
20853 // Ensure constants are different.
20854 if (D == ECD)
20855 continue;
20856
20857 // Create new vector and push values onto it.
20858 auto Vec = std::make_unique<ECDVector>();
20859 Vec->push_back(D);
20860 Vec->push_back(ECD);
20861
20862 // Update entry to point to the duplicates vector.
20863 Entry = Vec.get();
20864
20865 // Store the vector somewhere we can consult later for quick emission of
20866 // diagnostics.
20867 DupVector.emplace_back(std::move(Vec));
20868 continue;
20869 }
20870
20871 ECDVector *Vec = cast<ECDVector *>(Entry);
20872 // Make sure constants are not added more than once.
20873 if (*Vec->begin() == ECD)
20874 continue;
20875
20876 Vec->push_back(ECD);
20877 }
20878
20879 // Emit diagnostics.
20880 for (const auto &Vec : DupVector) {
20881 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20882
20883 // Emit warning for one enum constant.
20884 auto *FirstECD = Vec->front();
20885 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20886 << FirstECD << toString(FirstECD->getInitVal(), 10)
20887 << FirstECD->getSourceRange();
20888
20889 // Emit one note for each of the remaining enum constants with
20890 // the same value.
20891 for (auto *ECD : llvm::drop_begin(*Vec))
20892 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20893 << ECD << toString(ECD->getInitVal(), 10)
20894 << ECD->getSourceRange();
20895 }
20896}
20897
20898bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20899 bool AllowMask) const {
20900 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20901 assert(ED->isCompleteDefinition() && "expected enum definition");
20902
20903 auto R = FlagBitsCache.try_emplace(ED);
20904 llvm::APInt &FlagBits = R.first->second;
20905
20906 if (R.second) {
20907 for (auto *E : ED->enumerators()) {
20908 const auto &EVal = E->getInitVal();
20909 // Only single-bit enumerators introduce new flag values.
20910 if (EVal.isPowerOf2())
20911 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20912 }
20913 }
20914
20915 // A value is in a flag enum if either its bits are a subset of the enum's
20916 // flag bits (the first condition) or we are allowing masks and the same is
20917 // true of its complement (the second condition). When masks are allowed, we
20918 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20919 //
20920 // While it's true that any value could be used as a mask, the assumption is
20921 // that a mask will have all of the insignificant bits set. Anything else is
20922 // likely a logic error.
20923 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20924 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20925}
20926
20927// Emits a warning when a suspicious comparison operator is used along side
20928// binary operators in enum initializers.
20930 const EnumDecl *Enum) {
20931 bool HasBitwiseOp = false;
20932 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20933
20934 // Iterate over all the enum values, gather suspisious comparison ops and
20935 // whether any enum initialisers contain a binary operator.
20936 for (const auto *ECD : Enum->enumerators()) {
20937 const Expr *InitExpr = ECD->getInitExpr();
20938 if (!InitExpr)
20939 continue;
20940
20941 const Expr *E = InitExpr->IgnoreParenImpCasts();
20942
20943 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
20944 BinaryOperatorKind Op = BinOp->getOpcode();
20945
20946 // Check for bitwise ops (<<, >>, &, |)
20947 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
20948 HasBitwiseOp = true;
20949 } else if (Op == BO_LT || Op == BO_GT) {
20950 // Check for the typo pattern (Comparison < or >)
20951 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
20952 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(LHS)) {
20953 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
20954 if (IntLiteral->getValue() == 1)
20955 SuspiciousCompares.push_back(BinOp);
20956 }
20957 }
20958 }
20959 }
20960
20961 // If we found a bitwise op and some sus compares, iterate over the compares
20962 // and warn.
20963 if (HasBitwiseOp) {
20964 for (const auto *BinOp : SuspiciousCompares) {
20965 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
20968 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
20969
20970 Sema.Diag(OperatorLoc, diag::warn_comparison_in_enum_initializer)
20971 << BinOp->getOpcodeStr() << SuggestedOp;
20972
20973 Sema.Diag(OperatorLoc, diag::note_enum_compare_typo_suggest)
20974 << SuggestedOp
20975 << FixItHint::CreateReplacement(OperatorLoc, SuggestedOp);
20976 }
20977 }
20978}
20979
20981 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20982 const ParsedAttributesView &Attrs) {
20983 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20984 CanQualType EnumType = Context.getCanonicalTagType(Enum);
20985
20986 ProcessDeclAttributeList(S, Enum, Attrs);
20988
20989 if (Enum->isDependentType()) {
20990 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20991 EnumConstantDecl *ECD =
20992 cast_or_null<EnumConstantDecl>(Elements[i]);
20993 if (!ECD) continue;
20994
20995 ECD->setType(EnumType);
20996 }
20997
20998 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20999 return;
21000 }
21001
21002 // Verify that all the values are okay, compute the size of the values, and
21003 // reverse the list.
21004 unsigned NumNegativeBits = 0;
21005 unsigned NumPositiveBits = 0;
21006 bool MembersRepresentableByInt =
21007 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
21008
21009 // Figure out the type that should be used for this enum.
21010 QualType BestType;
21011 unsigned BestWidth;
21012
21013 // C++0x N3000 [conv.prom]p3:
21014 // An rvalue of an unscoped enumeration type whose underlying
21015 // type is not fixed can be converted to an rvalue of the first
21016 // of the following types that can represent all the values of
21017 // the enumeration: int, unsigned int, long int, unsigned long
21018 // int, long long int, or unsigned long long int.
21019 // C99 6.4.4.3p2:
21020 // An identifier declared as an enumeration constant has type int.
21021 // The C99 rule is modified by C23.
21022 QualType BestPromotionType;
21023
21024 bool Packed = Enum->hasAttr<PackedAttr>();
21025 // -fshort-enums is the equivalent to specifying the packed attribute on all
21026 // enum definitions.
21027 if (LangOpts.ShortEnums)
21028 Packed = true;
21029
21030 // If the enum already has a type because it is fixed or dictated by the
21031 // target, promote that type instead of analyzing the enumerators.
21032 if (Enum->isComplete()) {
21033 BestType = Enum->getIntegerType();
21034 if (Context.isPromotableIntegerType(BestType))
21035 BestPromotionType = Context.getPromotedIntegerType(BestType);
21036 else
21037 BestPromotionType = BestType;
21038
21039 BestWidth = Context.getIntWidth(BestType);
21040 } else {
21041 bool EnumTooLarge = Context.computeBestEnumTypes(
21042 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21043 BestWidth = Context.getIntWidth(BestType);
21044 if (EnumTooLarge)
21045 Diag(Enum->getLocation(), diag::ext_enum_too_large);
21046 }
21047
21048 // Loop over all of the enumerator constants, changing their types to match
21049 // the type of the enum if needed.
21050 for (auto *D : Elements) {
21051 auto *ECD = cast_or_null<EnumConstantDecl>(D);
21052 if (!ECD) continue; // Already issued a diagnostic.
21053
21054 // C99 says the enumerators have int type, but we allow, as an
21055 // extension, the enumerators to be larger than int size. If each
21056 // enumerator value fits in an int, type it as an int, otherwise type it the
21057 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21058 // that X has type 'int', not 'unsigned'.
21059
21060 // Determine whether the value fits into an int.
21061 llvm::APSInt InitVal = ECD->getInitVal();
21062
21063 // If it fits into an integer type, force it. Otherwise force it to match
21064 // the enum decl type.
21065 QualType NewTy;
21066 unsigned NewWidth;
21067 bool NewSign;
21068 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21069 MembersRepresentableByInt) {
21070 // C23 6.7.3.3.3p15:
21071 // The enumeration member type for an enumerated type without fixed
21072 // underlying type upon completion is:
21073 // - int if all the values of the enumeration are representable as an
21074 // int; or,
21075 // - the enumerated type
21076 NewTy = Context.IntTy;
21077 NewWidth = Context.getTargetInfo().getIntWidth();
21078 NewSign = true;
21079 } else if (ECD->getType() == BestType) {
21080 // Already the right type!
21081 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21082 // C++ [dcl.enum]p4: Following the closing brace of an
21083 // enum-specifier, each enumerator has the type of its
21084 // enumeration.
21085 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21086 // with fixed underlying type is the enumerated type.
21087 ECD->setType(EnumType);
21088 continue;
21089 } else {
21090 NewTy = BestType;
21091 NewWidth = BestWidth;
21092 NewSign = BestType->isSignedIntegerOrEnumerationType();
21093 }
21094
21095 // Adjust the APSInt value.
21096 InitVal = InitVal.extOrTrunc(NewWidth);
21097 InitVal.setIsSigned(NewSign);
21098 ECD->setInitVal(Context, InitVal);
21099
21100 // Adjust the Expr initializer and type.
21101 if (ECD->getInitExpr() &&
21102 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
21103 ECD->setInitExpr(ImplicitCastExpr::Create(
21104 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
21105 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
21106 if (getLangOpts().CPlusPlus ||
21107 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21108 // C++ [dcl.enum]p4: Following the closing brace of an
21109 // enum-specifier, each enumerator has the type of its
21110 // enumeration.
21111 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21112 // with fixed underlying type is the enumerated type.
21113 ECD->setType(EnumType);
21114 else
21115 ECD->setType(NewTy);
21116 }
21117
21118 Enum->completeDefinition(BestType, BestPromotionType,
21119 NumPositiveBits, NumNegativeBits);
21120
21121 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
21123
21124 if (Enum->isClosedFlag()) {
21125 for (Decl *D : Elements) {
21126 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
21127 if (!ECD) continue; // Already issued a diagnostic.
21128
21129 llvm::APSInt InitVal = ECD->getInitVal();
21130 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21131 !IsValueInFlagEnum(Enum, InitVal, true))
21132 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
21133 << ECD << Enum;
21134 }
21135 }
21136
21137 // Now that the enum type is defined, ensure it's not been underaligned.
21138 if (Enum->hasAttrs())
21140}
21141
21143 SourceLocation EndLoc) {
21144
21146 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
21147 CurContext->addDecl(New);
21148 return New;
21149}
21150
21152 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
21153 CurContext->addDecl(New);
21154 PushDeclContext(S, New);
21156 PushCompoundScope(false);
21157 return New;
21158}
21159
21161 if (Statement)
21162 D->setStmt(Statement);
21166}
21167
21169 IdentifierInfo* AliasName,
21170 SourceLocation PragmaLoc,
21171 SourceLocation NameLoc,
21172 SourceLocation AliasNameLoc) {
21173 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
21175 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21177 AsmLabelAttr *Attr =
21178 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
21179
21180 // If a declaration that:
21181 // 1) declares a function or a variable
21182 // 2) has external linkage
21183 // already exists, add a label attribute to it.
21184 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21185 if (isDeclExternC(PrevDecl))
21186 PrevDecl->addAttr(Attr);
21187 else
21188 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
21189 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
21190 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21191 } else
21192 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
21193}
21194
21196 SourceLocation PragmaLoc,
21197 SourceLocation NameLoc) {
21198 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
21199
21200 if (PrevDecl) {
21201 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
21202 } else {
21203 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
21204 }
21205}
21206
21208 IdentifierInfo* AliasName,
21209 SourceLocation PragmaLoc,
21210 SourceLocation NameLoc,
21211 SourceLocation AliasNameLoc) {
21212 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
21214 WeakInfo W = WeakInfo(Name, NameLoc);
21215
21216 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21217 if (!PrevDecl->hasAttr<AliasAttr>())
21218 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
21220 } else {
21221 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
21222 }
21223}
21224
21226 bool Final) {
21227 assert(FD && "Expected non-null FunctionDecl");
21228
21229 // Templates are emitted when they're instantiated.
21230 if (FD->isDependentContext())
21232
21233 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21234 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21235 FD->hasAttr<SYCLExternalAttr>()))
21237
21238 // Check whether this function is an externally visible definition.
21239 auto IsEmittedForExternalSymbol = [this, FD]() {
21240 // We have to check the GVA linkage of the function's *definition* -- if we
21241 // only have a declaration, we don't know whether or not the function will
21242 // be emitted, because (say) the definition could include "inline".
21243 const FunctionDecl *Def = FD->getDefinition();
21244
21245 // We can't compute linkage when we skip function bodies.
21246 return Def && !Def->hasSkippedBody() &&
21248 getASTContext().GetGVALinkageForFunction(Def));
21249 };
21250
21251 if (LangOpts.OpenMPIsTargetDevice) {
21252 // In OpenMP device mode we will not emit host only functions, or functions
21253 // we don't need due to their linkage.
21254 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21255 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21256 // DevTy may be changed later by
21257 // #pragma omp declare target to(*) device_type(*).
21258 // Therefore DevTy having no value does not imply host. The emission status
21259 // will be checked again at the end of compilation unit with Final = true.
21260 if (DevTy)
21261 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21263 // If we have an explicit value for the device type, or we are in a target
21264 // declare context, we need to emit all extern and used symbols.
21265 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21266 if (IsEmittedForExternalSymbol())
21268 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21269 // we'll omit it.
21270 if (Final)
21272 } else if (LangOpts.OpenMP > 45) {
21273 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21274 // function. In 5.0, no_host was introduced which might cause a function to
21275 // be omitted.
21276 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21277 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21278 if (DevTy)
21279 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21281 }
21282
21283 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21285
21286 if (LangOpts.CUDA) {
21287 // When compiling for device, host functions are never emitted. Similarly,
21288 // when compiling for host, device and global functions are never emitted.
21289 // (Technically, we do emit a host-side stub for global functions, but this
21290 // doesn't count for our purposes here.)
21292 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21294 if (!LangOpts.CUDAIsDevice &&
21297
21298 if (IsEmittedForExternalSymbol())
21300 }
21301
21302 // Otherwise, the function is known-emitted if it's in our set of
21303 // known-emitted functions.
21305}
21306
21308 // Host-side references to a __global__ function refer to the stub, so the
21309 // function itself is never emitted and therefore should not be marked.
21310 // If we have host fn calls kernel fn calls host+device, the HD function
21311 // does not get instantiated on the host. We model this by omitting at the
21312 // call to the kernel from the callgraph. This ensures that, when compiling
21313 // for host, only HD functions actually called from the host get marked as
21314 // known-emitted.
21315 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21317}
21318
21320 bool &Visible) {
21321 Visible = hasVisibleDefinition(D, Suggested);
21322 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21323 // for declaratins which is attached to named modules.
21324 // We only did this if the current module is named module as we have better
21325 // diagnostics for declarations in global module and named modules.
21326 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21327 D->isInNamedModule())
21328 return false;
21329 // The redefinition of D in the **current** TU is allowed if D is invisible or
21330 // D is defined in the global module of other module units.
21331 return D->isInAnotherModuleUnit() || !Visible;
21332}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
static bool isDeclExternC(const T &D)
Definition Decl.cpp:2208
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Defines helper utilities for supporting the HLSL runtime environment.
static const Decl * getCanonicalDecl(const Decl *D)
Result
Implement __builtin_bit_cast and related operations.
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition MachO.h:27
llvm::MachO::Record Record
Definition MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition Mangle.cpp:80
#define SM(sm)
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:183
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition SemaDecl.cpp:181
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool isMainVar(DeclarationName Name, VarDecl *VD)
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition SemaDecl.cpp:236
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND)
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition SemaDecl.cpp:848
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Merge alignment attributes from Old to New, taking into account the special semantics of C11's _Align...
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
static NestedNameSpecifier synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition SemaDecl.cpp:612
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND)
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD)
Given that we are within the definition of the given function, will that definition behave like C99's...
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From, Sema &S)
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
static Scope * getTagInjectionScope(Scope *S, const LangOptions &LangOpts)
Find the Scope in which a tag is implicitly declared if we see an elaborated type specifier in the sp...
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, SourceLocation NameLoc)
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, SourceLocation NameLoc, bool IsUnion, StorageClass SC)
We are trying to inject an anonymous member into the given scope; check if there's an existing declar...
static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous)
Check for conflict between this global or extern "C" declaration and previous global or extern "C" de...
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, RecordDecl *AnonRecord, AccessSpecifier AS, StorageClass SC, SmallVectorImpl< NamedDecl * > &Chaining)
InjectAnonymousStructOrUnionMembers - Inject the members of the anonymous struct or union AnonRecord ...
OpenCLParamType
@ InvalidAddrSpacePtrKernelParam
@ ValidKernelParam
@ InvalidKernelParam
@ RecordKernelParam
@ PtrKernelParam
@ PtrPtrKernelParam
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const ValueDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, CXXMethodDecl *M1, CXXMethodDecl *M2, CXXSpecialMemberKind CSM)
[class.mem.special]p5 Two special member functions are of the same kind if:
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition SemaDecl.cpp:631
static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record)
[class.dtor]p4: At the end of the definition of a class, overload resolution is performed among the p...
static bool shouldConsiderLinkage(const VarDecl *VD)
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
static void checkInheritableAttr(Sema &S, NamedDecl &ND)
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, ArrayRef< CXXMethodDecl * > Methods, CXXSpecialMemberKind CSM)
[class.mem.special]p6: An eligible special member function is a special member function for which:
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition SemaDecl.cpp:863
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
@ SDK_StructuredBinding
@ SDK_Field
@ SDK_Global
@ SDK_Local
@ SDK_Typedef
@ SDK_StaticMember
@ SDK_Using
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
static void CheckForComparisonInEnumInitializer(SemaBase &Sema, const EnumDecl *Enum)
static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
static void checkWeakAttr(Sema &S, NamedDecl &ND)
static void checkModularFormatAttr(Sema &S, NamedDecl &ND)
static void checkSelectAnyAttr(Sema &S, NamedDecl &ND)
static bool isImplicitInstantiation(NamedDecl *D)
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
static bool looksMutable(QualType T, const ASTContext &Ctx)
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From, F &&propagator)
static const NamedDecl * getDefinition(const Decl *D)
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static bool hasDeducedAuto(DeclaratorDecl *DD)
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
static QualType getCoreType(QualType Ty)
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, AvailabilityMergeKind AMK)
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a new function declaration being added to an existing multiversioned declaratio...
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
static void checkAliasAttr(Sema &S, NamedDecl &ND)
static void filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don't have linkage, but they still denote the same entity if their types are the...
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
static void checkWeakRefAttr(Sema &S, NamedDecl &ND)
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
static bool isAttributeTargetADefinition(Decl *D)
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualified na...
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to Wasm.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
@ GE_None
No error.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_type
Missing a type.
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
SourceManager & getSourceManager()
Definition ASTContext.h:863
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:802
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const VariableArrayType * getAsVariableArrayType(QualType T) const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:921
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
@ GE_Missing_type
Missing a type.
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3553
Wrapper for source info for arrays.
Definition TypeLoc.h:1777
SourceLocation getLBracketLoc() const
Definition TypeLoc.h:1779
Expr * getSizeExpr() const
Definition TypeLoc.h:1799
TypeLoc getElementLoc() const
Definition TypeLoc.h:1807
SourceLocation getRBracketLoc() const
Definition TypeLoc.h:1787
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3798
Attr - This represents one attribute.
Definition Attr.h:46
attr::Kind getKind() const
Definition Attr.h:92
bool isInherited() const
Definition Attr.h:101
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition Attr.h:106
SourceLocation getLocation() const
Definition Attr.h:99
bool isStandardAttributeSyntax() const
The attribute is spelled [[]] in either C or C++ mode, including standard attributes spelled with a k...
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition ParsedAttr.h:622
AttributeFactory & getFactory() const
Definition ParsedAttr.h:718
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4513
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4501
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
Expr * getLHS() const
Definition Expr.h:4094
StringRef getOpcodeStr() const
Definition Expr.h:4110
Expr * getRHS() const
Definition Expr.h:4096
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4185
A binding in a decomposition declaration.
Definition DeclCXX.h:4203
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4694
bool doesNotEscape() const
Definition Decl.h:4845
This class is used for builtin types like 'int'.
Definition TypeBase.h:3228
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:236
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:383
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclCXX.h:195
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition DeclCXX.cpp:3056
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:3016
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2965
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:3271
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:2381
Represents a C++ destructor within a class.
Definition DeclCXX.h:2895
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:3146
A mapping from each virtual member function to its set of final overriders.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2717
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition DeclCXX.cpp:2803
bool isVirtual() const
Definition DeclCXX.h:2200
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2502
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2868
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2749
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2319
bool isConst() const
Definition DeclCXX.h:2197
bool isStatic() const
Definition DeclCXX.cpp:2415
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2728
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2254
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
base_class_iterator bases_end()
Definition DeclCXX.h:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1377
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1573
base_class_range bases()
Definition DeclCXX.h:608
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
base_class_iterator bases_begin()
Definition DeclCXX.h:615
capture_const_range captures() const
Definition DeclCXX.h:1102
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1153
bool hasDefinition() const
Definition DeclCXX.h:561
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2052
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2152
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1064
UnresolvedSetIterator conversion_iterator
Definition DeclCXX.h:1124
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2056
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:209
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
bool isCallToStdMove() const
Definition Expr.cpp:3651
Expr * getCallee()
Definition Expr.h:3096
arg_range arguments()
Definition Expr.h:3201
CastKind getCastKind() const
Definition Expr.h:3726
Expr * getSubExpr()
Definition Expr.h:3732
static CharSourceRange getCharRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
Declaration of a class template.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:251
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:291
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3880
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclListNode::iterator iterator
Definition DeclBase.h:1405
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2251
bool isFileContext() const
Definition DeclBase.h:2193
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2590
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool isClosure() const
Definition DeclBase.h:2155
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2138
bool isNamespace() const
Definition DeclBase.h:2211
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
bool isTranslationUnit() const
Definition DeclBase.h:2198
bool isRecord() const
Definition DeclBase.h:2202
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2386
bool isFunctionOrMethod() const
Definition DeclBase.h:2174
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2115
DeclContext * getNonTransparentContext()
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition DeclGroup.h:64
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
ValueDecl * getDecl()
Definition Expr.h:1344
SourceLocation getBeginLoc() const
Definition Expr.h:1355
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:655
bool isModulePrivateSpecified() const
Definition DeclSpec.h:836
static const TST TST_typeof_unqualType
Definition DeclSpec.h:282
bool hasAutoTypeSpec() const
Definition DeclSpec.h:580
static const TST TST_typename
Definition DeclSpec.h:279
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition DeclSpec.cpp:631
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:237
void ClearStorageClassSpecs()
Definition DeclSpec.h:500
bool isNoreturnSpecified() const
Definition DeclSpec.h:668
TST getTypeSpecType() const
Definition DeclSpec.h:522
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:495
SCS getStorageClassSpec() const
Definition DeclSpec.h:486
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:846
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:560
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:559
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:716
static const TST TST_interface
Definition DeclSpec.h:277
static const TST TST_typeofExpr
Definition DeclSpec.h:281
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:602
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:715
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:669
bool isExternInLinkageSpec() const
Definition DeclSpec.h:490
static const TST TST_union
Definition DeclSpec.h:275
SCS
storage-class-specifier
Definition DeclSpec.h:224
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:661
static const TST TST_int
Definition DeclSpec.h:258
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:837
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
ParsedType getRepAsType() const
Definition DeclSpec.h:532
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:795
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:487
ParsedAttributes & getAttributes()
Definition DeclSpec.h:880
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:631
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:603
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:662
Expr * getRepAsExpr() const
Definition DeclSpec.h:540
static const TST TST_enum
Definition DeclSpec.h:274
static const TST TST_decltype
Definition DeclSpec.h:284
static bool isDeclRep(TST T)
Definition DeclSpec.h:453
bool isInlineSpecified() const
Definition DeclSpec.h:644
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:604
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:283
static const TST TST_class
Definition DeclSpec.h:278
TypeSpecifierType TST
Definition DeclSpec.h:250
static const TST TST_void
Definition DeclSpec.h:252
void ClearConstexprSpec()
Definition DeclSpec.h:848
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:532
static const TST TST_atomic
Definition DeclSpec.h:294
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:496
Decl * getRepAsDecl() const
Definition DeclSpec.h:536
static const TST TST_unspecified
Definition DeclSpec.h:251
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:606
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:656
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:843
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:567
void UpdateExprRep(Expr *Rep)
Definition DeclSpec.h:799
static const TSCS TSCS_thread_local
Definition DeclSpec.h:240
static const TST TST_error
Definition DeclSpec.h:301
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclSpec.h:651
bool isTypeSpecOwned() const
Definition DeclSpec.h:526
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:647
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:607
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:605
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:828
bool hasExplicitSpecifier() const
Definition DeclSpec.h:658
bool hasConstexprSpecifier() const
Definition DeclSpec.h:844
static const TST TST_typeofType
Definition DeclSpec.h:280
static const TST TST_auto
Definition DeclSpec.h:291
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:839
static const TST TST_struct
Definition DeclSpec.h:276
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1074
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1089
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:341
bool isInStdNamespace() const
Definition DeclBase.cpp:450
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1239
bool isFromGlobalModule() const
Whether this declaration comes from global module.
T * getAttr() const
Definition DeclBase.h:581
bool hasAttrs() const
Definition DeclBase.h:526
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
void setAttrs(const AttrVec &Attrs)
Definition DeclBase.h:528
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition DeclBase.h:779
bool isInNamedModule() const
Whether this declaration comes from a named module.
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition DeclBase.h:1164
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void setTopLevelDeclInObjCContainer(bool V=true)
Definition DeclBase.h:646
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:906
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1232
@ FOK_None
Not a friend object.
Definition DeclBase.h:1230
@ FOK_Declared
A friend of a previously-declared entity.
Definition DeclBase.h:1231
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:601
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:850
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
void dropAttrs()
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition DeclBase.h:210
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1193
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2806
bool isInvalidDecl() const
Definition DeclBase.h:596
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1182
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:510
SourceLocation getLocation() const
Definition DeclBase.h:447
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
void setImplicit(bool I=true)
Definition DeclBase.h:602
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:576
DeclContext * getDeclContext()
Definition DeclBase.h:456
attr_range attrs() const
Definition DeclBase.h:543
AccessSpecifier getAccess() const
Definition DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
void dropAttr()
Definition DeclBase.h:564
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:382
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition Decl.cpp:1637
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:931
bool hasAttr() const
Definition DeclBase.h:585
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1248
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:386
Kind getKind() const
Definition DeclBase.h:450
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isAnyOperatorNewOrDelete() const
bool isAnyOperatorDelete() const
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function),...
NameKind getNameKind() const
Determine what kind of name this is.
bool isEmpty() const
Evaluates true when this declaration name is empty.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:822
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition Decl.cpp:2065
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2069
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2003
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2015
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:837
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:2049
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h: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:4267
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3730
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:2513
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2601
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2590
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:960
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3445
llvm::APSInt getInitVal() const
Definition Decl.h:3465
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5712
const Expr * getInitExpr() const
Definition Decl.h:3463
Represents an enum.
Definition Decl.h:4033
enumerator_range enumerators() const
Definition Decl.h:4179
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4251
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:4215
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:4218
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4265
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5070
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:5109
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4260
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:5084
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:4201
void setEnumKeyRange(SourceRange Range)
Definition Decl.h:4113
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4206
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1944
This represents one expression.
Definition Expr.h:112
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
bool isConstantInitializer(ASTContext &Ctx, bool ForRef=false, const Expr **Culprit=nullptr) const
Returns true if this expression can be emitted to IR as a constant, and thus can be used as a constan...
Definition Expr.cpp:3356
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3079
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
bool isFPConstrained() const
Represents a member of a struct/union/class.
Definition Decl.h:3182
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3285
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4711
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3418
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:4696
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4757
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5845
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:104
Represents a function declaration or definition.
Definition Decl.h:2018
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2707
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2207
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2494
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4181
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3709
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4174
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4169
void setIsPureVirtual(bool P=true)
Definition Decl.cpp:3274
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2332
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2719
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2698
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4000
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3738
param_iterator param_end()
Definition Decl.h:2805
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2939
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2713
QualType getReturnType() const
Definition Decl.h:2863
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2792
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3682
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2407
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2395
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3590
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4289
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2466
void setWillHaveBody(bool V=true)
Definition Decl.h:2704
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition Decl.h:2612
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2461
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4299
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3723
param_iterator param_begin()
Definition Decl.h:2804
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2841
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2344
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2558
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3156
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3351
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4233
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2906
bool isStatic() const
Definition Decl.h:2947
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4522
void setTrivial(bool IT)
Definition Decl.h:2396
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4120
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2488
bool isDeletedAsWritten() const
Definition Decl.h:2562
redecl_iterator redecls_end() const
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2371
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3594
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2375
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2446
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2367
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2697
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2300
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3344
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:2934
bool param_empty() const
Definition Decl.h:2803
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3199
void setRangeEnd(SourceLocation E)
Definition Decl.h:2236
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3678
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2403
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2439
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4545
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2951
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4114
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2491
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4393
void setDefaulted(bool D=true)
Definition Decl.h:2404
bool isConsteval() const
Definition Decl.h:2500
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:2880
void setBody(Stmt *B)
Definition Decl.cpp:3267
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3608
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3145
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2477
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4141
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3802
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2229
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3175
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2453
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3222
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition Decl.h:2917
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3664
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2703
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5307
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5339
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5892
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5171
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
unsigned getNumParams() const
Definition TypeBase.h:5649
QualType getParamType(unsigned i) const
Definition TypeBase.h:5651
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5868
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5684
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5775
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
Declaration of a template function.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
Wrapper for source info for functions.
Definition TypeLoc.h:1644
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4678
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4790
CallingConv getCC() const
Definition TypeBase.h:4737
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4756
unsigned getRegParm() const
Definition TypeBase.h:4730
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4726
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4749
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4770
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4784
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
ExtInfo getExtInfo() const
Definition TypeBase.h:4923
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3704
unsigned getRegParmType() const
Definition TypeBase.h:4910
CallingConv getCallConv() const
Definition TypeBase.h:4922
QualType getReturnType() const
Definition TypeBase.h:4907
bool getCmseNSCallAttr() const
Definition TypeBase.h:4921
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2079
Represents a C array with an unspecified size.
Definition TypeBase.h:3973
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3489
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5739
void setInherited(bool I)
Definition Attr.h:163
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2604
child_range children()
Definition Expr.h:5501
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
step_iterator step_begin() const
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
Describes an entity that is being initialized.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:981
Represents the declaration of a label.
Definition Decl.h:524
bool isResolvedMSAsmLabel() const
Definition Decl.h:559
LabelStmt * getStmt() const
Definition Decl.h:548
bool isMSAsmLabel() const
Definition Decl.h:558
llvm::iterator_range< capture_init_iterator > capture_inits()
Retrieve the initialization expressions for this lambda's captures.
Definition ExprCXX.h:2087
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
FPExceptionModeKind getDefaultExceptionMode() const
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
bool isCompatibleWithMSVC() const
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition Lexer.cpp:1431
Visibility getVisibility() const
Definition Visibility.h:89
Linkage getLinkage() const
Definition Visibility.h:88
Represents a linkage specification.
Definition DeclCXX.h:3033
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3301
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
bool isAmbiguous() const
Definition Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
Expr * getBase() const
Definition Expr.h:3447
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
Describes a module or submodule.
Definition Module.h:340
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:346
Module * Parent
The parent of this module.
Definition Module.h:389
bool isPrivateModule() const
Definition Module.h:448
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:866
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:882
bool isModulePartition() const
Is this a module partition.
Definition Module.h:871
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:423
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:940
@ ClassId_NSObject
Definition NSAPI.h:30
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isLinkageValid() const
True if the computed linkage is valid.
Definition Decl.cpp:1085
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:444
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition Decl.h:479
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:429
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
bool declarationReplaces(const NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition Decl.cpp:1871
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:714
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1943
bool isExternallyVisible() const
Definition Decl.h:433
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition Decl.cpp:1132
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:397
Represent a C++ namespace.
Definition Decl.h:592
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition Decl.h:643
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
static constexpr NestedNameSpecifier getGlobal()
bool containsErrors() const
Whether this nested name specifier contains an error.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2329
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition DeclObjC.h:2775
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:948
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition DeclObjC.cpp:78
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2597
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
known_extensions_range known_extensions() const
Definition DeclObjC.h:1762
Wrapper for source info for ObjC interfaces.
Definition TypeLoc.h:1303
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1313
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
param_const_iterator param_end() const
Definition DeclObjC.h:358
param_const_iterator param_begin() const
Definition DeclObjC.h:354
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:349
bool isOptional() const
Definition DeclObjC.h:505
ParmVarDecl *const * param_iterator
Definition DeclObjC.h:350
ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for protocol qualifiers are stored aft...
Definition TypeLoc.h:895
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(DeclGroupRef P)
Definition Ownership.h:61
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
MapType::iterator iterator
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1415
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1428
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1411
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3366
Represents a parameter to a function.
Definition Decl.h:1808
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1868
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1872
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1841
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1900
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2933
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2956
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
static const ParsedAttributesView & none()
Definition ParsedAttr.h:817
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:897
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:937
AttributePool & getPool() const
Definition ParsedAttr.h:944
PipeType - OpenCL20.
Definition TypeBase.h:8265
Pointer-authentication qualifiers.
Definition TypeBase.h:152
bool isAddressDiscriminated() const
Definition TypeBase.h:265
TypeLoc getPointeeLoc() const
Definition TypeLoc.h:1494
Wrapper for source info for pointers.
Definition TypeLoc.h:1513
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1519
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8525
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition Type.h:85
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1468
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:3023
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:111
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1229
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1311
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition Type.cpp:3089
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition Type.h:79
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:3073
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition TypeBase.h:1448
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8568
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1560
bool isCanonical() const
Definition TypeBase.h:8504
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1324
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1457
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2788
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition TypeBase.h:1508
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition TypeBase.h:1513
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition Type.h:73
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8387
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8394
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4792
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasConst() const
Definition TypeBase.h:457
bool hasVolatile() const
Definition TypeBase.h:467
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
bool empty() const
Definition TypeBase.h:647
Represents a struct/union/class.
Definition Decl.h:4347
field_range fields() const
Definition Decl.h:4550
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5228
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4547
field_iterator field_begin() const
Definition Decl.cpp:5271
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7506
void setMemberSpecialization()
Note that this member template is a specialization.
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5352
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3637
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3170
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:3213
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void setEntity(DeclContext *E)
Definition Scope.h:391
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:410
unsigned getDepth() const
Returns the depth of this scope. The translation-unit has scope depth 0.
Definition Scope.h:321
unsigned getNextFunctionPrototypeIndex()
Return the number of parameters declared in this function prototype, increasing it by one for the nex...
Definition Scope.h:331
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:344
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:610
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:380
void RemoveDecl(Decl *D)
Definition Scope.h:352
void setLookupEntity(DeclContext *E)
Definition Scope.h:396
unsigned getMSLastManglingNumber() const
Definition Scope.h:368
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:383
unsigned getMSCurManglingNumber() const
Definition Scope.h:374
bool decl_empty() const
Definition Scope.h:342
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:463
unsigned getFunctionPrototypeDepth() const
Returns the number of function prototype scopes in this scope chain.
Definition Scope.h:325
Scope * getDeclParent()
Definition Scope.h:317
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition Scope.h:601
decl_range decls() const
Definition Scope.h:338
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:469
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred within this scope.
Definition Scope.h:402
void applyNRVO()
Definition Scope.cpp:171
Scope * getTemplateParamParent()
Definition Scope.h:314
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
void DiagnoseUnguardedBuiltinUsage(FunctionDecl *FD)
void CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition SemaARM.cpp:1446
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:741
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:208
void maybeAddHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition SemaCUDA.cpp:829
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition SemaCUDA.cpp:894
void CheckEntryPoint(FunctionDecl *FD)
Definition SemaHLSL.cpp:984
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:748
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:714
void deduceAddressSpace(VarDecl *Decl)
QualType ActOnTemplateShorthand(TemplateDecl *Template, SourceLocation NameLoc)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:817
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:784
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:728
void ActOnVariableDeclarator(VarDecl *VD)
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
void AddCFAuditedAttribute(Decl *D)
AddCFAuditedAttribute - Check whether we're currently within '#pragma clang arc_cf_code_audited' and,...
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void ActOnVariableDeclarator(VarDecl *VD)
Function called when a variable declarator is created, which lets us implement the 'routine' 'functio...
OpenACCRoutineDeclAttr * mergeRoutineDeclAttr(const OpenACCRoutineDeclAttr &Old)
void ActOnFunctionDeclarator(FunctionDecl *FD)
Called when a function decl is created, which lets us implement the 'routine' 'doesn't match next thi...
void ActOnVariableInit(VarDecl *VD, QualType InitType)
Called when a variable is initialized, so we can implement the 'routine 'doesn't match the next thing...
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Decl *D, SmallVectorImpl< FunctionDecl * > &Bases)
Register D as specialization of all base functions in Bases in the current omp begin/end declare vari...
void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl< FunctionDecl * > &Bases)
The declarator D defines a function in the scope S which is nested in an omp begin/end declare varian...
void ActOnOpenMPDeclareTargetInitializer(Decl *D)
Adds OMPDeclareTargetDeclAttr to referenced variables in declare target directive.
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D, const llvm::StringMap< bool > &FeatureMap)
StmtResult BuildUnresolvedSYCLKernelCallStmt(CompoundStmt *Body, Expr *LaunchIdExpr)
Builds an UnresolvedSYCLKernelCallStmt to wrap 'Body'.
Definition SemaSYCL.cpp:713
StmtResult BuildSYCLKernelCallStmt(FunctionDecl *FD, CompoundStmt *Body, Expr *LaunchIdExpr)
Builds a SYCLKernelCallStmt to wrap 'Body' and to be used as the body of 'FD'.
Definition SemaSYCL.cpp:670
void CheckSYCLExternalFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:280
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:297
ExprResult BuildSYCLKernelLaunchIdExpr(FunctionDecl *FD, QualType KernelName)
Builds an expression for the lookup of a 'sycl_kernel_launch' template with 'KernelName' as an explic...
Definition SemaSYCL.cpp:427
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition SemaSwift.cpp:26
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition SemaWasm.cpp:340
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition SemaWasm.cpp:319
bool IsAlignAttr() const
Definition Sema.h:1919
Mode getAlignMode() const
Definition Sema.h:1921
A RAII object to temporarily push a declaration context.
Definition Sema.h:3526
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1386
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1398
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:3747
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3757
static NameClassification Unknown()
Definition Sema.h:3727
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3731
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3775
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3763
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3737
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3769
static NameClassification UndeclaredNonType()
Definition Sema.h:3743
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3751
static NameClassification Error()
Definition Sema.h:3723
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12552
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12586
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1448
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition Sema.h:3625
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13148
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2655
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1141
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls)
MergeTypedefNameDecl - We just parsed a typedef 'New' which has the same name and scope as a previous...
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8330
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6389
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9416
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9439
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9455
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9452
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9428
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9423
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
void ActOnPopScope(SourceLocation Loc, Scope *S)
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
void deduceOpenCLAddressSpace(VarDecl *decl)
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld, bool NewDeclIsDefn)
MergeFunctionDecl - We just parsed a function 'New' from declarator D which has the same name and sco...
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val, SkipBodyInfo *SkipBody=nullptr)
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
SemaOpenMP & OpenMP()
Definition Sema.h:1533
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition Sema.h:4797
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3607
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1845
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition Sema.h:6581
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
SemaCUDA & CUDA()
Definition Sema.h:1473
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
void ActOnExitFunctionContext()
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:lifetime_capture_by(this)]] to STL container methods.
Definition SemaAttr.cpp:318
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
Preprocessor & getPreprocessor() const
Definition Sema.h:938
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2076
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2070
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
DLLImportAttr * mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI)
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
ErrorAttr * mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic)
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
void CheckMain(FunctionDecl *FD, const DeclSpec &D)
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
@ Default
= default ;
Definition Sema.h:4200
@ Delete
deleted-function-body
Definition Sema.h:4206
ExprResult VerifyBitField(SourceLocation FieldLoc, const IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth)
VerifyBitField - verifies that a bit field expression is an ICE and has the correct width,...
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS)
Check whether the given variable declaration has a size that fits within the address space it is decl...
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation=false, bool RetainFunctionScopeInfo=false)
Performs semantic analysis at the end of a function body.
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
PersonalityAttr * mergePersonalityAttr(Decl *D, FunctionDecl *Routine, const AttributeCommonInfo &CI)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
SemaSYCL & SYCL()
Definition Sema.h:1558
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1725
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition SemaDecl.cpp:689
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
AvailabilityAttr * mergeAndInferAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, const IdentifierInfo *IIEnvironment, const IdentifierInfo *InferredPlatformII)
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ASTContext & Context
Definition Sema.h:1308
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2358
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void * SkippedDefinitionContext
Definition Sema.h:4424
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1518
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1373
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:81
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2073
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used.
Definition Sema.h:3615
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
ASTContext & getASTContext() const
Definition Sema.h:939
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
void CheckCoroutineWrapper(FunctionDecl *FD)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
PragmaStack< StringLiteral * > ConstSegStack
Definition Sema.h:2069
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:713
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition SemaAttr.cpp:112
void mergeVisibilityType(Decl *D, SourceLocation Loc, VisibilityAttr::VisibilityType Type)
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1212
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1730
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
void CheckAttributesOnDeducedType(Decl *D)
CheckAttributesOnDeducedType - Calls Sema functions for attributes that requires the type to be deduc...
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12250
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8448
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition SemaAttr.cpp:838
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2446
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken)
Act on the result of classifying a name as a specific non-type declaration.
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:170
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition Sema.h:4635
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition Sema.h:934
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2464
void PopCompoundScope()
Definition Sema.cpp:2597
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:14526
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14529
@ UPPC_Initializer
An initializer.
Definition Sema.h:14541
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14535
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14514
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14553
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14538
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14517
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14520
const LangOptions & getLangOpts() const
Definition Sema.h:932
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2558
SourceLocation CurInitSegLoc
Definition Sema.h:2112
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:238
ModularFormatAttr * mergeModularFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *ModularImplFn, StringRef ImplName, MutableArrayRef< StringRef > Aspects)
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition Sema.h:3632
SemaOpenACC & OpenACC()
Definition Sema.h:1523
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
NamedDecl * findLocallyScopedExternCDecl(DeclarationName Name)
Look for a locally scoped extern "C" declaration by the given name.
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1307
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2236
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1306
bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2673
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15622
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1483
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
CXXRecordDecl * getStdBadAlloc() const
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident)
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
PragmaClangSection PragmaClangRelroSection
Definition Sema.h:1846
SemaRISCV & RISCV()
Definition Sema.h:1548
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition Sema.h:15799
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *RetExpr, const AutoType *AT)
Deduce the return type for a function from a returned expression, per C++1y [dcl.spec....
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:215
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
SemaSwift & Swift()
Definition Sema.h:1563
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
PragmaStack< AlignPackInfo > AlignPackStack
Definition Sema.h:2058
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7048
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2068
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1145
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition SemaDecl.cpp:912
void ExitDeclaratorContext(Scope *S)
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition Sema.h:4812
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1341
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2592
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
bool CheckNontrivialField(FieldDecl *FD)
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:7045
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:644
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15616
llvm::MapVector< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3603
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2111
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9946
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
AddOverriddenMethods - See if a method overrides any in the base classes, and if so,...
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl)
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1446
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SemaOpenCL & OpenCL()
Definition Sema.h:1528
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1705
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
void CleanupMergedEnum(Scope *S, Decl *New)
CleanupMergedEnum - We have just merged the decl 'New' by making another definition visible.
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition Sema.h:3629
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
CodeSegAttr * mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
SectionAttr * mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT)
Determines if we can perform a correct type check for D as a redeclaration of PrevDecl.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14054
SourceManager & getSourceManager() const
Definition Sema.h:937
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_bits attribute.
Definition Sema.h:3577
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
bool areMultiversionVariantFunctionsCompatible(const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer)
Checks if the variant/multiversion functions are compatible.
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
PragmaClangSection PragmaClangTextSection
Definition Sema.h:1847
@ NTCUK_Destruct
Definition Sema.h:4139
@ NTCUK_Init
Definition Sema.h:4138
@ NTCUK_Copy
Definition Sema.h:4140
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1844
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc)
Act on the result of classifying a name as an undeclared (ADL-only) non-type declaration.
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, 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:6842
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
TopLevelStmtDecl * ActOnStartTopLevelStmtDecl(Scope *S)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
void ProcessPragmaExport(DeclaratorDecl *newDecl)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
void CheckCompleteVariableDeclaration(VarDecl *VD)
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2613
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:6603
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)
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:1309
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4698
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:7052
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1346
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1851
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9975
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:1538
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:1267
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:3622
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8403
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:1310
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:933
FPOptions CurFPFeatures
Definition Sema.h:1304
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:1097
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2067
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:11682
@ TPC_ClassTemplateMember
Definition Sema.h:11680
@ TPC_FunctionTemplate
Definition Sema.h:11679
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11683
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:1588
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:964
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:6619
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W)
DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak applied to it,...
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
void ActOnUninitializedDecl(Decl *dcl)
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
void ActOnCXXForRangeDecl(Decl *D)
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition Sema.h:3596
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2219
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:1843
Decl * ActOnDeclarator(Scope *S, Declarator &D)
@ AbstractVariableType
Definition Sema.h:6313
@ AbstractReturnType
Definition Sema.h:6311
@ AbstractFieldType
Definition Sema.h:6314
@ AbstractIvarType
Definition Sema.h:6315
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:8452
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:6500
void CheckVariableDeclarationType(VarDecl *NewVD)
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1300
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:3573
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:1573
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, int FirstArg)
IdentifierResolver IdResolver
Definition Sema.h:3519
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:2604
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:8411
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1299
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:3870
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:1453
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:365
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8748
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
child_range children()
Definition Stmt.cpp:304
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition Expr.h:1951
StringRef getString() const
Definition Expr.h:1873
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3739
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition Decl.h:4025
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition Decl.cpp:4925
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3835
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3821
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3840
bool isStruct() const
Definition Decl.h:3947
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:4897
bool isUnion() const
Definition Decl.h:3950
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:3972
TagKind getTagKind() const
Definition Decl.h:3939
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3885
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:227
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:4657
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition Decl.cpp:5863
void setStmt(Stmt *S)
Definition Decl.cpp:5883
Represents a declaration of a type.
Definition Decl.h:3535
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition TypeLoc.h:349
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1437
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:217
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:884
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2735
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8418
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:8429
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isStructureType() const
Definition Type.cpp:715
bool isDependentSizedArrayType() const
Definition TypeBase.h:8803
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isFunctionReferenceType() const
Definition TypeBase.h:8758
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2289
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9237
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3113
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9353
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:8787
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9217
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8783
bool isFunctionPointerType() const
Definition TypeBase.h:8751
bool isPointerType() const
Definition TypeBase.h:8684
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isScalarType() const
Definition TypeBase.h:9156
bool isVariableArrayType() const
Definition TypeBase.h:8795
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9172
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:8948
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2963
bool isOpenCLSpecificType() const
Definition TypeBase.h:8984
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2503
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isHalfType() const
Definition TypeBase.h:9054
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2109
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2651
bool containsErrors() const
Whether this type is an error type.
Definition TypeBase.h:2840
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9230
bool isAtomicType() const
Definition TypeBase.h:8876
bool isFunctionProtoType() const
Definition TypeBase.h:2661
bool isObjCIdType() const
Definition TypeBase.h:8896
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2864
bool isObjCObjectType() const
Definition TypeBase.h:8867
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9193
bool isEventT() const
Definition TypeBase.h:8932
bool isPointerOrReferenceType() const
Definition TypeBase.h:8688
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2527
bool isFunctionType() const
Definition TypeBase.h:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8769
bool isFloatingType() const
Definition Type.cpp:2389
bool isAnyPointerType() const
Definition TypeBase.h:8692
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition Type.cpp:2114
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5514
bool isUnionType() const
Definition Type.cpp:755
bool isReserveIDT() const
Definition TypeBase.h:8944
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5152
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3689
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5762
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3584
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3634
QualType getUnderlyingType() const
Definition Decl.h:3639
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition Decl.h:3645
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
TypedefNameDecl * getDecl() const
Definition TypeBase.h:6216
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:2291
Opcode getOpcode() const
Definition Expr.h:2286
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2346
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:437
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:3417
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3481
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3475
Wrapper for source info for types used via transparent aliases.
Definition TypeLoc.h:785
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5589
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5583
Represents a variable declaration or definition.
Definition Decl.h:924
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2770
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2130
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1538
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:1582
TLSKind getTLSKind() const
Definition Decl.cpp:2147
bool hasInit() const
Definition Decl.cpp:2377
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1465
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:2239
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2169
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:2440
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2236
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1591
bool isCXXCondDecl() const
Definition Decl.h:1624
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:935
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition Decl.h:938
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:932
void setStorageClass(StorageClass SC)
Definition Decl.cpp:2142
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1606
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1296
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1239
void assignAddressSpace(const ASTContext &Ctxt, LangAS AS)
Apply a deduced address space, if one isn't already set.
Definition Decl.cpp:2902
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2345
void setInlineSpecified()
Definition Decl.h:1571
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1206
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2732
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1355
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1171
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1564
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1175
const Expr * getInit() const
Definition Decl.h:1381
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1230
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1182
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition Decl.cpp:2408
void setConstexpr(bool IC)
Definition Decl.h:1585
@ TLS_Static
TLS with a known-constant initializer.
Definition Decl.h:947
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:950
void setInit(Expr *I)
Definition Decl.cpp:2456
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition Decl.cpp:2324
@ TentativeDefinition
This declaration is a tentative definition.
Definition Decl.h:1311
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1308
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1314
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2775
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition Decl.cpp:2224
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1266
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1166
void setImplicitlyInline()
Definition Decl.h:1576
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition Decl.h:1489
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1601
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:2679
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1275
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:2739
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1371
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:4030
Expr * getSizeExpr() const
Definition TypeBase.h:4044
Captures information about a #pragma weak directive.
Definition Weak.h:25
ValueDecl * getVariable() const
Definition ScopeInfo.h:671
bool isVariableCapture() const
Definition ScopeInfo.h:646
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:682
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:741
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:728
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:717
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:704
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:751
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition ScopeInfo.h:1092
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:733
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:494
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition ScopeInfo.h:150
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition ScopeInfo.h:167
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition ScopeInfo.h:145
Expr * SYCLKernelLaunchIdExpr
An unresolved identifier lookup expression for an implicit call to a SYCL kernel launch function in a...
Definition ScopeInfo.h:250
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition ScopeInfo.h:158
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:880
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition ScopeInfo.h:911
ParmVarDecl * ExplicitObjectParameter
Definition ScopeInfo.h:877
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition ScopeInfo.h:944
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:867
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:875
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:870
bool Mutable
Whether this is a mutable lambda.
Definition ScopeInfo.h:892
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)
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_struct
Definition Specifiers.h: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:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h: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
@ GVA_AvailableExternally
Definition Linkage.h:74
CUDAFunctionTarget
Definition Cuda.h:63
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:604
@ TemplateTemplateArgument
Definition Sema.h:613
NonTrivialCUnionContext
Definition Sema.h:532
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:628
@ None
Don't merge availability attributes at all.
Definition Sema.h:630
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:636
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:642
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:633
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:639
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h: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:343
@ SD_Static
Static storage duration.
Definition Specifiers.h:344
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:908
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:616
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
OptionalUnsigned< unsigned > UnsignedOrNone
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:320
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:451
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5995
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6000
@ Struct
The "struct" keyword.
Definition TypeBase.h:5997
@ Class
The "class" keyword.
Definition TypeBase.h:6006
@ Union
The "union" keyword.
Definition TypeBase.h:6003
@ Enum
The "enum" keyword.
Definition TypeBase.h:6009
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:4340
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
@ Deduced
The normal deduced case.
Definition TypeBase.h:1814
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1809
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition Lambda.h:22
@ LCD_ByRef
Definition Lambda.h:25
@ LCD_None
Definition Lambda.h:23
@ LCD_ByCopy
Definition Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
MultiVersionKind
Definition Decl.h:1997
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:1301
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
@ 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:840
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5991
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5981
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5984
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5988
ReservedIdentifierStatus
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1763
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition Visibility.h:37
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition ASTLambda.h:60
const Expr * ConstraintExpr
Definition Decl.h:88
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword).
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h: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:652
Extra information about a function prototype.
Definition TypeBase.h:5456
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition TypeBase.h:5483
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:6034
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3367
An element in an Objective-C dictionary literal.
Definition ExprObjC.h:295
Expr * Value
The value of the dictionary element.
Definition ExprObjC.h:300
Expr * Key
The key for the dictionary element.
Definition ExprObjC.h:297
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:60
std::vector< std::string > Features
Definition TargetInfo.h:61
Describes how types, statements, expressions, and declarations should be printed.
ValueType CurrentValue
Definition Sema.h:2043
SourceLocation CurrentPragmaLocation
Definition Sema.h:2044
bool CheckSameAsPrevious
Definition Sema.h:355
NamedDecl * Previous
Definition Sema.h:356
NamedDecl * New
Definition Sema.h:357
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
OpaquePtr< T > get() const
Definition Ownership.h:105
SourceLocation SymbolLocations[3]
The source locations of the individual tokens that name the operator, e.g., the "new",...
Definition DeclSpec.h:1059
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1050