clang 22.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
36#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41#include "clang/Sema/DeclSpec.h"
44#include "clang/Sema/Lookup.h"
46#include "clang/Sema/Scope.h"
48#include "clang/Sema/SemaARM.h"
49#include "clang/Sema/SemaCUDA.h"
50#include "clang/Sema/SemaHLSL.h"
52#include "clang/Sema/SemaObjC.h"
55#include "clang/Sema/SemaPPC.h"
57#include "clang/Sema/SemaSYCL.h"
59#include "clang/Sema/SemaWasm.h"
60#include "clang/Sema/Template.h"
61#include "llvm/ADT/STLForwardCompat.h"
62#include "llvm/ADT/ScopeExit.h"
63#include "llvm/ADT/SmallPtrSet.h"
64#include "llvm/ADT/SmallString.h"
65#include "llvm/ADT/StringExtras.h"
66#include "llvm/ADT/StringRef.h"
67#include "llvm/Support/SaveAndRestore.h"
68#include "llvm/TargetParser/Triple.h"
69#include <algorithm>
70#include <cstring>
71#include <optional>
72#include <unordered_map>
73
74using namespace clang;
75using namespace sema;
76
78 if (OwnedType) {
79 Decl *Group[2] = { OwnedType, Ptr };
81 }
82
84}
85
86namespace {
87
88class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
89 public:
90 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
91 bool AllowTemplates = false,
92 bool AllowNonTemplates = true)
93 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
94 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
95 WantExpressionKeywords = false;
96 WantCXXNamedCasts = false;
97 WantRemainingKeywords = false;
98 }
99
100 bool ValidateCandidate(const TypoCorrection &candidate) override {
101 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
102 if (!AllowInvalidDecl && ND->isInvalidDecl())
103 return false;
104
105 if (getAsTypeTemplateDecl(ND))
106 return AllowTemplates;
107
108 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
109 if (!IsType)
110 return false;
111
112 if (AllowNonTemplates)
113 return true;
114
115 // An injected-class-name of a class template (specialization) is valid
116 // as a template or as a non-template.
117 if (AllowTemplates) {
118 auto *RD = dyn_cast<CXXRecordDecl>(ND);
119 if (!RD || !RD->isInjectedClassName())
120 return false;
121 RD = cast<CXXRecordDecl>(RD->getDeclContext());
122 return RD->getDescribedClassTemplate() ||
124 }
125
126 return false;
127 }
128
129 return !WantClassName && candidate.isKeyword();
130 }
131
132 std::unique_ptr<CorrectionCandidateCallback> clone() override {
133 return std::make_unique<TypeNameValidatorCCC>(*this);
134 }
135
136 private:
137 bool AllowInvalidDecl;
138 bool WantClassName;
139 bool AllowTemplates;
140 bool AllowNonTemplates;
141};
142
143} // end anonymous namespace
144
146 TypeDecl *TD, SourceLocation NameLoc) {
147 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
148 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
149 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
150 FoundRD->isInjectedClassName() &&
151 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
152 Diag(NameLoc,
154 ? diag::ext_out_of_line_qualified_id_type_names_constructor
155 : diag::err_out_of_line_qualified_id_type_names_constructor)
156 << TD->getIdentifier() << /*Type=*/1
157 << 0 /*if any keyword was present, it was 'typename'*/;
158 }
159
160 DiagnoseUseOfDecl(TD, NameLoc);
161 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
162}
163
164namespace {
165enum class UnqualifiedTypeNameLookupResult {
166 NotFound,
167 FoundNonType,
168 FoundType
169};
170} // end anonymous namespace
171
172/// Tries to perform unqualified lookup of the type decls in bases for
173/// dependent class.
174/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
175/// type decl, \a FoundType if only type decls are found.
176static UnqualifiedTypeNameLookupResult
178 SourceLocation NameLoc,
179 const CXXRecordDecl *RD) {
180 if (!RD->hasDefinition())
181 return UnqualifiedTypeNameLookupResult::NotFound;
182 // Look for type decls in base classes.
183 UnqualifiedTypeNameLookupResult FoundTypeDecl =
184 UnqualifiedTypeNameLookupResult::NotFound;
185 for (const auto &Base : RD->bases()) {
186 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
187 if (BaseRD) {
188 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
189 Base.getType().getCanonicalType())) {
190 // Look for type decls in dependent base classes that have known primary
191 // templates.
192 if (!TST->isDependentType())
193 continue;
194 auto *TD = TST->getTemplateName().getAsTemplateDecl();
195 if (!TD)
196 continue;
197 if (auto *BasePrimaryTemplate =
198 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
199 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
200 BaseRD = BasePrimaryTemplate;
201 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
203 CTD->findPartialSpecialization(Base.getType()))
204 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
205 BaseRD = PS;
206 }
207 }
208 }
209 if (BaseRD) {
210 for (NamedDecl *ND : BaseRD->lookup(&II)) {
211 if (!isa<TypeDecl>(ND))
212 return UnqualifiedTypeNameLookupResult::FoundNonType;
213 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
214 }
215 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
216 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
217 case UnqualifiedTypeNameLookupResult::FoundNonType:
218 return UnqualifiedTypeNameLookupResult::FoundNonType;
219 case UnqualifiedTypeNameLookupResult::FoundType:
220 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
221 break;
222 case UnqualifiedTypeNameLookupResult::NotFound:
223 break;
224 }
225 }
226 }
227 }
228
229 return FoundTypeDecl;
230}
231
233 const IdentifierInfo &II,
234 SourceLocation NameLoc) {
235 // Lookup in the parent class template context, if any.
236 const CXXRecordDecl *RD = nullptr;
237 UnqualifiedTypeNameLookupResult FoundTypeDecl =
238 UnqualifiedTypeNameLookupResult::NotFound;
239 for (DeclContext *DC = S.CurContext;
240 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
241 DC = DC->getParent()) {
242 // Look for type decls in dependent base classes that have known primary
243 // templates.
244 RD = dyn_cast<CXXRecordDecl>(DC);
245 if (RD && RD->getDescribedClassTemplate())
246 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
247 }
248 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
249 return nullptr;
250
251 // We found some types in dependent base classes. Recover as if the user
252 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
253 // allowed. We'll fully resolve the lookup during template instantiation.
254 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
255
256 ASTContext &Context = S.Context;
257 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
258 QualType T =
259 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
260
261 CXXScopeSpec SS;
262 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
263
264 TypeLocBuilder Builder;
265 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
266 DepTL.setNameLoc(NameLoc);
268 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
269 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
270}
271
273 Scope *S, CXXScopeSpec *SS, bool isClassName,
274 bool HasTrailingDot, ParsedType ObjectTypePtr,
275 bool IsCtorOrDtorName,
276 bool WantNontrivialTypeSourceInfo,
277 bool IsClassTemplateDeductionContext,
278 ImplicitTypenameContext AllowImplicitTypename,
279 IdentifierInfo **CorrectedII) {
280 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
281 // FIXME: Consider allowing this outside C++1z mode as an extension.
282 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
283 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
284 !HasTrailingDot;
285
286 // Determine where we will perform name lookup.
287 DeclContext *LookupCtx = nullptr;
288 if (ObjectTypePtr) {
289 QualType ObjectType = ObjectTypePtr.get();
290 if (ObjectType->isRecordType())
291 LookupCtx = computeDeclContext(ObjectType);
292 } else if (SS && SS->isNotEmpty()) {
293 LookupCtx = computeDeclContext(*SS, false);
294
295 if (!LookupCtx) {
296 if (isDependentScopeSpecifier(*SS)) {
297 // C++ [temp.res]p3:
298 // A qualified-id that refers to a type and in which the
299 // nested-name-specifier depends on a template-parameter (14.6.2)
300 // shall be prefixed by the keyword typename to indicate that the
301 // qualified-id denotes a type, forming an
302 // elaborated-type-specifier (7.1.5.3).
303 //
304 // We therefore do not perform any name lookup if the result would
305 // refer to a member of an unknown specialization.
306 // In C++2a, in several contexts a 'typename' is not required. Also
307 // allow this as an extension.
308 if (IsImplicitTypename) {
309 if (AllowImplicitTypename == ImplicitTypenameContext::No)
310 return nullptr;
311 SourceLocation QualifiedLoc = SS->getRange().getBegin();
312 // FIXME: Defer the diagnostic after we build the type and use it.
313 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
314 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
315 SS->getScopeRep(), &II);
317 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
318 }
319
320 // We know from the grammar that this name refers to a type,
321 // so build a dependent node to describe the type.
322 if (WantNontrivialTypeSourceInfo)
323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
324 (ImplicitTypenameContext)IsImplicitTypename)
325 .get();
326
329 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
331 SourceLocation(), QualifierLoc, II, NameLoc);
332 return ParsedType::make(T);
333 }
334
335 return nullptr;
336 }
337
338 if (!LookupCtx->isDependentContext() &&
339 RequireCompleteDeclContext(*SS, LookupCtx))
340 return nullptr;
341 }
342
343 // In the case where we know that the identifier is a class name, we know that
344 // it is a type declaration (struct, class, union or enum) so we can use tag
345 // name lookup.
346 //
347 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
348 // the component name of the type-name or simple-template-id is type-only.
349 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
350 LookupResult Result(*this, &II, NameLoc, Kind);
351 if (LookupCtx) {
352 // Perform "qualified" name lookup into the declaration context we
353 // computed, which is either the type of the base of a member access
354 // expression or the declaration context associated with a prior
355 // nested-name-specifier.
356 LookupQualifiedName(Result, LookupCtx);
357
358 if (ObjectTypePtr && Result.empty()) {
359 // C++ [basic.lookup.classref]p3:
360 // If the unqualified-id is ~type-name, the type-name is looked up
361 // in the context of the entire postfix-expression. If the type T of
362 // the object expression is of a class type C, the type-name is also
363 // looked up in the scope of class C. At least one of the lookups shall
364 // find a name that refers to (possibly cv-qualified) T.
365 LookupName(Result, S);
366 }
367 } else {
368 // Perform unqualified name lookup.
369 LookupName(Result, S);
370
371 // For unqualified lookup in a class template in MSVC mode, look into
372 // dependent base classes where the primary class template is known.
373 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
374 if (ParsedType TypeInBase =
375 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
376 return TypeInBase;
377 }
378 }
379
380 NamedDecl *IIDecl = nullptr;
381 UsingShadowDecl *FoundUsingShadow = nullptr;
382 switch (Result.getResultKind()) {
384 if (CorrectedII) {
385 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
386 AllowDeducedTemplate);
387 TypoCorrection Correction =
388 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
390 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
392 bool MemberOfUnknownSpecialization;
394 TemplateName.setIdentifier(NewII, NameLoc);
396 CXXScopeSpec NewSS, *NewSSPtr = SS;
397 if (SS && NNS) {
398 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
399 NewSSPtr = &NewSS;
400 }
401 if (Correction && (NNS || NewII != &II) &&
402 // Ignore a correction to a template type as the to-be-corrected
403 // identifier is not a template (typo correction for template names
404 // is handled elsewhere).
405 !(getLangOpts().CPlusPlus && NewSSPtr &&
406 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
407 Template, MemberOfUnknownSpecialization))) {
408 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
409 isClassName, HasTrailingDot, ObjectTypePtr,
410 IsCtorOrDtorName,
411 WantNontrivialTypeSourceInfo,
412 IsClassTemplateDeductionContext);
413 if (Ty) {
414 diagnoseTypo(Correction,
415 PDiag(diag::err_unknown_type_or_class_name_suggest)
416 << Result.getLookupName() << isClassName);
417 if (SS && NNS)
418 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
419 *CorrectedII = NewII;
420 return Ty;
421 }
422 }
423 }
424 Result.suppressDiagnostics();
425 return nullptr;
427 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
428 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
429 SS->getScopeRep(), &II);
430 TypeLocBuilder TLB;
434 TL.setNameLoc(NameLoc);
436 }
437 [[fallthrough]];
440 Result.suppressDiagnostics();
441 return nullptr;
442
444 // Recover from type-hiding ambiguities by hiding the type. We'll
445 // do the lookup again when looking for an object, and we can
446 // diagnose the error then. If we don't do this, then the error
447 // about hiding the type will be immediately followed by an error
448 // that only makes sense if the identifier was treated like a type.
449 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
450 Result.suppressDiagnostics();
451 return nullptr;
452 }
453
454 // Look to see if we have a type anywhere in the list of results.
455 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
456 Res != ResEnd; ++Res) {
457 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
459 RealRes) ||
460 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
461 if (!IIDecl ||
462 // Make the selection of the recovery decl deterministic.
463 RealRes->getLocation() < IIDecl->getLocation()) {
464 IIDecl = RealRes;
465 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
466 }
467 }
468 }
469
470 if (!IIDecl) {
471 // None of the entities we found is a type, so there is no way
472 // to even assume that the result is a type. In this case, don't
473 // complain about the ambiguity. The parser will either try to
474 // perform this lookup again (e.g., as an object name), which
475 // will produce the ambiguity, or will complain that it expected
476 // a type name.
477 Result.suppressDiagnostics();
478 return nullptr;
479 }
480
481 // We found a type within the ambiguous lookup; diagnose the
482 // ambiguity and then return that type. This might be the right
483 // answer, or it might not be, but it suppresses any attempt to
484 // perform the name lookup again.
485 break;
486
488 IIDecl = Result.getFoundDecl();
489 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
490 break;
491 }
492
493 assert(IIDecl && "Didn't find decl");
494
495 TypeLocBuilder TLB;
496 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
497 checkTypeDeclType(LookupCtx,
498 IsImplicitTypename ? DiagCtorKind::Implicit
500 TD, NameLoc);
501 QualType T;
502 if (FoundUsingShadow) {
504 SS ? SS->getScopeRep() : std::nullopt,
505 FoundUsingShadow);
506 if (!WantNontrivialTypeSourceInfo)
507 return ParsedType::make(T);
508 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
511 NameLoc);
512 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
514 SS ? SS->getScopeRep() : std::nullopt, Tag,
515 /*OwnsTag=*/false);
516 if (!WantNontrivialTypeSourceInfo)
517 return ParsedType::make(T);
518 auto TL = TLB.push<TagTypeLoc>(T);
520 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
522 TL.setNameLoc(NameLoc);
523 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
524 TN && !isa<ObjCTypeParamDecl>(TN)) {
525 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
526 SS ? SS->getScopeRep() : std::nullopt, TN);
527 if (!WantNontrivialTypeSourceInfo)
528 return ParsedType::make(T);
529 TLB.push<TypedefTypeLoc>(T).set(
530 /*ElaboratedKeywordLoc=*/SourceLocation(),
532 NameLoc);
533 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
534 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
535 SS ? SS->getScopeRep() : std::nullopt,
536 UD);
537 if (!WantNontrivialTypeSourceInfo)
538 return ParsedType::make(T);
539 TLB.push<UnresolvedUsingTypeLoc>(T).set(
540 /*ElaboratedKeywordLoc=*/SourceLocation(),
542 NameLoc);
543 } else {
544 T = Context.getTypeDeclType(TD);
545 if (!WantNontrivialTypeSourceInfo)
546 return ParsedType::make(T);
548 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
549 else
550 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
551 }
553 }
554 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
555 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
556 if (!HasTrailingDot) {
557 // FIXME: Support UsingType for this case.
558 QualType T = Context.getObjCInterfaceType(IDecl);
559 if (!WantNontrivialTypeSourceInfo)
560 return ParsedType::make(T);
561 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
562 TL.setNameLoc(NameLoc);
563 // FIXME: Pass in this source location.
564 TL.setNameEndLoc(NameLoc);
566 }
567 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
568 (void)DiagnoseUseOfDecl(UD, NameLoc);
569 // Recover with 'int'
570 return ParsedType::make(Context.IntTy);
571 } else if (AllowDeducedTemplate) {
572 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
573 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
574 // FIXME: Support UsingType here.
575 TemplateName Template = Context.getQualifiedTemplateName(
576 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
577 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
578 QualType T = Context.getDeducedTemplateSpecializationType(
582 TL.setNameLoc(NameLoc);
583 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
586 }
587 }
588
589 // As it's not plausibly a type, suppress diagnostics.
590 Result.suppressDiagnostics();
591 return nullptr;
592}
593
594// Builds a fake NNS for the given decl context.
597 for (;; DC = DC->getLookupParent()) {
598 DC = DC->getPrimaryContext();
599 auto *ND = dyn_cast<NamespaceDecl>(DC);
600 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
601 return NestedNameSpecifier(Context, ND, std::nullopt);
602 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
603 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
606 }
607 llvm_unreachable("something isn't in TU scope?");
608}
609
610/// Find the parent class with dependent bases of the innermost enclosing method
611/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
612/// up allowing unqualified dependent type names at class-level, which MSVC
613/// correctly rejects.
614static const CXXRecordDecl *
616 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
617 DC = DC->getPrimaryContext();
618 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
619 if (MD->getParent()->hasAnyDependentBases())
620 return MD->getParent();
621 }
622 return nullptr;
623}
624
626 SourceLocation NameLoc,
627 bool IsTemplateTypeArg) {
628 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
629
630 NestedNameSpecifier NNS = std::nullopt;
631 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
632 // If we weren't able to parse a default template argument, delay lookup
633 // until instantiation time by making a non-dependent DependentTypeName. We
634 // pretend we saw a NestedNameSpecifier referring to the current scope, and
635 // lookup is retried.
636 // FIXME: This hurts our diagnostic quality, since we get errors like "no
637 // type named 'Foo' in 'current_namespace'" when the user didn't write any
638 // name specifiers.
640 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
641 } else if (const CXXRecordDecl *RD =
643 // Build a DependentNameType that will perform lookup into RD at
644 // instantiation time.
645 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
646
647 // Diagnose that this identifier was undeclared, and retry the lookup during
648 // template instantiation.
649 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
650 << RD;
651 } else {
652 // This is not a situation that we should recover from.
653 return ParsedType();
654 }
655
656 QualType T =
657 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
658
659 // Build type location information. We synthesized the qualifier, so we have
660 // to build a fake NestedNameSpecifierLoc.
661 NestedNameSpecifierLocBuilder NNSLocBuilder;
662 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
663 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
664
665 TypeLocBuilder Builder;
666 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
667 DepTL.setNameLoc(NameLoc);
669 DepTL.setQualifierLoc(QualifierLoc);
670 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
671}
672
674 // Do a tag name lookup in this scope.
675 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
676 LookupName(R, S, false);
679 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
680 switch (TD->getTagKind()) {
686 return DeclSpec::TST_union;
688 return DeclSpec::TST_class;
690 return DeclSpec::TST_enum;
691 }
692 }
693
695}
696
698 if (!CurContext->isRecord())
699 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
700
701 switch (SS->getScopeRep().getKind()) {
703 return true;
705 QualType T(SS->getScopeRep().getAsType(), 0);
706 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
707 if (Context.hasSameUnqualifiedType(T, Base.getType()))
708 return true;
709 [[fallthrough]];
710 }
711 default:
712 return S->isFunctionPrototypeScope();
713 }
714}
715
717 SourceLocation IILoc,
718 Scope *S,
719 CXXScopeSpec *SS,
720 ParsedType &SuggestedType,
721 bool IsTemplateName) {
722 // Don't report typename errors for editor placeholders.
723 if (II->isEditorPlaceholder())
724 return;
725 // We don't have anything to suggest (yet).
726 SuggestedType = nullptr;
727
728 // There may have been a typo in the name of the type. Look up typo
729 // results, in case we have something that we can suggest.
730 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
731 /*AllowTemplates=*/IsTemplateName,
732 /*AllowNonTemplates=*/!IsTemplateName);
733 if (TypoCorrection Corrected =
736 // FIXME: Support error recovery for the template-name case.
737 bool CanRecover = !IsTemplateName;
738 if (Corrected.isKeyword()) {
739 // We corrected to a keyword.
740 diagnoseTypo(Corrected,
741 PDiag(IsTemplateName ? diag::err_no_template_suggest
742 : diag::err_unknown_typename_suggest)
743 << II);
744 II = Corrected.getCorrectionAsIdentifierInfo();
745 } else {
746 // We found a similarly-named type or interface; suggest that.
747 if (!SS || !SS->isSet()) {
748 diagnoseTypo(Corrected,
749 PDiag(IsTemplateName ? diag::err_no_template_suggest
750 : diag::err_unknown_typename_suggest)
751 << II, CanRecover);
752 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
753 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
754 bool DroppedSpecifier =
755 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
756 diagnoseTypo(Corrected,
757 PDiag(IsTemplateName
758 ? diag::err_no_member_template_suggest
759 : diag::err_unknown_nested_typename_suggest)
760 << II << DC << DroppedSpecifier << SS->getRange(),
761 CanRecover);
762 } else {
763 llvm_unreachable("could not have corrected a typo here");
764 }
765
766 if (!CanRecover)
767 return;
768
769 CXXScopeSpec tmpSS;
770 if (Corrected.getCorrectionSpecifier())
771 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
772 SourceRange(IILoc));
773 // FIXME: Support class template argument deduction here.
774 SuggestedType =
775 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
776 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
777 /*IsCtorOrDtorName=*/false,
778 /*WantNontrivialTypeSourceInfo=*/true);
779 }
780 return;
781 }
782
783 if (getLangOpts().CPlusPlus && !IsTemplateName) {
784 // See if II is a class template that the user forgot to pass arguments to.
785 UnqualifiedId Name;
786 Name.setIdentifier(II, IILoc);
787 CXXScopeSpec EmptySS;
788 TemplateTy TemplateResult;
789 bool MemberOfUnknownSpecialization;
790 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
791 Name, nullptr, true, TemplateResult,
792 MemberOfUnknownSpecialization) == TNK_Type_template) {
793 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
794 return;
795 }
796 }
797
798 // FIXME: Should we move the logic that tries to recover from a missing tag
799 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
800
801 if (!SS || (!SS->isSet() && !SS->isInvalid()))
802 Diag(IILoc, IsTemplateName ? diag::err_no_template
803 : diag::err_unknown_typename)
804 << II;
805 else if (DeclContext *DC = computeDeclContext(*SS, false))
806 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
807 : diag::err_typename_nested_not_found)
808 << II << DC << SS->getRange();
809 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
810 SuggestedType =
811 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
812 } else if (isDependentScopeSpecifier(*SS)) {
813 unsigned DiagID = diag::err_typename_missing;
814 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
815 DiagID = diag::ext_typename_missing;
816
817 SuggestedType =
818 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
819
820 Diag(SS->getRange().getBegin(), DiagID)
821 << GetTypeFromParser(SuggestedType)
822 << SourceRange(SS->getRange().getBegin(), IILoc)
823 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
824 } else {
825 assert(SS && SS->isInvalid() &&
826 "Invalid scope specifier has already been diagnosed");
827 }
828}
829
830/// Determine whether the given result set contains either a type name
831/// or
832static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
833 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
834 NextToken.is(tok::less);
835
836 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
838 return true;
839
840 if (CheckTemplate && isa<TemplateDecl>(*I))
841 return true;
842 }
843
844 return false;
845}
846
847static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
848 Scope *S, CXXScopeSpec &SS,
849 IdentifierInfo *&Name,
850 SourceLocation NameLoc) {
851 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
852 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
853 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
854 StringRef FixItTagName;
855 switch (Tag->getTagKind()) {
857 FixItTagName = "class ";
858 break;
859
861 FixItTagName = "enum ";
862 break;
863
865 FixItTagName = "struct ";
866 break;
867
869 FixItTagName = "__interface ";
870 break;
871
873 FixItTagName = "union ";
874 break;
875 }
876
877 StringRef TagName = FixItTagName.drop_back();
878 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
879 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
880 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
881
882 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
883 I != IEnd; ++I)
884 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
885 << Name << TagName;
886
887 // Replace lookup results with just the tag decl.
888 Result.clear(Sema::LookupTagName);
889 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
890 return true;
891 }
892
893 return false;
894}
895
897 IdentifierInfo *&Name,
898 SourceLocation NameLoc,
899 const Token &NextToken,
901 DeclarationNameInfo NameInfo(Name, NameLoc);
902 ObjCMethodDecl *CurMethod = getCurMethodDecl();
903
904 assert(NextToken.isNot(tok::coloncolon) &&
905 "parse nested name specifiers before calling ClassifyName");
906 if (getLangOpts().CPlusPlus && SS.isSet() &&
907 isCurrentClassName(*Name, S, &SS)) {
908 // Per [class.qual]p2, this names the constructors of SS, not the
909 // injected-class-name. We don't have a classification for that.
910 // There's not much point caching this result, since the parser
911 // will reject it later.
913 }
914
915 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
916 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
917 /*AllowBuiltinCreation=*/!CurMethod);
918
919 if (SS.isInvalid())
921
922 // For unqualified lookup in a class template in MSVC mode, look into
923 // dependent base classes where the primary class template is known.
924 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
925 if (ParsedType TypeInBase =
926 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
927 return TypeInBase;
928 }
929
930 // Perform lookup for Objective-C instance variables (including automatically
931 // synthesized instance variables), if we're in an Objective-C method.
932 // FIXME: This lookup really, really needs to be folded in to the normal
933 // unqualified lookup mechanism.
934 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
935 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
936 if (Ivar.isInvalid())
938 if (Ivar.isUsable())
940
941 // We defer builtin creation until after ivar lookup inside ObjC methods.
942 if (Result.empty())
944 }
945
946 bool SecondTry = false;
947 bool IsFilteredTemplateName = false;
948
949Corrected:
950 switch (Result.getResultKind()) {
952 // If an unqualified-id is followed by a '(', then we have a function
953 // call.
954 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
955 // In C++, this is an ADL-only call.
956 // FIXME: Reference?
959
960 // C90 6.3.2.2:
961 // If the expression that precedes the parenthesized argument list in a
962 // function call consists solely of an identifier, and if no
963 // declaration is visible for this identifier, the identifier is
964 // implicitly declared exactly as if, in the innermost block containing
965 // the function call, the declaration
966 //
967 // extern int identifier ();
968 //
969 // appeared.
970 //
971 // We also allow this in C99 as an extension. However, this is not
972 // allowed in all language modes as functions without prototypes may not
973 // be supported.
974 if (getLangOpts().implicitFunctionsAllowed()) {
975 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
977 }
978 }
979
980 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
981 // In C++20 onwards, this could be an ADL-only call to a function
982 // template, and we're required to assume that this is a template name.
983 //
984 // FIXME: Find a way to still do typo correction in this case.
986 Context.getAssumedTemplateName(NameInfo.getName());
988 }
989
990 // In C, we first see whether there is a tag type by the same name, in
991 // which case it's likely that the user just forgot to write "enum",
992 // "struct", or "union".
993 if (!getLangOpts().CPlusPlus && !SecondTry &&
994 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
995 break;
996 }
997
998 // Perform typo correction to determine if there is another name that is
999 // close to this name.
1000 if (!SecondTry && CCC) {
1001 SecondTry = true;
1002 if (TypoCorrection Corrected =
1003 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1004 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1005 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1006 unsigned QualifiedDiag = diag::err_no_member_suggest;
1007
1008 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1009 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1010 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1011 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1012 UnqualifiedDiag = diag::err_no_template_suggest;
1013 QualifiedDiag = diag::err_no_member_template_suggest;
1014 } else if (UnderlyingFirstDecl &&
1015 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1016 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1017 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1018 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1019 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1020 }
1021
1022 if (SS.isEmpty()) {
1023 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1024 } else {// FIXME: is this even reachable? Test it.
1025 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1026 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1027 Name->getName() == CorrectedStr;
1028 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1029 << Name << computeDeclContext(SS, false)
1030 << DroppedSpecifier << SS.getRange());
1031 }
1032
1033 // Update the name, so that the caller has the new name.
1034 Name = Corrected.getCorrectionAsIdentifierInfo();
1035
1036 // Typo correction corrected to a keyword.
1037 if (Corrected.isKeyword())
1038 return Name;
1039
1040 // Also update the LookupResult...
1041 // FIXME: This should probably go away at some point
1042 Result.clear();
1043 Result.setLookupName(Corrected.getCorrection());
1044 if (FirstDecl)
1045 Result.addDecl(FirstDecl);
1046
1047 // If we found an Objective-C instance variable, let
1048 // LookupInObjCMethod build the appropriate expression to
1049 // reference the ivar.
1050 // FIXME: This is a gross hack.
1051 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1052 DeclResult R =
1053 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1054 if (R.isInvalid())
1056 if (R.isUsable())
1057 return NameClassification::NonType(Ivar);
1058 }
1059
1060 goto Corrected;
1061 }
1062 }
1063
1064 // We failed to correct; just fall through and let the parser deal with it.
1065 Result.suppressDiagnostics();
1067
1069 // We performed name lookup into the current instantiation, and there were
1070 // dependent bases, so we treat this result the same way as any other
1071 // dependent nested-name-specifier.
1072
1073 // C++ [temp.res]p2:
1074 // A name used in a template declaration or definition and that is
1075 // dependent on a template-parameter is assumed not to name a type
1076 // unless the applicable name lookup finds a type name or the name is
1077 // qualified by the keyword typename.
1078 //
1079 // FIXME: If the next token is '<', we might want to ask the parser to
1080 // perform some heroics to see if we actually have a
1081 // template-argument-list, which would indicate a missing 'template'
1082 // keyword here.
1084 }
1085
1089 break;
1090
1092 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1093 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1094 /*AllowDependent=*/false)) {
1095 // C++ [temp.local]p3:
1096 // A lookup that finds an injected-class-name (10.2) can result in an
1097 // ambiguity in certain cases (for example, if it is found in more than
1098 // one base class). If all of the injected-class-names that are found
1099 // refer to specializations of the same class template, and if the name
1100 // is followed by a template-argument-list, the reference refers to the
1101 // class template itself and not a specialization thereof, and is not
1102 // ambiguous.
1103 //
1104 // This filtering can make an ambiguous result into an unambiguous one,
1105 // so try again after filtering out template names.
1107 if (!Result.isAmbiguous()) {
1108 IsFilteredTemplateName = true;
1109 break;
1110 }
1111 }
1112
1113 // Diagnose the ambiguity and return an error.
1115 }
1116
1117 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1118 (IsFilteredTemplateName ||
1120 Result, /*AllowFunctionTemplates=*/true,
1121 /*AllowDependent=*/false,
1122 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1124 // C++ [temp.names]p3:
1125 // After name lookup (3.4) finds that a name is a template-name or that
1126 // an operator-function-id or a literal- operator-id refers to a set of
1127 // overloaded functions any member of which is a function template if
1128 // this is followed by a <, the < is always taken as the delimiter of a
1129 // template-argument-list and never as the less-than operator.
1130 // C++2a [temp.names]p2:
1131 // A name is also considered to refer to a template if it is an
1132 // unqualified-id followed by a < and name lookup finds either one
1133 // or more functions or finds nothing.
1134 if (!IsFilteredTemplateName)
1136
1137 bool IsFunctionTemplate;
1138 bool IsVarTemplate;
1140 if (Result.end() - Result.begin() > 1) {
1141 IsFunctionTemplate = true;
1142 Template = Context.getOverloadedTemplateName(Result.begin(),
1143 Result.end());
1144 } else if (!Result.empty()) {
1146 *Result.begin(), /*AllowFunctionTemplates=*/true,
1147 /*AllowDependent=*/false));
1148 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1149 IsVarTemplate = isa<VarTemplateDecl>(TD);
1150
1151 UsingShadowDecl *FoundUsingShadow =
1152 dyn_cast<UsingShadowDecl>(*Result.begin());
1153 assert(!FoundUsingShadow ||
1154 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1155 Template = Context.getQualifiedTemplateName(
1156 SS.getScopeRep(),
1157 /*TemplateKeyword=*/false,
1158 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1159 } else {
1160 // All results were non-template functions. This is a function template
1161 // name.
1162 IsFunctionTemplate = true;
1163 Template = Context.getAssumedTemplateName(NameInfo.getName());
1164 }
1165
1166 if (IsFunctionTemplate) {
1167 // Function templates always go through overload resolution, at which
1168 // point we'll perform the various checks (e.g., accessibility) we need
1169 // to based on which function we selected.
1170 Result.suppressDiagnostics();
1171
1173 }
1174
1175 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1177 }
1178
1179 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1180 QualType T;
1181 TypeLocBuilder TLB;
1182 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1183 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1184 USD);
1185 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1186 SS.getWithLocInContext(Context), NameLoc);
1187 } else {
1188 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1189 Type);
1190 if (isa<TagType>(T)) {
1191 auto TTL = TLB.push<TagTypeLoc>(T);
1193 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1194 TTL.setNameLoc(NameLoc);
1195 } else if (isa<TypedefType>(T)) {
1196 TLB.push<TypedefTypeLoc>(T).set(
1197 /*ElaboratedKeywordLoc=*/SourceLocation(),
1198 SS.getWithLocInContext(Context), NameLoc);
1199 } else if (isa<UnresolvedUsingType>(T)) {
1200 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1201 /*ElaboratedKeywordLoc=*/SourceLocation(),
1202 SS.getWithLocInContext(Context), NameLoc);
1203 } else {
1204 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1205 }
1206 }
1208 };
1209
1210 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1211 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1212 DiagnoseUseOfDecl(Type, NameLoc);
1213 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1214 return BuildTypeFor(Type, *Result.begin());
1215 }
1216
1217 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1218 if (!Class) {
1219 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1220 if (ObjCCompatibleAliasDecl *Alias =
1221 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1222 Class = Alias->getClassInterface();
1223 }
1224
1225 if (Class) {
1226 DiagnoseUseOfDecl(Class, NameLoc);
1227
1228 if (NextToken.is(tok::period)) {
1229 // Interface. <something> is parsed as a property reference expression.
1230 // Just return "unknown" as a fall-through for now.
1231 Result.suppressDiagnostics();
1233 }
1234
1235 QualType T = Context.getObjCInterfaceType(Class);
1236 return ParsedType::make(T);
1237 }
1238
1240 // We want to preserve the UsingShadowDecl for concepts.
1241 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1245 }
1246
1247 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1248 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1250 }
1251
1252 // We can have a type template here if we're classifying a template argument.
1257
1258 // Check for a tag type hidden by a non-type decl in a few cases where it
1259 // seems likely a type is wanted instead of the non-type that was found.
1260 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1261 if ((NextToken.is(tok::identifier) ||
1262 (NextIsOp &&
1263 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1264 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1265 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1266 DiagnoseUseOfDecl(Type, NameLoc);
1267 return BuildTypeFor(Type, *Result.begin());
1268 }
1269
1270 // If we already know which single declaration is referenced, just annotate
1271 // that declaration directly. Defer resolving even non-overloaded class
1272 // member accesses, as we need to defer certain access checks until we know
1273 // the context.
1274 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1275 if (Result.isSingleResult() && !ADL &&
1276 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1277 return NameClassification::NonType(Result.getRepresentativeDecl());
1278
1279 // Otherwise, this is an overload set that we will need to resolve later.
1280 Result.suppressDiagnostics();
1282 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1283 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1284 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1285}
1286
1289 SourceLocation NameLoc) {
1290 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1291 CXXScopeSpec SS;
1292 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1293 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1294}
1295
1298 IdentifierInfo *Name,
1299 SourceLocation NameLoc,
1300 bool IsAddressOfOperand) {
1301 DeclarationNameInfo NameInfo(Name, NameLoc);
1302 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1303 NameInfo, IsAddressOfOperand,
1304 /*TemplateArgs=*/nullptr);
1305}
1306
1309 SourceLocation NameLoc,
1310 const Token &NextToken) {
1311 if (getCurMethodDecl() && SS.isEmpty())
1312 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1313 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1314
1315 // Reconstruct the lookup result.
1316 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1317 Result.addDecl(Found);
1318 Result.resolveKind();
1319
1320 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1321 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1322}
1323
1325 // For an implicit class member access, transform the result into a member
1326 // access expression if necessary.
1327 auto *ULE = cast<UnresolvedLookupExpr>(E);
1328 if ((*ULE->decls_begin())->isCXXClassMember()) {
1329 CXXScopeSpec SS;
1330 SS.Adopt(ULE->getQualifierLoc());
1331
1332 // Reconstruct the lookup result.
1333 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1335 Result.setNamingClass(ULE->getNamingClass());
1336 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1337 Result.addDecl(*I, I.getAccess());
1338 Result.resolveKind();
1340 nullptr, S);
1341 }
1342
1343 // Otherwise, this is already in the form we needed, and no further checks
1344 // are necessary.
1345 return ULE;
1346}
1347
1367
1369 assert(DC->getLexicalParent() == CurContext &&
1370 "The next DeclContext should be lexically contained in the current one.");
1371 CurContext = DC;
1372 S->setEntity(DC);
1373}
1374
1376 assert(CurContext && "DeclContext imbalance!");
1377
1378 CurContext = CurContext->getLexicalParent();
1379 assert(CurContext && "Popped translation unit!");
1380}
1381
1383 Decl *D) {
1384 // Unlike PushDeclContext, the context to which we return is not necessarily
1385 // the containing DC of TD, because the new context will be some pre-existing
1386 // TagDecl definition instead of a fresh one.
1387 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1388 CurContext = cast<TagDecl>(D)->getDefinition();
1389 assert(CurContext && "skipping definition of undefined tag");
1390 // Start lookups from the parent of the current context; we don't want to look
1391 // into the pre-existing complete definition.
1392 S->setEntity(CurContext->getLookupParent());
1393 return Result;
1394}
1395
1399
1401 // C++0x [basic.lookup.unqual]p13:
1402 // A name used in the definition of a static data member of class
1403 // X (after the qualified-id of the static member) is looked up as
1404 // if the name was used in a member function of X.
1405 // C++0x [basic.lookup.unqual]p14:
1406 // If a variable member of a namespace is defined outside of the
1407 // scope of its namespace then any name used in the definition of
1408 // the variable member (after the declarator-id) is looked up as
1409 // if the definition of the variable member occurred in its
1410 // namespace.
1411 // Both of these imply that we should push a scope whose context
1412 // is the semantic context of the declaration. We can't use
1413 // PushDeclContext here because that context is not necessarily
1414 // lexically contained in the current context. Fortunately,
1415 // the containing scope should have the appropriate information.
1416
1417 assert(!S->getEntity() && "scope already has entity");
1418
1419#ifndef NDEBUG
1420 Scope *Ancestor = S->getParent();
1421 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1422 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1423#endif
1424
1425 CurContext = DC;
1426 S->setEntity(DC);
1427
1428 if (S->getParent()->isTemplateParamScope()) {
1429 // Also set the corresponding entities for all immediately-enclosing
1430 // template parameter scopes.
1432 }
1433}
1434
1436 assert(S->getEntity() == CurContext && "Context imbalance!");
1437
1438 // Switch back to the lexical context. The safety of this is
1439 // enforced by an assert in EnterDeclaratorContext.
1440 Scope *Ancestor = S->getParent();
1441 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1442 CurContext = Ancestor->getEntity();
1443
1444 // We don't need to do anything with the scope, which is going to
1445 // disappear.
1446}
1447
1449 assert(S->isTemplateParamScope() &&
1450 "expected to be initializing a template parameter scope");
1451
1452 // C++20 [temp.local]p7:
1453 // In the definition of a member of a class template that appears outside
1454 // of the class template definition, the name of a member of the class
1455 // template hides the name of a template-parameter of any enclosing class
1456 // templates (but not a template-parameter of the member if the member is a
1457 // class or function template).
1458 // C++20 [temp.local]p9:
1459 // In the definition of a class template or in the definition of a member
1460 // of such a template that appears outside of the template definition, for
1461 // each non-dependent base class (13.8.2.1), if the name of the base class
1462 // or the name of a member of the base class is the same as the name of a
1463 // template-parameter, the base class name or member name hides the
1464 // template-parameter name (6.4.10).
1465 //
1466 // This means that a template parameter scope should be searched immediately
1467 // after searching the DeclContext for which it is a template parameter
1468 // scope. For example, for
1469 // template<typename T> template<typename U> template<typename V>
1470 // void N::A<T>::B<U>::f(...)
1471 // we search V then B<U> (and base classes) then U then A<T> (and base
1472 // classes) then T then N then ::.
1473 unsigned ScopeDepth = getTemplateDepth(S);
1474 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1475 DeclContext *SearchDCAfterScope = DC;
1476 for (; DC; DC = DC->getLookupParent()) {
1477 if (const TemplateParameterList *TPL =
1478 cast<Decl>(DC)->getDescribedTemplateParams()) {
1479 unsigned DCDepth = TPL->getDepth() + 1;
1480 if (DCDepth > ScopeDepth)
1481 continue;
1482 if (ScopeDepth == DCDepth)
1483 SearchDCAfterScope = DC = DC->getLookupParent();
1484 break;
1485 }
1486 }
1487 S->setLookupEntity(SearchDCAfterScope);
1488 }
1489}
1490
1492 // We assume that the caller has already called
1493 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1494 FunctionDecl *FD = D->getAsFunction();
1495 if (!FD)
1496 return;
1497
1498 // Same implementation as PushDeclContext, but enters the context
1499 // from the lexical parent, rather than the top-level class.
1500 assert(CurContext == FD->getLexicalParent() &&
1501 "The next DeclContext should be lexically contained in the current one.");
1502 CurContext = FD;
1504
1505 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1506 ParmVarDecl *Param = FD->getParamDecl(P);
1507 // If the parameter has an identifier, then add it to the scope
1508 if (Param->getIdentifier()) {
1509 S->AddDecl(Param);
1510 IdResolver.AddDecl(Param);
1511 }
1512 }
1513}
1514
1516 // Same implementation as PopDeclContext, but returns to the lexical parent,
1517 // rather than the top-level class.
1518 assert(CurContext && "DeclContext imbalance!");
1519 CurContext = CurContext->getLexicalParent();
1520 assert(CurContext && "Popped translation unit!");
1521}
1522
1523/// Determine whether overloading is allowed for a new function
1524/// declaration considering prior declarations of the same name.
1525///
1526/// This routine determines whether overloading is possible, not
1527/// whether a new declaration actually overloads a previous one.
1528/// It will return true in C++ (where overloads are always permitted)
1529/// or, as a C extension, when either the new declaration or a
1530/// previous one is declared with the 'overloadable' attribute.
1532 ASTContext &Context,
1533 const FunctionDecl *New) {
1534 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1535 return true;
1536
1537 // Multiversion function declarations are not overloads in the
1538 // usual sense of that term, but lookup will report that an
1539 // overload set was found if more than one multiversion function
1540 // declaration is present for the same name. It is therefore
1541 // inadequate to assume that some prior declaration(s) had
1542 // the overloadable attribute; checking is required. Since one
1543 // declaration is permitted to omit the attribute, it is necessary
1544 // to check at least two; hence the 'any_of' check below. Note that
1545 // the overloadable attribute is implicitly added to declarations
1546 // that were required to have it but did not.
1547 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1548 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1549 return ND->hasAttr<OverloadableAttr>();
1550 });
1551 } else if (Previous.getResultKind() == LookupResultKind::Found)
1552 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1553
1554 return false;
1555}
1556
1557void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1558 // Move up the scope chain until we find the nearest enclosing
1559 // non-transparent context. The declaration will be introduced into this
1560 // scope.
1561 while (S->getEntity() && S->getEntity()->isTransparentContext())
1562 S = S->getParent();
1563
1564 // Add scoped declarations into their context, so that they can be
1565 // found later. Declarations without a context won't be inserted
1566 // into any context.
1567 if (AddToContext)
1568 CurContext->addDecl(D);
1569
1570 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1571 // are function-local declarations.
1572 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1573 return;
1574
1575 // Template instantiations should also not be pushed into scope.
1576 if (isa<FunctionDecl>(D) &&
1577 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1578 return;
1579
1580 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1581 S->AddDecl(D);
1582 return;
1583 }
1584 // If this replaces anything in the current scope,
1586 IEnd = IdResolver.end();
1587 for (; I != IEnd; ++I) {
1588 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1589 S->RemoveDecl(*I);
1590 IdResolver.RemoveDecl(*I);
1591
1592 // Should only need to replace one decl.
1593 break;
1594 }
1595 }
1596
1597 S->AddDecl(D);
1598
1599 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1600 // Implicitly-generated labels may end up getting generated in an order that
1601 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1602 // the label at the appropriate place in the identifier chain.
1603 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1604 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1605 if (IDC == CurContext) {
1606 if (!S->isDeclScope(*I))
1607 continue;
1608 } else if (IDC->Encloses(CurContext))
1609 break;
1610 }
1611
1612 IdResolver.InsertDeclAfter(I, D);
1613 } else {
1614 IdResolver.AddDecl(D);
1615 }
1617}
1618
1620 bool AllowInlineNamespace) const {
1621 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1622}
1623
1625 DeclContext *TargetDC = DC->getPrimaryContext();
1626 do {
1627 if (DeclContext *ScopeDC = S->getEntity())
1628 if (ScopeDC->getPrimaryContext() == TargetDC)
1629 return S;
1630 } while ((S = S->getParent()));
1631
1632 return nullptr;
1633}
1634
1636 DeclContext*,
1637 ASTContext&);
1638
1640 bool ConsiderLinkage,
1641 bool AllowInlineNamespace) {
1643 while (F.hasNext()) {
1644 NamedDecl *D = F.next();
1645
1646 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1647 continue;
1648
1649 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1650 continue;
1651
1652 F.erase();
1653 }
1654
1655 F.done();
1656}
1657
1659 if (auto *VD = dyn_cast<VarDecl>(D))
1660 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1661 if (auto *FD = dyn_cast<FunctionDecl>(D))
1662 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1663 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1664 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1665
1666 return false;
1667}
1668
1670 // [module.interface]p7:
1671 // A declaration is attached to a module as follows:
1672 // - If the declaration is a non-dependent friend declaration that nominates a
1673 // function with a declarator-id that is a qualified-id or template-id or that
1674 // nominates a class other than with an elaborated-type-specifier with neither
1675 // a nested-name-specifier nor a simple-template-id, it is attached to the
1676 // module to which the friend is attached ([basic.link]).
1677 if (New->getFriendObjectKind() &&
1678 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1679 New->setLocalOwningModule(Old->getOwningModule());
1681 return false;
1682 }
1683
1684 // Although we have questions for the module ownership of implicit
1685 // instantiations, it should be sure that we shouldn't diagnose the
1686 // redeclaration of incorrect module ownership for different implicit
1687 // instantiations in different modules. We will diagnose the redeclaration of
1688 // incorrect module ownership for the template itself.
1690 return false;
1691
1692 Module *NewM = New->getOwningModule();
1693 Module *OldM = Old->getOwningModule();
1694
1695 if (NewM && NewM->isPrivateModule())
1696 NewM = NewM->Parent;
1697 if (OldM && OldM->isPrivateModule())
1698 OldM = OldM->Parent;
1699
1700 if (NewM == OldM)
1701 return false;
1702
1703 if (NewM && OldM) {
1704 // A module implementation unit has visibility of the decls in its
1705 // implicitly imported interface.
1706 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1707 return false;
1708
1709 // Partitions are part of the module, but a partition could import another
1710 // module, so verify that the PMIs agree.
1711 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1712 getASTContext().isInSameModule(NewM, OldM))
1713 return false;
1714 }
1715
1716 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1717 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1718 if (NewIsModuleInterface || OldIsModuleInterface) {
1719 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1720 // if a declaration of D [...] appears in the purview of a module, all
1721 // other such declarations shall appear in the purview of the same module
1722 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1723 << New
1724 << NewIsModuleInterface
1725 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1726 << OldIsModuleInterface
1727 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1728 Diag(Old->getLocation(), diag::note_previous_declaration);
1729 New->setInvalidDecl();
1730 return true;
1731 }
1732
1733 return false;
1734}
1735
1737 // [module.interface]p1:
1738 // An export-declaration shall inhabit a namespace scope.
1739 //
1740 // So it is meaningless to talk about redeclaration which is not at namespace
1741 // scope.
1742 if (!New->getLexicalDeclContext()
1743 ->getNonTransparentContext()
1744 ->isFileContext() ||
1745 !Old->getLexicalDeclContext()
1747 ->isFileContext())
1748 return false;
1749
1750 bool IsNewExported = New->isInExportDeclContext();
1751 bool IsOldExported = Old->isInExportDeclContext();
1752
1753 // It should be irrevelant if both of them are not exported.
1754 if (!IsNewExported && !IsOldExported)
1755 return false;
1756
1757 if (IsOldExported)
1758 return false;
1759
1760 // If the Old declaration are not attached to named modules
1761 // and the New declaration are attached to global module.
1762 // It should be fine to allow the export since it doesn't change
1763 // the linkage of declarations. See
1764 // https://github.com/llvm/llvm-project/issues/98583 for details.
1765 if (!Old->isInNamedModule() && New->getOwningModule() &&
1766 New->getOwningModule()->isImplicitGlobalModule())
1767 return false;
1768
1769 assert(IsNewExported);
1770
1771 auto Lk = Old->getFormalLinkage();
1772 int S = 0;
1773 if (Lk == Linkage::Internal)
1774 S = 1;
1775 else if (Lk == Linkage::Module)
1776 S = 2;
1777 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1778 Diag(Old->getLocation(), diag::note_previous_declaration);
1779 return true;
1780}
1781
1784 return true;
1785
1787 return true;
1788
1789 return false;
1790}
1791
1793 const NamedDecl *Old) const {
1794 assert(getASTContext().isSameEntity(New, Old) &&
1795 "New and Old are not the same definition, we should diagnostic it "
1796 "immediately instead of checking it.");
1797 assert(const_cast<Sema *>(this)->isReachable(New) &&
1798 const_cast<Sema *>(this)->isReachable(Old) &&
1799 "We shouldn't see unreachable definitions here.");
1800
1801 Module *NewM = New->getOwningModule();
1802 Module *OldM = Old->getOwningModule();
1803
1804 // We only checks for named modules here. The header like modules is skipped.
1805 // FIXME: This is not right if we import the header like modules in the module
1806 // purview.
1807 //
1808 // For example, assuming "header.h" provides definition for `D`.
1809 // ```C++
1810 // //--- M.cppm
1811 // export module M;
1812 // import "header.h"; // or #include "header.h" but import it by clang modules
1813 // actually.
1814 //
1815 // //--- Use.cpp
1816 // import M;
1817 // import "header.h"; // or uses clang modules.
1818 // ```
1819 //
1820 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1821 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1822 // reject it. But the current implementation couldn't detect the case since we
1823 // don't record the information about the importee modules.
1824 //
1825 // But this might not be painful in practice. Since the design of C++20 Named
1826 // Modules suggests us to use headers in global module fragment instead of
1827 // module purview.
1828 if (NewM && NewM->isHeaderLikeModule())
1829 NewM = nullptr;
1830 if (OldM && OldM->isHeaderLikeModule())
1831 OldM = nullptr;
1832
1833 if (!NewM && !OldM)
1834 return true;
1835
1836 // [basic.def.odr]p14.3
1837 // Each such definition shall not be attached to a named module
1838 // ([module.unit]).
1839 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1840 return true;
1841
1842 // Then New and Old lives in the same TU if their share one same module unit.
1843 if (NewM)
1844 NewM = NewM->getTopLevelModule();
1845 if (OldM)
1846 OldM = OldM->getTopLevelModule();
1847 return OldM == NewM;
1848}
1849
1851 if (D->getDeclContext()->isFileContext())
1852 return false;
1853
1854 return isa<UsingShadowDecl>(D) ||
1857}
1858
1859/// Removes using shadow declarations not at class scope from the lookup
1860/// results.
1863 while (F.hasNext())
1865 F.erase();
1866
1867 F.done();
1868}
1869
1870/// Check for this common pattern:
1871/// @code
1872/// class S {
1873/// S(const S&); // DO NOT IMPLEMENT
1874/// void operator=(const S&); // DO NOT IMPLEMENT
1875/// };
1876/// @endcode
1878 // FIXME: Should check for private access too but access is set after we get
1879 // the decl here.
1881 return false;
1882
1883 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1884 return CD->isCopyConstructor();
1885 return D->isCopyAssignmentOperator();
1886}
1887
1888bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1889 const DeclContext *DC = D->getDeclContext();
1890 while (!DC->isTranslationUnit()) {
1891 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1892 if (!RD->hasNameForLinkage())
1893 return true;
1894 }
1895 DC = DC->getParent();
1896 }
1897
1898 return !D->isExternallyVisible();
1899}
1900
1901// FIXME: This needs to be refactored; some other isInMainFile users want
1902// these semantics.
1903static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1905 return false;
1906 return S.SourceMgr.isInMainFile(Loc);
1907}
1908
1910 assert(D);
1911
1912 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1913 return false;
1914
1915 // Ignore all entities declared within templates, and out-of-line definitions
1916 // of members of class templates.
1917 if (D->getDeclContext()->isDependentContext() ||
1919 return false;
1920
1921 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1922 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1923 return false;
1924 // A non-out-of-line declaration of a member specialization was implicitly
1925 // instantiated; it's the out-of-line declaration that we're interested in.
1926 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1927 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1928 return false;
1929
1930 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1931 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1932 return false;
1933 } else {
1934 // 'static inline' functions are defined in headers; don't warn.
1935 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1936 return false;
1937 }
1938
1939 if (FD->doesThisDeclarationHaveABody() &&
1940 Context.DeclMustBeEmitted(FD))
1941 return false;
1942 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1943 // Constants and utility variables are defined in headers with internal
1944 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1945 // like "inline".)
1946 if (!isMainFileLoc(*this, VD->getLocation()))
1947 return false;
1948
1949 if (Context.DeclMustBeEmitted(VD))
1950 return false;
1951
1952 if (VD->isStaticDataMember() &&
1953 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1954 return false;
1955 if (VD->isStaticDataMember() &&
1956 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1957 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1958 return false;
1959
1960 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1961 return false;
1962 } else {
1963 return false;
1964 }
1965
1966 // Only warn for unused decls internal to the translation unit.
1967 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1968 // for inline functions defined in the main source file, for instance.
1969 return mightHaveNonExternalLinkage(D);
1970}
1971
1973 if (!D)
1974 return;
1975
1976 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1977 const FunctionDecl *First = FD->getFirstDecl();
1979 return; // First should already be in the vector.
1980 }
1981
1982 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1983 const VarDecl *First = VD->getFirstDecl();
1985 return; // First should already be in the vector.
1986 }
1987
1989 UnusedFileScopedDecls.push_back(D);
1990}
1991
1992static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1993 const NamedDecl *D) {
1994 if (D->isInvalidDecl())
1995 return false;
1996
1997 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1998 // For a decomposition declaration, warn if none of the bindings are
1999 // referenced, instead of if the variable itself is referenced (which
2000 // it is, by the bindings' expressions).
2001 bool IsAllIgnored = true;
2002 for (const auto *BD : DD->bindings()) {
2003 if (BD->isReferenced())
2004 return false;
2005 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2006 BD->hasAttr<UnusedAttr>());
2007 }
2008 if (IsAllIgnored)
2009 return false;
2010 } else if (!D->getDeclName()) {
2011 return false;
2012 } else if (D->isReferenced() || D->isUsed()) {
2013 return false;
2014 }
2015
2016 if (D->isPlaceholderVar(LangOpts))
2017 return false;
2018
2019 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2020 D->hasAttr<CleanupAttr>())
2021 return false;
2022
2023 if (isa<LabelDecl>(D))
2024 return true;
2025
2026 // Except for labels, we only care about unused decls that are local to
2027 // functions.
2028 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2029 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2030 // For dependent types, the diagnostic is deferred.
2031 WithinFunction =
2032 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2033 if (!WithinFunction)
2034 return false;
2035
2036 if (isa<TypedefNameDecl>(D))
2037 return true;
2038
2039 // White-list anything that isn't a local variable.
2041 return false;
2042
2043 // Types of valid local variables should be complete, so this should succeed.
2044 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2045
2046 const Expr *Init = VD->getInit();
2047 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2048 Init = Cleanups->getSubExpr();
2049
2050 const auto *Ty = VD->getType().getTypePtr();
2051
2052 // Only look at the outermost level of typedef.
2053 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2054 // Allow anything marked with __attribute__((unused)).
2055 if (TT->getDecl()->hasAttr<UnusedAttr>())
2056 return false;
2057 }
2058
2059 // Warn for reference variables whose initializtion performs lifetime
2060 // extension.
2061 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2062 MTE && MTE->getExtendingDecl()) {
2063 Ty = VD->getType().getNonReferenceType().getTypePtr();
2064 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2065 }
2066
2067 // If we failed to complete the type for some reason, or if the type is
2068 // dependent, don't diagnose the variable.
2069 if (Ty->isIncompleteType() || Ty->isDependentType())
2070 return false;
2071
2072 // Look at the element type to ensure that the warning behaviour is
2073 // consistent for both scalars and arrays.
2074 Ty = Ty->getBaseElementTypeUnsafe();
2075
2076 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2077 if (Tag->hasAttr<UnusedAttr>())
2078 return false;
2079
2080 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2081 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2082 return false;
2083
2084 if (Init) {
2085 const auto *Construct =
2086 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2087 if (Construct && !Construct->isElidable()) {
2088 const CXXConstructorDecl *CD = Construct->getConstructor();
2089 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2090 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2091 return false;
2092 }
2093
2094 // Suppress the warning if we don't know how this is constructed, and
2095 // it could possibly be non-trivial constructor.
2096 if (Init->isTypeDependent()) {
2097 for (const CXXConstructorDecl *Ctor : RD->ctors())
2098 if (!Ctor->isTrivial())
2099 return false;
2100 }
2101
2102 // Suppress the warning if the constructor is unresolved because
2103 // its arguments are dependent.
2105 return false;
2106 }
2107 }
2108 }
2109
2110 // TODO: __attribute__((unused)) templates?
2111 }
2112
2113 return true;
2114}
2115
2117 FixItHint &Hint) {
2118 if (isa<LabelDecl>(D)) {
2120 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2121 /*SkipTrailingWhitespaceAndNewline=*/false);
2122 if (AfterColon.isInvalid())
2123 return;
2125 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2126 }
2127}
2128
2131 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2132}
2133
2135 DiagReceiverTy DiagReceiver) {
2136 if (D->isDependentType())
2137 return;
2138
2139 for (auto *TmpD : D->decls()) {
2140 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2141 DiagnoseUnusedDecl(T, DiagReceiver);
2142 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2143 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2144 }
2145}
2146
2149 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2150}
2151
2154 return;
2155
2156 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2157 // typedefs can be referenced later on, so the diagnostics are emitted
2158 // at end-of-translation-unit.
2160 return;
2161 }
2162
2163 FixItHint Hint;
2165
2166 unsigned DiagID;
2167 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2168 DiagID = diag::warn_unused_exception_param;
2169 else if (isa<LabelDecl>(D))
2170 DiagID = diag::warn_unused_label;
2171 else
2172 DiagID = diag::warn_unused_variable;
2173
2174 SourceLocation DiagLoc = D->getLocation();
2175 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2176}
2177
2179 DiagReceiverTy DiagReceiver) {
2180 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2181 // it's not really unused.
2182 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2183 return;
2184
2185 // In C++, `_` variables behave as if they were maybe_unused
2186 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2187 return;
2188
2189 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2190
2191 if (Ty->isReferenceType() || Ty->isDependentType())
2192 return;
2193
2194 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2195 if (Tag->hasAttr<UnusedAttr>())
2196 return;
2197 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2198 // mimic gcc's behavior.
2199 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2200 RD && !RD->hasAttr<WarnUnusedAttr>())
2201 return;
2202 }
2203
2204 // Don't warn about __block Objective-C pointer variables, as they might
2205 // be assigned in the block but not used elsewhere for the purpose of lifetime
2206 // extension.
2207 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2208 return;
2209
2210 // Don't warn about Objective-C pointer variables with precise lifetime
2211 // semantics; they can be used to ensure ARC releases the object at a known
2212 // time, which may mean assignment but no other references.
2213 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2214 return;
2215
2216 auto iter = RefsMinusAssignments.find(VD);
2217 if (iter == RefsMinusAssignments.end())
2218 return;
2219
2220 assert(iter->getSecond() >= 0 &&
2221 "Found a negative number of references to a VarDecl");
2222 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2223 // Assume the given VarDecl is "used" if its ref count stored in
2224 // `RefMinusAssignments` is positive, with one exception.
2225 //
2226 // For a C++ variable whose decl (with initializer) entirely consist the
2227 // condition expression of a if/while/for construct,
2228 // Clang creates a DeclRefExpr for the condition expression rather than a
2229 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2230 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2231 // used in the body of the if/while/for construct.
2232 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2233 if (!UnusedCXXCondDecl)
2234 return;
2235 }
2236
2237 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2238 : diag::warn_unused_but_set_variable;
2239 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2240}
2241
2243 Sema::DiagReceiverTy DiagReceiver) {
2244 // Verify that we have no forward references left. If so, there was a goto
2245 // or address of a label taken, but no definition of it. Label fwd
2246 // definitions are indicated with a null substmt which is also not a resolved
2247 // MS inline assembly label name.
2248 bool Diagnose = false;
2249 if (L->isMSAsmLabel())
2250 Diagnose = !L->isResolvedMSAsmLabel();
2251 else
2252 Diagnose = L->getStmt() == nullptr;
2253 if (Diagnose)
2254 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2255 << L);
2256}
2257
2259 S->applyNRVO();
2260
2261 if (S->decl_empty()) return;
2263 "Scope shouldn't contain decls!");
2264
2265 /// We visit the decls in non-deterministic order, but we want diagnostics
2266 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2267 /// and sort the diagnostics before emitting them, after we visited all decls.
2268 struct LocAndDiag {
2269 SourceLocation Loc;
2270 std::optional<SourceLocation> PreviousDeclLoc;
2272 };
2274 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2275 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2276 };
2277 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2278 SourceLocation PreviousDeclLoc,
2279 PartialDiagnostic PD) {
2280 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2281 };
2282
2283 for (auto *TmpD : S->decls()) {
2284 assert(TmpD && "This decl didn't get pushed??");
2285
2286 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2287 NamedDecl *D = cast<NamedDecl>(TmpD);
2288
2289 // Diagnose unused variables in this scope.
2291 DiagnoseUnusedDecl(D, addDiag);
2292 if (const auto *RD = dyn_cast<RecordDecl>(D))
2293 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2294 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2295 DiagnoseUnusedButSetDecl(VD, addDiag);
2296 RefsMinusAssignments.erase(VD);
2297 }
2298 }
2299
2300 if (!D->getDeclName()) continue;
2301
2302 // If this was a forward reference to a label, verify it was defined.
2303 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2304 CheckPoppedLabel(LD, *this, addDiag);
2305
2306 // Partial translation units that are created in incremental processing must
2307 // not clean up the IdResolver because PTUs should take into account the
2308 // declarations that came from previous PTUs.
2309 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2311 IdResolver.RemoveDecl(D);
2312
2313 // Warn on it if we are shadowing a declaration.
2314 auto ShadowI = ShadowingDecls.find(D);
2315 if (ShadowI != ShadowingDecls.end()) {
2316 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2317 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2318 PDiag(diag::warn_ctor_parm_shadows_field)
2319 << D << FD << FD->getParent());
2320 }
2321 ShadowingDecls.erase(ShadowI);
2322 }
2323 }
2324
2325 llvm::sort(DeclDiags,
2326 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2327 // The particular order for diagnostics is not important, as long
2328 // as the order is deterministic. Using the raw location is going
2329 // to generally be in source order unless there are macro
2330 // expansions involved.
2331 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2332 });
2333 for (const LocAndDiag &D : DeclDiags) {
2334 Diag(D.Loc, D.PD);
2335 if (D.PreviousDeclLoc)
2336 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2337 }
2338}
2339
2341 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2342 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2343 (S->isClassScope() && !getLangOpts().CPlusPlus))
2344 S = S->getParent();
2345 return S;
2346}
2347
2348static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2350 switch (Error) {
2352 return "";
2354 return BuiltinInfo.getHeaderName(ID);
2356 return "stdio.h";
2358 return "setjmp.h";
2360 return "ucontext.h";
2361 }
2362 llvm_unreachable("unhandled error kind");
2363}
2364
2366 unsigned ID, SourceLocation Loc) {
2367 DeclContext *Parent = Context.getTranslationUnitDecl();
2368
2369 if (getLangOpts().CPlusPlus) {
2371 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2372 CLinkageDecl->setImplicit();
2373 Parent->addDecl(CLinkageDecl);
2374 Parent = CLinkageDecl;
2375 }
2376
2378 if (Context.BuiltinInfo.isImmediate(ID)) {
2379 assert(getLangOpts().CPlusPlus20 &&
2380 "consteval builtins should only be available in C++20 mode");
2381 ConstexprKind = ConstexprSpecKind::Consteval;
2382 }
2383
2385 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2386 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2387 Type->isFunctionProtoType(), ConstexprKind);
2388 New->setImplicit();
2389 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2390
2391 // Create Decl objects for each parameter, adding them to the
2392 // FunctionDecl.
2393 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2395 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2397 Context, New, SourceLocation(), SourceLocation(), nullptr,
2398 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2399 parm->setScopeInfo(0, i);
2400 Params.push_back(parm);
2401 }
2402 New->setParams(Params);
2403 }
2404
2406 return New;
2407}
2408
2410 Scope *S, bool ForRedeclaration,
2411 SourceLocation Loc) {
2413
2415 QualType R = Context.GetBuiltinType(ID, Error);
2416 if (Error) {
2417 if (!ForRedeclaration)
2418 return nullptr;
2419
2420 // If we have a builtin without an associated type we should not emit a
2421 // warning when we were not able to find a type for it.
2423 Context.BuiltinInfo.allowTypeMismatch(ID))
2424 return nullptr;
2425
2426 // If we could not find a type for setjmp it is because the jmp_buf type was
2427 // not defined prior to the setjmp declaration.
2429 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2430 << Context.BuiltinInfo.getName(ID);
2431 return nullptr;
2432 }
2433
2434 // Generally, we emit a warning that the declaration requires the
2435 // appropriate header.
2436 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2437 << getHeaderName(Context.BuiltinInfo, ID, Error)
2438 << Context.BuiltinInfo.getName(ID);
2439 return nullptr;
2440 }
2441
2442 if (!ForRedeclaration &&
2443 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2444 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2445 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2446 : diag::ext_implicit_lib_function_decl)
2447 << Context.BuiltinInfo.getName(ID) << R;
2448 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2449 Diag(Loc, diag::note_include_header_or_declare)
2450 << Header << Context.BuiltinInfo.getName(ID);
2451 }
2452
2453 if (R.isNull())
2454 return nullptr;
2455
2456 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2458
2459 // TUScope is the translation-unit scope to insert this function into.
2460 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2461 // relate Scopes to DeclContexts, and probably eliminate CurContext
2462 // entirely, but we're not there yet.
2463 DeclContext *SavedContext = CurContext;
2464 CurContext = New->getDeclContext();
2466 CurContext = SavedContext;
2467 return New;
2468}
2469
2470/// Typedef declarations don't have linkage, but they still denote the same
2471/// entity if their types are the same.
2472/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2473/// isSameEntity.
2474static void
2477 // This is only interesting when modules are enabled.
2478 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2479 return;
2480
2481 // Empty sets are uninteresting.
2482 if (Previous.empty())
2483 return;
2484
2485 LookupResult::Filter Filter = Previous.makeFilter();
2486 while (Filter.hasNext()) {
2487 NamedDecl *Old = Filter.next();
2488
2489 // Non-hidden declarations are never ignored.
2490 if (S.isVisible(Old))
2491 continue;
2492
2493 // Declarations of the same entity are not ignored, even if they have
2494 // different linkages.
2495 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2496 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2497 Decl->getUnderlyingType()))
2498 continue;
2499
2500 // If both declarations give a tag declaration a typedef name for linkage
2501 // purposes, then they declare the same entity.
2502 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2503 Decl->getAnonDeclWithTypedefName())
2504 continue;
2505 }
2506
2507 Filter.erase();
2508 }
2509
2510 Filter.done();
2511}
2512
2514 QualType OldType;
2515 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2516 OldType = OldTypedef->getUnderlyingType();
2517 else
2518 OldType = Context.getTypeDeclType(Old);
2519 QualType NewType = New->getUnderlyingType();
2520
2521 if (NewType->isVariablyModifiedType()) {
2522 // Must not redefine a typedef with a variably-modified type.
2523 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2524 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2525 << Kind << NewType;
2526 if (Old->getLocation().isValid())
2527 notePreviousDefinition(Old, New->getLocation());
2528 New->setInvalidDecl();
2529 return true;
2530 }
2531
2532 if (OldType != NewType &&
2533 !OldType->isDependentType() &&
2534 !NewType->isDependentType() &&
2535 !Context.hasSameType(OldType, NewType)) {
2536 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2537 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2538 << Kind << NewType << OldType;
2539 if (Old->getLocation().isValid())
2540 notePreviousDefinition(Old, New->getLocation());
2541 New->setInvalidDecl();
2542 return true;
2543 }
2544 return false;
2545}
2546
2548 LookupResult &OldDecls) {
2549 // If the new decl is known invalid already, don't bother doing any
2550 // merging checks.
2551 if (New->isInvalidDecl()) return;
2552
2553 // Allow multiple definitions for ObjC built-in typedefs.
2554 // FIXME: Verify the underlying types are equivalent!
2555 if (getLangOpts().ObjC) {
2556 const IdentifierInfo *TypeID = New->getIdentifier();
2557 switch (TypeID->getLength()) {
2558 default: break;
2559 case 2:
2560 {
2561 if (!TypeID->isStr("id"))
2562 break;
2563 QualType T = New->getUnderlyingType();
2564 if (!T->isPointerType())
2565 break;
2566 if (!T->isVoidPointerType()) {
2567 QualType PT = T->castAs<PointerType>()->getPointeeType();
2568 if (!PT->isStructureType())
2569 break;
2570 }
2571 Context.setObjCIdRedefinitionType(T);
2572 // Install the built-in type for 'id', ignoring the current definition.
2573 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2574 Context.getObjCIdType());
2575 return;
2576 }
2577 case 5:
2578 if (!TypeID->isStr("Class"))
2579 break;
2580 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2581 // Install the built-in type for 'Class', ignoring the current definition.
2582 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2583 Context.getObjCClassType());
2584 return;
2585 case 3:
2586 if (!TypeID->isStr("SEL"))
2587 break;
2588 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2589 // Install the built-in type for 'SEL', ignoring the current definition.
2590 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2591 Context.getObjCSelType());
2592 return;
2593 }
2594 // Fall through - the typedef name was not a builtin type.
2595 }
2596
2597 // Verify the old decl was also a type.
2598 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2599 if (!Old) {
2600 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2601 << New->getDeclName();
2602
2603 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2604 if (OldD->getLocation().isValid())
2605 notePreviousDefinition(OldD, New->getLocation());
2606
2607 return New->setInvalidDecl();
2608 }
2609
2610 // If the old declaration is invalid, just give up here.
2611 if (Old->isInvalidDecl())
2612 return New->setInvalidDecl();
2613
2614 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2615 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2616 auto *NewTag = New->getAnonDeclWithTypedefName();
2617 NamedDecl *Hidden = nullptr;
2618 if (OldTag && NewTag &&
2619 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2620 !hasVisibleDefinition(OldTag, &Hidden)) {
2621 // There is a definition of this tag, but it is not visible. Use it
2622 // instead of our tag.
2623 if (OldTD->isModed())
2624 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2625 OldTD->getUnderlyingType());
2626 else
2627 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2628
2629 // Make the old tag definition visible.
2631
2633 }
2634 }
2635
2636 // If the typedef types are not identical, reject them in all languages and
2637 // with any extensions enabled.
2638 if (isIncompatibleTypedef(Old, New))
2639 return;
2640
2641 // The types match. Link up the redeclaration chain and merge attributes if
2642 // the old declaration was a typedef.
2643 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2644 New->setPreviousDecl(Typedef);
2646 }
2647
2648 if (getLangOpts().MicrosoftExt)
2649 return;
2650
2651 if (getLangOpts().CPlusPlus) {
2652 // C++ [dcl.typedef]p2:
2653 // In a given non-class scope, a typedef specifier can be used to
2654 // redefine the name of any type declared in that scope to refer
2655 // to the type to which it already refers.
2657 return;
2658
2659 // C++0x [dcl.typedef]p4:
2660 // In a given class scope, a typedef specifier can be used to redefine
2661 // any class-name declared in that scope that is not also a typedef-name
2662 // to refer to the type to which it already refers.
2663 //
2664 // This wording came in via DR424, which was a correction to the
2665 // wording in DR56, which accidentally banned code like:
2666 //
2667 // struct S {
2668 // typedef struct A { } A;
2669 // };
2670 //
2671 // in the C++03 standard. We implement the C++0x semantics, which
2672 // allow the above but disallow
2673 //
2674 // struct S {
2675 // typedef int I;
2676 // typedef int I;
2677 // };
2678 //
2679 // since that was the intent of DR56.
2680 if (!isa<TypedefNameDecl>(Old))
2681 return;
2682
2683 Diag(New->getLocation(), diag::err_redefinition)
2684 << New->getDeclName();
2685 notePreviousDefinition(Old, New->getLocation());
2686 return New->setInvalidDecl();
2687 }
2688
2689 // Modules always permit redefinition of typedefs, as does C11.
2690 if (getLangOpts().Modules || getLangOpts().C11)
2691 return;
2692
2693 // If we have a redefinition of a typedef in C, emit a warning. This warning
2694 // is normally mapped to an error, but can be controlled with
2695 // -Wtypedef-redefinition. If either the original or the redefinition is
2696 // in a system header, don't emit this for compatibility with GCC.
2697 if (getDiagnostics().getSuppressSystemWarnings() &&
2698 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2699 (Old->isImplicit() ||
2700 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2701 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2702 return;
2703
2704 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2705 << New->getDeclName();
2706 notePreviousDefinition(Old, New->getLocation());
2707}
2708
2710 // If this was an unscoped enumeration, yank all of its enumerators
2711 // out of the scope.
2712 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2713 Scope *EnumScope = getNonFieldDeclScope(S);
2714 for (auto *ECD : ED->enumerators()) {
2715 assert(EnumScope->isDeclScope(ECD));
2716 EnumScope->RemoveDecl(ECD);
2717 IdResolver.RemoveDecl(ECD);
2718 }
2719 }
2720}
2721
2722/// DeclhasAttr - returns true if decl Declaration already has the target
2723/// attribute.
2724static bool DeclHasAttr(const Decl *D, const Attr *A) {
2725 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2726 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2727 for (const auto *i : D->attrs())
2728 if (i->getKind() == A->getKind()) {
2729 if (Ann) {
2730 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2731 return true;
2732 continue;
2733 }
2734 // FIXME: Don't hardcode this check
2735 if (OA && isa<OwnershipAttr>(i))
2736 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2737 return true;
2738 }
2739
2740 return false;
2741}
2742
2744 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2745 return VD->isThisDeclarationADefinition();
2746 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2747 return TD->isCompleteDefinition() || TD->isBeingDefined();
2748 return true;
2749}
2750
2751/// Merge alignment attributes from \p Old to \p New, taking into account the
2752/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2753///
2754/// \return \c true if any attributes were added to \p New.
2755static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2756 // Look for alignas attributes on Old, and pick out whichever attribute
2757 // specifies the strictest alignment requirement.
2758 AlignedAttr *OldAlignasAttr = nullptr;
2759 AlignedAttr *OldStrictestAlignAttr = nullptr;
2760 unsigned OldAlign = 0;
2761 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2762 // FIXME: We have no way of representing inherited dependent alignments
2763 // in a case like:
2764 // template<int A, int B> struct alignas(A) X;
2765 // template<int A, int B> struct alignas(B) X {};
2766 // For now, we just ignore any alignas attributes which are not on the
2767 // definition in such a case.
2768 if (I->isAlignmentDependent())
2769 return false;
2770
2771 if (I->isAlignas())
2772 OldAlignasAttr = I;
2773
2774 unsigned Align = I->getAlignment(S.Context);
2775 if (Align > OldAlign) {
2776 OldAlign = Align;
2777 OldStrictestAlignAttr = I;
2778 }
2779 }
2780
2781 // Look for alignas attributes on New.
2782 AlignedAttr *NewAlignasAttr = nullptr;
2783 unsigned NewAlign = 0;
2784 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2785 if (I->isAlignmentDependent())
2786 return false;
2787
2788 if (I->isAlignas())
2789 NewAlignasAttr = I;
2790
2791 unsigned Align = I->getAlignment(S.Context);
2792 if (Align > NewAlign)
2793 NewAlign = Align;
2794 }
2795
2796 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2797 // Both declarations have 'alignas' attributes. We require them to match.
2798 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2799 // fall short. (If two declarations both have alignas, they must both match
2800 // every definition, and so must match each other if there is a definition.)
2801
2802 // If either declaration only contains 'alignas(0)' specifiers, then it
2803 // specifies the natural alignment for the type.
2804 if (OldAlign == 0 || NewAlign == 0) {
2805 QualType Ty;
2806 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2807 Ty = VD->getType();
2808 else
2810
2811 if (OldAlign == 0)
2812 OldAlign = S.Context.getTypeAlign(Ty);
2813 if (NewAlign == 0)
2814 NewAlign = S.Context.getTypeAlign(Ty);
2815 }
2816
2817 if (OldAlign != NewAlign) {
2818 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2821 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2822 }
2823 }
2824
2825 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2826 // C++11 [dcl.align]p6:
2827 // if any declaration of an entity has an alignment-specifier,
2828 // every defining declaration of that entity shall specify an
2829 // equivalent alignment.
2830 // C11 6.7.5/7:
2831 // If the definition of an object does not have an alignment
2832 // specifier, any other declaration of that object shall also
2833 // have no alignment specifier.
2834 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2835 << OldAlignasAttr;
2836 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2837 << OldAlignasAttr;
2838 }
2839
2840 bool AnyAdded = false;
2841
2842 // Ensure we have an attribute representing the strictest alignment.
2843 if (OldAlign > NewAlign) {
2844 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2845 Clone->setInherited(true);
2846 New->addAttr(Clone);
2847 AnyAdded = true;
2848 }
2849
2850 // Ensure we have an alignas attribute if the old declaration had one.
2851 if (OldAlignasAttr && !NewAlignasAttr &&
2852 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2853 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2854 Clone->setInherited(true);
2855 New->addAttr(Clone);
2856 AnyAdded = true;
2857 }
2858
2859 return AnyAdded;
2860}
2861
2862#define WANT_DECL_MERGE_LOGIC
2863#include "clang/Sema/AttrParsedAttrImpl.inc"
2864#undef WANT_DECL_MERGE_LOGIC
2865
2867 const InheritableAttr *Attr,
2869 // Diagnose any mutual exclusions between the attribute that we want to add
2870 // and attributes that already exist on the declaration.
2871 if (!DiagnoseMutualExclusions(S, D, Attr))
2872 return false;
2873
2874 // This function copies an attribute Attr from a previous declaration to the
2875 // new declaration D if the new declaration doesn't itself have that attribute
2876 // yet or if that attribute allows duplicates.
2877 // If you're adding a new attribute that requires logic different from
2878 // "use explicit attribute on decl if present, else use attribute from
2879 // previous decl", for example if the attribute needs to be consistent
2880 // between redeclarations, you need to call a custom merge function here.
2881 InheritableAttr *NewAttr = nullptr;
2882 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2883 NewAttr = S.mergeAvailabilityAttr(
2884 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2885 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2886 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2887 AA->getPriority(), AA->getEnvironment());
2888 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2889 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2890 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2891 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2892 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2893 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2894 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2895 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2896 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2897 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2898 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2899 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2900 FA->getFirstArg());
2901 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2902 NewAttr = S.mergeFormatMatchesAttr(
2903 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2904 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2905 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2906 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2907 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2908 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2909 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2910 IA->getInheritanceModel());
2911 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2912 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2913 &S.Context.Idents.get(AA->getSpelling()));
2914 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2917 // CUDA target attributes are part of function signature for
2918 // overloading purposes and must not be merged.
2919 return false;
2920 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2921 NewAttr = S.mergeMinSizeAttr(D, *MA);
2922 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2923 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2924 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2925 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2926 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2927 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2928 else if (isa<AlignedAttr>(Attr))
2929 // AlignedAttrs are handled separately, because we need to handle all
2930 // such attributes on a declaration at the same time.
2931 NewAttr = nullptr;
2936 NewAttr = nullptr;
2937 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2938 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2939 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2940 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2941 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2942 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2943 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2944 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2945 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2946 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2947 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2948 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2949 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2950 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2951 NT->getZ());
2952 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2953 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2954 WS->getPreferred(),
2955 WS->getSpelledArgsCount());
2956 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
2957 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
2958 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2959 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2960 else if (isa<SuppressAttr>(Attr))
2961 // Do nothing. Each redeclaration should be suppressed separately.
2962 NewAttr = nullptr;
2963 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
2964 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
2965 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2966 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2967
2968 if (NewAttr) {
2969 NewAttr->setInherited(true);
2970 D->addAttr(NewAttr);
2971 if (isa<MSInheritanceAttr>(NewAttr))
2973 return true;
2974 }
2975
2976 return false;
2977}
2978
2979static const NamedDecl *getDefinition(const Decl *D) {
2980 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
2981 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
2982 return Def;
2983 return nullptr;
2984 }
2985 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2986 const VarDecl *Def = VD->getDefinition();
2987 if (Def)
2988 return Def;
2989 return VD->getActingDefinition();
2990 }
2991 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2992 const FunctionDecl *Def = nullptr;
2993 if (FD->isDefined(Def, true))
2994 return Def;
2995 }
2996 return nullptr;
2997}
2998
2999static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3000 for (const auto *Attribute : D->attrs())
3001 if (Attribute->getKind() == Kind)
3002 return true;
3003 return false;
3004}
3005
3006/// checkNewAttributesAfterDef - If we already have a definition, check that
3007/// there are no new attributes in this declaration.
3008static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3009 if (!New->hasAttrs())
3010 return;
3011
3012 const NamedDecl *Def = getDefinition(Old);
3013 if (!Def || Def == New)
3014 return;
3015
3016 AttrVec &NewAttributes = New->getAttrs();
3017 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3018 Attr *NewAttribute = NewAttributes[I];
3019
3020 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3021 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3022 SkipBodyInfo SkipBody;
3023 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3024
3025 // If we're skipping this definition, drop the "alias" attribute.
3026 if (SkipBody.ShouldSkip) {
3027 NewAttributes.erase(NewAttributes.begin() + I);
3028 --E;
3029 continue;
3030 }
3031 } else {
3032 VarDecl *VD = cast<VarDecl>(New);
3033 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3035 ? diag::err_alias_after_tentative
3036 : diag::err_redefinition;
3037 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3038 if (Diag == diag::err_redefinition)
3039 S.notePreviousDefinition(Def, VD->getLocation());
3040 else
3041 S.Diag(Def->getLocation(), diag::note_previous_definition);
3042 VD->setInvalidDecl();
3043 }
3044 ++I;
3045 continue;
3046 }
3047
3048 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3049 // Tentative definitions are only interesting for the alias check above.
3050 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3051 ++I;
3052 continue;
3053 }
3054 }
3055
3056 if (hasAttribute(Def, NewAttribute->getKind())) {
3057 ++I;
3058 continue; // regular attr merging will take care of validating this.
3059 }
3060
3061 if (isa<C11NoReturnAttr>(NewAttribute)) {
3062 // C's _Noreturn is allowed to be added to a function after it is defined.
3063 ++I;
3064 continue;
3065 } else if (isa<UuidAttr>(NewAttribute)) {
3066 // msvc will allow a subsequent definition to add an uuid to a class
3067 ++I;
3068 continue;
3070 NewAttribute) &&
3071 NewAttribute->isStandardAttributeSyntax()) {
3072 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3073 // deprecated attribute can later be re-declared with the attribute and
3074 // vice-versa.
3075 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3076 // maybe_unused attribute can later be redeclared with the attribute and
3077 // vice versa.
3078 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3079 // nodiscard attribute can later be redeclared with the attribute and
3080 // vice-versa.
3081 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3082 ++I;
3083 continue;
3084 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3085 if (AA->isAlignas()) {
3086 // C++11 [dcl.align]p6:
3087 // if any declaration of an entity has an alignment-specifier,
3088 // every defining declaration of that entity shall specify an
3089 // equivalent alignment.
3090 // C11 6.7.5/7:
3091 // If the definition of an object does not have an alignment
3092 // specifier, any other declaration of that object shall also
3093 // have no alignment specifier.
3094 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3095 << AA;
3096 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3097 << AA;
3098 NewAttributes.erase(NewAttributes.begin() + I);
3099 --E;
3100 continue;
3101 }
3102 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3103 // If there is a C definition followed by a redeclaration with this
3104 // attribute then there are two different definitions. In C++, prefer the
3105 // standard diagnostics.
3106 if (!S.getLangOpts().CPlusPlus) {
3107 S.Diag(NewAttribute->getLocation(),
3108 diag::err_loader_uninitialized_redeclaration);
3109 S.Diag(Def->getLocation(), diag::note_previous_definition);
3110 NewAttributes.erase(NewAttributes.begin() + I);
3111 --E;
3112 continue;
3113 }
3114 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3115 cast<VarDecl>(New)->isInline() &&
3116 !cast<VarDecl>(New)->isInlineSpecified()) {
3117 // Don't warn about applying selectany to implicitly inline variables.
3118 // Older compilers and language modes would require the use of selectany
3119 // to make such variables inline, and it would have no effect if we
3120 // honored it.
3121 ++I;
3122 continue;
3123 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3124 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3125 // declarations after definitions.
3126 ++I;
3127 continue;
3128 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3129 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3130 // error since the definition will have already been created without
3131 // the semantic effects of the attribute having been applied.
3132 S.Diag(NewAttribute->getLocation(),
3133 diag::err_sycl_entry_point_after_definition)
3134 << NewAttribute;
3135 S.Diag(Def->getLocation(), diag::note_previous_definition);
3136 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3137 ++I;
3138 continue;
3139 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3140 // SYCLExternalAttr may be added after a definition.
3141 ++I;
3142 continue;
3143 }
3144
3145 S.Diag(NewAttribute->getLocation(),
3146 diag::warn_attribute_precede_definition);
3147 S.Diag(Def->getLocation(), diag::note_previous_definition);
3148 NewAttributes.erase(NewAttributes.begin() + I);
3149 --E;
3150 }
3151}
3152
3153static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3154 const ConstInitAttr *CIAttr,
3155 bool AttrBeforeInit) {
3156 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3157
3158 // Figure out a good way to write this specifier on the old declaration.
3159 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3160 // enough of the attribute list spelling information to extract that without
3161 // heroics.
3162 std::string SuitableSpelling;
3163 if (S.getLangOpts().CPlusPlus20)
3164 SuitableSpelling = std::string(
3165 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3166 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3167 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3168 InsertLoc, {tok::l_square, tok::l_square,
3169 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3170 S.PP.getIdentifierInfo("require_constant_initialization"),
3171 tok::r_square, tok::r_square}));
3172 if (SuitableSpelling.empty())
3173 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3174 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3175 S.PP.getIdentifierInfo("require_constant_initialization"),
3176 tok::r_paren, tok::r_paren}));
3177 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3178 SuitableSpelling = "constinit";
3179 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3180 SuitableSpelling = "[[clang::require_constant_initialization]]";
3181 if (SuitableSpelling.empty())
3182 SuitableSpelling = "__attribute__((require_constant_initialization))";
3183 SuitableSpelling += " ";
3184
3185 if (AttrBeforeInit) {
3186 // extern constinit int a;
3187 // int a = 0; // error (missing 'constinit'), accepted as extension
3188 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3189 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3190 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3191 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3192 } else {
3193 // int a = 0;
3194 // constinit extern int a; // error (missing 'constinit')
3195 S.Diag(CIAttr->getLocation(),
3196 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3197 : diag::warn_require_const_init_added_too_late)
3198 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3199 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3200 << CIAttr->isConstinit()
3201 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3202 }
3203}
3204
3207 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3208 UsedAttr *NewAttr = OldAttr->clone(Context);
3209 NewAttr->setInherited(true);
3210 New->addAttr(NewAttr);
3211 }
3212 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3213 RetainAttr *NewAttr = OldAttr->clone(Context);
3214 NewAttr->setInherited(true);
3215 New->addAttr(NewAttr);
3216 }
3217
3218 if (!Old->hasAttrs() && !New->hasAttrs())
3219 return;
3220
3221 // [dcl.constinit]p1:
3222 // If the [constinit] specifier is applied to any declaration of a
3223 // variable, it shall be applied to the initializing declaration.
3224 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3225 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3226 if (bool(OldConstInit) != bool(NewConstInit)) {
3227 const auto *OldVD = cast<VarDecl>(Old);
3228 auto *NewVD = cast<VarDecl>(New);
3229
3230 // Find the initializing declaration. Note that we might not have linked
3231 // the new declaration into the redeclaration chain yet.
3232 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3233 if (!InitDecl &&
3234 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3235 InitDecl = NewVD;
3236
3237 if (InitDecl == NewVD) {
3238 // This is the initializing declaration. If it would inherit 'constinit',
3239 // that's ill-formed. (Note that we do not apply this to the attribute
3240 // form).
3241 if (OldConstInit && OldConstInit->isConstinit())
3242 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3243 /*AttrBeforeInit=*/true);
3244 } else if (NewConstInit) {
3245 // This is the first time we've been told that this declaration should
3246 // have a constant initializer. If we already saw the initializing
3247 // declaration, this is too late.
3248 if (InitDecl && InitDecl != NewVD) {
3249 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3250 /*AttrBeforeInit=*/false);
3251 NewVD->dropAttr<ConstInitAttr>();
3252 }
3253 }
3254 }
3255
3256 // Attributes declared post-definition are currently ignored.
3257 checkNewAttributesAfterDef(*this, New, Old);
3258
3259 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3260 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3261 if (!OldA->isEquivalent(NewA)) {
3262 // This redeclaration changes __asm__ label.
3263 Diag(New->getLocation(), diag::err_different_asm_label);
3264 Diag(OldA->getLocation(), diag::note_previous_declaration);
3265 }
3266 } else if (Old->isUsed()) {
3267 // This redeclaration adds an __asm__ label to a declaration that has
3268 // already been ODR-used.
3269 Diag(New->getLocation(), diag::err_late_asm_label_name)
3270 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3271 }
3272 }
3273
3274 // Re-declaration cannot add abi_tag's.
3275 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3276 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3277 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3278 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3279 Diag(NewAbiTagAttr->getLocation(),
3280 diag::err_new_abi_tag_on_redeclaration)
3281 << NewTag;
3282 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3283 }
3284 }
3285 } else {
3286 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3287 Diag(Old->getLocation(), diag::note_previous_declaration);
3288 }
3289 }
3290
3291 // This redeclaration adds a section attribute.
3292 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3293 if (auto *VD = dyn_cast<VarDecl>(New)) {
3294 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3295 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3296 Diag(Old->getLocation(), diag::note_previous_declaration);
3297 }
3298 }
3299 }
3300
3301 // Redeclaration adds code-seg attribute.
3302 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3303 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3304 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3305 Diag(New->getLocation(), diag::warn_mismatched_section)
3306 << 0 /*codeseg*/;
3307 Diag(Old->getLocation(), diag::note_previous_declaration);
3308 }
3309
3310 if (!Old->hasAttrs())
3311 return;
3312
3313 bool foundAny = New->hasAttrs();
3314
3315 // Ensure that any moving of objects within the allocated map is done before
3316 // we process them.
3317 if (!foundAny) New->setAttrs(AttrVec());
3318
3319 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3320 // Ignore deprecated/unavailable/availability attributes if requested.
3322 if (isa<DeprecatedAttr>(I) ||
3325 switch (AMK) {
3327 continue;
3328
3333 LocalAMK = AMK;
3334 break;
3335 }
3336 }
3337
3338 // Already handled.
3339 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3340 continue;
3341
3343 if (auto *FD = dyn_cast<FunctionDecl>(New);
3344 FD &&
3345 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3346 continue; // Don't propagate inferred noreturn attributes to explicit
3347 }
3348
3349 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3350 foundAny = true;
3351 }
3352
3353 if (mergeAlignedAttrs(*this, New, Old))
3354 foundAny = true;
3355
3356 if (!foundAny) New->dropAttrs();
3357}
3358
3360 for (const Attr *A : D->attrs())
3361 checkAttrIsTypeDependent(D, A);
3362}
3363
3364// Returns the number of added attributes.
3365template <class T>
3366static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3367 Sema &S) {
3368 unsigned found = 0;
3369 for (const auto *I : From->specific_attrs<T>()) {
3370 if (!DeclHasAttr(To, I)) {
3371 T *newAttr = cast<T>(I->clone(S.Context));
3372 newAttr->setInherited(true);
3373 To->addAttr(newAttr);
3374 ++found;
3375 }
3376 }
3377 return found;
3378}
3379
3380template <class F>
3381static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3382 F &&propagator) {
3383 if (!From->hasAttrs()) {
3384 return;
3385 }
3386
3387 bool foundAny = To->hasAttrs();
3388
3389 // Ensure that any moving of objects within the allocated map is
3390 // done before we process them.
3391 if (!foundAny)
3392 To->setAttrs(AttrVec());
3393
3394 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3395
3396 if (!foundAny)
3397 To->dropAttrs();
3398}
3399
3400/// mergeParamDeclAttributes - Copy attributes from the old parameter
3401/// to the new one.
3403 const ParmVarDecl *oldDecl,
3404 Sema &S) {
3405 // C++11 [dcl.attr.depend]p2:
3406 // The first declaration of a function shall specify the
3407 // carries_dependency attribute for its declarator-id if any declaration
3408 // of the function specifies the carries_dependency attribute.
3409 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3410 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3411 S.Diag(CDA->getLocation(),
3412 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3413 // Find the first declaration of the parameter.
3414 // FIXME: Should we build redeclaration chains for function parameters?
3415 const FunctionDecl *FirstFD =
3416 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3417 const ParmVarDecl *FirstVD =
3418 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3419 S.Diag(FirstVD->getLocation(),
3420 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3421 }
3422
3424 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3425 unsigned found = 0;
3426 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3427 // Propagate the lifetimebound attribute from parameters to the
3428 // most recent declaration. Note that this doesn't include the implicit
3429 // 'this' parameter, as the attribute is applied to the function type in
3430 // that case.
3431 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3432 return found;
3433 });
3434}
3435
3437 const ASTContext &Ctx) {
3438
3439 auto NoSizeInfo = [&Ctx](QualType Ty) {
3440 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3441 return true;
3442 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3443 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3444 return false;
3445 };
3446
3447 // `type[]` is equivalent to `type *` and `type[*]`.
3448 if (NoSizeInfo(Old) && NoSizeInfo(New))
3449 return true;
3450
3451 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3452 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3453 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3454 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3455 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3456 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3457 return false;
3458 return true;
3459 }
3460
3461 // Only compare size, ignore Size modifiers and CVR.
3462 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3463 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3465 }
3466
3467 // Don't try to compare dependent sized array
3468 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3469 return true;
3470 }
3471
3472 return Old == New;
3473}
3474
3475static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3476 const ParmVarDecl *OldParam,
3477 Sema &S) {
3478 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3479 if (auto Newnullability = NewParam->getType()->getNullability()) {
3480 if (*Oldnullability != *Newnullability) {
3481 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3483 *Newnullability,
3485 != 0))
3487 *Oldnullability,
3489 != 0));
3490 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3491 }
3492 } else {
3493 QualType NewT = NewParam->getType();
3494 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3495 NewParam->setType(NewT);
3496 }
3497 }
3498 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3499 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3500 if (OldParamDT && NewParamDT &&
3501 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3502 QualType OldParamOT = OldParamDT->getOriginalType();
3503 QualType NewParamOT = NewParamDT->getOriginalType();
3504 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3505 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3506 << NewParam << NewParamOT;
3507 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3508 << OldParamOT;
3509 }
3510 }
3511}
3512
3513namespace {
3514
3515/// Used in MergeFunctionDecl to keep track of function parameters in
3516/// C.
3517struct GNUCompatibleParamWarning {
3518 ParmVarDecl *OldParm;
3519 ParmVarDecl *NewParm;
3520 QualType PromotedType;
3521};
3522
3523} // end anonymous namespace
3524
3525// Determine whether the previous declaration was a definition, implicit
3526// declaration, or a declaration.
3527template <typename T>
3528static std::pair<diag::kind, SourceLocation>
3530 diag::kind PrevDiag;
3531 SourceLocation OldLocation = Old->getLocation();
3532 if (Old->isThisDeclarationADefinition())
3533 PrevDiag = diag::note_previous_definition;
3534 else if (Old->isImplicit()) {
3535 PrevDiag = diag::note_previous_implicit_declaration;
3536 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3537 if (FD->getBuiltinID())
3538 PrevDiag = diag::note_previous_builtin_declaration;
3539 }
3540 if (OldLocation.isInvalid())
3541 OldLocation = New->getLocation();
3542 } else
3543 PrevDiag = diag::note_previous_declaration;
3544 return std::make_pair(PrevDiag, OldLocation);
3545}
3546
3547/// canRedefineFunction - checks if a function can be redefined. Currently,
3548/// only extern inline functions can be redefined, and even then only in
3549/// GNU89 mode.
3550static bool canRedefineFunction(const FunctionDecl *FD,
3551 const LangOptions& LangOpts) {
3552 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3553 !LangOpts.CPlusPlus &&
3554 FD->isInlineSpecified() &&
3555 FD->getStorageClass() == SC_Extern);
3556}
3557
3558const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3559 const AttributedType *AT = T->getAs<AttributedType>();
3560 while (AT && !AT->isCallingConv())
3561 AT = AT->getModifiedType()->getAs<AttributedType>();
3562 return AT;
3563}
3564
3565template <typename T>
3566static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3567 const DeclContext *DC = Old->getDeclContext();
3568 if (DC->isRecord())
3569 return false;
3570
3571 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3572 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3573 return true;
3574 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3575 return true;
3576 return false;
3577}
3578
3579template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3580static bool isExternC(VarTemplateDecl *) { return false; }
3581static bool isExternC(FunctionTemplateDecl *) { return false; }
3582
3583/// Check whether a redeclaration of an entity introduced by a
3584/// using-declaration is valid, given that we know it's not an overload
3585/// (nor a hidden tag declaration).
3586template<typename ExpectedDecl>
3588 ExpectedDecl *New) {
3589 // C++11 [basic.scope.declarative]p4:
3590 // Given a set of declarations in a single declarative region, each of
3591 // which specifies the same unqualified name,
3592 // -- they shall all refer to the same entity, or all refer to functions
3593 // and function templates; or
3594 // -- exactly one declaration shall declare a class name or enumeration
3595 // name that is not a typedef name and the other declarations shall all
3596 // refer to the same variable or enumerator, or all refer to functions
3597 // and function templates; in this case the class name or enumeration
3598 // name is hidden (3.3.10).
3599
3600 // C++11 [namespace.udecl]p14:
3601 // If a function declaration in namespace scope or block scope has the
3602 // same name and the same parameter-type-list as a function introduced
3603 // by a using-declaration, and the declarations do not declare the same
3604 // function, the program is ill-formed.
3605
3606 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3607 if (Old &&
3608 !Old->getDeclContext()->getRedeclContext()->Equals(
3609 New->getDeclContext()->getRedeclContext()) &&
3610 !(isExternC(Old) && isExternC(New)))
3611 Old = nullptr;
3612
3613 if (!Old) {
3614 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3615 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3616 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3617 return true;
3618 }
3619 return false;
3620}
3621
3623 const FunctionDecl *B) {
3624 assert(A->getNumParams() == B->getNumParams());
3625
3626 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3627 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3628 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3629 if (AttrA == AttrB)
3630 return true;
3631 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3632 AttrA->isDynamic() == AttrB->isDynamic();
3633 };
3634
3635 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3636}
3637
3638/// If necessary, adjust the semantic declaration context for a qualified
3639/// declaration to name the correct inline namespace within the qualifier.
3641 DeclaratorDecl *OldD) {
3642 // The only case where we need to update the DeclContext is when
3643 // redeclaration lookup for a qualified name finds a declaration
3644 // in an inline namespace within the context named by the qualifier:
3645 //
3646 // inline namespace N { int f(); }
3647 // int ::f(); // Sema DC needs adjusting from :: to N::.
3648 //
3649 // For unqualified declarations, the semantic context *can* change
3650 // along the redeclaration chain (for local extern declarations,
3651 // extern "C" declarations, and friend declarations in particular).
3652 if (!NewD->getQualifier())
3653 return;
3654
3655 // NewD is probably already in the right context.
3656 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3657 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3658 if (NamedDC->Equals(SemaDC))
3659 return;
3660
3661 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3662 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3663 "unexpected context for redeclaration");
3664
3665 auto *LexDC = NewD->getLexicalDeclContext();
3666 auto FixSemaDC = [=](NamedDecl *D) {
3667 if (!D)
3668 return;
3669 D->setDeclContext(SemaDC);
3670 D->setLexicalDeclContext(LexDC);
3671 };
3672
3673 FixSemaDC(NewD);
3674 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3675 FixSemaDC(FD->getDescribedFunctionTemplate());
3676 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3677 FixSemaDC(VD->getDescribedVarTemplate());
3678}
3679
3681 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3682 // Verify the old decl was also a function.
3683 FunctionDecl *Old = OldD->getAsFunction();
3684 if (!Old) {
3685 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3686 // We don't need to check the using friend pattern from other module unit
3687 // since we should have diagnosed such cases in its unit already.
3688 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3689 Diag(New->getLocation(), diag::err_using_decl_friend);
3690 Diag(Shadow->getTargetDecl()->getLocation(),
3691 diag::note_using_decl_target);
3692 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3693 << 0;
3694 return true;
3695 }
3696
3697 // Check whether the two declarations might declare the same function or
3698 // function template.
3699 if (FunctionTemplateDecl *NewTemplate =
3700 New->getDescribedFunctionTemplate()) {
3702 NewTemplate))
3703 return true;
3704 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3705 ->getAsFunction();
3706 } else {
3707 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3708 return true;
3709 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3710 }
3711 } else {
3712 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3713 << New->getDeclName();
3714 notePreviousDefinition(OldD, New->getLocation());
3715 return true;
3716 }
3717 }
3718
3719 // If the old declaration was found in an inline namespace and the new
3720 // declaration was qualified, update the DeclContext to match.
3722
3723 // If the old declaration is invalid, just give up here.
3724 if (Old->isInvalidDecl())
3725 return true;
3726
3727 // Disallow redeclaration of some builtins.
3728 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3729 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3730 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3731 << Old << Old->getType();
3732 return true;
3733 }
3734
3735 diag::kind PrevDiag;
3736 SourceLocation OldLocation;
3737 std::tie(PrevDiag, OldLocation) =
3739
3740 // Don't complain about this if we're in GNU89 mode and the old function
3741 // is an extern inline function.
3742 // Don't complain about specializations. They are not supposed to have
3743 // storage classes.
3744 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3745 New->getStorageClass() == SC_Static &&
3746 Old->hasExternalFormalLinkage() &&
3747 !New->getTemplateSpecializationInfo() &&
3749 if (getLangOpts().MicrosoftExt) {
3750 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3751 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3752 } else {
3753 Diag(New->getLocation(), diag::err_static_non_static) << New;
3754 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3755 return true;
3756 }
3757 }
3758
3759 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3760 if (!Old->hasAttr<InternalLinkageAttr>()) {
3761 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3762 << ILA;
3763 Diag(Old->getLocation(), diag::note_previous_declaration);
3764 New->dropAttr<InternalLinkageAttr>();
3765 }
3766
3767 if (auto *EA = New->getAttr<ErrorAttr>()) {
3768 if (!Old->hasAttr<ErrorAttr>()) {
3769 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3770 Diag(Old->getLocation(), diag::note_previous_declaration);
3771 New->dropAttr<ErrorAttr>();
3772 }
3773 }
3774
3776 return true;
3777
3778 if (!getLangOpts().CPlusPlus) {
3779 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3780 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3781 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3782 << New << OldOvl;
3783
3784 // Try our best to find a decl that actually has the overloadable
3785 // attribute for the note. In most cases (e.g. programs with only one
3786 // broken declaration/definition), this won't matter.
3787 //
3788 // FIXME: We could do this if we juggled some extra state in
3789 // OverloadableAttr, rather than just removing it.
3790 const Decl *DiagOld = Old;
3791 if (OldOvl) {
3792 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3793 const auto *A = D->getAttr<OverloadableAttr>();
3794 return A && !A->isImplicit();
3795 });
3796 // If we've implicitly added *all* of the overloadable attrs to this
3797 // chain, emitting a "previous redecl" note is pointless.
3798 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3799 }
3800
3801 if (DiagOld)
3802 Diag(DiagOld->getLocation(),
3803 diag::note_attribute_overloadable_prev_overload)
3804 << OldOvl;
3805
3806 if (OldOvl)
3807 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3808 else
3809 New->dropAttr<OverloadableAttr>();
3810 }
3811 }
3812
3813 // It is not permitted to redeclare an SME function with different SME
3814 // attributes.
3815 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3816 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3817 << New->getType() << Old->getType();
3818 Diag(OldLocation, diag::note_previous_declaration);
3819 return true;
3820 }
3821
3822 // If a function is first declared with a calling convention, but is later
3823 // declared or defined without one, all following decls assume the calling
3824 // convention of the first.
3825 //
3826 // It's OK if a function is first declared without a calling convention,
3827 // but is later declared or defined with the default calling convention.
3828 //
3829 // To test if either decl has an explicit calling convention, we look for
3830 // AttributedType sugar nodes on the type as written. If they are missing or
3831 // were canonicalized away, we assume the calling convention was implicit.
3832 //
3833 // Note also that we DO NOT return at this point, because we still have
3834 // other tests to run.
3835 QualType OldQType = Context.getCanonicalType(Old->getType());
3836 QualType NewQType = Context.getCanonicalType(New->getType());
3837 const FunctionType *OldType = cast<FunctionType>(OldQType);
3838 const FunctionType *NewType = cast<FunctionType>(NewQType);
3839 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3840 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3841 bool RequiresAdjustment = false;
3842
3843 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3845 const FunctionType *FT =
3846 First->getType().getCanonicalType()->castAs<FunctionType>();
3848 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3849 if (!NewCCExplicit) {
3850 // Inherit the CC from the previous declaration if it was specified
3851 // there but not here.
3852 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3853 RequiresAdjustment = true;
3854 } else if (Old->getBuiltinID()) {
3855 // Builtin attribute isn't propagated to the new one yet at this point,
3856 // so we check if the old one is a builtin.
3857
3858 // Calling Conventions on a Builtin aren't really useful and setting a
3859 // default calling convention and cdecl'ing some builtin redeclarations is
3860 // common, so warn and ignore the calling convention on the redeclaration.
3861 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3862 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3864 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3865 RequiresAdjustment = true;
3866 } else {
3867 // Calling conventions aren't compatible, so complain.
3868 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3869 Diag(New->getLocation(), diag::err_cconv_change)
3870 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3871 << !FirstCCExplicit
3872 << (!FirstCCExplicit ? "" :
3874
3875 // Put the note on the first decl, since it is the one that matters.
3876 Diag(First->getLocation(), diag::note_previous_declaration);
3877 return true;
3878 }
3879 }
3880
3881 // FIXME: diagnose the other way around?
3882 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3883 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3884 RequiresAdjustment = true;
3885 }
3886
3887 // If the declaration is marked with cfi_unchecked_callee but the definition
3888 // isn't, the definition is also cfi_unchecked_callee.
3889 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3890 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3891 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3892 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3893
3894 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3895 EPI2.CFIUncheckedCallee = true;
3896 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3897 FPT2->getParamTypes(), EPI2);
3898 NewType = cast<FunctionType>(NewQType);
3899 New->setType(NewQType);
3900 }
3901 }
3902 }
3903
3904 // Merge regparm attribute.
3905 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3906 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3907 if (NewTypeInfo.getHasRegParm()) {
3908 Diag(New->getLocation(), diag::err_regparm_mismatch)
3909 << NewType->getRegParmType()
3910 << OldType->getRegParmType();
3911 Diag(OldLocation, diag::note_previous_declaration);
3912 return true;
3913 }
3914
3915 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3916 RequiresAdjustment = true;
3917 }
3918
3919 // Merge ns_returns_retained attribute.
3920 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3921 if (NewTypeInfo.getProducesResult()) {
3922 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3923 << "'ns_returns_retained'";
3924 Diag(OldLocation, diag::note_previous_declaration);
3925 return true;
3926 }
3927
3928 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3929 RequiresAdjustment = true;
3930 }
3931
3932 if (OldTypeInfo.getNoCallerSavedRegs() !=
3933 NewTypeInfo.getNoCallerSavedRegs()) {
3934 if (NewTypeInfo.getNoCallerSavedRegs()) {
3935 AnyX86NoCallerSavedRegistersAttr *Attr =
3936 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3937 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3938 Diag(OldLocation, diag::note_previous_declaration);
3939 return true;
3940 }
3941
3942 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3943 RequiresAdjustment = true;
3944 }
3945
3946 if (RequiresAdjustment) {
3947 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3948 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3949 New->setType(QualType(AdjustedType, 0));
3950 NewQType = Context.getCanonicalType(New->getType());
3951 }
3952
3953 // If this redeclaration makes the function inline, we may need to add it to
3954 // UndefinedButUsed.
3955 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3956 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
3957 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3958 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3959 SourceLocation()));
3960
3961 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3962 // about it.
3963 if (New->hasAttr<GNUInlineAttr>() &&
3964 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3965 UndefinedButUsed.erase(Old->getCanonicalDecl());
3966 }
3967
3968 // If pass_object_size params don't match up perfectly, this isn't a valid
3969 // redeclaration.
3970 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3972 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3973 << New->getDeclName();
3974 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3975 return true;
3976 }
3977
3978 QualType OldQTypeForComparison = OldQType;
3979 if (Context.hasAnyFunctionEffects()) {
3980 const auto OldFX = Old->getFunctionEffects();
3981 const auto NewFX = New->getFunctionEffects();
3982 if (OldFX != NewFX) {
3983 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3984 for (const auto &Diff : Diffs) {
3985 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3986 Diag(New->getLocation(),
3987 diag::warn_mismatched_func_effect_redeclaration)
3988 << Diff.effectName();
3989 Diag(Old->getLocation(), diag::note_previous_declaration);
3990 }
3991 }
3992 // Following a warning, we could skip merging effects from the previous
3993 // declaration, but that would trigger an additional "conflicting types"
3994 // error.
3995 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3997 FunctionEffectSet MergedFX =
3998 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3999 if (!MergeErrs.empty())
4000 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
4001 Old->getLocation());
4002
4003 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4004 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4005 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
4006 NewFPT->getParamTypes(), EPI);
4007
4008 New->setType(ModQT);
4009 NewQType = New->getType();
4010
4011 // Revise OldQTForComparison to include the merged effects,
4012 // so as not to fail due to differences later.
4013 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4014 EPI = OldFPT->getExtProtoInfo();
4015 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4016 OldQTypeForComparison = Context.getFunctionType(
4017 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4018 }
4019 if (OldFX.empty()) {
4020 // A redeclaration may add the attribute to a previously seen function
4021 // body which needs to be verified.
4022 maybeAddDeclWithEffects(Old, MergedFX);
4023 }
4024 }
4025 }
4026 }
4027
4028 if (getLangOpts().CPlusPlus) {
4029 OldQType = Context.getCanonicalType(Old->getType());
4030 NewQType = Context.getCanonicalType(New->getType());
4031
4032 // Go back to the type source info to compare the declared return types,
4033 // per C++1y [dcl.type.auto]p13:
4034 // Redeclarations or specializations of a function or function template
4035 // with a declared return type that uses a placeholder type shall also
4036 // use that placeholder, not a deduced type.
4037 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4038 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4039 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4040 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4041 OldDeclaredReturnType)) {
4042 QualType ResQT;
4043 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4044 OldDeclaredReturnType->isObjCObjectPointerType())
4045 // FIXME: This does the wrong thing for a deduced return type.
4046 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4047 if (ResQT.isNull()) {
4048 if (New->isCXXClassMember() && New->isOutOfLine())
4049 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4050 << New << New->getReturnTypeSourceRange();
4051 else if (Old->isExternC() && New->isExternC() &&
4052 !Old->hasAttr<OverloadableAttr>() &&
4053 !New->hasAttr<OverloadableAttr>())
4054 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4055 else
4056 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4057 << New->getReturnTypeSourceRange();
4058 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4059 << Old->getReturnTypeSourceRange();
4060 return true;
4061 }
4062 else
4063 NewQType = ResQT;
4064 }
4065
4066 QualType OldReturnType = OldType->getReturnType();
4067 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4068 if (OldReturnType != NewReturnType) {
4069 // If this function has a deduced return type and has already been
4070 // defined, copy the deduced value from the old declaration.
4071 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4072 if (OldAT && OldAT->isDeduced()) {
4073 QualType DT = OldAT->getDeducedType();
4074 if (DT.isNull()) {
4075 New->setType(SubstAutoTypeDependent(New->getType()));
4076 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4077 } else {
4078 New->setType(SubstAutoType(New->getType(), DT));
4079 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4080 }
4081 }
4082 }
4083
4084 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4085 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4086 if (OldMethod && NewMethod) {
4087 // Preserve triviality.
4088 NewMethod->setTrivial(OldMethod->isTrivial());
4089
4090 // MSVC allows explicit template specialization at class scope:
4091 // 2 CXXMethodDecls referring to the same function will be injected.
4092 // We don't want a redeclaration error.
4093 bool IsClassScopeExplicitSpecialization =
4094 OldMethod->isFunctionTemplateSpecialization() &&
4096 bool isFriend = NewMethod->getFriendObjectKind();
4097
4098 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4099 !IsClassScopeExplicitSpecialization) {
4100 // -- Member function declarations with the same name and the
4101 // same parameter types cannot be overloaded if any of them
4102 // is a static member function declaration.
4103 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4104 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4105 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4106 return true;
4107 }
4108
4109 // C++ [class.mem]p1:
4110 // [...] A member shall not be declared twice in the
4111 // member-specification, except that a nested class or member
4112 // class template can be declared and then later defined.
4113 if (!inTemplateInstantiation()) {
4114 unsigned NewDiag;
4115 if (isa<CXXConstructorDecl>(OldMethod))
4116 NewDiag = diag::err_constructor_redeclared;
4117 else if (isa<CXXDestructorDecl>(NewMethod))
4118 NewDiag = diag::err_destructor_redeclared;
4119 else if (isa<CXXConversionDecl>(NewMethod))
4120 NewDiag = diag::err_conv_function_redeclared;
4121 else
4122 NewDiag = diag::err_member_redeclared;
4123
4124 Diag(New->getLocation(), NewDiag);
4125 } else {
4126 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4127 << New << New->getType();
4128 }
4129 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4130 return true;
4131
4132 // Complain if this is an explicit declaration of a special
4133 // member that was initially declared implicitly.
4134 //
4135 // As an exception, it's okay to befriend such methods in order
4136 // to permit the implicit constructor/destructor/operator calls.
4137 } else if (OldMethod->isImplicit()) {
4138 if (isFriend) {
4139 NewMethod->setImplicit();
4140 } else {
4141 Diag(NewMethod->getLocation(),
4142 diag::err_definition_of_implicitly_declared_member)
4143 << New << getSpecialMember(OldMethod);
4144 return true;
4145 }
4146 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4147 Diag(NewMethod->getLocation(),
4148 diag::err_definition_of_explicitly_defaulted_member)
4149 << getSpecialMember(OldMethod);
4150 return true;
4151 }
4152 }
4153
4154 // C++1z [over.load]p2
4155 // Certain function declarations cannot be overloaded:
4156 // -- Function declarations that differ only in the return type,
4157 // the exception specification, or both cannot be overloaded.
4158
4159 // Check the exception specifications match. This may recompute the type of
4160 // both Old and New if it resolved exception specifications, so grab the
4161 // types again after this. Because this updates the type, we do this before
4162 // any of the other checks below, which may update the "de facto" NewQType
4163 // but do not necessarily update the type of New.
4165 return true;
4166
4167 // C++11 [dcl.attr.noreturn]p1:
4168 // The first declaration of a function shall specify the noreturn
4169 // attribute if any declaration of that function specifies the noreturn
4170 // attribute.
4171 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4172 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4173 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4174 << NRA;
4175 Diag(Old->getLocation(), diag::note_previous_declaration);
4176 }
4177
4178 // C++11 [dcl.attr.depend]p2:
4179 // The first declaration of a function shall specify the
4180 // carries_dependency attribute for its declarator-id if any declaration
4181 // of the function specifies the carries_dependency attribute.
4182 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4183 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4184 Diag(CDA->getLocation(),
4185 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4186 Diag(Old->getFirstDecl()->getLocation(),
4187 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4188 }
4189
4190 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4191 // When a function is declared with SYCL_EXTERNAL, that macro must be
4192 // used on the first declaration of that function in the translation unit.
4193 // Redeclarations of the function in the same translation unit may
4194 // optionally use SYCL_EXTERNAL, but this is not required.
4195 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4196 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4197 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4198 << SEA;
4199 Diag(Old->getLocation(), diag::note_previous_declaration);
4200 }
4201
4202 // (C++98 8.3.5p3):
4203 // All declarations for a function shall agree exactly in both the
4204 // return type and the parameter-type-list.
4205 // We also want to respect all the extended bits except noreturn.
4206
4207 // noreturn should now match unless the old type info didn't have it.
4208 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4209 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4210 const FunctionType *OldTypeForComparison
4211 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4212 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4213 assert(OldQTypeForComparison.isCanonical());
4214 }
4215
4217 // As a special case, retain the language linkage from previous
4218 // declarations of a friend function as an extension.
4219 //
4220 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4221 // and is useful because there's otherwise no way to specify language
4222 // linkage within class scope.
4223 //
4224 // Check cautiously as the friend object kind isn't yet complete.
4225 if (New->getFriendObjectKind() != Decl::FOK_None) {
4226 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4227 Diag(OldLocation, PrevDiag);
4228 } else {
4229 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4230 Diag(OldLocation, PrevDiag);
4231 return true;
4232 }
4233 }
4234
4235 // HLSL check parameters for matching ABI specifications.
4236 if (getLangOpts().HLSL) {
4237 if (HLSL().CheckCompatibleParameterABI(New, Old))
4238 return true;
4239
4240 // If no errors are generated when checking parameter ABIs we can check if
4241 // the two declarations have the same type ignoring the ABIs and if so,
4242 // the declarations can be merged. This case for merging is only valid in
4243 // HLSL because there are no valid cases of merging mismatched parameter
4244 // ABIs except the HLSL implicit in and explicit in.
4245 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4246 NewQType))
4247 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4248 // Fall through for conflicting redeclarations and redefinitions.
4249 }
4250
4251 // If the function types are compatible, merge the declarations. Ignore the
4252 // exception specifier because it was already checked above in
4253 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4254 // about incompatible types under -fms-compatibility.
4255 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4256 NewQType))
4257 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4258
4259 // If the types are imprecise (due to dependent constructs in friends or
4260 // local extern declarations), it's OK if they differ. We'll check again
4261 // during instantiation.
4262 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4263 return false;
4264
4265 // Fall through for conflicting redeclarations and redefinitions.
4266 }
4267
4268 // C: Function types need to be compatible, not identical. This handles
4269 // duplicate function decls like "void f(int); void f(enum X);" properly.
4270 if (!getLangOpts().CPlusPlus) {
4271 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4272 // type is specified by a function definition that contains a (possibly
4273 // empty) identifier list, both shall agree in the number of parameters
4274 // and the type of each parameter shall be compatible with the type that
4275 // results from the application of default argument promotions to the
4276 // type of the corresponding identifier. ...
4277 // This cannot be handled by ASTContext::typesAreCompatible() because that
4278 // doesn't know whether the function type is for a definition or not when
4279 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4280 // we need to cover here is that the number of arguments agree as the
4281 // default argument promotion rules were already checked by
4282 // ASTContext::typesAreCompatible().
4283 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4284 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4285 if (Old->hasInheritedPrototype())
4286 Old = Old->getCanonicalDecl();
4287 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4288 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4289 return true;
4290 }
4291
4292 // If we are merging two functions where only one of them has a prototype,
4293 // we may have enough information to decide to issue a diagnostic that the
4294 // function without a prototype will change behavior in C23. This handles
4295 // cases like:
4296 // void i(); void i(int j);
4297 // void i(int j); void i();
4298 // void i(); void i(int j) {}
4299 // See ActOnFinishFunctionBody() for other cases of the behavior change
4300 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4301 // type without a prototype.
4302 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4303 !New->isImplicit() && !Old->isImplicit()) {
4304 const FunctionDecl *WithProto, *WithoutProto;
4305 if (New->hasWrittenPrototype()) {
4306 WithProto = New;
4307 WithoutProto = Old;
4308 } else {
4309 WithProto = Old;
4310 WithoutProto = New;
4311 }
4312
4313 if (WithProto->getNumParams() != 0) {
4314 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4315 // The one without the prototype will be changing behavior in C23, so
4316 // warn about that one so long as it's a user-visible declaration.
4317 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4318 if (WithoutProto == New)
4319 IsWithoutProtoADef = NewDeclIsDefn;
4320 else
4321 IsWithProtoADef = NewDeclIsDefn;
4322 Diag(WithoutProto->getLocation(),
4323 diag::warn_non_prototype_changes_behavior)
4324 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4325 << (WithoutProto == Old) << IsWithProtoADef;
4326
4327 // The reason the one without the prototype will be changing behavior
4328 // is because of the one with the prototype, so note that so long as
4329 // it's a user-visible declaration. There is one exception to this:
4330 // when the new declaration is a definition without a prototype, the
4331 // old declaration with a prototype is not the cause of the issue,
4332 // and that does not need to be noted because the one with a
4333 // prototype will not change behavior in C23.
4334 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4335 !IsWithoutProtoADef)
4336 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4337 }
4338 }
4339 }
4340
4341 if (Context.typesAreCompatible(OldQType, NewQType)) {
4342 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4343 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4344 const FunctionProtoType *OldProto = nullptr;
4345 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4346 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4347 // The old declaration provided a function prototype, but the
4348 // new declaration does not. Merge in the prototype.
4349 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4350 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4351 OldProto->getParamTypes(),
4352 OldProto->getExtProtoInfo());
4353 New->setType(NewQType);
4354 New->setHasInheritedPrototype();
4355
4356 // Synthesize parameters with the same types.
4358 for (const auto &ParamType : OldProto->param_types()) {
4360 Context, New, SourceLocation(), SourceLocation(), nullptr,
4361 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4362 Param->setScopeInfo(0, Params.size());
4363 Param->setImplicit();
4364 Params.push_back(Param);
4365 }
4366
4367 New->setParams(Params);
4368 }
4369
4370 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4371 }
4372 }
4373
4374 // Check if the function types are compatible when pointer size address
4375 // spaces are ignored.
4376 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4377 return false;
4378
4379 // GNU C permits a K&R definition to follow a prototype declaration
4380 // if the declared types of the parameters in the K&R definition
4381 // match the types in the prototype declaration, even when the
4382 // promoted types of the parameters from the K&R definition differ
4383 // from the types in the prototype. GCC then keeps the types from
4384 // the prototype.
4385 //
4386 // If a variadic prototype is followed by a non-variadic K&R definition,
4387 // the K&R definition becomes variadic. This is sort of an edge case, but
4388 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4389 // C99 6.9.1p8.
4390 if (!getLangOpts().CPlusPlus &&
4391 Old->hasPrototype() && !New->hasPrototype() &&
4392 New->getType()->getAs<FunctionProtoType>() &&
4393 Old->getNumParams() == New->getNumParams()) {
4396 const FunctionProtoType *OldProto
4397 = Old->getType()->getAs<FunctionProtoType>();
4398 const FunctionProtoType *NewProto
4399 = New->getType()->getAs<FunctionProtoType>();
4400
4401 // Determine whether this is the GNU C extension.
4402 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4403 NewProto->getReturnType());
4404 bool LooseCompatible = !MergedReturn.isNull();
4405 for (unsigned Idx = 0, End = Old->getNumParams();
4406 LooseCompatible && Idx != End; ++Idx) {
4407 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4408 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4409 if (Context.typesAreCompatible(OldParm->getType(),
4410 NewProto->getParamType(Idx))) {
4411 ArgTypes.push_back(NewParm->getType());
4412 } else if (Context.typesAreCompatible(OldParm->getType(),
4413 NewParm->getType(),
4414 /*CompareUnqualified=*/true)) {
4415 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4416 NewProto->getParamType(Idx) };
4417 Warnings.push_back(Warn);
4418 ArgTypes.push_back(NewParm->getType());
4419 } else
4420 LooseCompatible = false;
4421 }
4422
4423 if (LooseCompatible) {
4424 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4425 Diag(Warnings[Warn].NewParm->getLocation(),
4426 diag::ext_param_promoted_not_compatible_with_prototype)
4427 << Warnings[Warn].PromotedType
4428 << Warnings[Warn].OldParm->getType();
4429 if (Warnings[Warn].OldParm->getLocation().isValid())
4430 Diag(Warnings[Warn].OldParm->getLocation(),
4431 diag::note_previous_declaration);
4432 }
4433
4434 if (MergeTypeWithOld)
4435 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4436 OldProto->getExtProtoInfo()));
4437 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4438 }
4439
4440 // Fall through to diagnose conflicting types.
4441 }
4442
4443 // A function that has already been declared has been redeclared or
4444 // defined with a different type; show an appropriate diagnostic.
4445
4446 // If the previous declaration was an implicitly-generated builtin
4447 // declaration, then at the very least we should use a specialized note.
4448 unsigned BuiltinID;
4449 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4450 // If it's actually a library-defined builtin function like 'malloc'
4451 // or 'printf', just warn about the incompatible redeclaration.
4452 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4453 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4454 Diag(OldLocation, diag::note_previous_builtin_declaration)
4455 << Old << Old->getType();
4456 return false;
4457 }
4458
4459 PrevDiag = diag::note_previous_builtin_declaration;
4460 }
4461
4462 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4463 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4464 return true;
4465}
4466
4468 Scope *S, bool MergeTypeWithOld) {
4469 // Merge the attributes
4471
4472 // Merge "pure" flag.
4473 if (Old->isPureVirtual())
4474 New->setIsPureVirtual();
4475
4476 // Merge "used" flag.
4477 if (Old->getMostRecentDecl()->isUsed(false))
4478 New->setIsUsed();
4479
4480 // Merge attributes from the parameters. These can mismatch with K&R
4481 // declarations.
4482 if (New->getNumParams() == Old->getNumParams())
4483 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4484 ParmVarDecl *NewParam = New->getParamDecl(i);
4485 ParmVarDecl *OldParam = Old->getParamDecl(i);
4486 mergeParamDeclAttributes(NewParam, OldParam, *this);
4487 mergeParamDeclTypes(NewParam, OldParam, *this);
4488 }
4489
4490 if (getLangOpts().CPlusPlus)
4491 return MergeCXXFunctionDecl(New, Old, S);
4492
4493 // Merge the function types so the we get the composite types for the return
4494 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4495 // was visible.
4496 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4497 if (!Merged.isNull() && MergeTypeWithOld)
4498 New->setType(Merged);
4499
4500 return false;
4501}
4502
4504 ObjCMethodDecl *oldMethod) {
4505 // Merge the attributes, including deprecated/unavailable
4506 AvailabilityMergeKind MergeKind =
4508 ? (oldMethod->isOptional()
4511 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4514
4515 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4516
4517 // Merge attributes from the parameters.
4519 oe = oldMethod->param_end();
4521 ni = newMethod->param_begin(), ne = newMethod->param_end();
4522 ni != ne && oi != oe; ++ni, ++oi)
4523 mergeParamDeclAttributes(*ni, *oi, *this);
4524
4525 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4526}
4527
4529 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4530
4531 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4532 ? diag::err_redefinition_different_type
4533 : diag::err_redeclaration_different_type)
4534 << New->getDeclName() << New->getType() << Old->getType();
4535
4536 diag::kind PrevDiag;
4537 SourceLocation OldLocation;
4538 std::tie(PrevDiag, OldLocation)
4540 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4541 New->setInvalidDecl();
4542}
4543
4545 bool MergeTypeWithOld) {
4546 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4547 return;
4548
4549 QualType MergedT;
4550 if (getLangOpts().CPlusPlus) {
4551 if (New->getType()->isUndeducedType()) {
4552 // We don't know what the new type is until the initializer is attached.
4553 return;
4554 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4555 // These could still be something that needs exception specs checked.
4556 return MergeVarDeclExceptionSpecs(New, Old);
4557 }
4558 // C++ [basic.link]p10:
4559 // [...] the types specified by all declarations referring to a given
4560 // object or function shall be identical, except that declarations for an
4561 // array object can specify array types that differ by the presence or
4562 // absence of a major array bound (8.3.4).
4563 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4564 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4565 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4566
4567 // We are merging a variable declaration New into Old. If it has an array
4568 // bound, and that bound differs from Old's bound, we should diagnose the
4569 // mismatch.
4570 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4571 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4572 PrevVD = PrevVD->getPreviousDecl()) {
4573 QualType PrevVDTy = PrevVD->getType();
4574 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4575 continue;
4576
4577 if (!Context.hasSameType(New->getType(), PrevVDTy))
4578 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4579 }
4580 }
4581
4582 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4583 if (Context.hasSameType(OldArray->getElementType(),
4584 NewArray->getElementType()))
4585 MergedT = New->getType();
4586 }
4587 // FIXME: Check visibility. New is hidden but has a complete type. If New
4588 // has no array bound, it should not inherit one from Old, if Old is not
4589 // visible.
4590 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4591 if (Context.hasSameType(OldArray->getElementType(),
4592 NewArray->getElementType()))
4593 MergedT = Old->getType();
4594 }
4595 }
4596 else if (New->getType()->isObjCObjectPointerType() &&
4597 Old->getType()->isObjCObjectPointerType()) {
4598 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4599 Old->getType());
4600 }
4601 } else {
4602 // C 6.2.7p2:
4603 // All declarations that refer to the same object or function shall have
4604 // compatible type.
4605 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4606 }
4607 if (MergedT.isNull()) {
4608 // It's OK if we couldn't merge types if either type is dependent, for a
4609 // block-scope variable. In other cases (static data members of class
4610 // templates, variable templates, ...), we require the types to be
4611 // equivalent.
4612 // FIXME: The C++ standard doesn't say anything about this.
4613 if ((New->getType()->isDependentType() ||
4614 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4615 // If the old type was dependent, we can't merge with it, so the new type
4616 // becomes dependent for now. We'll reproduce the original type when we
4617 // instantiate the TypeSourceInfo for the variable.
4618 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4619 New->setType(Context.DependentTy);
4620 return;
4621 }
4622 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4623 }
4624
4625 // Don't actually update the type on the new declaration if the old
4626 // declaration was an extern declaration in a different scope.
4627 if (MergeTypeWithOld)
4628 New->setType(MergedT);
4629}
4630
4631static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4633 // C11 6.2.7p4:
4634 // For an identifier with internal or external linkage declared
4635 // in a scope in which a prior declaration of that identifier is
4636 // visible, if the prior declaration specifies internal or
4637 // external linkage, the type of the identifier at the later
4638 // declaration becomes the composite type.
4639 //
4640 // If the variable isn't visible, we do not merge with its type.
4641 if (Previous.isShadowed())
4642 return false;
4643
4644 if (S.getLangOpts().CPlusPlus) {
4645 // C++11 [dcl.array]p3:
4646 // If there is a preceding declaration of the entity in the same
4647 // scope in which the bound was specified, an omitted array bound
4648 // is taken to be the same as in that earlier declaration.
4649 return NewVD->isPreviousDeclInSameBlockScope() ||
4650 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4652 } else {
4653 // If the old declaration was function-local, don't merge with its
4654 // type unless we're in the same function.
4655 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4656 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4657 }
4658}
4659
4661 // If the new decl is already invalid, don't do any other checking.
4662 if (New->isInvalidDecl())
4663 return;
4664
4665 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4666 return;
4667
4668 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4669
4670 // Verify the old decl was also a variable or variable template.
4671 VarDecl *Old = nullptr;
4672 VarTemplateDecl *OldTemplate = nullptr;
4673 if (Previous.isSingleResult()) {
4674 if (NewTemplate) {
4675 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4676 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4677
4678 if (auto *Shadow =
4679 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4680 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4681 return New->setInvalidDecl();
4682 } else {
4683 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4684
4685 if (auto *Shadow =
4686 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4687 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4688 return New->setInvalidDecl();
4689 }
4690 }
4691 if (!Old) {
4692 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4693 << New->getDeclName();
4694 notePreviousDefinition(Previous.getRepresentativeDecl(),
4695 New->getLocation());
4696 return New->setInvalidDecl();
4697 }
4698
4699 // If the old declaration was found in an inline namespace and the new
4700 // declaration was qualified, update the DeclContext to match.
4702
4703 // Ensure the template parameters are compatible.
4704 if (NewTemplate &&
4706 OldTemplate->getTemplateParameters(),
4707 /*Complain=*/true, TPL_TemplateMatch))
4708 return New->setInvalidDecl();
4709
4710 // C++ [class.mem]p1:
4711 // A member shall not be declared twice in the member-specification [...]
4712 //
4713 // Here, we need only consider static data members.
4714 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4715 Diag(New->getLocation(), diag::err_duplicate_member)
4716 << New->getIdentifier();
4717 Diag(Old->getLocation(), diag::note_previous_declaration);
4718 New->setInvalidDecl();
4719 }
4720
4722 // Warn if an already-defined variable is made a weak_import in a subsequent
4723 // declaration
4724 if (New->hasAttr<WeakImportAttr>())
4725 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4726 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4727 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4728 Diag(D->getLocation(), diag::note_previous_definition);
4729 // Remove weak_import attribute on new declaration.
4730 New->dropAttr<WeakImportAttr>();
4731 break;
4732 }
4733 }
4734
4735 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4736 if (!Old->hasAttr<InternalLinkageAttr>()) {
4737 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4738 << ILA;
4739 Diag(Old->getLocation(), diag::note_previous_declaration);
4740 New->dropAttr<InternalLinkageAttr>();
4741 }
4742
4743 // Merge the types.
4744 VarDecl *MostRecent = Old->getMostRecentDecl();
4745 if (MostRecent != Old) {
4746 MergeVarDeclTypes(New, MostRecent,
4747 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4748 if (New->isInvalidDecl())
4749 return;
4750 }
4751
4753 if (New->isInvalidDecl())
4754 return;
4755
4756 diag::kind PrevDiag;
4757 SourceLocation OldLocation;
4758 std::tie(PrevDiag, OldLocation) =
4760
4761 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4762 if (New->getStorageClass() == SC_Static &&
4763 !New->isStaticDataMember() &&
4764 Old->hasExternalFormalLinkage()) {
4765 if (getLangOpts().MicrosoftExt) {
4766 Diag(New->getLocation(), diag::ext_static_non_static)
4767 << New->getDeclName();
4768 Diag(OldLocation, PrevDiag);
4769 } else {
4770 Diag(New->getLocation(), diag::err_static_non_static)
4771 << New->getDeclName();
4772 Diag(OldLocation, PrevDiag);
4773 return New->setInvalidDecl();
4774 }
4775 }
4776 // C99 6.2.2p4:
4777 // For an identifier declared with the storage-class specifier
4778 // extern in a scope in which a prior declaration of that
4779 // identifier is visible,23) if the prior declaration specifies
4780 // internal or external linkage, the linkage of the identifier at
4781 // the later declaration is the same as the linkage specified at
4782 // the prior declaration. If no prior declaration is visible, or
4783 // if the prior declaration specifies no linkage, then the
4784 // identifier has external linkage.
4785 if (New->hasExternalStorage() && Old->hasLinkage())
4786 /* Okay */;
4787 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4788 !New->isStaticDataMember() &&
4790 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4791 Diag(OldLocation, PrevDiag);
4792 return New->setInvalidDecl();
4793 }
4794
4795 // Check if extern is followed by non-extern and vice-versa.
4796 if (New->hasExternalStorage() &&
4797 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4798 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4799 Diag(OldLocation, PrevDiag);
4800 return New->setInvalidDecl();
4801 }
4802 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4803 !New->hasExternalStorage()) {
4804 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4805 Diag(OldLocation, PrevDiag);
4806 return New->setInvalidDecl();
4807 }
4808
4810 return;
4811
4812 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4813
4814 // FIXME: The test for external storage here seems wrong? We still
4815 // need to check for mismatches.
4816 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4817 // Don't complain about out-of-line definitions of static members.
4818 !(Old->getLexicalDeclContext()->isRecord() &&
4819 !New->getLexicalDeclContext()->isRecord())) {
4820 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4821 Diag(OldLocation, PrevDiag);
4822 return New->setInvalidDecl();
4823 }
4824
4825 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4826 if (VarDecl *Def = Old->getDefinition()) {
4827 // C++1z [dcl.fcn.spec]p4:
4828 // If the definition of a variable appears in a translation unit before
4829 // its first declaration as inline, the program is ill-formed.
4830 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4831 Diag(Def->getLocation(), diag::note_previous_definition);
4832 }
4833 }
4834
4835 // If this redeclaration makes the variable inline, we may need to add it to
4836 // UndefinedButUsed.
4837 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4838 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4839 !Old->isInAnotherModuleUnit())
4840 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4841 SourceLocation()));
4842
4843 if (New->getTLSKind() != Old->getTLSKind()) {
4844 if (!Old->getTLSKind()) {
4845 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4846 Diag(OldLocation, PrevDiag);
4847 } else if (!New->getTLSKind()) {
4848 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4849 Diag(OldLocation, PrevDiag);
4850 } else {
4851 // Do not allow redeclaration to change the variable between requiring
4852 // static and dynamic initialization.
4853 // FIXME: GCC allows this, but uses the TLS keyword on the first
4854 // declaration to determine the kind. Do we need to be compatible here?
4855 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4856 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4857 Diag(OldLocation, PrevDiag);
4858 }
4859 }
4860
4861 // C++ doesn't have tentative definitions, so go right ahead and check here.
4862 if (getLangOpts().CPlusPlus) {
4863 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4864 Old->getCanonicalDecl()->isConstexpr()) {
4865 // This definition won't be a definition any more once it's been merged.
4866 Diag(New->getLocation(),
4867 diag::warn_deprecated_redundant_constexpr_static_def);
4868 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4869 VarDecl *Def = Old->getDefinition();
4870 if (Def && checkVarDeclRedefinition(Def, New))
4871 return;
4872 }
4873 } else {
4874 // C++ may not have a tentative definition rule, but it has a different
4875 // rule about what constitutes a definition in the first place. See
4876 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4877 // contains the extern specifier and doesn't have an initializer, it's fine
4878 // in C++.
4879 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4880 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4881 << New;
4882 Diag(Old->getLocation(), diag::note_previous_declaration);
4883 }
4884 }
4885
4887 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4888 Diag(OldLocation, PrevDiag);
4889 New->setInvalidDecl();
4890 return;
4891 }
4892
4893 // Merge "used" flag.
4894 if (Old->getMostRecentDecl()->isUsed(false))
4895 New->setIsUsed();
4896
4897 // Keep a chain of previous declarations.
4898 New->setPreviousDecl(Old);
4899 if (NewTemplate)
4900 NewTemplate->setPreviousDecl(OldTemplate);
4901
4902 // Inherit access appropriately.
4903 New->setAccess(Old->getAccess());
4904 if (NewTemplate)
4905 NewTemplate->setAccess(New->getAccess());
4906
4907 if (Old->isInline())
4908 New->setImplicitlyInline();
4909}
4910
4913 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4914 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4915 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4916 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4917 auto &HSI = PP.getHeaderSearchInfo();
4918 StringRef HdrFilename =
4919 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4920
4921 auto noteFromModuleOrInclude = [&](Module *Mod,
4922 SourceLocation IncLoc) -> bool {
4923 // Redefinition errors with modules are common with non modular mapped
4924 // headers, example: a non-modular header H in module A that also gets
4925 // included directly in a TU. Pointing twice to the same header/definition
4926 // is confusing, try to get better diagnostics when modules is on.
4927 if (IncLoc.isValid()) {
4928 if (Mod) {
4929 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4930 << HdrFilename.str() << Mod->getFullModuleName();
4931 if (!Mod->DefinitionLoc.isInvalid())
4932 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4933 << Mod->getFullModuleName();
4934 } else {
4935 Diag(IncLoc, diag::note_redefinition_include_same_file)
4936 << HdrFilename.str();
4937 }
4938 return true;
4939 }
4940
4941 return false;
4942 };
4943
4944 // Is it the same file and same offset? Provide more information on why
4945 // this leads to a redefinition error.
4946 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4947 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4948 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4949 bool EmittedDiag =
4950 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4951 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4952
4953 // If the header has no guards, emit a note suggesting one.
4954 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4955 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4956
4957 if (EmittedDiag)
4958 return;
4959 }
4960
4961 // Redefinition coming from different files or couldn't do better above.
4962 if (Old->getLocation().isValid())
4963 Diag(Old->getLocation(), diag::note_previous_definition);
4964}
4965
4967 if (!hasVisibleDefinition(Old) &&
4968 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4970 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4971 New->getDeclContext()->isDependentContext() ||
4972 New->hasAttr<SelectAnyAttr>())) {
4973 // The previous definition is hidden, and multiple definitions are
4974 // permitted (in separate TUs). Demote this to a declaration.
4975 New->demoteThisDefinitionToDeclaration();
4976
4977 // Make the canonical definition visible.
4978 if (auto *OldTD = Old->getDescribedVarTemplate())
4981 return false;
4982 } else {
4983 Diag(New->getLocation(), diag::err_redefinition) << New;
4984 notePreviousDefinition(Old, New->getLocation());
4985 New->setInvalidDecl();
4986 return true;
4987 }
4988}
4989
4991 DeclSpec &DS,
4992 const ParsedAttributesView &DeclAttrs,
4993 RecordDecl *&AnonRecord) {
4995 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4996}
4997
4998// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4999// disambiguate entities defined in different scopes.
5000// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5001// compatibility.
5002// We will pick our mangling number depending on which version of MSVC is being
5003// targeted.
5004static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5008}
5009
5010void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5011 if (!Context.getLangOpts().CPlusPlus)
5012 return;
5013
5014 if (isa<CXXRecordDecl>(Tag->getParent())) {
5015 // If this tag is the direct child of a class, number it if
5016 // it is anonymous.
5017 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5018 return;
5020 Context.getManglingNumberContext(Tag->getParent());
5021 Context.setManglingNumber(
5022 Tag, MCtx.getManglingNumber(
5023 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5024 return;
5025 }
5026
5027 // If this tag isn't a direct child of a class, number it if it is local.
5029 Decl *ManglingContextDecl;
5030 std::tie(MCtx, ManglingContextDecl) =
5031 getCurrentMangleNumberContext(Tag->getDeclContext());
5032 if (MCtx) {
5033 Context.setManglingNumber(
5034 Tag, MCtx->getManglingNumber(
5035 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5036 }
5037}
5038
5039namespace {
5040struct NonCLikeKind {
5041 enum {
5042 None,
5043 BaseClass,
5044 DefaultMemberInit,
5045 Lambda,
5046 Friend,
5047 OtherMember,
5048 Invalid,
5049 } Kind = None;
5050 SourceRange Range;
5051
5052 explicit operator bool() { return Kind != None; }
5053};
5054}
5055
5056/// Determine whether a class is C-like, according to the rules of C++
5057/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5058static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5059 if (RD->isInvalidDecl())
5060 return {NonCLikeKind::Invalid, {}};
5061
5062 // C++ [dcl.typedef]p9: [P1766R1]
5063 // An unnamed class with a typedef name for linkage purposes shall not
5064 //
5065 // -- have any base classes
5066 if (RD->getNumBases())
5067 return {NonCLikeKind::BaseClass,
5069 RD->bases_end()[-1].getEndLoc())};
5070 bool Invalid = false;
5071 for (Decl *D : RD->decls()) {
5072 // Don't complain about things we already diagnosed.
5073 if (D->isInvalidDecl()) {
5074 Invalid = true;
5075 continue;
5076 }
5077
5078 // -- have any [...] default member initializers
5079 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5080 if (FD->hasInClassInitializer()) {
5081 auto *Init = FD->getInClassInitializer();
5082 return {NonCLikeKind::DefaultMemberInit,
5083 Init ? Init->getSourceRange() : D->getSourceRange()};
5084 }
5085 continue;
5086 }
5087
5088 // FIXME: We don't allow friend declarations. This violates the wording of
5089 // P1766, but not the intent.
5090 if (isa<FriendDecl>(D))
5091 return {NonCLikeKind::Friend, D->getSourceRange()};
5092
5093 // -- declare any members other than non-static data members, member
5094 // enumerations, or member classes,
5096 isa<EnumDecl>(D))
5097 continue;
5098 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5099 if (!MemberRD) {
5100 if (D->isImplicit())
5101 continue;
5102 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5103 }
5104
5105 // -- contain a lambda-expression,
5106 if (MemberRD->isLambda())
5107 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5108
5109 // and all member classes shall also satisfy these requirements
5110 // (recursively).
5111 if (MemberRD->isThisDeclarationADefinition()) {
5112 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5113 return Kind;
5114 }
5115 }
5116
5117 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5118}
5119
5121 TypedefNameDecl *NewTD) {
5122 if (TagFromDeclSpec->isInvalidDecl())
5123 return;
5124
5125 // Do nothing if the tag already has a name for linkage purposes.
5126 if (TagFromDeclSpec->hasNameForLinkage())
5127 return;
5128
5129 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5130 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5131
5132 // The type must match the tag exactly; no qualifiers allowed.
5133 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5134 Context.getCanonicalTagType(TagFromDeclSpec))) {
5135 if (getLangOpts().CPlusPlus)
5136 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5137 return;
5138 }
5139
5140 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5141 // An unnamed class with a typedef name for linkage purposes shall [be
5142 // C-like].
5143 //
5144 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5145 // shouldn't happen, but there are constructs that the language rule doesn't
5146 // disallow for which we can't reasonably avoid computing linkage early.
5147 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5148 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5149 : NonCLikeKind();
5150 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5151 if (NonCLike || ChangesLinkage) {
5152 if (NonCLike.Kind == NonCLikeKind::Invalid)
5153 return;
5154
5155 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5156 if (ChangesLinkage) {
5157 // If the linkage changes, we can't accept this as an extension.
5158 if (NonCLike.Kind == NonCLikeKind::None)
5159 DiagID = diag::err_typedef_changes_linkage;
5160 else
5161 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5162 }
5163
5164 SourceLocation FixitLoc =
5165 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5166 llvm::SmallString<40> TextToInsert;
5167 TextToInsert += ' ';
5168 TextToInsert += NewTD->getIdentifier()->getName();
5169
5170 Diag(FixitLoc, DiagID)
5171 << isa<TypeAliasDecl>(NewTD)
5172 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5173 if (NonCLike.Kind != NonCLikeKind::None) {
5174 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5175 << NonCLike.Kind - 1 << NonCLike.Range;
5176 }
5177 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5178 << NewTD << isa<TypeAliasDecl>(NewTD);
5179
5180 if (ChangesLinkage)
5181 return;
5182 }
5183
5184 // Otherwise, set this as the anon-decl typedef for the tag.
5185 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5186
5187 // Now that we have a name for the tag, process API notes again.
5188 ProcessAPINotes(TagFromDeclSpec);
5189}
5190
5191static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5193 switch (T) {
5195 return 0;
5197 return 1;
5199 return 2;
5201 return 3;
5202 case DeclSpec::TST_enum:
5203 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5204 if (ED->isScopedUsingClassTag())
5205 return 5;
5206 if (ED->isScoped())
5207 return 6;
5208 }
5209 return 4;
5210 default:
5211 llvm_unreachable("unexpected type specifier");
5212 }
5213}
5214
5216 DeclSpec &DS,
5217 const ParsedAttributesView &DeclAttrs,
5218 MultiTemplateParamsArg TemplateParams,
5219 bool IsExplicitInstantiation,
5220 RecordDecl *&AnonRecord,
5221 SourceLocation EllipsisLoc) {
5222 Decl *TagD = nullptr;
5223 TagDecl *Tag = nullptr;
5229 TagD = DS.getRepAsDecl();
5230
5231 if (!TagD) // We probably had an error
5232 return nullptr;
5233
5234 // Note that the above type specs guarantee that the
5235 // type rep is a Decl, whereas in many of the others
5236 // it's a Type.
5237 if (isa<TagDecl>(TagD))
5238 Tag = cast<TagDecl>(TagD);
5239 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5240 Tag = CTD->getTemplatedDecl();
5241 }
5242
5243 if (Tag) {
5244 handleTagNumbering(Tag, S);
5245 Tag->setFreeStanding();
5246 if (Tag->isInvalidDecl())
5247 return Tag;
5248 }
5249
5250 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5251 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5252 // or incomplete types shall not be restrict-qualified."
5253 if (TypeQuals & DeclSpec::TQ_restrict)
5255 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5256 << DS.getSourceRange();
5257 }
5258
5259 if (DS.isInlineSpecified())
5260 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5261 << getLangOpts().CPlusPlus17;
5262
5263 if (DS.hasConstexprSpecifier()) {
5264 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5265 // and definitions of functions and variables.
5266 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5267 // the declaration of a function or function template
5268 if (Tag)
5269 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5271 << static_cast<int>(DS.getConstexprSpecifier());
5272 else if (getLangOpts().C23)
5273 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5274 else
5275 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5276 << static_cast<int>(DS.getConstexprSpecifier());
5277 // Don't emit warnings after this error.
5278 return TagD;
5279 }
5280
5282
5283 if (DS.isFriendSpecified()) {
5284 // If we're dealing with a decl but not a TagDecl, assume that
5285 // whatever routines created it handled the friendship aspect.
5286 if (TagD && !Tag)
5287 return nullptr;
5288 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5289 }
5290
5291 assert(EllipsisLoc.isInvalid() &&
5292 "Friend ellipsis but not friend-specified?");
5293
5294 // Track whether this decl-specifier declares anything.
5295 bool DeclaresAnything = true;
5296
5297 // Handle anonymous struct definitions.
5298 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5299 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5301 if (getLangOpts().CPlusPlus ||
5302 Record->getDeclContext()->isRecord()) {
5303 // If CurContext is a DeclContext that can contain statements,
5304 // RecursiveASTVisitor won't visit the decls that
5305 // BuildAnonymousStructOrUnion() will put into CurContext.
5306 // Also store them here so that they can be part of the
5307 // DeclStmt that gets created in this case.
5308 // FIXME: Also return the IndirectFieldDecls created by
5309 // BuildAnonymousStructOr union, for the same reason?
5310 if (CurContext->isFunctionOrMethod())
5311 AnonRecord = Record;
5312 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5313 Context.getPrintingPolicy());
5314 }
5315
5316 DeclaresAnything = false;
5317 }
5318 }
5319
5320 // C11 6.7.2.1p2:
5321 // A struct-declaration that does not declare an anonymous structure or
5322 // anonymous union shall contain a struct-declarator-list.
5323 //
5324 // This rule also existed in C89 and C99; the grammar for struct-declaration
5325 // did not permit a struct-declaration without a struct-declarator-list.
5326 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5328 // Check for Microsoft C extension: anonymous struct/union member.
5329 // Handle 2 kinds of anonymous struct/union:
5330 // struct STRUCT;
5331 // union UNION;
5332 // and
5333 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5334 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5335 if ((Tag && Tag->getDeclName()) ||
5337 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5338 : DS.getRepAsType().get()->getAsRecordDecl();
5339 if (Record && getLangOpts().MicrosoftExt) {
5340 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5341 << Record->isUnion() << DS.getSourceRange();
5343 }
5344
5345 DeclaresAnything = false;
5346 }
5347 }
5348
5349 // Skip all the checks below if we have a type error.
5351 (TagD && TagD->isInvalidDecl()))
5352 return TagD;
5353
5354 if (getLangOpts().CPlusPlus &&
5356 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5357 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5358 !Enum->isInvalidDecl())
5359 DeclaresAnything = false;
5360
5361 if (!DS.isMissingDeclaratorOk()) {
5362 // Customize diagnostic for a typedef missing a name.
5364 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5365 << DS.getSourceRange();
5366 else
5367 DeclaresAnything = false;
5368 }
5369
5370 if (DS.isModulePrivateSpecified() &&
5371 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5372 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5373 << Tag->getTagKind()
5375
5377
5378 // C 6.7/2:
5379 // A declaration [...] shall declare at least a declarator [...], a tag,
5380 // or the members of an enumeration.
5381 // C++ [dcl.dcl]p3:
5382 // [If there are no declarators], and except for the declaration of an
5383 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5384 // names into the program, or shall redeclare a name introduced by a
5385 // previous declaration.
5386 if (!DeclaresAnything) {
5387 // In C, we allow this as a (popular) extension / bug. Don't bother
5388 // producing further diagnostics for redundant qualifiers after this.
5389 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5390 ? diag::err_no_declarators
5391 : diag::ext_no_declarators)
5392 << DS.getSourceRange();
5393 return TagD;
5394 }
5395
5396 // C++ [dcl.stc]p1:
5397 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5398 // init-declarator-list of the declaration shall not be empty.
5399 // C++ [dcl.fct.spec]p1:
5400 // If a cv-qualifier appears in a decl-specifier-seq, the
5401 // init-declarator-list of the declaration shall not be empty.
5402 //
5403 // Spurious qualifiers here appear to be valid in C.
5404 unsigned DiagID = diag::warn_standalone_specifier;
5405 if (getLangOpts().CPlusPlus)
5406 DiagID = diag::ext_standalone_specifier;
5407
5408 // Note that a linkage-specification sets a storage class, but
5409 // 'extern "C" struct foo;' is actually valid and not theoretically
5410 // useless.
5411 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5412 if (SCS == DeclSpec::SCS_mutable)
5413 // Since mutable is not a viable storage class specifier in C, there is
5414 // no reason to treat it as an extension. Instead, diagnose as an error.
5415 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5416 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5417 Diag(DS.getStorageClassSpecLoc(), DiagID)
5419 }
5420
5424 if (DS.getTypeQualifiers()) {
5426 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5428 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5429 // Restrict is covered above.
5431 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5433 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5434 }
5435
5436 // Warn about ignored type attributes, for example:
5437 // __attribute__((aligned)) struct A;
5438 // Attributes should be placed after tag to apply to type declaration.
5439 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5440 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5441 if (TypeSpecType == DeclSpec::TST_class ||
5442 TypeSpecType == DeclSpec::TST_struct ||
5443 TypeSpecType == DeclSpec::TST_interface ||
5444 TypeSpecType == DeclSpec::TST_union ||
5445 TypeSpecType == DeclSpec::TST_enum) {
5446
5447 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5448 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5449 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5450 DiagnosticId = diag::warn_attribute_ignored;
5451 else if (AL.isRegularKeywordAttribute())
5452 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5453 else
5454 DiagnosticId = diag::warn_declspec_attribute_ignored;
5455 Diag(AL.getLoc(), DiagnosticId)
5456 << AL << GetDiagnosticTypeSpecifierID(DS);
5457 };
5458
5459 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5460 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5461 }
5462 }
5463
5464 return TagD;
5465}
5466
5467/// We are trying to inject an anonymous member into the given scope;
5468/// check if there's an existing declaration that can't be overloaded.
5469///
5470/// \return true if this is a forbidden redeclaration
5471static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5472 DeclContext *Owner,
5473 DeclarationName Name,
5474 SourceLocation NameLoc, bool IsUnion,
5475 StorageClass SC) {
5476 LookupResult R(SemaRef, Name, NameLoc,
5480 if (!SemaRef.LookupName(R, S)) return false;
5481
5482 // Pick a representative declaration.
5484 assert(PrevDecl && "Expected a non-null Decl");
5485
5486 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5487 return false;
5488
5489 if (SC == StorageClass::SC_None &&
5490 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5491 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5492 if (!Owner->isRecord())
5493 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5494 return false;
5495 }
5496
5497 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5498 << IsUnion << Name;
5499 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5500
5501 return true;
5502}
5503
5505 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5507}
5508
5510 if (!getLangOpts().CPlusPlus)
5511 return;
5512
5513 // This function can be parsed before we have validated the
5514 // structure as an anonymous struct
5515 if (Record->isAnonymousStructOrUnion())
5516 return;
5517
5518 const NamedDecl *First = 0;
5519 for (const Decl *D : Record->decls()) {
5520 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5521 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5522 continue;
5523 if (!First)
5524 First = ND;
5525 else
5527 }
5528}
5529
5530/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5531/// anonymous struct or union AnonRecord into the owning context Owner
5532/// and scope S. This routine will be invoked just after we realize
5533/// that an unnamed union or struct is actually an anonymous union or
5534/// struct, e.g.,
5535///
5536/// @code
5537/// union {
5538/// int i;
5539/// float f;
5540/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5541/// // f into the surrounding scope.x
5542/// @endcode
5543///
5544/// This routine is recursive, injecting the names of nested anonymous
5545/// structs/unions into the owning context and scope as well.
5546static bool
5548 RecordDecl *AnonRecord, AccessSpecifier AS,
5549 StorageClass SC,
5550 SmallVectorImpl<NamedDecl *> &Chaining) {
5551 bool Invalid = false;
5552
5553 // Look every FieldDecl and IndirectFieldDecl with a name.
5554 for (auto *D : AnonRecord->decls()) {
5555 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5556 cast<NamedDecl>(D)->getDeclName()) {
5557 ValueDecl *VD = cast<ValueDecl>(D);
5558 // C++ [class.union]p2:
5559 // The names of the members of an anonymous union shall be
5560 // distinct from the names of any other entity in the
5561 // scope in which the anonymous union is declared.
5562
5563 bool FieldInvalid = CheckAnonMemberRedeclaration(
5564 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5565 AnonRecord->isUnion(), SC);
5566 if (FieldInvalid)
5567 Invalid = true;
5568
5569 // Inject the IndirectFieldDecl even if invalid, because later
5570 // diagnostics may depend on it being present, see findDefaultInitializer.
5571
5572 // C++ [class.union]p2:
5573 // For the purpose of name lookup, after the anonymous union
5574 // definition, the members of the anonymous union are
5575 // considered to have been defined in the scope in which the
5576 // anonymous union is declared.
5577 unsigned OldChainingSize = Chaining.size();
5578 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5579 Chaining.append(IF->chain_begin(), IF->chain_end());
5580 else
5581 Chaining.push_back(VD);
5582
5583 assert(Chaining.size() >= 2);
5584 NamedDecl **NamedChain =
5585 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5586 for (unsigned i = 0; i < Chaining.size(); i++)
5587 NamedChain[i] = Chaining[i];
5588
5590 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5591 VD->getType(), {NamedChain, Chaining.size()});
5592
5593 for (const auto *Attr : VD->attrs())
5594 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5595
5596 IndirectField->setAccess(AS);
5597 IndirectField->setImplicit();
5598 IndirectField->setInvalidDecl(FieldInvalid);
5599 SemaRef.PushOnScopeChains(IndirectField, S);
5600
5601 // That includes picking up the appropriate access specifier.
5602 if (AS != AS_none)
5603 IndirectField->setAccess(AS);
5604
5605 Chaining.resize(OldChainingSize);
5606 }
5607 }
5608
5609 return Invalid;
5610}
5611
5612/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5613/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5614/// illegal input values are mapped to SC_None.
5615static StorageClass
5617 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5618 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5619 "Parser allowed 'typedef' as storage class VarDecl.");
5620 switch (StorageClassSpec) {
5623 if (DS.isExternInLinkageSpec())
5624 return SC_None;
5625 return SC_Extern;
5626 case DeclSpec::SCS_static: return SC_Static;
5627 case DeclSpec::SCS_auto: return SC_Auto;
5630 // Illegal SCSs map to None: error reporting is up to the caller.
5631 case DeclSpec::SCS_mutable: // Fall through.
5632 case DeclSpec::SCS_typedef: return SC_None;
5633 }
5634 llvm_unreachable("unknown storage class specifier");
5635}
5636
5638 assert(Record->hasInClassInitializer());
5639
5640 for (const auto *I : Record->decls()) {
5641 const auto *FD = dyn_cast<FieldDecl>(I);
5642 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5643 FD = IFD->getAnonField();
5644 if (FD && FD->hasInClassInitializer())
5645 return FD->getLocation();
5646 }
5647
5648 llvm_unreachable("couldn't find in-class initializer");
5649}
5650
5652 SourceLocation DefaultInitLoc) {
5653 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5654 return;
5655
5656 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5657 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5658}
5659
5661 CXXRecordDecl *AnonUnion) {
5662 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5663 return;
5664
5666}
5667
5669 AccessSpecifier AS,
5671 const PrintingPolicy &Policy) {
5672 DeclContext *Owner = Record->getDeclContext();
5673
5674 // Diagnose whether this anonymous struct/union is an extension.
5675 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5676 Diag(Record->getLocation(), diag::ext_anonymous_union);
5677 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5678 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5679 else if (!Record->isUnion() && !getLangOpts().C11)
5680 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5681
5682 // C and C++ require different kinds of checks for anonymous
5683 // structs/unions.
5684 bool Invalid = false;
5685 if (getLangOpts().CPlusPlus) {
5686 const char *PrevSpec = nullptr;
5687 if (Record->isUnion()) {
5688 // C++ [class.union]p6:
5689 // C++17 [class.union.anon]p2:
5690 // Anonymous unions declared in a named namespace or in the
5691 // global namespace shall be declared static.
5692 unsigned DiagID;
5693 DeclContext *OwnerScope = Owner->getRedeclContext();
5695 (OwnerScope->isTranslationUnit() ||
5696 (OwnerScope->isNamespace() &&
5697 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5698 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5699 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5700
5701 // Recover by adding 'static'.
5703 PrevSpec, DiagID, Policy);
5704 }
5705 // C++ [class.union]p6:
5706 // A storage class is not allowed in a declaration of an
5707 // anonymous union in a class scope.
5709 isa<RecordDecl>(Owner)) {
5711 diag::err_anonymous_union_with_storage_spec)
5713
5714 // Recover by removing the storage specifier.
5717 PrevSpec, DiagID, Context.getPrintingPolicy());
5718 }
5719 }
5720
5721 // Ignore const/volatile/restrict qualifiers.
5722 if (DS.getTypeQualifiers()) {
5724 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5725 << Record->isUnion() << "const"
5729 diag::ext_anonymous_struct_union_qualified)
5730 << Record->isUnion() << "volatile"
5734 diag::ext_anonymous_struct_union_qualified)
5735 << Record->isUnion() << "restrict"
5739 diag::ext_anonymous_struct_union_qualified)
5740 << Record->isUnion() << "_Atomic"
5744 diag::ext_anonymous_struct_union_qualified)
5745 << Record->isUnion() << "__unaligned"
5747
5749 }
5750
5751 // C++ [class.union]p2:
5752 // The member-specification of an anonymous union shall only
5753 // define non-static data members. [Note: nested types and
5754 // functions cannot be declared within an anonymous union. ]
5755 for (auto *Mem : Record->decls()) {
5756 // Ignore invalid declarations; we already diagnosed them.
5757 if (Mem->isInvalidDecl())
5758 continue;
5759
5760 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5761 // C++ [class.union]p3:
5762 // An anonymous union shall not have private or protected
5763 // members (clause 11).
5764 assert(FD->getAccess() != AS_none);
5765 if (FD->getAccess() != AS_public) {
5766 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5767 << Record->isUnion() << (FD->getAccess() == AS_protected);
5768 Invalid = true;
5769 }
5770
5771 // C++ [class.union]p1
5772 // An object of a class with a non-trivial constructor, a non-trivial
5773 // copy constructor, a non-trivial destructor, or a non-trivial copy
5774 // assignment operator cannot be a member of a union, nor can an
5775 // array of such objects.
5776 if (CheckNontrivialField(FD))
5777 Invalid = true;
5778 } else if (Mem->isImplicit()) {
5779 // Any implicit members are fine.
5780 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5781 // This is a type that showed up in an
5782 // elaborated-type-specifier inside the anonymous struct or
5783 // union, but which actually declares a type outside of the
5784 // anonymous struct or union. It's okay.
5785 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5786 if (!MemRecord->isAnonymousStructOrUnion() &&
5787 MemRecord->getDeclName()) {
5788 // Visual C++ allows type definition in anonymous struct or union.
5789 if (getLangOpts().MicrosoftExt)
5790 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5791 << Record->isUnion();
5792 else {
5793 // This is a nested type declaration.
5794 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5795 << Record->isUnion();
5796 Invalid = true;
5797 }
5798 } else {
5799 // This is an anonymous type definition within another anonymous type.
5800 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5801 // not part of standard C++.
5802 Diag(MemRecord->getLocation(),
5803 diag::ext_anonymous_record_with_anonymous_type)
5804 << Record->isUnion();
5805 }
5806 } else if (isa<AccessSpecDecl>(Mem)) {
5807 // Any access specifier is fine.
5808 } else if (isa<StaticAssertDecl>(Mem)) {
5809 // In C++1z, static_assert declarations are also fine.
5810 } else {
5811 // We have something that isn't a non-static data
5812 // member. Complain about it.
5813 unsigned DK = diag::err_anonymous_record_bad_member;
5814 if (isa<TypeDecl>(Mem))
5815 DK = diag::err_anonymous_record_with_type;
5816 else if (isa<FunctionDecl>(Mem))
5817 DK = diag::err_anonymous_record_with_function;
5818 else if (isa<VarDecl>(Mem))
5819 DK = diag::err_anonymous_record_with_static;
5820
5821 // Visual C++ allows type definition in anonymous struct or union.
5822 if (getLangOpts().MicrosoftExt &&
5823 DK == diag::err_anonymous_record_with_type)
5824 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5825 << Record->isUnion();
5826 else {
5827 Diag(Mem->getLocation(), DK) << Record->isUnion();
5828 Invalid = true;
5829 }
5830 }
5831 }
5832
5833 // C++11 [class.union]p8 (DR1460):
5834 // At most one variant member of a union may have a
5835 // brace-or-equal-initializer.
5836 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5837 Owner->isRecord())
5840 }
5841
5842 if (!Record->isUnion() && !Owner->isRecord()) {
5843 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5844 << getLangOpts().CPlusPlus;
5845 Invalid = true;
5846 }
5847
5848 // C++ [dcl.dcl]p3:
5849 // [If there are no declarators], and except for the declaration of an
5850 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5851 // names into the program
5852 // C++ [class.mem]p2:
5853 // each such member-declaration shall either declare at least one member
5854 // name of the class or declare at least one unnamed bit-field
5855 //
5856 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5857 if (getLangOpts().CPlusPlus && Record->field_empty())
5858 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5859
5860 // Mock up a declarator.
5864 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5865
5866 // Create a declaration for this anonymous struct/union.
5867 NamedDecl *Anon = nullptr;
5868 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5869 Anon = FieldDecl::Create(
5870 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5871 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5872 /*BitWidth=*/nullptr, /*Mutable=*/false,
5873 /*InitStyle=*/ICIS_NoInit);
5874 Anon->setAccess(AS);
5875 ProcessDeclAttributes(S, Anon, Dc);
5876
5877 if (getLangOpts().CPlusPlus)
5878 FieldCollector->Add(cast<FieldDecl>(Anon));
5879 } else {
5880 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5881 if (SCSpec == DeclSpec::SCS_mutable) {
5882 // mutable can only appear on non-static class members, so it's always
5883 // an error here
5884 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5885 Invalid = true;
5886 SC = SC_None;
5887 }
5888
5889 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5890 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5891 Context.getCanonicalTagType(Record), TInfo, SC);
5892 if (Invalid)
5893 Anon->setInvalidDecl();
5894
5895 ProcessDeclAttributes(S, Anon, Dc);
5896
5897 // Default-initialize the implicit variable. This initialization will be
5898 // trivial in almost all cases, except if a union member has an in-class
5899 // initializer:
5900 // union { int n = 0; };
5902 }
5903 Anon->setImplicit();
5904
5905 // Mark this as an anonymous struct/union type.
5906 Record->setAnonymousStructOrUnion(true);
5907
5908 // Add the anonymous struct/union object to the current
5909 // context. We'll be referencing this object when we refer to one of
5910 // its members.
5911 Owner->addDecl(Anon);
5912
5913 // Inject the members of the anonymous struct/union into the owning
5914 // context and into the identifier resolver chain for name lookup
5915 // purposes.
5917 Chain.push_back(Anon);
5918
5919 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5920 Chain))
5921 Invalid = true;
5922
5923 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5924 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5926 Decl *ManglingContextDecl;
5927 std::tie(MCtx, ManglingContextDecl) =
5928 getCurrentMangleNumberContext(NewVD->getDeclContext());
5929 if (MCtx) {
5930 Context.setManglingNumber(
5931 NewVD, MCtx->getManglingNumber(
5932 NewVD, getMSManglingNumber(getLangOpts(), S)));
5933 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5934 }
5935 }
5936 }
5937
5938 if (Invalid)
5939 Anon->setInvalidDecl();
5940
5941 return Anon;
5942}
5943
5945 RecordDecl *Record) {
5946 assert(Record && "expected a record!");
5947
5948 // Mock up a declarator.
5951 assert(TInfo && "couldn't build declarator info for anonymous struct");
5952
5953 auto *ParentDecl = cast<RecordDecl>(CurContext);
5954 CanQualType RecTy = Context.getCanonicalTagType(Record);
5955
5956 // Create a declaration for this anonymous struct.
5957 NamedDecl *Anon =
5958 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5959 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5960 /*BitWidth=*/nullptr, /*Mutable=*/false,
5961 /*InitStyle=*/ICIS_NoInit);
5962 Anon->setImplicit();
5963
5964 // Add the anonymous struct object to the current context.
5965 CurContext->addDecl(Anon);
5966
5967 // Inject the members of the anonymous struct into the current
5968 // context and into the identifier resolver chain for name lookup
5969 // purposes.
5971 Chain.push_back(Anon);
5972
5973 RecordDecl *RecordDef = Record->getDefinition();
5974 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5975 diag::err_field_incomplete_or_sizeless) ||
5977 *this, S, CurContext, RecordDef, AS_none,
5979 Anon->setInvalidDecl();
5980 ParentDecl->setInvalidDecl();
5981 }
5982
5983 return Anon;
5984}
5985
5989
5992 DeclarationNameInfo NameInfo;
5993 NameInfo.setLoc(Name.StartLocation);
5994
5995 switch (Name.getKind()) {
5996
5999 NameInfo.setName(Name.Identifier);
6000 return NameInfo;
6001
6003 // C++ [temp.deduct.guide]p3:
6004 // The simple-template-id shall name a class template specialization.
6005 // The template-name shall be the same identifier as the template-name
6006 // of the simple-template-id.
6007 // These together intend to imply that the template-name shall name a
6008 // class template.
6009 // FIXME: template<typename T> struct X {};
6010 // template<typename T> using Y = X<T>;
6011 // Y(int) -> Y<int>;
6012 // satisfies these rules but does not name a class template.
6013 TemplateName TN = Name.TemplateName.get().get();
6014 auto *Template = TN.getAsTemplateDecl();
6016 Diag(Name.StartLocation,
6017 diag::err_deduction_guide_name_not_class_template)
6018 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6019 if (Template)
6021 return DeclarationNameInfo();
6022 }
6023
6024 NameInfo.setName(
6025 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6026 return NameInfo;
6027 }
6028
6030 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6034 return NameInfo;
6035
6037 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6038 Name.Identifier));
6040 return NameInfo;
6041
6043 TypeSourceInfo *TInfo;
6045 if (Ty.isNull())
6046 return DeclarationNameInfo();
6047 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6048 Context.getCanonicalType(Ty)));
6049 NameInfo.setNamedTypeInfo(TInfo);
6050 return NameInfo;
6051 }
6052
6054 TypeSourceInfo *TInfo;
6055 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6056 if (Ty.isNull())
6057 return DeclarationNameInfo();
6058 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6059 Context.getCanonicalType(Ty)));
6060 NameInfo.setNamedTypeInfo(TInfo);
6061 return NameInfo;
6062 }
6063
6065 // In well-formed code, we can only have a constructor
6066 // template-id that refers to the current context, so go there
6067 // to find the actual type being constructed.
6068 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6069 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6070 return DeclarationNameInfo();
6071
6072 // Determine the type of the class being constructed.
6073 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6074
6075 // FIXME: Check two things: that the template-id names the same type as
6076 // CurClassType, and that the template-id does not occur when the name
6077 // was qualified.
6078
6079 NameInfo.setName(
6080 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6081 // FIXME: should we retrieve TypeSourceInfo?
6082 NameInfo.setNamedTypeInfo(nullptr);
6083 return NameInfo;
6084 }
6085
6087 TypeSourceInfo *TInfo;
6088 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6089 if (Ty.isNull())
6090 return DeclarationNameInfo();
6091 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6092 Context.getCanonicalType(Ty)));
6093 NameInfo.setNamedTypeInfo(TInfo);
6094 return NameInfo;
6095 }
6096
6098 TemplateName TName = Name.TemplateId->Template.get();
6099 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6100 return Context.getNameForTemplate(TName, TNameLoc);
6101 }
6102
6103 } // switch (Name.getKind())
6104
6105 llvm_unreachable("Unknown name kind");
6106}
6107
6109 do {
6110 if (Ty->isPointerOrReferenceType())
6111 Ty = Ty->getPointeeType();
6112 else if (Ty->isArrayType())
6114 else
6115 return Ty.withoutLocalFastQualifiers();
6116 } while (true);
6117}
6118
6119/// hasSimilarParameters - Determine whether the C++ functions Declaration
6120/// and Definition have "nearly" matching parameters. This heuristic is
6121/// used to improve diagnostics in the case where an out-of-line function
6122/// definition doesn't match any declaration within the class or namespace.
6123/// Also sets Params to the list of indices to the parameters that differ
6124/// between the declaration and the definition. If hasSimilarParameters
6125/// returns true and Params is empty, then all of the parameters match.
6129 SmallVectorImpl<unsigned> &Params) {
6130 Params.clear();
6131 if (Declaration->param_size() != Definition->param_size())
6132 return false;
6133 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6134 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6135 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6136
6137 // The parameter types are identical
6138 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6139 continue;
6140
6141 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6142 QualType DefParamBaseTy = getCoreType(DefParamTy);
6143 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6144 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6145
6146 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6147 (DeclTyName && DeclTyName == DefTyName))
6148 Params.push_back(Idx);
6149 else // The two parameters aren't even close
6150 return false;
6151 }
6152
6153 return true;
6154}
6155
6156/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6157/// declarator needs to be rebuilt in the current instantiation.
6158/// Any bits of declarator which appear before the name are valid for
6159/// consideration here. That's specifically the type in the decl spec
6160/// and the base type in any member-pointer chunks.
6162 DeclarationName Name) {
6163 // The types we specifically need to rebuild are:
6164 // - typenames, typeofs, and decltypes
6165 // - types which will become injected class names
6166 // Of course, we also need to rebuild any type referencing such a
6167 // type. It's safest to just say "dependent", but we call out a
6168 // few cases here.
6169
6170 DeclSpec &DS = D.getMutableDeclSpec();
6171 switch (DS.getTypeSpecType()) {
6175#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6176#include "clang/Basic/TransformTypeTraits.def"
6177 case DeclSpec::TST_atomic: {
6178 // Grab the type from the parser.
6179 TypeSourceInfo *TSI = nullptr;
6180 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6181 if (T.isNull() || !T->isInstantiationDependentType()) break;
6182
6183 // Make sure there's a type source info. This isn't really much
6184 // of a waste; most dependent types should have type source info
6185 // attached already.
6186 if (!TSI)
6188
6189 // Rebuild the type in the current instantiation.
6191 if (!TSI) return true;
6192
6193 // Store the new type back in the decl spec.
6194 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6195 DS.UpdateTypeRep(LocType);
6196 break;
6197 }
6198
6202 Expr *E = DS.getRepAsExpr();
6204 if (Result.isInvalid()) return true;
6205 DS.UpdateExprRep(Result.get());
6206 break;
6207 }
6208
6209 default:
6210 // Nothing to do for these decl specs.
6211 break;
6212 }
6213
6214 // It doesn't matter what order we do this in.
6215 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6216 DeclaratorChunk &Chunk = D.getTypeObject(I);
6217
6218 // The only type information in the declarator which can come
6219 // before the declaration name is the base type of a member
6220 // pointer.
6222 continue;
6223
6224 // Rebuild the scope specifier in-place.
6225 CXXScopeSpec &SS = Chunk.Mem.Scope();
6227 return true;
6228 }
6229
6230 return false;
6231}
6232
6233/// Returns true if the declaration is declared in a system header or from a
6234/// system macro.
6235static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6236 return SM.isInSystemHeader(D->getLocation()) ||
6237 SM.isInSystemMacro(D->getLocation());
6238}
6239
6241 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6242 // of system decl.
6243 if (D->getPreviousDecl() || D->isImplicit())
6244 return;
6247 !isFromSystemHeader(Context.getSourceManager(), D)) {
6248 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6249 << D << static_cast<int>(Status);
6250 }
6251}
6252
6255
6256 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6257 // declaration only if the `bind_to_declaration` extension is set.
6259 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6260 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6261 llvm::omp::TraitProperty::
6262 implementation_extension_bind_to_declaration))
6264 S, D, MultiTemplateParamsArg(), Bases);
6265
6267
6268 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6269 Dcl && Dcl->getDeclContext()->isFileContext())
6271
6272 if (!Bases.empty())
6274 Bases);
6275
6276 return Dcl;
6277}
6278
6280 DeclarationNameInfo NameInfo) {
6281 DeclarationName Name = NameInfo.getName();
6282
6283 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6284 while (Record && Record->isAnonymousStructOrUnion())
6285 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6286 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6287 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6288 return true;
6289 }
6290
6291 return false;
6292}
6293
6295 DeclarationName Name,
6296 SourceLocation Loc,
6297 TemplateIdAnnotation *TemplateId,
6298 bool IsMemberSpecialization) {
6299 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6300 "without nested-name-specifier");
6301 DeclContext *Cur = CurContext;
6302 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6303 Cur = Cur->getParent();
6304
6305 // If the user provided a superfluous scope specifier that refers back to the
6306 // class in which the entity is already declared, diagnose and ignore it.
6307 //
6308 // class X {
6309 // void X::f();
6310 // };
6311 //
6312 // Note, it was once ill-formed to give redundant qualification in all
6313 // contexts, but that rule was removed by DR482.
6314 if (Cur->Equals(DC)) {
6315 if (Cur->isRecord()) {
6316 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6317 : diag::err_member_extra_qualification)
6318 << Name << FixItHint::CreateRemoval(SS.getRange());
6319 SS.clear();
6320 } else {
6321 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6322 }
6323 return false;
6324 }
6325
6326 // Check whether the qualifying scope encloses the scope of the original
6327 // declaration. For a template-id, we perform the checks in
6328 // CheckTemplateSpecializationScope.
6329 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6330 if (Cur->isRecord())
6331 Diag(Loc, diag::err_member_qualification)
6332 << Name << SS.getRange();
6333 else if (isa<TranslationUnitDecl>(DC))
6334 Diag(Loc, diag::err_invalid_declarator_global_scope)
6335 << Name << SS.getRange();
6336 else if (isa<FunctionDecl>(Cur))
6337 Diag(Loc, diag::err_invalid_declarator_in_function)
6338 << Name << SS.getRange();
6339 else if (isa<BlockDecl>(Cur))
6340 Diag(Loc, diag::err_invalid_declarator_in_block)
6341 << Name << SS.getRange();
6342 else if (isa<ExportDecl>(Cur)) {
6343 if (!isa<NamespaceDecl>(DC))
6344 Diag(Loc, diag::err_export_non_namespace_scope_name)
6345 << Name << SS.getRange();
6346 else
6347 // The cases that DC is not NamespaceDecl should be handled in
6348 // CheckRedeclarationExported.
6349 return false;
6350 } else
6351 Diag(Loc, diag::err_invalid_declarator_scope)
6352 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6353
6354 return true;
6355 }
6356
6357 if (Cur->isRecord()) {
6358 // Cannot qualify members within a class.
6359 Diag(Loc, diag::err_member_qualification)
6360 << Name << SS.getRange();
6361 SS.clear();
6362
6363 // C++ constructors and destructors with incorrect scopes can break
6364 // our AST invariants by having the wrong underlying types. If
6365 // that's the case, then drop this declaration entirely.
6368 !Context.hasSameType(
6369 Name.getCXXNameType(),
6370 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6371 return true;
6372
6373 return false;
6374 }
6375
6376 // C++23 [temp.names]p5:
6377 // The keyword template shall not appear immediately after a declarative
6378 // nested-name-specifier.
6379 //
6380 // First check the template-id (if any), and then check each component of the
6381 // nested-name-specifier in reverse order.
6382 //
6383 // FIXME: nested-name-specifiers in friend declarations are declarative,
6384 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6385 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6386 Diag(Loc, diag::ext_template_after_declarative_nns)
6388
6390 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6391 TL = std::exchange(NextTL, TypeLoc())) {
6392 SourceLocation TemplateKeywordLoc;
6393 switch (TL.getTypeLocClass()) {
6394 case TypeLoc::TemplateSpecialization: {
6395 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6396 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6397 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6398 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6399 << TST.getLocalSourceRange();
6400 break;
6401 }
6402 case TypeLoc::Decltype:
6403 case TypeLoc::PackIndexing: {
6404 const Type *T = TL.getTypePtr();
6405 // C++23 [expr.prim.id.qual]p2:
6406 // [...] A declarative nested-name-specifier shall not have a
6407 // computed-type-specifier.
6408 //
6409 // CWG2858 changed this from 'decltype-specifier' to
6410 // 'computed-type-specifier'.
6411 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6412 << T->isDecltypeType() << TL.getSourceRange();
6413 break;
6414 }
6415 case TypeLoc::DependentName:
6416 NextTL =
6417 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6418 break;
6419 default:
6420 break;
6421 }
6422 if (TemplateKeywordLoc.isValid())
6423 Diag(Loc, diag::ext_template_after_declarative_nns)
6424 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6425 }
6426
6427 return false;
6428}
6429
6431 MultiTemplateParamsArg TemplateParamLists) {
6432 // TODO: consider using NameInfo for diagnostic.
6434 DeclarationName Name = NameInfo.getName();
6435
6436 // All of these full declarators require an identifier. If it doesn't have
6437 // one, the ParsedFreeStandingDeclSpec action should be used.
6438 if (D.isDecompositionDeclarator()) {
6439 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6440 } else if (!Name) {
6441 if (!D.isInvalidType()) // Reject this if we think it is valid.
6442 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6444 return nullptr;
6446 return nullptr;
6447
6448 DeclContext *DC = CurContext;
6449 if (D.getCXXScopeSpec().isInvalid())
6450 D.setInvalidType();
6451 else if (D.getCXXScopeSpec().isSet()) {
6454 return nullptr;
6455
6456 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6457 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6458 if (!DC || isa<EnumDecl>(DC)) {
6459 // If we could not compute the declaration context, it's because the
6460 // declaration context is dependent but does not refer to a class,
6461 // class template, or class template partial specialization. Complain
6462 // and return early, to avoid the coming semantic disaster.
6464 diag::err_template_qualified_declarator_no_match)
6466 << D.getCXXScopeSpec().getRange();
6467 return nullptr;
6468 }
6469 bool IsDependentContext = DC->isDependentContext();
6470
6471 if (!IsDependentContext &&
6473 return nullptr;
6474
6475 // If a class is incomplete, do not parse entities inside it.
6478 diag::err_member_def_undefined_record)
6479 << Name << DC << D.getCXXScopeSpec().getRange();
6480 return nullptr;
6481 }
6482 if (!D.getDeclSpec().isFriendSpecified()) {
6483 TemplateIdAnnotation *TemplateId =
6485 ? D.getName().TemplateId
6486 : nullptr;
6488 D.getIdentifierLoc(), TemplateId,
6489 /*IsMemberSpecialization=*/false)) {
6490 if (DC->isRecord())
6491 return nullptr;
6492
6493 D.setInvalidType();
6494 }
6495 }
6496
6497 // Check whether we need to rebuild the type of the given
6498 // declaration in the current instantiation.
6499 if (EnteringContext && IsDependentContext &&
6500 TemplateParamLists.size() != 0) {
6501 ContextRAII SavedContext(*this, DC);
6502 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6503 D.setInvalidType();
6504 }
6505 }
6506
6508 QualType R = TInfo->getType();
6509
6512 D.setInvalidType();
6513
6514 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6516
6517 // See if this is a redefinition of a variable in the same scope.
6518 if (!D.getCXXScopeSpec().isSet()) {
6519 bool IsLinkageLookup = false;
6520 bool CreateBuiltins = false;
6521
6522 // If the declaration we're planning to build will be a function
6523 // or object with linkage, then look for another declaration with
6524 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6525 //
6526 // If the declaration we're planning to build will be declared with
6527 // external linkage in the translation unit, create any builtin with
6528 // the same name.
6530 /* Do nothing*/;
6531 else if (CurContext->isFunctionOrMethod() &&
6533 R->isFunctionType())) {
6534 IsLinkageLookup = true;
6535 CreateBuiltins =
6536 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6537 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6539 CreateBuiltins = true;
6540
6541 if (IsLinkageLookup) {
6543 Previous.setRedeclarationKind(
6545 }
6546
6547 LookupName(Previous, S, CreateBuiltins);
6548 } else { // Something like "int foo::x;"
6550
6551 // C++ [dcl.meaning]p1:
6552 // When the declarator-id is qualified, the declaration shall refer to a
6553 // previously declared member of the class or namespace to which the
6554 // qualifier refers (or, in the case of a namespace, of an element of the
6555 // inline namespace set of that namespace (7.3.1)) or to a specialization
6556 // thereof; [...]
6557 //
6558 // Note that we already checked the context above, and that we do not have
6559 // enough information to make sure that Previous contains the declaration
6560 // we want to match. For example, given:
6561 //
6562 // class X {
6563 // void f();
6564 // void f(float);
6565 // };
6566 //
6567 // void X::f(int) { } // ill-formed
6568 //
6569 // In this case, Previous will point to the overload set
6570 // containing the two f's declared in X, but neither of them
6571 // matches.
6572
6574 }
6575
6576 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6577 TPD && TPD->isTemplateParameter()) {
6578 // Older versions of clang allowed the names of function/variable templates
6579 // to shadow the names of their template parameters. For the compatibility
6580 // purposes we detect such cases and issue a default-to-error warning that
6581 // can be disabled with -Wno-strict-primary-template-shadow.
6582 if (!D.isInvalidType()) {
6583 bool AllowForCompatibility = false;
6584 if (Scope *DeclParent = S->getDeclParent();
6585 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6586 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6587 TemplateParamParent->isDeclScope(TPD);
6588 }
6590 AllowForCompatibility);
6591 }
6592
6593 // Just pretend that we didn't see the previous declaration.
6594 Previous.clear();
6595 }
6596
6597 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6598 // Forget that the previous declaration is the injected-class-name.
6599 Previous.clear();
6600
6601 // In C++, the previous declaration we find might be a tag type
6602 // (class or enum). In this case, the new declaration will hide the
6603 // tag type. Note that this applies to functions, function templates, and
6604 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6605 if (Previous.isSingleTagDecl() &&
6607 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6608 Previous.clear();
6609
6610 // Check that there are no default arguments other than in the parameters
6611 // of a function declaration (C++ only).
6612 if (getLangOpts().CPlusPlus)
6614
6615 /// Get the innermost enclosing declaration scope.
6616 S = S->getDeclParent();
6617
6618 NamedDecl *New;
6619
6620 bool AddToScope = true;
6622 if (TemplateParamLists.size()) {
6623 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6624 return nullptr;
6625 }
6626
6627 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6628 } else if (R->isFunctionType()) {
6629 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6630 TemplateParamLists,
6631 AddToScope);
6632 } else {
6633 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6634 AddToScope);
6635 }
6636
6637 if (!New)
6638 return nullptr;
6639
6641
6642 // If this has an identifier and is not a function template specialization,
6643 // add it to the scope stack.
6644 if (New->getDeclName() && AddToScope)
6646
6647 if (OpenMP().isInOpenMPDeclareTargetContext())
6649
6650 return New;
6651}
6652
6653/// Helper method to turn variable array types into constant array
6654/// types in certain situations which would otherwise be errors (for
6655/// GCC compatibility).
6657 ASTContext &Context,
6658 bool &SizeIsNegative,
6659 llvm::APSInt &Oversized) {
6660 // This method tries to turn a variable array into a constant
6661 // array even when the size isn't an ICE. This is necessary
6662 // for compatibility with code that depends on gcc's buggy
6663 // constant expression folding, like struct {char x[(int)(char*)2];}
6664 SizeIsNegative = false;
6665 Oversized = 0;
6666
6667 if (T->isDependentType())
6668 return QualType();
6669
6671 const Type *Ty = Qs.strip(T);
6672
6673 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6674 QualType Pointee = PTy->getPointeeType();
6675 QualType FixedType =
6676 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6677 Oversized);
6678 if (FixedType.isNull()) return FixedType;
6679 FixedType = Context.getPointerType(FixedType);
6680 return Qs.apply(Context, FixedType);
6681 }
6682 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6683 QualType Inner = PTy->getInnerType();
6684 QualType FixedType =
6685 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6686 Oversized);
6687 if (FixedType.isNull()) return FixedType;
6688 FixedType = Context.getParenType(FixedType);
6689 return Qs.apply(Context, FixedType);
6690 }
6691
6692 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6693 if (!VLATy)
6694 return QualType();
6695
6696 QualType ElemTy = VLATy->getElementType();
6697 if (ElemTy->isVariablyModifiedType()) {
6698 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6699 SizeIsNegative, Oversized);
6700 if (ElemTy.isNull())
6701 return QualType();
6702 }
6703
6704 Expr::EvalResult Result;
6705 if (!VLATy->getSizeExpr() ||
6706 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6707 return QualType();
6708
6709 llvm::APSInt Res = Result.Val.getInt();
6710
6711 // Check whether the array size is negative.
6712 if (Res.isSigned() && Res.isNegative()) {
6713 SizeIsNegative = true;
6714 return QualType();
6715 }
6716
6717 // Check whether the array is too large to be addressed.
6718 unsigned ActiveSizeBits =
6719 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6720 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6721 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6722 : Res.getActiveBits();
6723 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6724 Oversized = Res;
6725 return QualType();
6726 }
6727
6728 QualType FoldedArrayType = Context.getConstantArrayType(
6729 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6730 return Qs.apply(Context, FoldedArrayType);
6731}
6732
6733static void
6735 SrcTL = SrcTL.getUnqualifiedLoc();
6736 DstTL = DstTL.getUnqualifiedLoc();
6737 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6738 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6739 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6740 DstPTL.getPointeeLoc());
6741 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6742 return;
6743 }
6744 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6745 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6746 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6747 DstPTL.getInnerLoc());
6748 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6749 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6750 return;
6751 }
6752 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6753 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6754 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6755 TypeLoc DstElemTL = DstATL.getElementLoc();
6756 if (VariableArrayTypeLoc SrcElemATL =
6757 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6758 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6759 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6760 } else {
6761 DstElemTL.initializeFullCopy(SrcElemTL);
6762 }
6763 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6764 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6765 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6766}
6767
6768/// Helper method to turn variable array types into constant array
6769/// types in certain situations which would otherwise be errors (for
6770/// GCC compatibility).
6771static TypeSourceInfo*
6773 ASTContext &Context,
6774 bool &SizeIsNegative,
6775 llvm::APSInt &Oversized) {
6776 QualType FixedTy
6777 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6778 SizeIsNegative, Oversized);
6779 if (FixedTy.isNull())
6780 return nullptr;
6781 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6783 FixedTInfo->getTypeLoc());
6784 return FixedTInfo;
6785}
6786
6789 unsigned FailedFoldDiagID) {
6790 bool SizeIsNegative;
6791 llvm::APSInt Oversized;
6793 TInfo, Context, SizeIsNegative, Oversized);
6794 if (FixedTInfo) {
6795 Diag(Loc, diag::ext_vla_folded_to_constant);
6796 TInfo = FixedTInfo;
6797 T = FixedTInfo->getType();
6798 return true;
6799 }
6800
6801 if (SizeIsNegative)
6802 Diag(Loc, diag::err_typecheck_negative_array_size);
6803 else if (Oversized.getBoolValue())
6804 Diag(Loc, diag::err_array_too_large) << toString(
6805 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6806 /*UpperCase=*/false, /*InsertSeparators=*/true);
6807 else if (FailedFoldDiagID)
6808 Diag(Loc, FailedFoldDiagID);
6809 return false;
6810}
6811
6812void
6814 if (!getLangOpts().CPlusPlus &&
6816 // Don't need to track declarations in the TU in C.
6817 return;
6818
6819 // Note that we have a locally-scoped external with this name.
6820 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6821}
6822
6824 // FIXME: We can have multiple results via __attribute__((overloadable)).
6825 auto Result = Context.getExternCContextDecl()->lookup(Name);
6826 return Result.empty() ? nullptr : *Result.begin();
6827}
6828
6830 // FIXME: We should probably indicate the identifier in question to avoid
6831 // confusion for constructs like "virtual int a(), b;"
6832 if (DS.isVirtualSpecified())
6834 diag::err_virtual_non_function);
6835
6836 if (DS.hasExplicitSpecifier())
6838 diag::err_explicit_non_function);
6839
6840 if (DS.isNoreturnSpecified())
6842 diag::err_noreturn_non_function);
6843}
6844
6845NamedDecl*
6848 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6849 if (D.getCXXScopeSpec().isSet()) {
6850 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6851 << D.getCXXScopeSpec().getRange();
6852 D.setInvalidType();
6853 // Pretend we didn't see the scope specifier.
6854 DC = CurContext;
6855 Previous.clear();
6856 }
6857
6859
6862 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6863 ? diag::warn_ms_inline_non_function
6864 : diag::err_inline_non_function)
6865 << getLangOpts().CPlusPlus17;
6867 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6868 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6869
6873 diag::err_deduction_guide_invalid_specifier)
6874 << "typedef";
6875 else
6876 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6877 << D.getName().getSourceRange();
6878 return nullptr;
6879 }
6880
6881 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6882 if (!NewTD) return nullptr;
6883
6884 // Handle attributes prior to checking for duplicates in MergeVarDecl
6885 ProcessDeclAttributes(S, NewTD, D);
6886
6888
6889 bool Redeclaration = D.isRedeclaration();
6892 return ND;
6893}
6894
6895void
6897 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6898 // then it shall have block scope.
6899 // Note that variably modified types must be fixed before merging the decl so
6900 // that redeclarations will match.
6901 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6902 QualType T = TInfo->getType();
6903 if (T->isVariablyModifiedType()) {
6905
6906 if (S->getFnParent() == nullptr) {
6907 bool SizeIsNegative;
6908 llvm::APSInt Oversized;
6909 TypeSourceInfo *FixedTInfo =
6911 SizeIsNegative,
6912 Oversized);
6913 if (FixedTInfo) {
6914 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6915 NewTD->setTypeSourceInfo(FixedTInfo);
6916 } else {
6917 if (SizeIsNegative)
6918 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6919 else if (T->isVariableArrayType())
6920 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6921 else if (Oversized.getBoolValue())
6922 Diag(NewTD->getLocation(), diag::err_array_too_large)
6923 << toString(Oversized, 10);
6924 else
6925 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6926 NewTD->setInvalidDecl();
6927 }
6928 }
6929 }
6930}
6931
6932NamedDecl*
6935
6936 // Find the shadowed declaration before filtering for scope.
6937 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6938
6939 // Merge the decl with the existing one if appropriate. If the decl is
6940 // in an outer scope, it isn't the same thing.
6941 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6942 /*AllowInlineNamespace*/false);
6944 if (!Previous.empty()) {
6945 Redeclaration = true;
6946 MergeTypedefNameDecl(S, NewTD, Previous);
6947 } else {
6949 }
6950
6951 if (ShadowedDecl && !Redeclaration)
6952 CheckShadow(NewTD, ShadowedDecl, Previous);
6953
6954 // If this is the C FILE type, notify the AST context.
6955 if (IdentifierInfo *II = NewTD->getIdentifier())
6956 if (!NewTD->isInvalidDecl() &&
6958 switch (II->getNotableIdentifierID()) {
6959 case tok::NotableIdentifierKind::FILE:
6960 Context.setFILEDecl(NewTD);
6961 break;
6962 case tok::NotableIdentifierKind::jmp_buf:
6963 Context.setjmp_bufDecl(NewTD);
6964 break;
6965 case tok::NotableIdentifierKind::sigjmp_buf:
6966 Context.setsigjmp_bufDecl(NewTD);
6967 break;
6968 case tok::NotableIdentifierKind::ucontext_t:
6969 Context.setucontext_tDecl(NewTD);
6970 break;
6971 case tok::NotableIdentifierKind::float_t:
6972 case tok::NotableIdentifierKind::double_t:
6973 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6974 break;
6975 default:
6976 break;
6977 }
6978 }
6979
6980 return NewTD;
6981}
6982
6983/// Determines whether the given declaration is an out-of-scope
6984/// previous declaration.
6985///
6986/// This routine should be invoked when name lookup has found a
6987/// previous declaration (PrevDecl) that is not in the scope where a
6988/// new declaration by the same name is being introduced. If the new
6989/// declaration occurs in a local scope, previous declarations with
6990/// linkage may still be considered previous declarations (C99
6991/// 6.2.2p4-5, C++ [basic.link]p6).
6992///
6993/// \param PrevDecl the previous declaration found by name
6994/// lookup
6995///
6996/// \param DC the context in which the new declaration is being
6997/// declared.
6998///
6999/// \returns true if PrevDecl is an out-of-scope previous declaration
7000/// for a new delcaration with the same name.
7001static bool
7003 ASTContext &Context) {
7004 if (!PrevDecl)
7005 return false;
7006
7007 if (!PrevDecl->hasLinkage())
7008 return false;
7009
7010 if (Context.getLangOpts().CPlusPlus) {
7011 // C++ [basic.link]p6:
7012 // If there is a visible declaration of an entity with linkage
7013 // having the same name and type, ignoring entities declared
7014 // outside the innermost enclosing namespace scope, the block
7015 // scope declaration declares that same entity and receives the
7016 // linkage of the previous declaration.
7017 DeclContext *OuterContext = DC->getRedeclContext();
7018 if (!OuterContext->isFunctionOrMethod())
7019 // This rule only applies to block-scope declarations.
7020 return false;
7021
7022 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7023 if (PrevOuterContext->isRecord())
7024 // We found a member function: ignore it.
7025 return false;
7026
7027 // Find the innermost enclosing namespace for the new and
7028 // previous declarations.
7029 OuterContext = OuterContext->getEnclosingNamespaceContext();
7030 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7031
7032 // The previous declaration is in a different namespace, so it
7033 // isn't the same function.
7034 if (!OuterContext->Equals(PrevOuterContext))
7035 return false;
7036 }
7037
7038 return true;
7039}
7040
7042 CXXScopeSpec &SS = D.getCXXScopeSpec();
7043 if (!SS.isSet()) return;
7045}
7046
7048 if (Decl->getType().hasAddressSpace())
7049 return;
7050 if (Decl->getType()->isDependentType())
7051 return;
7052 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
7053 QualType Type = Var->getType();
7054 if (Type->isSamplerT() || Type->isVoidType())
7055 return;
7057 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7058 // __opencl_c_program_scope_global_variables feature, the address space
7059 // for a variable at program scope or a static or extern variable inside
7060 // a function are inferred to be __global.
7061 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7062 Var->hasGlobalStorage())
7063 ImplAS = LangAS::opencl_global;
7064 // If the original type from a decayed type is an array type and that array
7065 // type has no address space yet, deduce it now.
7066 if (auto DT = dyn_cast<DecayedType>(Type)) {
7067 auto OrigTy = DT->getOriginalType();
7068 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7069 // Add the address space to the original array type and then propagate
7070 // that to the element type through `getAsArrayType`.
7071 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7072 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7073 // Re-generate the decayed type.
7074 Type = Context.getDecayedType(OrigTy);
7075 }
7076 }
7077 Type = Context.getAddrSpaceQualType(Type, ImplAS);
7078 // Apply any qualifiers (including address space) from the array type to
7079 // the element type. This implements C99 6.7.3p8: "If the specification of
7080 // an array type includes any type qualifiers, the element type is so
7081 // qualified, not the array type."
7082 if (Type->isArrayType())
7083 Type = QualType(Context.getAsArrayType(Type), 0);
7084 Decl->setType(Type);
7085 }
7086}
7087
7088static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7089 // 'weak' only applies to declarations with external linkage.
7090 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7091 if (!ND.isExternallyVisible()) {
7092 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7093 ND.dropAttr<WeakAttr>();
7094 }
7095 }
7096}
7097
7098static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7099 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7100 if (ND.isExternallyVisible()) {
7101 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7102 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7103 }
7104 }
7105}
7106
7107static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7108 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7109 if (VD->hasInit()) {
7110 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7111 assert(VD->isThisDeclarationADefinition() &&
7112 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7113 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7114 VD->dropAttr<AliasAttr>();
7115 }
7116 }
7117 }
7118}
7119
7120static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7121 // 'selectany' only applies to externally visible variable declarations.
7122 // It does not apply to functions.
7123 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7124 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7125 S.Diag(Attr->getLocation(),
7126 diag::err_attribute_selectany_non_extern_data);
7127 ND.dropAttr<SelectAnyAttr>();
7128 }
7129 }
7130}
7131
7133 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7134 if (!ND.isExternallyVisible())
7135 S.Diag(Attr->getLocation(),
7136 diag::warn_attribute_hybrid_patchable_non_extern);
7137 }
7138}
7139
7141 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7142 auto *VD = dyn_cast<VarDecl>(&ND);
7143 bool IsAnonymousNS = false;
7144 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7145 if (VD) {
7146 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7147 while (NS && !IsAnonymousNS) {
7148 IsAnonymousNS = NS->isAnonymousNamespace();
7149 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7150 }
7151 }
7152 // dll attributes require external linkage. Static locals may have external
7153 // linkage but still cannot be explicitly imported or exported.
7154 // In Microsoft mode, a variable defined in anonymous namespace must have
7155 // external linkage in order to be exported.
7156 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7157 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7158 (!AnonNSInMicrosoftMode &&
7159 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7160 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7161 << &ND << Attr;
7162 ND.setInvalidDecl();
7163 }
7164 }
7165}
7166
7168 // Check the attributes on the function type and function params, if any.
7169 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7170 FD = FD->getMostRecentDecl();
7171 // Don't declare this variable in the second operand of the for-statement;
7172 // GCC miscompiles that by ending its lifetime before evaluating the
7173 // third operand. See gcc.gnu.org/PR86769.
7175 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7176 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7177 TL = ATL.getModifiedLoc()) {
7178 // The [[lifetimebound]] attribute can be applied to the implicit object
7179 // parameter of a non-static member function (other than a ctor or dtor)
7180 // by applying it to the function type.
7181 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7182 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7183 int NoImplicitObjectError = -1;
7184 if (!MD)
7185 NoImplicitObjectError = 0;
7186 else if (MD->isStatic())
7187 NoImplicitObjectError = 1;
7188 else if (MD->isExplicitObjectMemberFunction())
7189 NoImplicitObjectError = 2;
7190 if (NoImplicitObjectError != -1) {
7191 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7192 << NoImplicitObjectError << A->getRange();
7193 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7194 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7195 << isa<CXXDestructorDecl>(MD) << A->getRange();
7196 } else if (MD->getReturnType()->isVoidType()) {
7197 S.Diag(
7198 MD->getLocation(),
7199 diag::
7200 err_lifetimebound_implicit_object_parameter_void_return_type);
7201 }
7202 }
7203 }
7204
7205 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7206 const ParmVarDecl *P = FD->getParamDecl(I);
7207
7208 // The [[lifetimebound]] attribute can be applied to a function parameter
7209 // only if the function returns a value.
7210 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7211 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7212 S.Diag(A->getLocation(),
7213 diag::err_lifetimebound_parameter_void_return_type);
7214 }
7215 }
7216 }
7217 }
7218}
7219
7221 // Ensure that an auto decl is deduced otherwise the checks below might cache
7222 // the wrong linkage.
7223 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7224
7225 checkWeakAttr(S, ND);
7226 checkWeakRefAttr(S, ND);
7227 checkAliasAttr(S, ND);
7228 checkSelectAnyAttr(S, ND);
7230 checkInheritableAttr(S, ND);
7232}
7233
7235 NamedDecl *NewDecl,
7236 bool IsSpecialization,
7237 bool IsDefinition) {
7238 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7239 return;
7240
7241 bool IsTemplate = false;
7242 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7243 OldDecl = OldTD->getTemplatedDecl();
7244 IsTemplate = true;
7245 if (!IsSpecialization)
7246 IsDefinition = false;
7247 }
7248 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7249 NewDecl = NewTD->getTemplatedDecl();
7250 IsTemplate = true;
7251 }
7252
7253 if (!OldDecl || !NewDecl)
7254 return;
7255
7256 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7257 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7258 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7259 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7260
7261 // dllimport and dllexport are inheritable attributes so we have to exclude
7262 // inherited attribute instances.
7263 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7264 (NewExportAttr && !NewExportAttr->isInherited());
7265
7266 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7267 // the only exception being explicit specializations.
7268 // Implicitly generated declarations are also excluded for now because there
7269 // is no other way to switch these to use dllimport or dllexport.
7270 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7271
7272 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7273 // Allow with a warning for free functions and global variables.
7274 bool JustWarn = false;
7275 if (!OldDecl->isCXXClassMember()) {
7276 auto *VD = dyn_cast<VarDecl>(OldDecl);
7277 if (VD && !VD->getDescribedVarTemplate())
7278 JustWarn = true;
7279 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7280 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7281 JustWarn = true;
7282 }
7283
7284 // We cannot change a declaration that's been used because IR has already
7285 // been emitted. Dllimported functions will still work though (modulo
7286 // address equality) as they can use the thunk.
7287 if (OldDecl->isUsed())
7288 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7289 JustWarn = false;
7290
7291 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7292 : diag::err_attribute_dll_redeclaration;
7293 S.Diag(NewDecl->getLocation(), DiagID)
7294 << NewDecl
7295 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7296 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7297 if (!JustWarn) {
7298 NewDecl->setInvalidDecl();
7299 return;
7300 }
7301 }
7302
7303 // A redeclaration is not allowed to drop a dllimport attribute, the only
7304 // exceptions being inline function definitions (except for function
7305 // templates), local extern declarations, qualified friend declarations or
7306 // special MSVC extension: in the last case, the declaration is treated as if
7307 // it were marked dllexport.
7308 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7309 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7310 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7311 // Ignore static data because out-of-line definitions are diagnosed
7312 // separately.
7313 IsStaticDataMember = VD->isStaticDataMember();
7314 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7316 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7317 IsInline = FD->isInlined();
7318 IsQualifiedFriend = FD->getQualifier() &&
7319 FD->getFriendObjectKind() == Decl::FOK_Declared;
7320 }
7321
7322 if (OldImportAttr && !HasNewAttr &&
7323 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7324 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7325 if (IsMicrosoftABI && IsDefinition) {
7326 if (IsSpecialization) {
7327 S.Diag(
7328 NewDecl->getLocation(),
7329 diag::err_attribute_dllimport_function_specialization_definition);
7330 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7331 NewDecl->dropAttr<DLLImportAttr>();
7332 } else {
7333 S.Diag(NewDecl->getLocation(),
7334 diag::warn_redeclaration_without_import_attribute)
7335 << NewDecl;
7336 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7337 NewDecl->dropAttr<DLLImportAttr>();
7338 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7339 S.Context, NewImportAttr->getRange()));
7340 }
7341 } else if (IsMicrosoftABI && IsSpecialization) {
7342 assert(!IsDefinition);
7343 // MSVC allows this. Keep the inherited attribute.
7344 } else {
7345 S.Diag(NewDecl->getLocation(),
7346 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7347 << NewDecl << OldImportAttr;
7348 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7349 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7350 OldDecl->dropAttr<DLLImportAttr>();
7351 NewDecl->dropAttr<DLLImportAttr>();
7352 }
7353 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7354 // In MinGW, seeing a function declared inline drops the dllimport
7355 // attribute.
7356 OldDecl->dropAttr<DLLImportAttr>();
7357 NewDecl->dropAttr<DLLImportAttr>();
7358 S.Diag(NewDecl->getLocation(),
7359 diag::warn_dllimport_dropped_from_inline_function)
7360 << NewDecl << OldImportAttr;
7361 }
7362
7363 // A specialization of a class template member function is processed here
7364 // since it's a redeclaration. If the parent class is dllexport, the
7365 // specialization inherits that attribute. This doesn't happen automatically
7366 // since the parent class isn't instantiated until later.
7367 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7368 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7369 !NewImportAttr && !NewExportAttr) {
7370 if (const DLLExportAttr *ParentExportAttr =
7371 MD->getParent()->getAttr<DLLExportAttr>()) {
7372 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7373 NewAttr->setInherited(true);
7374 NewDecl->addAttr(NewAttr);
7375 }
7376 }
7377 }
7378}
7379
7380/// Given that we are within the definition of the given function,
7381/// will that definition behave like C99's 'inline', where the
7382/// definition is discarded except for optimization purposes?
7384 // Try to avoid calling GetGVALinkageForFunction.
7385
7386 // All cases of this require the 'inline' keyword.
7387 if (!FD->isInlined()) return false;
7388
7389 // This is only possible in C++ with the gnu_inline attribute.
7390 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7391 return false;
7392
7393 // Okay, go ahead and call the relatively-more-expensive function.
7395}
7396
7397/// Determine whether a variable is extern "C" prior to attaching
7398/// an initializer. We can't just call isExternC() here, because that
7399/// will also compute and cache whether the declaration is externally
7400/// visible, which might change when we attach the initializer.
7401///
7402/// This can only be used if the declaration is known to not be a
7403/// redeclaration of an internal linkage declaration.
7404///
7405/// For instance:
7406///
7407/// auto x = []{};
7408///
7409/// Attaching the initializer here makes this declaration not externally
7410/// visible, because its type has internal linkage.
7411///
7412/// FIXME: This is a hack.
7413template<typename T>
7414static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7415 if (S.getLangOpts().CPlusPlus) {
7416 // In C++, the overloadable attribute negates the effects of extern "C".
7417 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7418 return false;
7419
7420 // So do CUDA's host/device attributes.
7421 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7422 D->template hasAttr<CUDAHostAttr>()))
7423 return false;
7424 }
7425 return D->isExternC();
7426}
7427
7428static bool shouldConsiderLinkage(const VarDecl *VD) {
7429 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7432 return VD->hasExternalStorage();
7433 if (DC->isFileContext())
7434 return true;
7435 if (DC->isRecord())
7436 return false;
7437 if (DC->getDeclKind() == Decl::HLSLBuffer)
7438 return false;
7439
7441 return false;
7442 llvm_unreachable("Unexpected context");
7443}
7444
7445static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7446 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7447 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7449 return true;
7450 if (DC->isRecord())
7451 return false;
7452 llvm_unreachable("Unexpected context");
7453}
7454
7455static bool hasParsedAttr(Scope *S, const Declarator &PD,
7456 ParsedAttr::Kind Kind) {
7457 // Check decl attributes on the DeclSpec.
7458 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7459 return true;
7460
7461 // Walk the declarator structure, checking decl attributes that were in a type
7462 // position to the decl itself.
7463 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7464 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7465 return true;
7466 }
7467
7468 // Finally, check attributes on the decl itself.
7469 return PD.getAttributes().hasAttribute(Kind) ||
7471}
7472
7474 if (!DC->isFunctionOrMethod())
7475 return false;
7476
7477 // If this is a local extern function or variable declared within a function
7478 // template, don't add it into the enclosing namespace scope until it is
7479 // instantiated; it might have a dependent type right now.
7480 if (DC->isDependentContext())
7481 return true;
7482
7483 // C++11 [basic.link]p7:
7484 // When a block scope declaration of an entity with linkage is not found to
7485 // refer to some other declaration, then that entity is a member of the
7486 // innermost enclosing namespace.
7487 //
7488 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7489 // semantically-enclosing namespace, not a lexically-enclosing one.
7490 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7491 DC = DC->getParent();
7492 return true;
7493}
7494
7495/// Returns true if given declaration has external C language linkage.
7496static bool isDeclExternC(const Decl *D) {
7497 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7498 return FD->isExternC();
7499 if (const auto *VD = dyn_cast<VarDecl>(D))
7500 return VD->isExternC();
7501
7502 llvm_unreachable("Unknown type of decl!");
7503}
7504
7505/// Returns true if there hasn't been any invalid type diagnosed.
7506static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7507 DeclContext *DC = NewVD->getDeclContext();
7508 QualType R = NewVD->getType();
7509
7510 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7511 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7512 // argument.
7513 if (R->isImageType() || R->isPipeType()) {
7514 Se.Diag(NewVD->getLocation(),
7515 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7516 << R;
7517 NewVD->setInvalidDecl();
7518 return false;
7519 }
7520
7521 // OpenCL v1.2 s6.9.r:
7522 // The event type cannot be used to declare a program scope variable.
7523 // OpenCL v2.0 s6.9.q:
7524 // The clk_event_t and reserve_id_t types cannot be declared in program
7525 // scope.
7526 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7527 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7528 Se.Diag(NewVD->getLocation(),
7529 diag::err_invalid_type_for_program_scope_var)
7530 << R;
7531 NewVD->setInvalidDecl();
7532 return false;
7533 }
7534 }
7535
7536 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7537 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7538 Se.getLangOpts())) {
7539 QualType NR = R.getCanonicalType();
7540 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7541 NR->isReferenceType()) {
7544 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7545 << NR->isReferenceType();
7546 NewVD->setInvalidDecl();
7547 return false;
7548 }
7549 NR = NR->getPointeeType();
7550 }
7551 }
7552
7553 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7554 Se.getLangOpts())) {
7555 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7556 // half array type (unless the cl_khr_fp16 extension is enabled).
7557 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7558 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7559 NewVD->setInvalidDecl();
7560 return false;
7561 }
7562 }
7563
7564 // OpenCL v1.2 s6.9.r:
7565 // The event type cannot be used with the __local, __constant and __global
7566 // address space qualifiers.
7567 if (R->isEventT()) {
7569 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7570 NewVD->setInvalidDecl();
7571 return false;
7572 }
7573 }
7574
7575 if (R->isSamplerT()) {
7576 // OpenCL v1.2 s6.9.b p4:
7577 // The sampler type cannot be used with the __local and __global address
7578 // space qualifiers.
7581 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7582 NewVD->setInvalidDecl();
7583 }
7584
7585 // OpenCL v1.2 s6.12.14.1:
7586 // A global sampler must be declared with either the constant address
7587 // space qualifier or with the const qualifier.
7588 if (DC->isTranslationUnit() &&
7590 R.isConstQualified())) {
7591 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7592 NewVD->setInvalidDecl();
7593 }
7594 if (NewVD->isInvalidDecl())
7595 return false;
7596 }
7597
7598 return true;
7599}
7600
7601template <typename AttrTy>
7602static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7603 const TypedefNameDecl *TND = TT->getDecl();
7604 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7605 AttrTy *Clone = Attribute->clone(S.Context);
7606 Clone->setInherited(true);
7607 D->addAttr(Clone);
7608 }
7609}
7610
7611// This function emits warning and a corresponding note based on the
7612// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7613// declarations of an annotated type must be const qualified.
7615 QualType VarType = VD->getType().getCanonicalType();
7616
7617 // Ignore local declarations (for now) and those with const qualification.
7618 // TODO: Local variables should not be allowed if their type declaration has
7619 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7620 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7621 return;
7622
7623 if (VarType->isArrayType()) {
7624 // Retrieve element type for array declarations.
7625 VarType = S.getASTContext().getBaseElementType(VarType);
7626 }
7627
7628 const RecordDecl *RD = VarType->getAsRecordDecl();
7629
7630 // Check if the record declaration is present and if it has any attributes.
7631 if (RD == nullptr)
7632 return;
7633
7634 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7635 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7636 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7637 return;
7638 }
7639}
7640
7641// Checks if VD is declared at global scope or with C language linkage.
7642static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7643 return Name.getAsIdentifierInfo() &&
7644 Name.getAsIdentifierInfo()->isStr("main") &&
7645 !VD->getDescribedVarTemplate() &&
7646 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7647 VD->isExternC());
7648}
7649
7650void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7651 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7652
7653 // Quickly return if the function does not have an `asm` attribute.
7654 if (E == nullptr)
7655 return;
7656
7657 // The parser guarantees this is a string.
7658 StringLiteral *SE = cast<StringLiteral>(E);
7659 StringRef Label = SE->getString();
7660 QualType R = TInfo->getType();
7661 if (S->getFnParent() != nullptr) {
7662 switch (SC) {
7663 case SC_None:
7664 case SC_Auto:
7665 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7666 break;
7667 case SC_Register:
7668 // Local Named register
7669 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7671 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7672 break;
7673 case SC_Static:
7674 case SC_Extern:
7675 case SC_PrivateExtern:
7676 break;
7677 }
7678 } else if (SC == SC_Register) {
7679 // Global Named register
7680 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7681 const auto &TI = Context.getTargetInfo();
7682 bool HasSizeMismatch;
7683
7684 if (!TI.isValidGCCRegisterName(Label))
7685 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7686 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),
7687 HasSizeMismatch))
7688 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7689 else if (HasSizeMismatch)
7690 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7691 }
7692
7693 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7694 Diag(TInfo->getTypeLoc().getBeginLoc(),
7695 diag::err_asm_unsupported_register_type)
7696 << TInfo->getTypeLoc().getSourceRange();
7697 NewVD->setInvalidDecl(true);
7698 }
7699 }
7700}
7701
7703 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7704 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7705 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7706 QualType R = TInfo->getType();
7708
7710 bool IsPlaceholderVariable = false;
7711
7712 if (D.isDecompositionDeclarator()) {
7713 // Take the name of the first declarator as our name for diagnostic
7714 // purposes.
7715 auto &Decomp = D.getDecompositionDeclarator();
7716 if (!Decomp.bindings().empty()) {
7717 II = Decomp.bindings()[0].Name;
7718 Name = II;
7719 }
7720 } else if (!II) {
7721 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7722 return nullptr;
7723 }
7724
7725
7728 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7729 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7730
7731 IsPlaceholderVariable = true;
7732
7733 if (!Previous.empty()) {
7734 NamedDecl *PrevDecl = *Previous.begin();
7735 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7736 DC->getRedeclContext());
7737 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7738 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7739 if (IsPlaceholderVariable)
7741 }
7742 }
7743 }
7744
7745 // dllimport globals without explicit storage class are treated as extern. We
7746 // have to change the storage class this early to get the right DeclContext.
7747 if (SC == SC_None && !DC->isRecord() &&
7748 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7749 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7750 SC = SC_Extern;
7751
7752 DeclContext *OriginalDC = DC;
7753 bool IsLocalExternDecl = SC == SC_Extern &&
7755
7756 if (SCSpec == DeclSpec::SCS_mutable) {
7757 // mutable can only appear on non-static class members, so it's always
7758 // an error here
7759 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7760 D.setInvalidType();
7761 SC = SC_None;
7762 }
7763
7764 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7765 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7767 // In C++11, the 'register' storage class specifier is deprecated.
7768 // Suppress the warning in system macros, it's used in macros in some
7769 // popular C system headers, such as in glibc's htonl() macro.
7771 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7772 : diag::warn_deprecated_register)
7774 }
7775
7777
7778 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7779 // C99 6.9p2: The storage-class specifiers auto and register shall not
7780 // appear in the declaration specifiers in an external declaration.
7781 // Global Register+Asm is a GNU extension we support.
7782 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7783 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7784 D.setInvalidType();
7785 }
7786 }
7787
7788 // If this variable has a VLA type and an initializer, try to
7789 // fold to a constant-sized type. This is otherwise invalid.
7790 if (D.hasInitializer() && R->isVariableArrayType())
7792 /*DiagID=*/0);
7793
7794 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7795 const AutoType *AT = TL.getTypePtr();
7796 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7797 }
7798
7799 bool IsMemberSpecialization = false;
7800 bool IsVariableTemplateSpecialization = false;
7801 bool IsPartialSpecialization = false;
7802 bool IsVariableTemplate = false;
7803 VarDecl *NewVD = nullptr;
7804 VarTemplateDecl *NewTemplate = nullptr;
7805 TemplateParameterList *TemplateParams = nullptr;
7806 if (!getLangOpts().CPlusPlus) {
7808 II, R, TInfo, SC);
7809
7810 if (R->getContainedDeducedType())
7811 ParsingInitForAutoVars.insert(NewVD);
7812
7813 if (D.isInvalidType())
7814 NewVD->setInvalidDecl();
7815
7817 NewVD->hasLocalStorage())
7818 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7820 } else {
7821 bool Invalid = false;
7822 // Match up the template parameter lists with the scope specifier, then
7823 // determine whether we have a template or a template specialization.
7826 D.getCXXScopeSpec(),
7828 ? D.getName().TemplateId
7829 : nullptr,
7830 TemplateParamLists,
7831 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7832
7833 if (TemplateParams) {
7834 if (DC->isDependentContext()) {
7835 ContextRAII SavedContext(*this, DC);
7837 Invalid = true;
7838 }
7839
7840 if (!TemplateParams->size() &&
7842 // There is an extraneous 'template<>' for this variable. Complain
7843 // about it, but allow the declaration of the variable.
7844 Diag(TemplateParams->getTemplateLoc(),
7845 diag::err_template_variable_noparams)
7846 << II
7847 << SourceRange(TemplateParams->getTemplateLoc(),
7848 TemplateParams->getRAngleLoc());
7849 TemplateParams = nullptr;
7850 } else {
7851 // Check that we can declare a template here.
7852 if (CheckTemplateDeclScope(S, TemplateParams))
7853 return nullptr;
7854
7856 // This is an explicit specialization or a partial specialization.
7857 IsVariableTemplateSpecialization = true;
7858 IsPartialSpecialization = TemplateParams->size() > 0;
7859 } else { // if (TemplateParams->size() > 0)
7860 // This is a template declaration.
7861 IsVariableTemplate = true;
7862
7863 // Only C++1y supports variable templates (N3651).
7864 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7865 }
7866 }
7867 } else {
7868 // Check that we can declare a member specialization here.
7869 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7870 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7871 return nullptr;
7872 assert((Invalid ||
7874 "should have a 'template<>' for this decl");
7875 }
7876
7877 bool IsExplicitSpecialization =
7878 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7879
7880 // C++ [temp.expl.spec]p2:
7881 // The declaration in an explicit-specialization shall not be an
7882 // export-declaration. An explicit specialization shall not use a
7883 // storage-class-specifier other than thread_local.
7884 //
7885 // We use the storage-class-specifier from DeclSpec because we may have
7886 // added implicit 'extern' for declarations with __declspec(dllimport)!
7887 if (SCSpec != DeclSpec::SCS_unspecified &&
7888 (IsExplicitSpecialization || IsMemberSpecialization)) {
7890 diag::ext_explicit_specialization_storage_class)
7892 }
7893
7894 if (CurContext->isRecord()) {
7895 if (SC == SC_Static) {
7896 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7897 // Walk up the enclosing DeclContexts to check for any that are
7898 // incompatible with static data members.
7899 const DeclContext *FunctionOrMethod = nullptr;
7900 const CXXRecordDecl *AnonStruct = nullptr;
7901 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7902 if (Ctxt->isFunctionOrMethod()) {
7903 FunctionOrMethod = Ctxt;
7904 break;
7905 }
7906 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7907 if (ParentDecl && !ParentDecl->getDeclName()) {
7908 AnonStruct = ParentDecl;
7909 break;
7910 }
7911 }
7912 if (FunctionOrMethod) {
7913 // C++ [class.static.data]p5: A local class shall not have static
7914 // data members.
7916 diag::err_static_data_member_not_allowed_in_local_class)
7917 << Name << RD->getDeclName() << RD->getTagKind();
7918 } else if (AnonStruct) {
7919 // C++ [class.static.data]p4: Unnamed classes and classes contained
7920 // directly or indirectly within unnamed classes shall not contain
7921 // static data members.
7923 diag::err_static_data_member_not_allowed_in_anon_struct)
7924 << Name << AnonStruct->getTagKind();
7925 Invalid = true;
7926 } else if (RD->isUnion()) {
7927 // C++98 [class.union]p1: If a union contains a static data member,
7928 // the program is ill-formed. C++11 drops this restriction.
7930 diag_compat::static_data_member_in_union)
7931 << Name;
7932 }
7933 }
7934 } else if (IsVariableTemplate || IsPartialSpecialization) {
7935 // There is no such thing as a member field template.
7936 Diag(D.getIdentifierLoc(), diag::err_template_member)
7937 << II << TemplateParams->getSourceRange();
7938 // Recover by pretending this is a static data member template.
7939 SC = SC_Static;
7940 }
7941 } else if (DC->isRecord()) {
7942 // This is an out-of-line definition of a static data member.
7943 switch (SC) {
7944 case SC_None:
7945 break;
7946 case SC_Static:
7948 diag::err_static_out_of_line)
7951 break;
7952 case SC_Auto:
7953 case SC_Register:
7954 case SC_Extern:
7955 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7956 // to names of variables declared in a block or to function parameters.
7957 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7958 // of class members
7959
7961 diag::err_storage_class_for_static_member)
7964 break;
7965 case SC_PrivateExtern:
7966 llvm_unreachable("C storage class in c++!");
7967 }
7968 }
7969
7970 if (IsVariableTemplateSpecialization) {
7971 SourceLocation TemplateKWLoc =
7972 TemplateParamLists.size() > 0
7973 ? TemplateParamLists[0]->getTemplateLoc()
7974 : SourceLocation();
7976 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7978 if (Res.isInvalid())
7979 return nullptr;
7980 NewVD = cast<VarDecl>(Res.get());
7981 AddToScope = false;
7982 } else if (D.isDecompositionDeclarator()) {
7984 D.getIdentifierLoc(), R, TInfo, SC,
7985 Bindings);
7986 } else
7987 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7988 D.getIdentifierLoc(), II, R, TInfo, SC);
7989
7990 // If this is supposed to be a variable template, create it as such.
7991 if (IsVariableTemplate) {
7992 NewTemplate =
7994 TemplateParams, NewVD);
7995 NewVD->setDescribedVarTemplate(NewTemplate);
7996 }
7997
7998 // If this decl has an auto type in need of deduction, make a note of the
7999 // Decl so we can diagnose uses of it in its own initializer.
8000 if (R->getContainedDeducedType())
8001 ParsingInitForAutoVars.insert(NewVD);
8002
8003 if (D.isInvalidType() || Invalid) {
8004 NewVD->setInvalidDecl();
8005 if (NewTemplate)
8006 NewTemplate->setInvalidDecl();
8007 }
8008
8009 SetNestedNameSpecifier(*this, NewVD, D);
8010
8011 // If we have any template parameter lists that don't directly belong to
8012 // the variable (matching the scope specifier), store them.
8013 // An explicit variable template specialization does not own any template
8014 // parameter lists.
8015 unsigned VDTemplateParamLists =
8016 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8017 if (TemplateParamLists.size() > VDTemplateParamLists)
8019 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
8020 }
8021
8022 if (D.getDeclSpec().isInlineSpecified()) {
8023 if (!getLangOpts().CPlusPlus) {
8024 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
8025 << 0;
8026 } else if (CurContext->isFunctionOrMethod()) {
8027 // 'inline' is not allowed on block scope variable declaration.
8029 diag::err_inline_declaration_block_scope) << Name
8031 } else {
8033 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8034 : diag::compat_pre_cxx17_inline_variable);
8035 NewVD->setInlineSpecified();
8036 }
8037 }
8038
8039 // Set the lexical context. If the declarator has a C++ scope specifier, the
8040 // lexical context will be different from the semantic context.
8042 if (NewTemplate)
8043 NewTemplate->setLexicalDeclContext(CurContext);
8044
8045 if (IsLocalExternDecl) {
8047 for (auto *B : Bindings)
8048 B->setLocalExternDecl();
8049 else
8050 NewVD->setLocalExternDecl();
8051 }
8052
8053 bool EmitTLSUnsupportedError = false;
8055 // C++11 [dcl.stc]p4:
8056 // When thread_local is applied to a variable of block scope the
8057 // storage-class-specifier static is implied if it does not appear
8058 // explicitly.
8059 // Core issue: 'static' is not implied if the variable is declared
8060 // 'extern'.
8061 if (NewVD->hasLocalStorage() &&
8062 (SCSpec != DeclSpec::SCS_unspecified ||
8064 !DC->isFunctionOrMethod()))
8066 diag::err_thread_non_global)
8068 else if (!Context.getTargetInfo().isTLSSupported()) {
8069 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8070 // Postpone error emission until we've collected attributes required to
8071 // figure out whether it's a host or device variable and whether the
8072 // error should be ignored.
8073 EmitTLSUnsupportedError = true;
8074 // We still need to mark the variable as TLS so it shows up in AST with
8075 // proper storage class for other tools to use even if we're not going
8076 // to emit any code for it.
8077 NewVD->setTSCSpec(TSCS);
8078 } else
8080 diag::err_thread_unsupported);
8081 } else
8082 NewVD->setTSCSpec(TSCS);
8083 }
8084
8085 switch (D.getDeclSpec().getConstexprSpecifier()) {
8087 break;
8088
8091 diag::err_constexpr_wrong_decl_kind)
8092 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8093 [[fallthrough]];
8094
8096 NewVD->setConstexpr(true);
8097 // C++1z [dcl.spec.constexpr]p1:
8098 // A static data member declared with the constexpr specifier is
8099 // implicitly an inline variable.
8100 if (NewVD->isStaticDataMember() &&
8102 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8103 NewVD->setImplicitlyInline();
8104 break;
8105
8107 if (!NewVD->hasGlobalStorage())
8109 diag::err_constinit_local_variable);
8110 else
8111 NewVD->addAttr(
8112 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8113 ConstInitAttr::Keyword_constinit));
8114 break;
8115 }
8116
8117 // C99 6.7.4p3
8118 // An inline definition of a function with external linkage shall
8119 // not contain a definition of a modifiable object with static or
8120 // thread storage duration...
8121 // We only apply this when the function is required to be defined
8122 // elsewhere, i.e. when the function is not 'extern inline'. Note
8123 // that a local variable with thread storage duration still has to
8124 // be marked 'static'. Also note that it's possible to get these
8125 // semantics in C++ using __attribute__((gnu_inline)).
8126 if (SC == SC_Static && S->getFnParent() != nullptr &&
8127 !NewVD->getType().isConstQualified()) {
8129 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8131 diag::warn_static_local_in_extern_inline);
8133 }
8134 }
8135
8137 if (IsVariableTemplateSpecialization)
8138 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8139 << (IsPartialSpecialization ? 1 : 0)
8142 else if (IsMemberSpecialization)
8143 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8144 << 2
8146 else if (NewVD->hasLocalStorage())
8147 Diag(NewVD->getLocation(), diag::err_module_private_local)
8148 << 0 << NewVD
8152 else {
8153 NewVD->setModulePrivate();
8154 if (NewTemplate)
8155 NewTemplate->setModulePrivate();
8156 for (auto *B : Bindings)
8157 B->setModulePrivate();
8158 }
8159 }
8160
8161 if (getLangOpts().OpenCL) {
8163
8165 if (TSC != TSCS_unspecified) {
8167 diag::err_opencl_unknown_type_specifier)
8169 << DeclSpec::getSpecifierName(TSC) << 1;
8170 NewVD->setInvalidDecl();
8171 }
8172 }
8173
8174 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8175 // address space if the table has local storage (semantic checks elsewhere
8176 // will produce an error anyway).
8177 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8178 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8179 !NewVD->hasLocalStorage()) {
8180 QualType Type = Context.getAddrSpaceQualType(
8181 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8182 NewVD->setType(Type);
8183 }
8184 }
8185
8186 if (Expr *E = D.getAsmLabel()) {
8187 // The parser guarantees this is a string.
8189 StringRef Label = SE->getString();
8190
8191 // Insert the asm attribute.
8192 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8193 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8194 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8196 if (I != ExtnameUndeclaredIdentifiers.end()) {
8197 if (isDeclExternC(NewVD)) {
8198 NewVD->addAttr(I->second);
8200 } else
8201 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8202 << /*Variable*/ 1 << NewVD;
8203 }
8204 }
8205
8206 // Handle attributes prior to checking for duplicates in MergeVarDecl
8207 ProcessDeclAttributes(S, NewVD, D);
8208
8209 if (getLangOpts().HLSL)
8211
8212 if (getLangOpts().OpenACC)
8214
8215 // FIXME: This is probably the wrong location to be doing this and we should
8216 // probably be doing this for more attributes (especially for function
8217 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8218 // the code to copy attributes would be generated by TableGen.
8219 if (R->isFunctionPointerType())
8220 if (const auto *TT = R->getAs<TypedefType>())
8222
8223 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8224 if (EmitTLSUnsupportedError &&
8226 (getLangOpts().OpenMPIsTargetDevice &&
8227 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8229 diag::err_thread_unsupported);
8230
8231 if (EmitTLSUnsupportedError &&
8232 (LangOpts.SYCLIsDevice ||
8233 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8234 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8235 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8236 // storage [duration]."
8237 if (SC == SC_None && S->getFnParent() != nullptr &&
8238 (NewVD->hasAttr<CUDASharedAttr>() ||
8239 NewVD->hasAttr<CUDAConstantAttr>())) {
8240 NewVD->setStorageClass(SC_Static);
8241 }
8242 }
8243
8244 // Ensure that dllimport globals without explicit storage class are treated as
8245 // extern. The storage class is set above using parsed attributes. Now we can
8246 // check the VarDecl itself.
8247 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8248 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8249 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8250
8251 // In auto-retain/release, infer strong retension for variables of
8252 // retainable type.
8253 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8254 NewVD->setInvalidDecl();
8255
8256 // Check the ASM label here, as we need to know all other attributes of the
8257 // Decl first. Otherwise, we can't know if the asm label refers to the
8258 // host or device in a CUDA context. The device has other registers than
8259 // host and we must know where the function will be placed.
8260 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);
8261
8262 // Find the shadowed declaration before filtering for scope.
8263 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8265 : nullptr;
8266
8267 // Don't consider existing declarations that are in a different
8268 // scope and are out-of-semantic-context declarations (if the new
8269 // declaration has linkage).
8272 IsMemberSpecialization ||
8273 IsVariableTemplateSpecialization);
8274
8275 // Check whether the previous declaration is in the same block scope. This
8276 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8277 if (getLangOpts().CPlusPlus &&
8278 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8280 Previous.isSingleResult() && !Previous.isShadowed() &&
8281 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8282
8283 if (!getLangOpts().CPlusPlus) {
8285 } else {
8286 // If this is an explicit specialization of a static data member, check it.
8287 if (IsMemberSpecialization && !IsVariableTemplate &&
8288 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8290 NewVD->setInvalidDecl();
8291
8292 // Merge the decl with the existing one if appropriate.
8293 if (!Previous.empty()) {
8294 if (Previous.isSingleResult() &&
8295 isa<FieldDecl>(Previous.getFoundDecl()) &&
8296 D.getCXXScopeSpec().isSet()) {
8297 // The user tried to define a non-static data member
8298 // out-of-line (C++ [dcl.meaning]p1).
8299 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8300 << D.getCXXScopeSpec().getRange();
8301 Previous.clear();
8302 NewVD->setInvalidDecl();
8303 }
8304 } else if (D.getCXXScopeSpec().isSet() &&
8305 !IsVariableTemplateSpecialization) {
8306 // No previous declaration in the qualifying scope.
8307 Diag(D.getIdentifierLoc(), diag::err_no_member)
8308 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8309 << D.getCXXScopeSpec().getRange();
8310 NewVD->setInvalidDecl();
8311 }
8312
8313 if (!IsPlaceholderVariable)
8315
8316 // CheckVariableDeclaration will set NewVD as invalid if something is in
8317 // error like WebAssembly tables being declared as arrays with a non-zero
8318 // size, but then parsing continues and emits further errors on that line.
8319 // To avoid that we check here if it happened and return nullptr.
8320 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8321 return nullptr;
8322
8323 if (NewTemplate) {
8324 VarTemplateDecl *PrevVarTemplate =
8325 NewVD->getPreviousDecl()
8327 : nullptr;
8328
8329 // Check the template parameter list of this declaration, possibly
8330 // merging in the template parameter list from the previous variable
8331 // template declaration.
8333 TemplateParams,
8334 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8335 : nullptr,
8336 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8337 DC->isDependentContext())
8339 : TPC_Other))
8340 NewVD->setInvalidDecl();
8341
8342 // If we are providing an explicit specialization of a static variable
8343 // template, make a note of that.
8344 if (PrevVarTemplate &&
8345 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8346 PrevVarTemplate->setMemberSpecialization();
8347 }
8348 }
8349
8350 // Diagnose shadowed variables iff this isn't a redeclaration.
8351 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8352 CheckShadow(NewVD, ShadowedDecl, Previous);
8353
8354 ProcessPragmaWeak(S, NewVD);
8355
8356 // If this is the first declaration of an extern C variable, update
8357 // the map of such variables.
8358 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8359 isIncompleteDeclExternC(*this, NewVD))
8361
8362 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8364 Decl *ManglingContextDecl;
8365 std::tie(MCtx, ManglingContextDecl) =
8367 if (MCtx) {
8368 Context.setManglingNumber(
8369 NewVD, MCtx->getManglingNumber(
8370 NewVD, getMSManglingNumber(getLangOpts(), S)));
8371 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8372 }
8373 }
8374
8375 // Special handling of variable named 'main'.
8376 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8377 // C++ [basic.start.main]p3:
8378 // A program that declares
8379 // - a variable main at global scope, or
8380 // - an entity named main with C language linkage (in any namespace)
8381 // is ill-formed
8382 if (getLangOpts().CPlusPlus)
8383 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8384 << NewVD->isExternC();
8385
8386 // In C, and external-linkage variable named main results in undefined
8387 // behavior.
8388 else if (NewVD->hasExternalFormalLinkage())
8389 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8390 }
8391
8392 if (D.isRedeclaration() && !Previous.empty()) {
8393 NamedDecl *Prev = Previous.getRepresentativeDecl();
8394 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8396 }
8397
8398 if (NewTemplate) {
8399 if (NewVD->isInvalidDecl())
8400 NewTemplate->setInvalidDecl();
8401 ActOnDocumentableDecl(NewTemplate);
8402 return NewTemplate;
8403 }
8404
8405 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8407
8409
8410 return NewVD;
8411}
8412
8413/// Enum describing the %select options in diag::warn_decl_shadow.
8423
8424/// Determine what kind of declaration we're shadowing.
8426 const DeclContext *OldDC) {
8427 if (isa<TypeAliasDecl>(ShadowedDecl))
8428 return SDK_Using;
8429 else if (isa<TypedefDecl>(ShadowedDecl))
8430 return SDK_Typedef;
8431 else if (isa<BindingDecl>(ShadowedDecl))
8432 return SDK_StructuredBinding;
8433 else if (isa<RecordDecl>(OldDC))
8434 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8435
8436 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8437}
8438
8439/// Return the location of the capture if the given lambda captures the given
8440/// variable \p VD, or an invalid source location otherwise.
8442 const ValueDecl *VD) {
8443 for (const Capture &Capture : LSI->Captures) {
8445 return Capture.getLocation();
8446 }
8447 return SourceLocation();
8448}
8449
8451 const LookupResult &R) {
8452 // Only diagnose if we're shadowing an unambiguous field or variable.
8454 return false;
8455
8456 // Return false if warning is ignored.
8457 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8458}
8459
8461 const LookupResult &R) {
8463 return nullptr;
8464
8465 // Don't diagnose declarations at file scope.
8466 if (D->hasGlobalStorage() && !D->isStaticLocal())
8467 return nullptr;
8468
8469 NamedDecl *ShadowedDecl = R.getFoundDecl();
8470 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8471 : nullptr;
8472}
8473
8475 const LookupResult &R) {
8476 // Don't warn if typedef declaration is part of a class
8477 if (D->getDeclContext()->isRecord())
8478 return nullptr;
8479
8481 return nullptr;
8482
8483 NamedDecl *ShadowedDecl = R.getFoundDecl();
8484 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8485}
8486
8488 const LookupResult &R) {
8490 return nullptr;
8491
8492 NamedDecl *ShadowedDecl = R.getFoundDecl();
8493 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8494 : nullptr;
8495}
8496
8498 const LookupResult &R) {
8499 DeclContext *NewDC = D->getDeclContext();
8500
8501 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8502 if (const auto *MD =
8503 dyn_cast<CXXMethodDecl>(getFunctionLevelDeclContext())) {
8504 // Fields aren't shadowed in C++ static members or in member functions
8505 // with an explicit object parameter.
8506 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8507 return;
8508 }
8509 // Fields shadowed by constructor parameters are a special case. Usually
8510 // the constructor initializes the field with the parameter.
8511 if (isa<CXXConstructorDecl>(NewDC))
8512 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8513 // Remember that this was shadowed so we can either warn about its
8514 // modification or its existence depending on warning settings.
8515 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8516 return;
8517 }
8518 }
8519
8520 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8521 if (shadowedVar->isExternC()) {
8522 // For shadowing external vars, make sure that we point to the global
8523 // declaration, not a locally scoped extern declaration.
8524 for (auto *I : shadowedVar->redecls())
8525 if (I->isFileVarDecl()) {
8526 ShadowedDecl = I;
8527 break;
8528 }
8529 }
8530
8531 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8532
8533 unsigned WarningDiag = diag::warn_decl_shadow;
8534 SourceLocation CaptureLoc;
8535 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8536 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8537 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8538 // Handle both VarDecl and BindingDecl in lambda contexts
8539 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8540 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8541 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8542 if (RD->getLambdaCaptureDefault() == LCD_None) {
8543 // Try to avoid warnings for lambdas with an explicit capture
8544 // list. Warn only when the lambda captures the shadowed decl
8545 // explicitly.
8546 CaptureLoc = getCaptureLocation(LSI, VD);
8547 if (CaptureLoc.isInvalid())
8548 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8549 } else {
8550 // Remember that this was shadowed so we can avoid the warning if
8551 // the shadowed decl isn't captured and the warning settings allow
8552 // it.
8554 ->ShadowingDecls.push_back({D, VD});
8555 return;
8556 }
8557 }
8558 if (isa<FieldDecl>(ShadowedDecl)) {
8559 // If lambda can capture this, then emit default shadowing warning,
8560 // Otherwise it is not really a shadowing case since field is not
8561 // available in lambda's body.
8562 // At this point we don't know that lambda can capture this, so
8563 // remember that this was shadowed and delay until we know.
8565 ->ShadowingDecls.push_back({D, ShadowedDecl});
8566 return;
8567 }
8568 }
8569 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8570 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8571 bool HasLocalStorage = false;
8572 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8573 HasLocalStorage = VD->hasLocalStorage();
8574 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8575 HasLocalStorage =
8576 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8577
8578 if (HasLocalStorage) {
8579 // A variable can't shadow a local variable or binding in an enclosing
8580 // scope, if they are separated by a non-capturing declaration
8581 // context.
8582 for (DeclContext *ParentDC = NewDC;
8583 ParentDC && !ParentDC->Equals(OldDC);
8584 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8585 // Only block literals, captured statements, and lambda expressions
8586 // can capture; other scopes don't.
8587 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8588 !isLambdaCallOperator(ParentDC))
8589 return;
8590 }
8591 }
8592 }
8593 }
8594 }
8595
8596 // Never warn about shadowing a placeholder variable.
8597 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8598 return;
8599
8600 // Only warn about certain kinds of shadowing for class members.
8601 if (NewDC) {
8602 // In particular, don't warn about shadowing non-class members.
8603 if (NewDC->isRecord() && !OldDC->isRecord())
8604 return;
8605
8606 // Skip shadowing check if we're in a class scope, dealing with an enum
8607 // constant in a different context.
8608 DeclContext *ReDC = NewDC->getRedeclContext();
8609 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8610 return;
8611
8612 // TODO: should we warn about static data members shadowing
8613 // static data members from base classes?
8614
8615 // TODO: don't diagnose for inaccessible shadowed members.
8616 // This is hard to do perfectly because we might friend the
8617 // shadowing context, but that's just a false negative.
8618 }
8619
8620 DeclarationName Name = R.getLookupName();
8621
8622 // Emit warning and note.
8623 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8624 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8625 if (!CaptureLoc.isInvalid())
8626 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8627 << Name << /*explicitly*/ 1;
8628 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8629}
8630
8632 for (const auto &Shadow : LSI->ShadowingDecls) {
8633 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8634 // Try to avoid the warning when the shadowed decl isn't captured.
8635 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8636 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8637 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8638 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8639 Diag(Shadow.VD->getLocation(),
8640 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8641 : diag::warn_decl_shadow)
8642 << Shadow.VD->getDeclName()
8643 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8644 if (CaptureLoc.isValid())
8645 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8646 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8647 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8648 } else if (isa<FieldDecl>(ShadowedDecl)) {
8649 Diag(Shadow.VD->getLocation(),
8650 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8651 : diag::warn_decl_shadow_uncaptured_local)
8652 << Shadow.VD->getDeclName()
8653 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8654 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8655 }
8656 }
8657}
8658
8660 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8661 return;
8662
8663 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8666 LookupName(R, S);
8667 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8668 CheckShadow(D, ShadowedDecl, R);
8669}
8670
8671/// Check if 'E', which is an expression that is about to be modified, refers
8672/// to a constructor parameter that shadows a field.
8674 // Quickly ignore expressions that can't be shadowing ctor parameters.
8675 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8676 return;
8677 E = E->IgnoreParenImpCasts();
8678 auto *DRE = dyn_cast<DeclRefExpr>(E);
8679 if (!DRE)
8680 return;
8681 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8682 auto I = ShadowingDecls.find(D);
8683 if (I == ShadowingDecls.end())
8684 return;
8685 const NamedDecl *ShadowedDecl = I->second;
8686 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8687 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8688 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8689 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8690
8691 // Avoid issuing multiple warnings about the same decl.
8692 ShadowingDecls.erase(I);
8693}
8694
8695/// Check for conflict between this global or extern "C" declaration and
8696/// previous global or extern "C" declarations. This is only used in C++.
8697template<typename T>
8699 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8700 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8701 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8702
8703 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8704 // The common case: this global doesn't conflict with any extern "C"
8705 // declaration.
8706 return false;
8707 }
8708
8709 if (Prev) {
8710 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8711 // Both the old and new declarations have C language linkage. This is a
8712 // redeclaration.
8713 Previous.clear();
8714 Previous.addDecl(Prev);
8715 return true;
8716 }
8717
8718 // This is a global, non-extern "C" declaration, and there is a previous
8719 // non-global extern "C" declaration. Diagnose if this is a variable
8720 // declaration.
8721 if (!isa<VarDecl>(ND))
8722 return false;
8723 } else {
8724 // The declaration is extern "C". Check for any declaration in the
8725 // translation unit which might conflict.
8726 if (IsGlobal) {
8727 // We have already performed the lookup into the translation unit.
8728 IsGlobal = false;
8729 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8730 I != E; ++I) {
8731 if (isa<VarDecl>(*I)) {
8732 Prev = *I;
8733 break;
8734 }
8735 }
8736 } else {
8738 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8739 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8740 I != E; ++I) {
8741 if (isa<VarDecl>(*I)) {
8742 Prev = *I;
8743 break;
8744 }
8745 // FIXME: If we have any other entity with this name in global scope,
8746 // the declaration is ill-formed, but that is a defect: it breaks the
8747 // 'stat' hack, for instance. Only variables can have mangled name
8748 // clashes with extern "C" declarations, so only they deserve a
8749 // diagnostic.
8750 }
8751 }
8752
8753 if (!Prev)
8754 return false;
8755 }
8756
8757 // Use the first declaration's location to ensure we point at something which
8758 // is lexically inside an extern "C" linkage-spec.
8759 assert(Prev && "should have found a previous declaration to diagnose");
8760 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8761 Prev = FD->getFirstDecl();
8762 else
8763 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8764
8765 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8766 << IsGlobal << ND;
8767 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8768 << IsGlobal;
8769 return false;
8770}
8771
8772/// Apply special rules for handling extern "C" declarations. Returns \c true
8773/// if we have found that this is a redeclaration of some prior entity.
8774///
8775/// Per C++ [dcl.link]p6:
8776/// Two declarations [for a function or variable] with C language linkage
8777/// with the same name that appear in different scopes refer to the same
8778/// [entity]. An entity with C language linkage shall not be declared with
8779/// the same name as an entity in global scope.
8780template<typename T>
8783 if (!S.getLangOpts().CPlusPlus) {
8784 // In C, when declaring a global variable, look for a corresponding 'extern'
8785 // variable declared in function scope. We don't need this in C++, because
8786 // we find local extern decls in the surrounding file-scope DeclContext.
8787 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8788 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8789 Previous.clear();
8790 Previous.addDecl(Prev);
8791 return true;
8792 }
8793 }
8794 return false;
8795 }
8796
8797 // A declaration in the translation unit can conflict with an extern "C"
8798 // declaration.
8799 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8800 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8801
8802 // An extern "C" declaration can conflict with a declaration in the
8803 // translation unit or can be a redeclaration of an extern "C" declaration
8804 // in another scope.
8805 if (isIncompleteDeclExternC(S,ND))
8806 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8807
8808 // Neither global nor extern "C": nothing to do.
8809 return false;
8810}
8811
8812static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8813 QualType T) {
8814 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8815 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8816 // any of its members, even recursively, shall not have an atomic type, or a
8817 // variably modified type, or a type that is volatile or restrict qualified.
8818 if (CanonT->isVariablyModifiedType()) {
8819 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8820 return true;
8821 }
8822
8823 // Arrays are qualified by their element type, so get the base type (this
8824 // works on non-arrays as well).
8825 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8826
8827 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8828 CanonT.isRestrictQualified()) {
8829 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8830 return true;
8831 }
8832
8833 if (CanonT->isRecordType()) {
8834 const RecordDecl *RD = CanonT->getAsRecordDecl();
8835 if (!RD->isInvalidDecl() &&
8836 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8837 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8838 }))
8839 return true;
8840 }
8841
8842 return false;
8843}
8844
8846 // If the decl is already known invalid, don't check it.
8847 if (NewVD->isInvalidDecl())
8848 return;
8849
8850 QualType T = NewVD->getType();
8851
8852 // Defer checking an 'auto' type until its initializer is attached.
8853 if (T->isUndeducedType())
8854 return;
8855
8856 if (NewVD->hasAttrs())
8858
8859 if (T->isObjCObjectType()) {
8860 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8861 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8862 T = Context.getObjCObjectPointerType(T);
8863 NewVD->setType(T);
8864 }
8865
8866 // Emit an error if an address space was applied to decl with local storage.
8867 // This includes arrays of objects with address space qualifiers, but not
8868 // automatic variables that point to other address spaces.
8869 // ISO/IEC TR 18037 S5.1.2
8870 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8871 T.getAddressSpace() != LangAS::Default) {
8872 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8873 NewVD->setInvalidDecl();
8874 return;
8875 }
8876
8877 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8878 // scope.
8879 if (getLangOpts().OpenCLVersion == 120 &&
8880 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8881 getLangOpts()) &&
8882 NewVD->isStaticLocal()) {
8883 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8884 NewVD->setInvalidDecl();
8885 return;
8886 }
8887
8888 if (getLangOpts().OpenCL) {
8889 if (!diagnoseOpenCLTypes(*this, NewVD))
8890 return;
8891
8892 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8893 if (NewVD->hasAttr<BlocksAttr>()) {
8894 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8895 return;
8896 }
8897
8898 if (T->isBlockPointerType()) {
8899 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8900 // can't use 'extern' storage class.
8901 if (!T.isConstQualified()) {
8902 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8903 << 0 /*const*/;
8904 NewVD->setInvalidDecl();
8905 return;
8906 }
8907 if (NewVD->hasExternalStorage()) {
8908 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8909 NewVD->setInvalidDecl();
8910 return;
8911 }
8912 }
8913
8914 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8915 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8916 NewVD->hasExternalStorage()) {
8917 if (!T->isSamplerT() && !T->isDependentType() &&
8918 !(T.getAddressSpace() == LangAS::opencl_constant ||
8919 (T.getAddressSpace() == LangAS::opencl_global &&
8920 getOpenCLOptions().areProgramScopeVariablesSupported(
8921 getLangOpts())))) {
8922 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8923 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8924 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8925 << Scope << "global or constant";
8926 else
8927 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8928 << Scope << "constant";
8929 NewVD->setInvalidDecl();
8930 return;
8931 }
8932 } else {
8933 if (T.getAddressSpace() == LangAS::opencl_global) {
8934 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8935 << 1 /*is any function*/ << "global";
8936 NewVD->setInvalidDecl();
8937 return;
8938 }
8939 if (T.getAddressSpace() == LangAS::opencl_constant ||
8940 T.getAddressSpace() == LangAS::opencl_local) {
8942 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8943 // in functions.
8944 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8945 if (T.getAddressSpace() == LangAS::opencl_constant)
8946 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8947 << 0 /*non-kernel only*/ << "constant";
8948 else
8949 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8950 << 0 /*non-kernel only*/ << "local";
8951 NewVD->setInvalidDecl();
8952 return;
8953 }
8954 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8955 // in the outermost scope of a kernel function.
8956 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
8957 if (!getCurScope()->isFunctionScope()) {
8958 if (T.getAddressSpace() == LangAS::opencl_constant)
8959 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8960 << "constant";
8961 else
8962 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8963 << "local";
8964 NewVD->setInvalidDecl();
8965 return;
8966 }
8967 }
8968 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8969 // If we are parsing a template we didn't deduce an addr
8970 // space yet.
8971 T.getAddressSpace() != LangAS::Default) {
8972 // Do not allow other address spaces on automatic variable.
8973 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8974 NewVD->setInvalidDecl();
8975 return;
8976 }
8977 }
8978 }
8979
8980 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8981 && !NewVD->hasAttr<BlocksAttr>()) {
8982 if (getLangOpts().getGC() != LangOptions::NonGC)
8983 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8984 else {
8985 assert(!getLangOpts().ObjCAutoRefCount);
8986 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8987 }
8988 }
8989
8990 // WebAssembly tables must be static with a zero length and can't be
8991 // declared within functions.
8992 if (T->isWebAssemblyTableType()) {
8993 if (getCurScope()->getParent()) { // Parent is null at top-level
8994 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8995 NewVD->setInvalidDecl();
8996 return;
8997 }
8998 if (NewVD->getStorageClass() != SC_Static) {
8999 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
9000 NewVD->setInvalidDecl();
9001 return;
9002 }
9003 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
9004 if (!ATy || ATy->getZExtSize() != 0) {
9005 Diag(NewVD->getLocation(),
9006 diag::err_typecheck_wasm_table_must_have_zero_length);
9007 NewVD->setInvalidDecl();
9008 return;
9009 }
9010 }
9011
9012 // zero sized static arrays are not allowed in HIP device functions
9013 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9014 if (FunctionDecl *FD = getCurFunctionDecl();
9015 FD &&
9016 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9017 if (const ConstantArrayType *ArrayT =
9018 getASTContext().getAsConstantArrayType(T);
9019 ArrayT && ArrayT->isZeroSize()) {
9020 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
9021 }
9022 }
9023 }
9024
9025 bool isVM = T->isVariablyModifiedType();
9026 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9027 NewVD->hasAttr<BlocksAttr>())
9029
9030 if ((isVM && NewVD->hasLinkage()) ||
9031 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9032 bool SizeIsNegative;
9033 llvm::APSInt Oversized;
9035 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9036 QualType FixedT;
9037 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9038 FixedT = FixedTInfo->getType();
9039 else if (FixedTInfo) {
9040 // Type and type-as-written are canonically different. We need to fix up
9041 // both types separately.
9042 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9043 Oversized);
9044 }
9045 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9046 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9047 // FIXME: This won't give the correct result for
9048 // int a[10][n];
9049 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9050
9051 if (NewVD->isFileVarDecl())
9052 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9053 << SizeRange;
9054 else if (NewVD->isStaticLocal())
9055 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9056 << SizeRange;
9057 else
9058 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9059 << SizeRange;
9060 NewVD->setInvalidDecl();
9061 return;
9062 }
9063
9064 if (!FixedTInfo) {
9065 if (NewVD->isFileVarDecl())
9066 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9067 else
9068 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9069 NewVD->setInvalidDecl();
9070 return;
9071 }
9072
9073 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9074 NewVD->setType(FixedT);
9075 NewVD->setTypeSourceInfo(FixedTInfo);
9076 }
9077
9078 if (T->isVoidType()) {
9079 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9080 // of objects and functions.
9082 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9083 << T;
9084 NewVD->setInvalidDecl();
9085 return;
9086 }
9087 }
9088
9089 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9090 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
9091 NewVD->setInvalidDecl();
9092 return;
9093 }
9094
9095 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9096 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9097 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9098 NewVD->setInvalidDecl();
9099 return;
9100 }
9101
9102 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9103 Diag(NewVD->getLocation(), diag::err_block_on_vm);
9104 NewVD->setInvalidDecl();
9105 return;
9106 }
9107
9108 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9109 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9110 NewVD->setInvalidDecl();
9111 return;
9112 }
9113
9114 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9115 !T->isDependentType() &&
9117 diag::err_constexpr_var_non_literal)) {
9118 NewVD->setInvalidDecl();
9119 return;
9120 }
9121
9122 // PPC MMA non-pointer types are not allowed as non-local variable types.
9123 if (Context.getTargetInfo().getTriple().isPPC64() &&
9124 !NewVD->isLocalVarDecl() &&
9125 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9126 NewVD->setInvalidDecl();
9127 return;
9128 }
9129
9130 // Check that SVE types are only used in functions with SVE available.
9131 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9133 llvm::StringMap<bool> CallerFeatureMap;
9134 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9135 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,
9136 CallerFeatureMap)) {
9137 NewVD->setInvalidDecl();
9138 return;
9139 }
9140 }
9141
9142 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9144 llvm::StringMap<bool> CallerFeatureMap;
9145 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9147 CallerFeatureMap);
9148 }
9149}
9150
9153
9154 // If the decl is already known invalid, don't check it.
9155 if (NewVD->isInvalidDecl())
9156 return false;
9157
9158 // If we did not find anything by this name, look for a non-visible
9159 // extern "C" declaration with the same name.
9160 if (Previous.empty() &&
9162 Previous.setShadowed();
9163
9164 if (!Previous.empty()) {
9165 MergeVarDecl(NewVD, Previous);
9166 return true;
9167 }
9168 return false;
9169}
9170
9173
9174 // Look for methods in base classes that this method might override.
9175 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9176 /*DetectVirtual=*/false);
9177 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9178 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9179 DeclarationName Name = MD->getDeclName();
9180
9182 // We really want to find the base class destructor here.
9183 Name = Context.DeclarationNames.getCXXDestructorName(
9184 Context.getCanonicalTagType(BaseRecord));
9185 }
9186
9187 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9188 CXXMethodDecl *BaseMD =
9189 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9190 if (!BaseMD || !BaseMD->isVirtual() ||
9191 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9192 /*ConsiderCudaAttrs=*/true))
9193 continue;
9194 if (!CheckExplicitObjectOverride(MD, BaseMD))
9195 continue;
9196 if (Overridden.insert(BaseMD).second) {
9197 MD->addOverriddenMethod(BaseMD);
9202 }
9203
9204 // A method can only override one function from each base class. We
9205 // don't track indirectly overridden methods from bases of bases.
9206 return true;
9207 }
9208
9209 return false;
9210 };
9211
9212 DC->lookupInBases(VisitBase, Paths);
9213 return !Overridden.empty();
9214}
9215
9216namespace {
9217 // Struct for holding all of the extra arguments needed by
9218 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9219 struct ActOnFDArgs {
9220 Scope *S;
9221 Declarator &D;
9222 MultiTemplateParamsArg TemplateParamLists;
9223 bool AddToScope;
9224 };
9225} // end anonymous namespace
9226
9227namespace {
9228
9229// Callback to only accept typo corrections that have a non-zero edit distance.
9230// Also only accept corrections that have the same parent decl.
9231class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9232 public:
9233 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9234 CXXRecordDecl *Parent)
9235 : Context(Context), OriginalFD(TypoFD),
9236 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9237
9238 bool ValidateCandidate(const TypoCorrection &candidate) override {
9239 if (candidate.getEditDistance() == 0)
9240 return false;
9241
9242 SmallVector<unsigned, 1> MismatchedParams;
9243 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9244 CDeclEnd = candidate.end();
9245 CDecl != CDeclEnd; ++CDecl) {
9246 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9247
9248 if (FD && !FD->hasBody() &&
9249 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9250 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9251 CXXRecordDecl *Parent = MD->getParent();
9252 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9253 return true;
9254 } else if (!ExpectedParent) {
9255 return true;
9256 }
9257 }
9258 }
9259
9260 return false;
9261 }
9262
9263 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9264 return std::make_unique<DifferentNameValidatorCCC>(*this);
9265 }
9266
9267 private:
9268 ASTContext &Context;
9269 FunctionDecl *OriginalFD;
9270 CXXRecordDecl *ExpectedParent;
9271};
9272
9273} // end anonymous namespace
9274
9278
9279/// Generate diagnostics for an invalid function redeclaration.
9280///
9281/// This routine handles generating the diagnostic messages for an invalid
9282/// function redeclaration, including finding possible similar declarations
9283/// or performing typo correction if there are no previous declarations with
9284/// the same name.
9285///
9286/// Returns a NamedDecl iff typo correction was performed and substituting in
9287/// the new declaration name does not cause new errors.
9289 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9290 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9291 DeclarationName Name = NewFD->getDeclName();
9292 DeclContext *NewDC = NewFD->getDeclContext();
9293 SmallVector<unsigned, 1> MismatchedParams;
9295 TypoCorrection Correction;
9296 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9297 unsigned DiagMsg =
9298 IsLocalFriend ? diag::err_no_matching_local_friend :
9299 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9300 diag::err_member_decl_does_not_match;
9301 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9302 IsLocalFriend ? Sema::LookupLocalFriendName
9305
9306 NewFD->setInvalidDecl();
9307 if (IsLocalFriend)
9308 SemaRef.LookupName(Prev, S);
9309 else
9310 SemaRef.LookupQualifiedName(Prev, NewDC);
9311 assert(!Prev.isAmbiguous() &&
9312 "Cannot have an ambiguity in previous-declaration lookup");
9313 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9314 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9315 MD ? MD->getParent() : nullptr);
9316 if (!Prev.empty()) {
9317 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9318 Func != FuncEnd; ++Func) {
9319 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9320 if (FD &&
9321 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9322 // Add 1 to the index so that 0 can mean the mismatch didn't
9323 // involve a parameter
9324 unsigned ParamNum =
9325 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9326 NearMatches.push_back(std::make_pair(FD, ParamNum));
9327 }
9328 }
9329 // If the qualified name lookup yielded nothing, try typo correction
9330 } else if ((Correction = SemaRef.CorrectTypo(
9331 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9332 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9334 IsLocalFriend ? nullptr : NewDC))) {
9335 // Set up everything for the call to ActOnFunctionDeclarator
9336 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9337 ExtraArgs.D.getIdentifierLoc());
9338 Previous.clear();
9339 Previous.setLookupName(Correction.getCorrection());
9340 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9341 CDeclEnd = Correction.end();
9342 CDecl != CDeclEnd; ++CDecl) {
9343 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9344 if (FD && !FD->hasBody() &&
9345 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9346 Previous.addDecl(FD);
9347 }
9348 }
9349 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9350
9351 NamedDecl *Result;
9352 // Retry building the function declaration with the new previous
9353 // declarations, and with errors suppressed.
9354 {
9355 // Trap errors.
9356 Sema::SFINAETrap Trap(SemaRef);
9357
9358 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9359 // pieces need to verify the typo-corrected C++ declaration and hopefully
9360 // eliminate the need for the parameter pack ExtraArgs.
9361 Result = SemaRef.ActOnFunctionDeclarator(
9362 ExtraArgs.S, ExtraArgs.D,
9363 Correction.getCorrectionDecl()->getDeclContext(),
9364 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9365 ExtraArgs.AddToScope);
9366
9367 if (Trap.hasErrorOccurred())
9368 Result = nullptr;
9369 }
9370
9371 if (Result) {
9372 // Determine which correction we picked.
9373 Decl *Canonical = Result->getCanonicalDecl();
9374 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9375 I != E; ++I)
9376 if ((*I)->getCanonicalDecl() == Canonical)
9377 Correction.setCorrectionDecl(*I);
9378
9379 // Let Sema know about the correction.
9381 SemaRef.diagnoseTypo(
9382 Correction,
9383 SemaRef.PDiag(IsLocalFriend
9384 ? diag::err_no_matching_local_friend_suggest
9385 : diag::err_member_decl_does_not_match_suggest)
9386 << Name << NewDC << IsDefinition);
9387 return Result;
9388 }
9389
9390 // Pretend the typo correction never occurred
9391 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9392 ExtraArgs.D.getIdentifierLoc());
9393 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9394 Previous.clear();
9395 Previous.setLookupName(Name);
9396 }
9397
9398 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9399 << Name << NewDC << IsDefinition << NewFD->getLocation();
9400
9401 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9402 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9403 CXXRecordDecl *RD = NewMD->getParent();
9404 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9405 << RD->getName() << RD->getLocation();
9406 }
9407
9408 bool NewFDisConst = NewMD && NewMD->isConst();
9409
9410 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9411 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9412 NearMatch != NearMatchEnd; ++NearMatch) {
9413 FunctionDecl *FD = NearMatch->first;
9414 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9415 bool FDisConst = MD && MD->isConst();
9416 bool IsMember = MD || !IsLocalFriend;
9417
9418 // FIXME: These notes are poorly worded for the local friend case.
9419 if (unsigned Idx = NearMatch->second) {
9420 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9421 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9422 if (Loc.isInvalid()) Loc = FD->getLocation();
9423 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9424 : diag::note_local_decl_close_param_match)
9425 << Idx << FDParam->getType()
9426 << NewFD->getParamDecl(Idx - 1)->getType();
9427 } else if (FDisConst != NewFDisConst) {
9428 auto DB = SemaRef.Diag(FD->getLocation(),
9429 diag::note_member_def_close_const_match)
9430 << NewFDisConst << FD->getSourceRange().getEnd();
9431 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9432 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9433 " const");
9434 else if (FTI.hasMethodTypeQualifiers() &&
9435 FTI.getConstQualifierLoc().isValid())
9436 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9437 } else {
9438 SemaRef.Diag(FD->getLocation(),
9439 IsMember ? diag::note_member_def_close_match
9440 : diag::note_local_decl_close_match);
9441 }
9442 }
9443 return nullptr;
9444}
9445
9447 switch (D.getDeclSpec().getStorageClassSpec()) {
9448 default: llvm_unreachable("Unknown storage class!");
9449 case DeclSpec::SCS_auto:
9453 diag::err_typecheck_sclass_func);
9455 D.setInvalidType();
9456 break;
9457 case DeclSpec::SCS_unspecified: break;
9460 return SC_None;
9461 return SC_Extern;
9462 case DeclSpec::SCS_static: {
9464 // C99 6.7.1p5:
9465 // The declaration of an identifier for a function that has
9466 // block scope shall have no explicit storage-class specifier
9467 // other than extern
9468 // See also (C++ [dcl.stc]p4).
9470 diag::err_static_block_func);
9471 break;
9472 } else
9473 return SC_Static;
9474 }
9476 }
9477
9478 // No explicit storage class has already been returned
9479 return SC_None;
9480}
9481
9483 DeclContext *DC, QualType &R,
9484 TypeSourceInfo *TInfo,
9485 StorageClass SC,
9486 bool &IsVirtualOkay) {
9487 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9488 DeclarationName Name = NameInfo.getName();
9489
9490 FunctionDecl *NewFD = nullptr;
9491 bool isInline = D.getDeclSpec().isInlineSpecified();
9492
9494 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9495 (SemaRef.getLangOpts().C23 &&
9496 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9497
9498 if (SemaRef.getLangOpts().C23)
9499 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9500 diag::err_c23_constexpr_not_variable);
9501 else
9502 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9503 diag::err_constexpr_wrong_decl_kind)
9504 << static_cast<int>(ConstexprKind);
9505 ConstexprKind = ConstexprSpecKind::Unspecified;
9507 }
9508
9509 if (!SemaRef.getLangOpts().CPlusPlus) {
9510 // Determine whether the function was written with a prototype. This is
9511 // true when:
9512 // - there is a prototype in the declarator, or
9513 // - the type R of the function is some kind of typedef or other non-
9514 // attributed reference to a type name (which eventually refers to a
9515 // function type). Note, we can't always look at the adjusted type to
9516 // check this case because attributes may cause a non-function
9517 // declarator to still have a function type. e.g.,
9518 // typedef void func(int a);
9519 // __attribute__((noreturn)) func other_func; // This has a prototype
9520 bool HasPrototype =
9522 (D.getDeclSpec().isTypeRep() &&
9523 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9524 ->isFunctionProtoType()) ||
9526 assert(
9527 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9528 "Strict prototypes are required");
9529
9530 NewFD = FunctionDecl::Create(
9531 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9532 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9534 /*TrailingRequiresClause=*/{});
9535 if (D.isInvalidType())
9536 NewFD->setInvalidDecl();
9537
9538 return NewFD;
9539 }
9540
9542 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9543
9544 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9545
9547 // This is a C++ constructor declaration.
9548 assert(DC->isRecord() &&
9549 "Constructors can only be declared in a member context");
9550
9551 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9553 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9555 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9556 InheritedConstructor(), TrailingRequiresClause);
9557
9558 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9559 // This is a C++ destructor declaration.
9560 if (DC->isRecord()) {
9561 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9564 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9565 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9566 /*isImplicitlyDeclared=*/false, ConstexprKind,
9567 TrailingRequiresClause);
9568 // User defined destructors start as not selected if the class definition is still
9569 // not done.
9570 if (Record->isBeingDefined())
9571 NewDD->setIneligibleOrNotSelected(true);
9572
9573 // If the destructor needs an implicit exception specification, set it
9574 // now. FIXME: It'd be nice to be able to create the right type to start
9575 // with, but the type needs to reference the destructor declaration.
9576 if (SemaRef.getLangOpts().CPlusPlus11)
9577 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9578
9579 IsVirtualOkay = true;
9580 return NewDD;
9581
9582 } else {
9583 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9584 D.setInvalidType();
9585
9586 // Create a FunctionDecl to satisfy the function definition parsing
9587 // code path.
9588 return FunctionDecl::Create(
9589 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9590 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9591 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9592 }
9593
9595 if (!DC->isRecord()) {
9596 SemaRef.Diag(D.getIdentifierLoc(),
9597 diag::err_conv_function_not_member);
9598 return nullptr;
9599 }
9600
9601 SemaRef.CheckConversionDeclarator(D, R, SC);
9602 if (D.isInvalidType())
9603 return nullptr;
9604
9605 IsVirtualOkay = true;
9607 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9608 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9609 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9610 TrailingRequiresClause);
9611
9613 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9614 return nullptr;
9616 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9617 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9618 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9619 } else if (DC->isRecord()) {
9620 // If the name of the function is the same as the name of the record,
9621 // then this must be an invalid constructor that has a return type.
9622 // (The parser checks for a return type and makes the declarator a
9623 // constructor if it has no return type).
9624 if (Name.getAsIdentifierInfo() &&
9625 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9626 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9629 return nullptr;
9630 }
9631
9632 // This is a C++ method declaration.
9634 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9635 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9636 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9637 IsVirtualOkay = !Ret->isStatic();
9638 return Ret;
9639 } else {
9640 bool isFriend =
9641 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9642 if (!isFriend && SemaRef.CurContext->isRecord())
9643 return nullptr;
9644
9645 // Determine whether the function was written with a
9646 // prototype. This true when:
9647 // - we're in C++ (where every function has a prototype),
9648 return FunctionDecl::Create(
9649 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9650 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9651 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9652 }
9653}
9654
9663
9665 // Size dependent types are just typedefs to normal integer types
9666 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9667 // integers other than by their names.
9668 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9669
9670 // Remove typedefs one by one until we reach a typedef
9671 // for a size dependent type.
9672 QualType DesugaredTy = Ty;
9673 do {
9674 ArrayRef<StringRef> Names(SizeTypeNames);
9675 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9676 if (Names.end() != Match)
9677 return true;
9678
9679 Ty = DesugaredTy;
9680 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9681 } while (DesugaredTy != Ty);
9682
9683 return false;
9684}
9685
9687 if (PT->isDependentType())
9688 return InvalidKernelParam;
9689
9690 if (PT->isPointerOrReferenceType()) {
9691 QualType PointeeType = PT->getPointeeType();
9692 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9693 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9694 PointeeType.getAddressSpace() == LangAS::Default)
9696
9697 if (PointeeType->isPointerType()) {
9698 // This is a pointer to pointer parameter.
9699 // Recursively check inner type.
9700 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9701 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9702 ParamKind == InvalidKernelParam)
9703 return ParamKind;
9704
9705 // OpenCL v3.0 s6.11.a:
9706 // A restriction to pass pointers to pointers only applies to OpenCL C
9707 // v1.2 or below.
9709 return ValidKernelParam;
9710
9711 return PtrPtrKernelParam;
9712 }
9713
9714 // C++ for OpenCL v1.0 s2.4:
9715 // Moreover the types used in parameters of the kernel functions must be:
9716 // Standard layout types for pointer parameters. The same applies to
9717 // reference if an implementation supports them in kernel parameters.
9718 if (S.getLangOpts().OpenCLCPlusPlus &&
9720 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9721 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9722 bool IsStandardLayoutType = true;
9723 if (CXXRec) {
9724 // If template type is not ODR-used its definition is only available
9725 // in the template definition not its instantiation.
9726 // FIXME: This logic doesn't work for types that depend on template
9727 // parameter (PR58590).
9728 if (!CXXRec->hasDefinition())
9729 CXXRec = CXXRec->getTemplateInstantiationPattern();
9730 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9731 IsStandardLayoutType = false;
9732 }
9733 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9734 !IsStandardLayoutType)
9735 return InvalidKernelParam;
9736 }
9737
9738 // OpenCL v1.2 s6.9.p:
9739 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9741 return ValidKernelParam;
9742
9743 return PtrKernelParam;
9744 }
9745
9746 // OpenCL v1.2 s6.9.k:
9747 // Arguments to kernel functions in a program cannot be declared with the
9748 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9749 // uintptr_t or a struct and/or union that contain fields declared to be one
9750 // of these built-in scalar types.
9752 return InvalidKernelParam;
9753
9754 if (PT->isImageType())
9755 return PtrKernelParam;
9756
9757 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9758 return InvalidKernelParam;
9759
9760 // OpenCL extension spec v1.2 s9.5:
9761 // This extension adds support for half scalar and vector types as built-in
9762 // types that can be used for arithmetic operations, conversions etc.
9763 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9764 PT->isHalfType())
9765 return InvalidKernelParam;
9766
9767 // Look into an array argument to check if it has a forbidden type.
9768 if (PT->isArrayType()) {
9769 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9770 // Call ourself to check an underlying type of an array. Since the
9771 // getPointeeOrArrayElementType returns an innermost type which is not an
9772 // array, this recursive call only happens once.
9773 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9774 }
9775
9776 // C++ for OpenCL v1.0 s2.4:
9777 // Moreover the types used in parameters of the kernel functions must be:
9778 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9779 // types) for parameters passed by value;
9780 if (S.getLangOpts().OpenCLCPlusPlus &&
9782 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9783 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9784 return InvalidKernelParam;
9785
9786 if (PT->isRecordType())
9787 return RecordKernelParam;
9788
9789 return ValidKernelParam;
9790}
9791
9793 Sema &S,
9794 Declarator &D,
9795 ParmVarDecl *Param,
9796 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9797 QualType PT = Param->getType();
9798
9799 // Cache the valid types we encounter to avoid rechecking structs that are
9800 // used again
9801 if (ValidTypes.count(PT.getTypePtr()))
9802 return;
9803
9804 switch (getOpenCLKernelParameterType(S, PT)) {
9805 case PtrPtrKernelParam:
9806 // OpenCL v3.0 s6.11.a:
9807 // A kernel function argument cannot be declared as a pointer to a pointer
9808 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9809 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9810 D.setInvalidType();
9811 return;
9812
9814 // OpenCL v1.0 s6.5:
9815 // __kernel function arguments declared to be a pointer of a type can point
9816 // to one of the following address spaces only : __global, __local or
9817 // __constant.
9818 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9819 D.setInvalidType();
9820 return;
9821
9822 // OpenCL v1.2 s6.9.k:
9823 // Arguments to kernel functions in a program cannot be declared with the
9824 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9825 // uintptr_t or a struct and/or union that contain fields declared to be
9826 // one of these built-in scalar types.
9827
9828 case InvalidKernelParam:
9829 // OpenCL v1.2 s6.8 n:
9830 // A kernel function argument cannot be declared
9831 // of event_t type.
9832 // Do not diagnose half type since it is diagnosed as invalid argument
9833 // type for any function elsewhere.
9834 if (!PT->isHalfType()) {
9835 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9836
9837 // Explain what typedefs are involved.
9838 const TypedefType *Typedef = nullptr;
9839 while ((Typedef = PT->getAs<TypedefType>())) {
9840 SourceLocation Loc = Typedef->getDecl()->getLocation();
9841 // SourceLocation may be invalid for a built-in type.
9842 if (Loc.isValid())
9843 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9844 PT = Typedef->desugar();
9845 }
9846 }
9847
9848 D.setInvalidType();
9849 return;
9850
9851 case PtrKernelParam:
9852 case ValidKernelParam:
9853 ValidTypes.insert(PT.getTypePtr());
9854 return;
9855
9856 case RecordKernelParam:
9857 break;
9858 }
9859
9860 // Track nested structs we will inspect
9862
9863 // Track where we are in the nested structs. Items will migrate from
9864 // VisitStack to HistoryStack as we do the DFS for bad field.
9866 HistoryStack.push_back(nullptr);
9867
9868 // At this point we already handled everything except of a RecordType.
9869 assert(PT->isRecordType() && "Unexpected type.");
9870 const auto *PD = PT->castAsRecordDecl();
9871 VisitStack.push_back(PD);
9872 assert(VisitStack.back() && "First decl null?");
9873
9874 do {
9875 const Decl *Next = VisitStack.pop_back_val();
9876 if (!Next) {
9877 assert(!HistoryStack.empty());
9878 // Found a marker, we have gone up a level
9879 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9880 ValidTypes.insert(Hist->getType().getTypePtr());
9881
9882 continue;
9883 }
9884
9885 // Adds everything except the original parameter declaration (which is not a
9886 // field itself) to the history stack.
9887 const RecordDecl *RD;
9888 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9889 HistoryStack.push_back(Field);
9890
9891 QualType FieldTy = Field->getType();
9892 // Other field types (known to be valid or invalid) are handled while we
9893 // walk around RecordDecl::fields().
9894 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9895 "Unexpected type.");
9896 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9897
9898 RD = FieldRecTy->castAsRecordDecl();
9899 } else {
9900 RD = cast<RecordDecl>(Next);
9901 }
9902
9903 // Add a null marker so we know when we've gone back up a level
9904 VisitStack.push_back(nullptr);
9905
9906 for (const auto *FD : RD->fields()) {
9907 QualType QT = FD->getType();
9908
9909 if (ValidTypes.count(QT.getTypePtr()))
9910 continue;
9911
9913 if (ParamType == ValidKernelParam)
9914 continue;
9915
9916 if (ParamType == RecordKernelParam) {
9917 VisitStack.push_back(FD);
9918 continue;
9919 }
9920
9921 // OpenCL v1.2 s6.9.p:
9922 // Arguments to kernel functions that are declared to be a struct or union
9923 // do not allow OpenCL objects to be passed as elements of the struct or
9924 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9925 // of SVM.
9926 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9927 ParamType == InvalidAddrSpacePtrKernelParam) {
9928 S.Diag(Param->getLocation(),
9929 diag::err_record_with_pointers_kernel_param)
9930 << PT->isUnionType()
9931 << PT;
9932 } else {
9933 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9934 }
9935
9936 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
9937 << PD->getDeclName();
9938
9939 // We have an error, now let's go back up through history and show where
9940 // the offending field came from
9942 I = HistoryStack.begin() + 1,
9943 E = HistoryStack.end();
9944 I != E; ++I) {
9945 const FieldDecl *OuterField = *I;
9946 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9947 << OuterField->getType();
9948 }
9949
9950 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9951 << QT->isPointerType()
9952 << QT;
9953 D.setInvalidType();
9954 return;
9955 }
9956 } while (!VisitStack.empty());
9957}
9958
9959/// Find the DeclContext in which a tag is implicitly declared if we see an
9960/// elaborated type specifier in the specified context, and lookup finds
9961/// nothing.
9963 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9964 DC = DC->getParent();
9965 return DC;
9966}
9967
9968/// Find the Scope in which a tag is implicitly declared if we see an
9969/// elaborated type specifier in the specified context, and lookup finds
9970/// nothing.
9971static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9972 while (S->isClassScope() ||
9973 (LangOpts.CPlusPlus &&
9975 ((S->getFlags() & Scope::DeclScope) == 0) ||
9976 (S->getEntity() && S->getEntity()->isTransparentContext()))
9977 S = S->getParent();
9978 return S;
9979}
9980
9981/// Determine whether a declaration matches a known function in namespace std.
9983 unsigned BuiltinID) {
9984 switch (BuiltinID) {
9985 case Builtin::BI__GetExceptionInfo:
9986 // No type checking whatsoever.
9987 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9988
9989 case Builtin::BIaddressof:
9990 case Builtin::BI__addressof:
9991 case Builtin::BIforward:
9992 case Builtin::BIforward_like:
9993 case Builtin::BImove:
9994 case Builtin::BImove_if_noexcept:
9995 case Builtin::BIas_const: {
9996 // Ensure that we don't treat the algorithm
9997 // OutputIt std::move(InputIt, InputIt, OutputIt)
9998 // as the builtin std::move.
9999 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10000 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10001 }
10002
10003 default:
10004 return false;
10005 }
10006}
10007
10008NamedDecl*
10011 MultiTemplateParamsArg TemplateParamListsRef,
10012 bool &AddToScope) {
10013 QualType R = TInfo->getType();
10014
10015 assert(R->isFunctionType());
10017 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10018
10019 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10020 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10022 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10023 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10024 TemplateParamLists.back() = Invented;
10025 else
10026 TemplateParamLists.push_back(Invented);
10027 }
10028
10029 // TODO: consider using NameInfo for diagnostic.
10031 DeclarationName Name = NameInfo.getName();
10033
10036 diag::err_invalid_thread)
10038
10043
10044 bool isFriend = false;
10046 bool isMemberSpecialization = false;
10047 bool isFunctionTemplateSpecialization = false;
10048
10049 bool HasExplicitTemplateArgs = false;
10050 TemplateArgumentListInfo TemplateArgs;
10051
10052 bool isVirtualOkay = false;
10053
10054 DeclContext *OriginalDC = DC;
10055 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10056
10057 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10058 isVirtualOkay);
10059 if (!NewFD) return nullptr;
10060
10061 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10063
10064 // Set the lexical context. If this is a function-scope declaration, or has a
10065 // C++ scope specifier, or is the object of a friend declaration, the lexical
10066 // context will be different from the semantic context.
10068
10069 if (IsLocalExternDecl)
10070 NewFD->setLocalExternDecl();
10071
10072 if (getLangOpts().CPlusPlus) {
10073 // The rules for implicit inlines changed in C++20 for methods and friends
10074 // with an in-class definition (when such a definition is not attached to
10075 // the global module). This does not affect declarations that are already
10076 // inline (whether explicitly or implicitly by being declared constexpr,
10077 // consteval, etc).
10078 // FIXME: We need a better way to separate C++ standard and clang modules.
10079 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10080 !NewFD->getOwningModule() ||
10081 NewFD->isFromGlobalModule() ||
10083 bool isInline = D.getDeclSpec().isInlineSpecified();
10084 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10085 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10086 isFriend = D.getDeclSpec().isFriendSpecified();
10087 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10088 // Pre-C++20 [class.friend]p5
10089 // A function can be defined in a friend declaration of a
10090 // class . . . . Such a function is implicitly inline.
10091 // Post C++20 [class.friend]p7
10092 // Such a function is implicitly an inline function if it is attached
10093 // to the global module.
10094 NewFD->setImplicitlyInline();
10095 }
10096
10097 // If this is a method defined in an __interface, and is not a constructor
10098 // or an overloaded operator, then set the pure flag (isVirtual will already
10099 // return true).
10100 if (const CXXRecordDecl *Parent =
10101 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10102 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10103 NewFD->setIsPureVirtual(true);
10104
10105 // C++ [class.union]p2
10106 // A union can have member functions, but not virtual functions.
10107 if (isVirtual && Parent->isUnion()) {
10108 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10109 NewFD->setInvalidDecl();
10110 }
10111 if ((Parent->isClass() || Parent->isStruct()) &&
10112 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10113 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10114 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10115 if (auto *Def = Parent->getDefinition())
10116 Def->setInitMethod(true);
10117 }
10118 }
10119
10120 SetNestedNameSpecifier(*this, NewFD, D);
10121 isMemberSpecialization = false;
10122 isFunctionTemplateSpecialization = false;
10123 if (D.isInvalidType())
10124 NewFD->setInvalidDecl();
10125
10126 // Match up the template parameter lists with the scope specifier, then
10127 // determine whether we have a template or a template specialization.
10128 bool Invalid = false;
10129 TemplateIdAnnotation *TemplateId =
10131 ? D.getName().TemplateId
10132 : nullptr;
10133 TemplateParameterList *TemplateParams =
10136 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10137 isMemberSpecialization, Invalid);
10138 if (TemplateParams) {
10139 // Check that we can declare a template here.
10140 if (CheckTemplateDeclScope(S, TemplateParams))
10141 NewFD->setInvalidDecl();
10142
10143 if (TemplateParams->size() > 0) {
10144 // This is a function template
10145
10146 // A destructor cannot be a template.
10148 Diag(NewFD->getLocation(), diag::err_destructor_template);
10149 NewFD->setInvalidDecl();
10150 // Function template with explicit template arguments.
10151 } else if (TemplateId) {
10152 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10153 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10154 NewFD->setInvalidDecl();
10155 }
10156
10157 // If we're adding a template to a dependent context, we may need to
10158 // rebuilding some of the types used within the template parameter list,
10159 // now that we know what the current instantiation is.
10160 if (DC->isDependentContext()) {
10161 ContextRAII SavedContext(*this, DC);
10163 Invalid = true;
10164 }
10165
10167 NewFD->getLocation(),
10168 Name, TemplateParams,
10169 NewFD);
10170 FunctionTemplate->setLexicalDeclContext(CurContext);
10172
10173 // For source fidelity, store the other template param lists.
10174 if (TemplateParamLists.size() > 1) {
10176 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10177 .drop_back(1));
10178 }
10179 } else {
10180 // This is a function template specialization.
10181 isFunctionTemplateSpecialization = true;
10182 // For source fidelity, store all the template param lists.
10183 if (TemplateParamLists.size() > 0)
10184 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10185
10186 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10187 if (isFriend) {
10188 // We want to remove the "template<>", found here.
10189 SourceRange RemoveRange = TemplateParams->getSourceRange();
10190
10191 // If we remove the template<> and the name is not a
10192 // template-id, we're actually silently creating a problem:
10193 // the friend declaration will refer to an untemplated decl,
10194 // and clearly the user wants a template specialization. So
10195 // we need to insert '<>' after the name.
10196 SourceLocation InsertLoc;
10198 InsertLoc = D.getName().getSourceRange().getEnd();
10199 InsertLoc = getLocForEndOfToken(InsertLoc);
10200 }
10201
10202 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10203 << Name << RemoveRange
10204 << FixItHint::CreateRemoval(RemoveRange)
10205 << FixItHint::CreateInsertion(InsertLoc, "<>");
10206 Invalid = true;
10207
10208 // Recover by faking up an empty template argument list.
10209 HasExplicitTemplateArgs = true;
10210 TemplateArgs.setLAngleLoc(InsertLoc);
10211 TemplateArgs.setRAngleLoc(InsertLoc);
10212 }
10213 }
10214 } else {
10215 // Check that we can declare a template here.
10216 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10217 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10218 NewFD->setInvalidDecl();
10219
10220 // All template param lists were matched against the scope specifier:
10221 // this is NOT (an explicit specialization of) a template.
10222 if (TemplateParamLists.size() > 0)
10223 // For source fidelity, store all the template param lists.
10224 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10225
10226 // "friend void foo<>(int);" is an implicit specialization decl.
10227 if (isFriend && TemplateId)
10228 isFunctionTemplateSpecialization = true;
10229 }
10230
10231 // If this is a function template specialization and the unqualified-id of
10232 // the declarator-id is a template-id, convert the template argument list
10233 // into our AST format and check for unexpanded packs.
10234 if (isFunctionTemplateSpecialization && TemplateId) {
10235 HasExplicitTemplateArgs = true;
10236
10237 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10238 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10239 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10240 TemplateId->NumArgs);
10241 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10242
10243 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10244 // declaration of a function template partial specialization? Should we
10245 // consider the unexpanded pack context to be a partial specialization?
10246 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10248 ArgLoc, isFriend ? UPPC_FriendDeclaration
10250 NewFD->setInvalidDecl();
10251 }
10252 }
10253
10254 if (Invalid) {
10255 NewFD->setInvalidDecl();
10256 if (FunctionTemplate)
10257 FunctionTemplate->setInvalidDecl();
10258 }
10259
10260 // C++ [dcl.fct.spec]p5:
10261 // The virtual specifier shall only be used in declarations of
10262 // nonstatic class member functions that appear within a
10263 // member-specification of a class declaration; see 10.3.
10264 //
10265 if (isVirtual && !NewFD->isInvalidDecl()) {
10266 if (!isVirtualOkay) {
10268 diag::err_virtual_non_function);
10269 } else if (!CurContext->isRecord()) {
10270 // 'virtual' was specified outside of the class.
10272 diag::err_virtual_out_of_class)
10274 } else if (NewFD->getDescribedFunctionTemplate()) {
10275 // C++ [temp.mem]p3:
10276 // A member function template shall not be virtual.
10278 diag::err_virtual_member_function_template)
10280 } else {
10281 // Okay: Add virtual to the method.
10282 NewFD->setVirtualAsWritten(true);
10283 }
10284
10285 if (getLangOpts().CPlusPlus14 &&
10286 NewFD->getReturnType()->isUndeducedType())
10287 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10288 }
10289
10290 // C++ [dcl.fct.spec]p3:
10291 // The inline specifier shall not appear on a block scope function
10292 // declaration.
10293 if (isInline && !NewFD->isInvalidDecl()) {
10294 if (CurContext->isFunctionOrMethod()) {
10295 // 'inline' is not allowed on block scope function declaration.
10297 diag::err_inline_declaration_block_scope) << Name
10299 }
10300 }
10301
10302 // C++ [dcl.fct.spec]p6:
10303 // The explicit specifier shall be used only in the declaration of a
10304 // constructor or conversion function within its class definition;
10305 // see 12.3.1 and 12.3.2.
10306 if (hasExplicit && !NewFD->isInvalidDecl() &&
10308 if (!CurContext->isRecord()) {
10309 // 'explicit' was specified outside of the class.
10311 diag::err_explicit_out_of_class)
10313 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10314 !isa<CXXConversionDecl>(NewFD)) {
10315 // 'explicit' was specified on a function that wasn't a constructor
10316 // or conversion function.
10318 diag::err_explicit_non_ctor_or_conv_function)
10320 }
10321 }
10322
10324 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10325 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10326 // are implicitly inline.
10327 NewFD->setImplicitlyInline();
10328
10329 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10330 // be either constructors or to return a literal type. Therefore,
10331 // destructors cannot be declared constexpr.
10332 if (isa<CXXDestructorDecl>(NewFD) &&
10334 ConstexprKind == ConstexprSpecKind::Consteval)) {
10335 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10336 << static_cast<int>(ConstexprKind);
10340 }
10341 // C++20 [dcl.constexpr]p2: An allocation function, or a
10342 // deallocation function shall not be declared with the consteval
10343 // specifier.
10344 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10347 diag::err_invalid_consteval_decl_kind)
10348 << NewFD;
10350 }
10351 }
10352
10353 // If __module_private__ was specified, mark the function accordingly.
10355 if (isFunctionTemplateSpecialization) {
10356 SourceLocation ModulePrivateLoc
10358 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10359 << 0
10360 << FixItHint::CreateRemoval(ModulePrivateLoc);
10361 } else {
10362 NewFD->setModulePrivate();
10363 if (FunctionTemplate)
10364 FunctionTemplate->setModulePrivate();
10365 }
10366 }
10367
10368 if (isFriend) {
10369 if (FunctionTemplate) {
10370 FunctionTemplate->setObjectOfFriendDecl();
10371 FunctionTemplate->setAccess(AS_public);
10372 }
10373 NewFD->setObjectOfFriendDecl();
10374 NewFD->setAccess(AS_public);
10375 }
10376
10377 // If a function is defined as defaulted or deleted, mark it as such now.
10378 // We'll do the relevant checks on defaulted / deleted functions later.
10379 switch (D.getFunctionDefinitionKind()) {
10382 break;
10383
10385 NewFD->setDefaulted();
10386 break;
10387
10389 NewFD->setDeletedAsWritten();
10390 break;
10391 }
10392
10393 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10395 // Pre C++20 [class.mfct]p2:
10396 // A member function may be defined (8.4) in its class definition, in
10397 // which case it is an inline member function (7.1.2)
10398 // Post C++20 [class.mfct]p1:
10399 // If a member function is attached to the global module and is defined
10400 // in its class definition, it is inline.
10401 NewFD->setImplicitlyInline();
10402 }
10403
10404 if (!isFriend && SC != SC_None) {
10405 // C++ [temp.expl.spec]p2:
10406 // The declaration in an explicit-specialization shall not be an
10407 // export-declaration. An explicit specialization shall not use a
10408 // storage-class-specifier other than thread_local.
10409 //
10410 // We diagnose friend declarations with storage-class-specifiers
10411 // elsewhere.
10412 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10414 diag::ext_explicit_specialization_storage_class)
10417 }
10418
10419 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10420 assert(isa<CXXMethodDecl>(NewFD) &&
10421 "Out-of-line member function should be a CXXMethodDecl");
10422 // C++ [class.static]p1:
10423 // A data or function member of a class may be declared static
10424 // in a class definition, in which case it is a static member of
10425 // the class.
10426
10427 // Complain about the 'static' specifier if it's on an out-of-line
10428 // member function definition.
10429
10430 // MSVC permits the use of a 'static' storage specifier on an
10431 // out-of-line member function template declaration and class member
10432 // template declaration (MSVC versions before 2015), warn about this.
10434 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10435 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10436 (getLangOpts().MSVCCompat &&
10438 ? diag::ext_static_out_of_line
10439 : diag::err_static_out_of_line)
10442 }
10443 }
10444
10445 // C++11 [except.spec]p15:
10446 // A deallocation function with no exception-specification is treated
10447 // as if it were specified with noexcept(true).
10448 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10449 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10450 !FPT->hasExceptionSpec())
10451 NewFD->setType(Context.getFunctionType(
10452 FPT->getReturnType(), FPT->getParamTypes(),
10454
10455 // C++20 [dcl.inline]/7
10456 // If an inline function or variable that is attached to a named module
10457 // is declared in a definition domain, it shall be defined in that
10458 // domain.
10459 // So, if the current declaration does not have a definition, we must
10460 // check at the end of the TU (or when the PMF starts) to see that we
10461 // have a definition at that point.
10462 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10463 NewFD->isInNamedModule()) {
10464 PendingInlineFuncDecls.insert(NewFD);
10465 }
10466 }
10467
10468 // Filter out previous declarations that don't match the scope.
10471 isMemberSpecialization ||
10472 isFunctionTemplateSpecialization);
10473
10474 // Handle GNU asm-label extension (encoded as an attribute).
10475 if (Expr *E = D.getAsmLabel()) {
10476 // The parser guarantees this is a string.
10478 NewFD->addAttr(
10479 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10480 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10481 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10483 if (I != ExtnameUndeclaredIdentifiers.end()) {
10484 if (isDeclExternC(NewFD)) {
10485 NewFD->addAttr(I->second);
10487 } else
10488 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10489 << /*Variable*/0 << NewFD;
10490 }
10491 }
10492
10493 // Copy the parameter declarations from the declarator D to the function
10494 // declaration NewFD, if they are available. First scavenge them into Params.
10496 unsigned FTIIdx;
10497 if (D.isFunctionDeclarator(FTIIdx)) {
10499
10500 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10501 // function that takes no arguments, not a function that takes a
10502 // single void argument.
10503 // We let through "const void" here because Sema::GetTypeForDeclarator
10504 // already checks for that case.
10505 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10506 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10507 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10508 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10509 Param->setDeclContext(NewFD);
10510 Params.push_back(Param);
10511
10512 if (Param->isInvalidDecl())
10513 NewFD->setInvalidDecl();
10514 }
10515 }
10516
10517 if (!getLangOpts().CPlusPlus) {
10518 // In C, find all the tag declarations from the prototype and move them
10519 // into the function DeclContext. Remove them from the surrounding tag
10520 // injection context of the function, which is typically but not always
10521 // the TU.
10522 DeclContext *PrototypeTagContext =
10524 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10525 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10526
10527 // We don't want to reparent enumerators. Look at their parent enum
10528 // instead.
10529 if (!TD) {
10530 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10531 TD = cast<EnumDecl>(ECD->getDeclContext());
10532 }
10533 if (!TD)
10534 continue;
10535 DeclContext *TagDC = TD->getLexicalDeclContext();
10536 if (!TagDC->containsDecl(TD))
10537 continue;
10538 TagDC->removeDecl(TD);
10539 TD->setDeclContext(NewFD);
10540 NewFD->addDecl(TD);
10541
10542 // Preserve the lexical DeclContext if it is not the surrounding tag
10543 // injection context of the FD. In this example, the semantic context of
10544 // E will be f and the lexical context will be S, while both the
10545 // semantic and lexical contexts of S will be f:
10546 // void f(struct S { enum E { a } f; } s);
10547 if (TagDC != PrototypeTagContext)
10548 TD->setLexicalDeclContext(TagDC);
10549 }
10550 }
10551 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10552 // When we're declaring a function with a typedef, typeof, etc as in the
10553 // following example, we'll need to synthesize (unnamed)
10554 // parameters for use in the declaration.
10555 //
10556 // @code
10557 // typedef void fn(int);
10558 // fn f;
10559 // @endcode
10560
10561 // Synthesize a parameter for each argument type.
10562 for (const auto &AI : FT->param_types()) {
10563 ParmVarDecl *Param =
10565 Param->setScopeInfo(0, Params.size());
10566 Params.push_back(Param);
10567 }
10568 } else {
10569 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10570 "Should not need args for typedef of non-prototype fn");
10571 }
10572
10573 // Finally, we know we have the right number of parameters, install them.
10574 NewFD->setParams(Params);
10575
10576 // If this declarator is a declaration and not a definition, its parameters
10577 // will not be pushed onto a scope chain. That means we will not issue any
10578 // reserved identifier warnings for the declaration, but we will for the
10579 // definition. Handle those here.
10580 if (!D.isFunctionDefinition()) {
10581 for (const ParmVarDecl *PVD : Params)
10583 }
10584
10586 NewFD->addAttr(
10587 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10588
10589 // Functions returning a variably modified type violate C99 6.7.5.2p2
10590 // because all functions have linkage.
10591 if (!NewFD->isInvalidDecl() &&
10593 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10594 NewFD->setInvalidDecl();
10595 }
10596
10597 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10599 !NewFD->hasAttr<SectionAttr>())
10600 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10601 Context, PragmaClangTextSection.SectionName,
10602 PragmaClangTextSection.PragmaLocation));
10603
10604 // Apply an implicit SectionAttr if #pragma code_seg is active.
10605 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10606 !NewFD->hasAttr<SectionAttr>()) {
10607 NewFD->addAttr(SectionAttr::CreateImplicit(
10608 Context, CodeSegStack.CurrentValue->getString(),
10609 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10610 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10613 NewFD))
10614 NewFD->dropAttr<SectionAttr>();
10615 }
10616
10617 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10618 // active.
10619 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10620 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10621 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10622 Context, PragmaClangTextSection.PragmaLocation));
10623
10624 // Apply an implicit CodeSegAttr from class declspec or
10625 // apply an implicit SectionAttr from #pragma code_seg if active.
10626 if (!NewFD->hasAttr<CodeSegAttr>()) {
10628 D.isFunctionDefinition())) {
10629 NewFD->addAttr(SAttr);
10630 }
10631 }
10632
10633 // Handle attributes.
10634 ProcessDeclAttributes(S, NewFD, D);
10635 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10636 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10637 !NewTVA->isDefaultVersion() &&
10638 !Context.getTargetInfo().hasFeature("fmv")) {
10639 // Don't add to scope fmv functions declarations if fmv disabled
10640 AddToScope = false;
10641 return NewFD;
10642 }
10643
10644 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10645 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10646 // type.
10647 //
10648 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10649 // type declaration will generate a compilation error.
10650 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10651 if (AddressSpace != LangAS::Default) {
10652 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10653 NewFD->setInvalidDecl();
10654 }
10655 }
10656
10657 if (!getLangOpts().CPlusPlus) {
10658 // Perform semantic checking on the function declaration.
10659 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10660 CheckMain(NewFD, D.getDeclSpec());
10661
10662 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10663 CheckMSVCRTEntryPoint(NewFD);
10664
10665 if (!NewFD->isInvalidDecl())
10667 isMemberSpecialization,
10669 else if (!Previous.empty())
10670 // Recover gracefully from an invalid redeclaration.
10671 D.setRedeclaration(true);
10672 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10673 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10674 "previous declaration set still overloaded");
10675
10676 // Diagnose no-prototype function declarations with calling conventions that
10677 // don't support variadic calls. Only do this in C and do it after merging
10678 // possibly prototyped redeclarations.
10679 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10681 CallingConv CC = FT->getExtInfo().getCC();
10682 if (!supportsVariadicCall(CC)) {
10683 // Windows system headers sometimes accidentally use stdcall without
10684 // (void) parameters, so we relax this to a warning.
10685 int DiagID =
10686 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10687 Diag(NewFD->getLocation(), DiagID)
10689 }
10690 }
10691
10695 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10697 } else {
10698 // C++11 [replacement.functions]p3:
10699 // The program's definitions shall not be specified as inline.
10700 //
10701 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10702 //
10703 // Suppress the diagnostic if the function is __attribute__((used)), since
10704 // that forces an external definition to be emitted.
10705 if (D.getDeclSpec().isInlineSpecified() &&
10707 !NewFD->hasAttr<UsedAttr>())
10709 diag::ext_operator_new_delete_declared_inline)
10710 << NewFD->getDeclName();
10711
10712 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10713 // C++20 [dcl.decl.general]p4:
10714 // The optional requires-clause in an init-declarator or
10715 // member-declarator shall be present only if the declarator declares a
10716 // templated function.
10717 //
10718 // C++20 [temp.pre]p8:
10719 // An entity is templated if it is
10720 // - a template,
10721 // - an entity defined or created in a templated entity,
10722 // - a member of a templated entity,
10723 // - an enumerator for an enumeration that is a templated entity, or
10724 // - the closure type of a lambda-expression appearing in the
10725 // declaration of a templated entity.
10726 //
10727 // [Note 6: A local class, a local or block variable, or a friend
10728 // function defined in a templated entity is a templated entity.
10729 // — end note]
10730 //
10731 // A templated function is a function template or a function that is
10732 // templated. A templated class is a class template or a class that is
10733 // templated. A templated variable is a variable template or a variable
10734 // that is templated.
10735 if (!FunctionTemplate) {
10736 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10737 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10738 // An explicit specialization shall not have a trailing
10739 // requires-clause unless it declares a function template.
10740 //
10741 // Since a friend function template specialization cannot be
10742 // definition, and since a non-template friend declaration with a
10743 // trailing requires-clause must be a definition, we diagnose
10744 // friend function template specializations with trailing
10745 // requires-clauses on the same path as explicit specializations
10746 // even though they aren't necessarily prohibited by the same
10747 // language rule.
10748 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10749 << isFriend;
10750 } else if (isFriend && NewFD->isTemplated() &&
10751 !D.isFunctionDefinition()) {
10752 // C++ [temp.friend]p9:
10753 // A non-template friend declaration with a requires-clause shall be
10754 // a definition.
10755 Diag(NewFD->getBeginLoc(),
10756 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10757 NewFD->setInvalidDecl();
10758 } else if (!NewFD->isTemplated() ||
10759 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10760 Diag(TRC->getBeginLoc(),
10761 diag::err_constrained_non_templated_function);
10762 }
10763 }
10764 }
10765
10766 // We do not add HD attributes to specializations here because
10767 // they may have different constexpr-ness compared to their
10768 // templates and, after maybeAddHostDeviceAttrs() is applied,
10769 // may end up with different effective targets. Instead, a
10770 // specialization inherits its target attributes from its template
10771 // in the CheckFunctionTemplateSpecialization() call below.
10772 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10774
10775 // Handle explicit specializations of function templates
10776 // and friend function declarations with an explicit
10777 // template argument list.
10778 if (isFunctionTemplateSpecialization) {
10779 bool isDependentSpecialization = false;
10780 if (isFriend) {
10781 // For friend function specializations, this is a dependent
10782 // specialization if its semantic context is dependent, its
10783 // type is dependent, or if its template-id is dependent.
10784 isDependentSpecialization =
10785 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10786 (HasExplicitTemplateArgs &&
10787 TemplateSpecializationType::
10788 anyInstantiationDependentTemplateArguments(
10789 TemplateArgs.arguments()));
10790 assert((!isDependentSpecialization ||
10791 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10792 "dependent friend function specialization without template "
10793 "args");
10794 } else {
10795 // For class-scope explicit specializations of function templates,
10796 // if the lexical context is dependent, then the specialization
10797 // is dependent.
10798 isDependentSpecialization =
10799 CurContext->isRecord() && CurContext->isDependentContext();
10800 }
10801
10802 TemplateArgumentListInfo *ExplicitTemplateArgs =
10803 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10804 if (isDependentSpecialization) {
10805 // If it's a dependent specialization, it may not be possible
10806 // to determine the primary template (for explicit specializations)
10807 // or befriended declaration (for friends) until the enclosing
10808 // template is instantiated. In such cases, we store the declarations
10809 // found by name lookup and defer resolution until instantiation.
10811 NewFD, ExplicitTemplateArgs, Previous))
10812 NewFD->setInvalidDecl();
10813 } else if (!NewFD->isInvalidDecl()) {
10814 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10815 Previous))
10816 NewFD->setInvalidDecl();
10817 }
10818 } else if (isMemberSpecialization && !FunctionTemplate) {
10820 NewFD->setInvalidDecl();
10821 }
10822
10823 // Perform semantic checking on the function declaration.
10824 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10825 CheckMain(NewFD, D.getDeclSpec());
10826
10827 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10828 CheckMSVCRTEntryPoint(NewFD);
10829
10830 if (!NewFD->isInvalidDecl())
10832 isMemberSpecialization,
10834 else if (!Previous.empty())
10835 // Recover gracefully from an invalid redeclaration.
10836 D.setRedeclaration(true);
10837
10838 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10839 !D.isRedeclaration() ||
10840 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10841 "previous declaration set still overloaded");
10842
10843 NamedDecl *PrincipalDecl = (FunctionTemplate
10845 : NewFD);
10846
10847 if (isFriend && NewFD->getPreviousDecl()) {
10848 AccessSpecifier Access = AS_public;
10849 if (!NewFD->isInvalidDecl())
10850 Access = NewFD->getPreviousDecl()->getAccess();
10851
10852 NewFD->setAccess(Access);
10853 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10854 }
10855
10856 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10858 PrincipalDecl->setNonMemberOperator();
10859
10860 // If we have a function template, check the template parameter
10861 // list. This will check and merge default template arguments.
10862 if (FunctionTemplate) {
10863 FunctionTemplateDecl *PrevTemplate =
10864 FunctionTemplate->getPreviousDecl();
10865 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10866 PrevTemplate ? PrevTemplate->getTemplateParameters()
10867 : nullptr,
10872 : (D.getCXXScopeSpec().isSet() &&
10873 DC && DC->isRecord() &&
10874 DC->isDependentContext())
10877 }
10878
10879 if (NewFD->isInvalidDecl()) {
10880 // Ignore all the rest of this.
10881 } else if (!D.isRedeclaration()) {
10882 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10883 AddToScope };
10884 // Fake up an access specifier if it's supposed to be a class member.
10885 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10886 NewFD->setAccess(AS_public);
10887
10888 // Qualified decls generally require a previous declaration.
10889 if (D.getCXXScopeSpec().isSet()) {
10890 // ...with the major exception of templated-scope or
10891 // dependent-scope friend declarations.
10892
10893 // TODO: we currently also suppress this check in dependent
10894 // contexts because (1) the parameter depth will be off when
10895 // matching friend templates and (2) we might actually be
10896 // selecting a friend based on a dependent factor. But there
10897 // are situations where these conditions don't apply and we
10898 // can actually do this check immediately.
10899 //
10900 // Unless the scope is dependent, it's always an error if qualified
10901 // redeclaration lookup found nothing at all. Diagnose that now;
10902 // nothing will diagnose that error later.
10903 if (isFriend &&
10905 (!Previous.empty() && CurContext->isDependentContext()))) {
10906 // ignore these
10907 } else if (NewFD->isCPUDispatchMultiVersion() ||
10908 NewFD->isCPUSpecificMultiVersion()) {
10909 // ignore this, we allow the redeclaration behavior here to create new
10910 // versions of the function.
10911 } else {
10912 // The user tried to provide an out-of-line definition for a
10913 // function that is a member of a class or namespace, but there
10914 // was no such member function declared (C++ [class.mfct]p2,
10915 // C++ [namespace.memdef]p2). For example:
10916 //
10917 // class X {
10918 // void f() const;
10919 // };
10920 //
10921 // void X::f() { } // ill-formed
10922 //
10923 // Complain about this problem, and attempt to suggest close
10924 // matches (e.g., those that differ only in cv-qualifiers and
10925 // whether the parameter types are references).
10926
10928 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10929 AddToScope = ExtraArgs.AddToScope;
10930 return Result;
10931 }
10932 }
10933
10934 // Unqualified local friend declarations are required to resolve
10935 // to something.
10936 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10938 *this, Previous, NewFD, ExtraArgs, true, S)) {
10939 AddToScope = ExtraArgs.AddToScope;
10940 return Result;
10941 }
10942 }
10943 } else if (!D.isFunctionDefinition() &&
10944 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10945 !isFriend && !isFunctionTemplateSpecialization &&
10946 !isMemberSpecialization) {
10947 // An out-of-line member function declaration must also be a
10948 // definition (C++ [class.mfct]p2).
10949 // Note that this is not the case for explicit specializations of
10950 // function templates or member functions of class templates, per
10951 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10952 // extension for compatibility with old SWIG code which likes to
10953 // generate them.
10954 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10955 << D.getCXXScopeSpec().getRange();
10956 }
10957 }
10958
10959 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10960 // Any top level function could potentially be specified as an entry.
10961 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10962 HLSL().ActOnTopLevelFunction(NewFD);
10963
10964 if (NewFD->hasAttr<HLSLShaderAttr>())
10965 HLSL().CheckEntryPoint(NewFD);
10966 }
10967
10968 // If this is the first declaration of a library builtin function, add
10969 // attributes as appropriate.
10970 if (!D.isRedeclaration()) {
10971 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10972 if (unsigned BuiltinID = II->getBuiltinID()) {
10973 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10974 if (!InStdNamespace &&
10976 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10977 // Validate the type matches unless this builtin is specified as
10978 // matching regardless of its declared type.
10979 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10980 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10981 } else {
10983 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10984 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10985
10986 if (!Error && !BuiltinType.isNull() &&
10987 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10988 NewFD->getType(), BuiltinType))
10989 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10990 }
10991 }
10992 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10993 isStdBuiltin(Context, NewFD, BuiltinID)) {
10994 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10995 }
10996 }
10997 }
10998 }
10999
11000 ProcessPragmaWeak(S, NewFD);
11001 checkAttributesAfterMerging(*this, *NewFD);
11002
11004
11005 if (NewFD->hasAttr<OverloadableAttr>() &&
11006 !NewFD->getType()->getAs<FunctionProtoType>()) {
11007 Diag(NewFD->getLocation(),
11008 diag::err_attribute_overloadable_no_prototype)
11009 << NewFD;
11010 NewFD->dropAttr<OverloadableAttr>();
11011 }
11012
11013 // If there's a #pragma GCC visibility in scope, and this isn't a class
11014 // member, set the visibility of this function.
11015 if (!DC->isRecord() && NewFD->isExternallyVisible())
11017
11018 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11019 // marking the function.
11020 ObjC().AddCFAuditedAttribute(NewFD);
11021
11022 // If this is a function definition, check if we have to apply any
11023 // attributes (i.e. optnone and no_builtin) due to a pragma.
11024 if (D.isFunctionDefinition()) {
11025 AddRangeBasedOptnone(NewFD);
11027 AddSectionMSAllocText(NewFD);
11029 }
11030
11031 // If this is the first declaration of an extern C variable, update
11032 // the map of such variables.
11033 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11034 isIncompleteDeclExternC(*this, NewFD))
11036
11037 // Set this FunctionDecl's range up to the right paren.
11038 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11039
11040 if (D.isRedeclaration() && !Previous.empty()) {
11041 NamedDecl *Prev = Previous.getRepresentativeDecl();
11042 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11043 isMemberSpecialization ||
11044 isFunctionTemplateSpecialization,
11046 }
11047
11048 if (getLangOpts().CUDA) {
11049 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11050 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11053 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11055 Context.setcudaConfigureCallDecl(NewFD);
11056 }
11057 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&
11058 !NewFD->isInvalidDecl() &&
11061 Diag(NewFD->getLocation(), diag::err_config_pointer_return)
11063 Context.setcudaGetParameterBufferDecl(NewFD);
11064 }
11065 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&
11066 !NewFD->isInvalidDecl() &&
11069 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11071 Context.setcudaLaunchDeviceDecl(NewFD);
11072 }
11073 }
11074 }
11075
11077
11078 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11079 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11080 if (SC == SC_Static) {
11081 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11082 D.setInvalidType();
11083 }
11084
11085 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11086 if (!NewFD->getReturnType()->isVoidType()) {
11087 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11088 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11089 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11090 : FixItHint());
11091 D.setInvalidType();
11092 }
11093
11095 for (auto *Param : NewFD->parameters())
11096 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11097
11098 if (getLangOpts().OpenCLCPlusPlus) {
11099 if (DC->isRecord()) {
11100 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11101 D.setInvalidType();
11102 }
11103 if (FunctionTemplate) {
11104 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11105 D.setInvalidType();
11106 }
11107 }
11108 }
11109
11110 if (getLangOpts().CPlusPlus) {
11111 // Precalculate whether this is a friend function template with a constraint
11112 // that depends on an enclosing template, per [temp.friend]p9.
11113 if (isFriend && FunctionTemplate &&
11116
11117 // C++ [temp.friend]p9:
11118 // A friend function template with a constraint that depends on a
11119 // template parameter from an enclosing template shall be a definition.
11120 if (!D.isFunctionDefinition()) {
11121 Diag(NewFD->getBeginLoc(),
11122 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11123 NewFD->setInvalidDecl();
11124 }
11125 }
11126
11127 if (FunctionTemplate) {
11128 if (NewFD->isInvalidDecl())
11129 FunctionTemplate->setInvalidDecl();
11130 return FunctionTemplate;
11131 }
11132
11133 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11135 }
11136
11137 for (const ParmVarDecl *Param : NewFD->parameters()) {
11138 QualType PT = Param->getType();
11139
11140 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11141 // types.
11142 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11143 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11144 QualType ElemTy = PipeTy->getElementType();
11145 if (ElemTy->isPointerOrReferenceType()) {
11146 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11147 D.setInvalidType();
11148 }
11149 }
11150 }
11151 // WebAssembly tables can't be used as function parameters.
11152 if (Context.getTargetInfo().getTriple().isWasm()) {
11154 Diag(Param->getTypeSpecStartLoc(),
11155 diag::err_wasm_table_as_function_parameter);
11156 D.setInvalidType();
11157 }
11158 }
11159 }
11160
11161 // Diagnose availability attributes. Availability cannot be used on functions
11162 // that are run during load/unload.
11163 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11164 if (NewFD->hasAttr<ConstructorAttr>()) {
11165 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11166 << 1;
11167 NewFD->dropAttr<AvailabilityAttr>();
11168 }
11169 if (NewFD->hasAttr<DestructorAttr>()) {
11170 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11171 << 2;
11172 NewFD->dropAttr<AvailabilityAttr>();
11173 }
11174 }
11175
11176 // Diagnose no_builtin attribute on function declaration that are not a
11177 // definition.
11178 // FIXME: We should really be doing this in
11179 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11180 // the FunctionDecl and at this point of the code
11181 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11182 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11183 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11184 switch (D.getFunctionDefinitionKind()) {
11187 Diag(NBA->getLocation(),
11188 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11189 << NBA->getSpelling();
11190 break;
11192 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11193 << NBA->getSpelling();
11194 break;
11196 break;
11197 }
11198
11199 // Similar to no_builtin logic above, at this point of the code
11200 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11201 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11202 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11203 !NewFD->isInvalidDecl() &&
11205 ExternalDeclarations.push_back(NewFD);
11206
11207 // Used for a warning on the 'next' declaration when used with a
11208 // `routine(name)`.
11209 if (getLangOpts().OpenACC)
11211
11212 return NewFD;
11213}
11214
11215/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11216/// when __declspec(code_seg) "is applied to a class, all member functions of
11217/// the class and nested classes -- this includes compiler-generated special
11218/// member functions -- are put in the specified segment."
11219/// The actual behavior is a little more complicated. The Microsoft compiler
11220/// won't check outer classes if there is an active value from #pragma code_seg.
11221/// The CodeSeg is always applied from the direct parent but only from outer
11222/// classes when the #pragma code_seg stack is empty. See:
11223/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11224/// available since MS has removed the page.
11226 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11227 if (!Method)
11228 return nullptr;
11229 const CXXRecordDecl *Parent = Method->getParent();
11230 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11231 Attr *NewAttr = SAttr->clone(S.getASTContext());
11232 NewAttr->setImplicit(true);
11233 return NewAttr;
11234 }
11235
11236 // The Microsoft compiler won't check outer classes for the CodeSeg
11237 // when the #pragma code_seg stack is active.
11238 if (S.CodeSegStack.CurrentValue)
11239 return nullptr;
11240
11241 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11242 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11243 Attr *NewAttr = SAttr->clone(S.getASTContext());
11244 NewAttr->setImplicit(true);
11245 return NewAttr;
11246 }
11247 }
11248 return nullptr;
11249}
11250
11252 bool IsDefinition) {
11253 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11254 return A;
11255 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11256 CodeSegStack.CurrentValue)
11257 return SectionAttr::CreateImplicit(
11258 getASTContext(), CodeSegStack.CurrentValue->getString(),
11259 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11260 return nullptr;
11261}
11262
11264 QualType NewT, QualType OldT) {
11266 return true;
11267
11268 // For dependently-typed local extern declarations and friends, we can't
11269 // perform a correct type check in general until instantiation:
11270 //
11271 // int f();
11272 // template<typename T> void g() { T f(); }
11273 //
11274 // (valid if g() is only instantiated with T = int).
11275 if (NewT->isDependentType() &&
11276 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11277 return false;
11278
11279 // Similarly, if the previous declaration was a dependent local extern
11280 // declaration, we don't really know its type yet.
11281 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11282 return false;
11283
11284 return true;
11285}
11286
11289 return true;
11290
11291 // Don't chain dependent friend function definitions until instantiation, to
11292 // permit cases like
11293 //
11294 // void func();
11295 // template<typename T> class C1 { friend void func() {} };
11296 // template<typename T> class C2 { friend void func() {} };
11297 //
11298 // ... which is valid if only one of C1 and C2 is ever instantiated.
11299 //
11300 // FIXME: This need only apply to function definitions. For now, we proxy
11301 // this by checking for a file-scope function. We do not want this to apply
11302 // to friend declarations nominating member functions, because that gets in
11303 // the way of access checks.
11305 return false;
11306
11307 auto *VD = dyn_cast<ValueDecl>(D);
11308 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11309 return !VD || !PrevVD ||
11310 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11311 PrevVD->getType());
11312}
11313
11314/// Check the target or target_version attribute of the function for
11315/// MultiVersion validity.
11316///
11317/// Returns true if there was an error, false otherwise.
11318static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11319 const auto *TA = FD->getAttr<TargetAttr>();
11320 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11321
11322 assert((TA || TVA) && "Expecting target or target_version attribute");
11323
11325 enum ErrType { Feature = 0, Architecture = 1 };
11326
11327 if (TA) {
11328 ParsedTargetAttr ParseInfo =
11329 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11330 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11331 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11332 << Architecture << ParseInfo.CPU;
11333 return true;
11334 }
11335 for (const auto &Feat : ParseInfo.Features) {
11336 auto BareFeat = StringRef{Feat}.substr(1);
11337 if (Feat[0] == '-') {
11338 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11339 << Feature << ("no-" + BareFeat).str();
11340 return true;
11341 }
11342
11343 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11344 !TargetInfo.isValidFeatureName(BareFeat) ||
11345 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11346 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11347 << Feature << BareFeat;
11348 return true;
11349 }
11350 }
11351 }
11352
11353 if (TVA) {
11355 ParsedTargetAttr ParseInfo;
11356 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11357 ParseInfo =
11358 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11359 for (auto &Feat : ParseInfo.Features)
11360 Feats.push_back(StringRef{Feat}.substr(1));
11361 } else {
11362 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11363 TVA->getFeatures(Feats);
11364 }
11365 for (const auto &Feat : Feats) {
11366 if (!TargetInfo.validateCpuSupports(Feat)) {
11367 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11368 << Feature << Feat;
11369 return true;
11370 }
11371 }
11372 }
11373 return false;
11374}
11375
11376// Provide a white-list of attributes that are allowed to be combined with
11377// multiversion functions.
11379 MultiVersionKind MVKind) {
11380 // Note: this list/diagnosis must match the list in
11381 // checkMultiversionAttributesAllSame.
11382 switch (Kind) {
11383 default:
11384 return false;
11385 case attr::ArmLocallyStreaming:
11386 return MVKind == MultiVersionKind::TargetVersion ||
11388 case attr::Used:
11389 return MVKind == MultiVersionKind::Target;
11390 case attr::NonNull:
11391 case attr::NoThrow:
11392 return true;
11393 }
11394}
11395
11397 const FunctionDecl *FD,
11398 const FunctionDecl *CausedFD,
11399 MultiVersionKind MVKind) {
11400 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11401 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11402 << static_cast<unsigned>(MVKind) << A;
11403 if (CausedFD)
11404 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11405 return true;
11406 };
11407
11408 for (const Attr *A : FD->attrs()) {
11409 switch (A->getKind()) {
11410 case attr::CPUDispatch:
11411 case attr::CPUSpecific:
11412 if (MVKind != MultiVersionKind::CPUDispatch &&
11414 return Diagnose(S, A);
11415 break;
11416 case attr::Target:
11417 if (MVKind != MultiVersionKind::Target)
11418 return Diagnose(S, A);
11419 break;
11420 case attr::TargetVersion:
11421 if (MVKind != MultiVersionKind::TargetVersion &&
11423 return Diagnose(S, A);
11424 break;
11425 case attr::TargetClones:
11426 if (MVKind != MultiVersionKind::TargetClones &&
11428 return Diagnose(S, A);
11429 break;
11430 default:
11431 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11432 return Diagnose(S, A);
11433 break;
11434 }
11435 }
11436 return false;
11437}
11438
11440 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11441 const PartialDiagnostic &NoProtoDiagID,
11442 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11443 const PartialDiagnosticAt &NoSupportDiagIDAt,
11444 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11445 bool ConstexprSupported, bool CLinkageMayDiffer) {
11446 enum DoesntSupport {
11447 FuncTemplates = 0,
11448 VirtFuncs = 1,
11449 DeducedReturn = 2,
11450 Constructors = 3,
11451 Destructors = 4,
11452 DeletedFuncs = 5,
11453 DefaultedFuncs = 6,
11454 ConstexprFuncs = 7,
11455 ConstevalFuncs = 8,
11456 Lambda = 9,
11457 };
11458 enum Different {
11459 CallingConv = 0,
11460 ReturnType = 1,
11461 ConstexprSpec = 2,
11462 InlineSpec = 3,
11463 Linkage = 4,
11464 LanguageLinkage = 5,
11465 };
11466
11467 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11468 !OldFD->getType()->getAs<FunctionProtoType>()) {
11469 Diag(OldFD->getLocation(), NoProtoDiagID);
11470 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11471 return true;
11472 }
11473
11474 if (NoProtoDiagID.getDiagID() != 0 &&
11475 !NewFD->getType()->getAs<FunctionProtoType>())
11476 return Diag(NewFD->getLocation(), NoProtoDiagID);
11477
11478 if (!TemplatesSupported &&
11480 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11481 << FuncTemplates;
11482
11483 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11484 if (NewCXXFD->isVirtual())
11485 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11486 << VirtFuncs;
11487
11488 if (isa<CXXConstructorDecl>(NewCXXFD))
11489 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11490 << Constructors;
11491
11492 if (isa<CXXDestructorDecl>(NewCXXFD))
11493 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11494 << Destructors;
11495 }
11496
11497 if (NewFD->isDeleted())
11498 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11499 << DeletedFuncs;
11500
11501 if (NewFD->isDefaulted())
11502 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11503 << DefaultedFuncs;
11504
11505 if (!ConstexprSupported && NewFD->isConstexpr())
11506 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11507 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11508
11509 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11510 const auto *NewType = cast<FunctionType>(NewQType);
11511 QualType NewReturnType = NewType->getReturnType();
11512
11513 if (NewReturnType->isUndeducedType())
11514 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11515 << DeducedReturn;
11516
11517 // Ensure the return type is identical.
11518 if (OldFD) {
11519 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11520 const auto *OldType = cast<FunctionType>(OldQType);
11521 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11522 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11523
11524 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11525 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11526
11527 bool ArmStreamingCCMismatched = false;
11528 if (OldFPT && NewFPT) {
11529 unsigned Diff =
11530 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11531 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11532 // cannot be mixed.
11535 ArmStreamingCCMismatched = true;
11536 }
11537
11538 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11539 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11540
11541 QualType OldReturnType = OldType->getReturnType();
11542
11543 if (OldReturnType != NewReturnType)
11544 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11545
11546 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11547 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11548
11549 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11550 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11551
11552 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11553 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11554
11555 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11556 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11557
11558 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11559 NewFD->getLocation()))
11560 return true;
11561 }
11562 return false;
11563}
11564
11566 const FunctionDecl *NewFD,
11567 bool CausesMV,
11568 MultiVersionKind MVKind) {
11570 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11571 if (OldFD)
11572 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11573 return true;
11574 }
11575
11576 bool IsCPUSpecificCPUDispatchMVKind =
11579
11580 if (CausesMV && OldFD &&
11581 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11582 return true;
11583
11584 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11585 return true;
11586
11587 // Only allow transition to MultiVersion if it hasn't been used.
11588 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11589 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11590 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11591 return true;
11592 }
11593
11595 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11597 S.PDiag(diag::note_multiversioning_caused_here)),
11599 S.PDiag(diag::err_multiversion_doesnt_support)
11600 << static_cast<unsigned>(MVKind)),
11602 S.PDiag(diag::err_multiversion_diff)),
11603 /*TemplatesSupported=*/false,
11604 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11605 /*CLinkageMayDiffer=*/false);
11606}
11607
11608/// Check the validity of a multiversion function declaration that is the
11609/// first of its kind. Also sets the multiversion'ness' of the function itself.
11610///
11611/// This sets NewFD->isInvalidDecl() to true if there was an error.
11612///
11613/// Returns true if there was an error, false otherwise.
11616 assert(MVKind != MultiVersionKind::None &&
11617 "Function lacks multiversion attribute");
11618 const auto *TA = FD->getAttr<TargetAttr>();
11619 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11620 // The target attribute only causes MV if this declaration is the default,
11621 // otherwise it is treated as a normal function.
11622 if (TA && !TA->isDefaultVersion())
11623 return false;
11624
11625 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11626 FD->setInvalidDecl();
11627 return true;
11628 }
11629
11630 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11631 FD->setInvalidDecl();
11632 return true;
11633 }
11634
11635 FD->setIsMultiVersion();
11636 return false;
11637}
11638
11640 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11642 return true;
11643 }
11644
11645 return false;
11646}
11647
11649 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11650 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11651 return;
11652
11653 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11654 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11655
11656 if (MVKindTo == MultiVersionKind::None &&
11657 (MVKindFrom == MultiVersionKind::TargetVersion ||
11658 MVKindFrom == MultiVersionKind::TargetClones))
11659 To->addAttr(TargetVersionAttr::CreateImplicit(
11660 To->getASTContext(), "default", To->getSourceRange()));
11661}
11662
11664 FunctionDecl *NewFD,
11665 bool &Redeclaration,
11666 NamedDecl *&OldDecl,
11668 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11669
11670 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11671 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11672 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11673 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11674
11675 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11676
11677 // The definitions should be allowed in any order. If we have discovered
11678 // a new target version and the preceeding was the default, then add the
11679 // corresponding attribute to it.
11680 patchDefaultTargetVersion(NewFD, OldFD);
11681
11682 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11683 // to change, this is a simple redeclaration.
11684 if (NewTA && !NewTA->isDefaultVersion() &&
11685 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11686 return false;
11687
11688 // Otherwise, this decl causes MultiVersioning.
11689 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11692 NewFD->setInvalidDecl();
11693 return true;
11694 }
11695
11696 if (CheckMultiVersionValue(S, NewFD)) {
11697 NewFD->setInvalidDecl();
11698 return true;
11699 }
11700
11701 // If this is 'default', permit the forward declaration.
11702 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11703 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11704 Redeclaration = true;
11705 OldDecl = OldFD;
11706 OldFD->setIsMultiVersion();
11707 NewFD->setIsMultiVersion();
11708 return false;
11709 }
11710
11711 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11712 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11713 NewFD->setInvalidDecl();
11714 return true;
11715 }
11716
11717 if (NewTA) {
11718 ParsedTargetAttr OldParsed =
11720 OldTA->getFeaturesStr());
11721 llvm::sort(OldParsed.Features);
11722 ParsedTargetAttr NewParsed =
11724 NewTA->getFeaturesStr());
11725 // Sort order doesn't matter, it just needs to be consistent.
11726 llvm::sort(NewParsed.Features);
11727 if (OldParsed == NewParsed) {
11728 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11729 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11730 NewFD->setInvalidDecl();
11731 return true;
11732 }
11733 }
11734
11735 for (const auto *FD : OldFD->redecls()) {
11736 const auto *CurTA = FD->getAttr<TargetAttr>();
11737 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11738 // We allow forward declarations before ANY multiversioning attributes, but
11739 // nothing after the fact.
11741 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11742 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11743 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11744 << (NewTA ? 0 : 2);
11745 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11746 NewFD->setInvalidDecl();
11747 return true;
11748 }
11749 }
11750
11751 OldFD->setIsMultiVersion();
11752 NewFD->setIsMultiVersion();
11753 Redeclaration = false;
11754 OldDecl = nullptr;
11755 Previous.clear();
11756 return false;
11757}
11758
11760 MultiVersionKind OldKind = Old->getMultiVersionKind();
11761 MultiVersionKind NewKind = New->getMultiVersionKind();
11762
11763 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11764 NewKind == MultiVersionKind::None)
11765 return true;
11766
11767 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11768 switch (OldKind) {
11770 return NewKind == MultiVersionKind::TargetClones;
11772 return NewKind == MultiVersionKind::TargetVersion;
11773 default:
11774 return false;
11775 }
11776 } else {
11777 switch (OldKind) {
11779 return NewKind == MultiVersionKind::CPUSpecific;
11781 return NewKind == MultiVersionKind::CPUDispatch;
11782 default:
11783 return false;
11784 }
11785 }
11786}
11787
11788/// Check the validity of a new function declaration being added to an existing
11789/// multiversioned declaration collection.
11791 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11792 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11793 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11795
11796 // Disallow mixing of multiversioning types.
11797 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11798 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11799 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11800 NewFD->setInvalidDecl();
11801 return true;
11802 }
11803
11804 // Add the default target_version attribute if it's missing.
11805 patchDefaultTargetVersion(OldFD, NewFD);
11806 patchDefaultTargetVersion(NewFD, OldFD);
11807
11808 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11809 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11810 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11811 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11812
11813 ParsedTargetAttr NewParsed;
11814 if (NewTA) {
11816 NewTA->getFeaturesStr());
11817 llvm::sort(NewParsed.Features);
11818 }
11820 if (NewTVA) {
11821 NewTVA->getFeatures(NewFeats);
11822 llvm::sort(NewFeats);
11823 }
11824
11825 bool UseMemberUsingDeclRules =
11826 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11827
11828 bool MayNeedOverloadableChecks =
11830
11831 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11832 // of a previous member of the MultiVersion set.
11833 for (NamedDecl *ND : Previous) {
11834 FunctionDecl *CurFD = ND->getAsFunction();
11835 if (!CurFD || CurFD->isInvalidDecl())
11836 continue;
11837 if (MayNeedOverloadableChecks &&
11838 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11839 continue;
11840
11841 switch (NewMVKind) {
11843 assert(OldMVKind == MultiVersionKind::TargetClones &&
11844 "Only target_clones can be omitted in subsequent declarations");
11845 break;
11847 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11848 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11849 NewFD->setIsMultiVersion();
11850 Redeclaration = true;
11851 OldDecl = ND;
11852 return false;
11853 }
11854
11855 ParsedTargetAttr CurParsed =
11857 CurTA->getFeaturesStr());
11858 llvm::sort(CurParsed.Features);
11859 if (CurParsed == NewParsed) {
11860 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11861 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11862 NewFD->setInvalidDecl();
11863 return true;
11864 }
11865 break;
11866 }
11868 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11869 if (CurTVA->getName() == NewTVA->getName()) {
11870 NewFD->setIsMultiVersion();
11871 Redeclaration = true;
11872 OldDecl = ND;
11873 return false;
11874 }
11876 CurTVA->getFeatures(CurFeats);
11877 llvm::sort(CurFeats);
11878
11879 if (CurFeats == NewFeats) {
11880 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11881 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11882 NewFD->setInvalidDecl();
11883 return true;
11884 }
11885 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11886 // Default
11887 if (NewFeats.empty())
11888 break;
11889
11890 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11892 CurClones->getFeatures(CurFeats, I);
11893 llvm::sort(CurFeats);
11894
11895 if (CurFeats == NewFeats) {
11896 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11897 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11898 NewFD->setInvalidDecl();
11899 return true;
11900 }
11901 }
11902 }
11903 break;
11904 }
11906 assert(NewClones && "MultiVersionKind does not match attribute type");
11907 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11908 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11909 !std::equal(CurClones->featuresStrs_begin(),
11910 CurClones->featuresStrs_end(),
11911 NewClones->featuresStrs_begin())) {
11912 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11913 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11914 NewFD->setInvalidDecl();
11915 return true;
11916 }
11917 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11919 CurTVA->getFeatures(CurFeats);
11920 llvm::sort(CurFeats);
11921
11922 // Default
11923 if (CurFeats.empty())
11924 break;
11925
11926 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11927 NewFeats.clear();
11928 NewClones->getFeatures(NewFeats, I);
11929 llvm::sort(NewFeats);
11930
11931 if (CurFeats == NewFeats) {
11932 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11933 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11934 NewFD->setInvalidDecl();
11935 return true;
11936 }
11937 }
11938 break;
11939 }
11940 Redeclaration = true;
11941 OldDecl = CurFD;
11942 NewFD->setIsMultiVersion();
11943 return false;
11944 }
11947 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11948 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11949 // Handle CPUDispatch/CPUSpecific versions.
11950 // Only 1 CPUDispatch function is allowed, this will make it go through
11951 // the redeclaration errors.
11952 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11953 CurFD->hasAttr<CPUDispatchAttr>()) {
11954 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11955 std::equal(
11956 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11957 NewCPUDisp->cpus_begin(),
11958 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11959 return Cur->getName() == New->getName();
11960 })) {
11961 NewFD->setIsMultiVersion();
11962 Redeclaration = true;
11963 OldDecl = ND;
11964 return false;
11965 }
11966
11967 // If the declarations don't match, this is an error condition.
11968 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11969 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11970 NewFD->setInvalidDecl();
11971 return true;
11972 }
11973 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11974 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11975 std::equal(
11976 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11977 NewCPUSpec->cpus_begin(),
11978 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11979 return Cur->getName() == New->getName();
11980 })) {
11981 NewFD->setIsMultiVersion();
11982 Redeclaration = true;
11983 OldDecl = ND;
11984 return false;
11985 }
11986
11987 // Only 1 version of CPUSpecific is allowed for each CPU.
11988 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11989 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11990 if (CurII == NewII) {
11991 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11992 << NewII;
11993 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11994 NewFD->setInvalidDecl();
11995 return true;
11996 }
11997 }
11998 }
11999 }
12000 break;
12001 }
12002 }
12003 }
12004
12005 // Redeclarations of a target_clones function may omit the attribute, in which
12006 // case it will be inherited during declaration merging.
12007 if (NewMVKind == MultiVersionKind::None &&
12008 OldMVKind == MultiVersionKind::TargetClones) {
12009 NewFD->setIsMultiVersion();
12010 Redeclaration = true;
12011 OldDecl = OldFD;
12012 return false;
12013 }
12014
12015 // Else, this is simply a non-redecl case. Checking the 'value' is only
12016 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12017 // handled in the attribute adding step.
12018 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
12019 NewFD->setInvalidDecl();
12020 return true;
12021 }
12022
12023 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12024 !OldFD->isMultiVersion(), NewMVKind)) {
12025 NewFD->setInvalidDecl();
12026 return true;
12027 }
12028
12029 // Permit forward declarations in the case where these two are compatible.
12030 if (!OldFD->isMultiVersion()) {
12031 OldFD->setIsMultiVersion();
12032 NewFD->setIsMultiVersion();
12033 Redeclaration = true;
12034 OldDecl = OldFD;
12035 return false;
12036 }
12037
12038 NewFD->setIsMultiVersion();
12039 Redeclaration = false;
12040 OldDecl = nullptr;
12041 Previous.clear();
12042 return false;
12043}
12044
12045/// Check the validity of a mulitversion function declaration.
12046/// Also sets the multiversion'ness' of the function itself.
12047///
12048/// This sets NewFD->isInvalidDecl() to true if there was an error.
12049///
12050/// Returns true if there was an error, false otherwise.
12052 bool &Redeclaration, NamedDecl *&OldDecl,
12054 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12055
12056 // Check if FMV is disabled.
12057 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12058 return false;
12059
12060 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12061 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12062 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12063 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12064 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12065 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12066
12067 // Main isn't allowed to become a multiversion function, however it IS
12068 // permitted to have 'main' be marked with the 'target' optimization hint,
12069 // for 'target_version' only default is allowed.
12070 if (NewFD->isMain()) {
12071 if (MVKind != MultiVersionKind::None &&
12072 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12073 !(MVKind == MultiVersionKind::TargetVersion &&
12074 NewTVA->isDefaultVersion())) {
12075 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12076 NewFD->setInvalidDecl();
12077 return true;
12078 }
12079 return false;
12080 }
12081
12082 // Target attribute on AArch64 is not used for multiversioning
12083 if (NewTA && TI.getTriple().isAArch64())
12084 return false;
12085
12086 // Target attribute on RISCV is not used for multiversioning
12087 if (NewTA && TI.getTriple().isRISCV())
12088 return false;
12089
12090 if (!OldDecl || !OldDecl->getAsFunction() ||
12091 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12092 NewFD->getDeclContext()->getRedeclContext())) {
12093 // If there's no previous declaration, AND this isn't attempting to cause
12094 // multiversioning, this isn't an error condition.
12095 if (MVKind == MultiVersionKind::None)
12096 return false;
12097 return CheckMultiVersionFirstFunction(S, NewFD);
12098 }
12099
12100 FunctionDecl *OldFD = OldDecl->getAsFunction();
12101
12102 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12103 return false;
12104
12105 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12106 // for target_clones and target_version.
12107 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12110 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12112 NewFD->setInvalidDecl();
12113 return true;
12114 }
12115
12116 if (!OldFD->isMultiVersion()) {
12117 switch (MVKind) {
12121 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12123 if (OldFD->isUsed(false)) {
12124 NewFD->setInvalidDecl();
12125 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12126 }
12127 OldFD->setIsMultiVersion();
12128 break;
12129
12133 break;
12134 }
12135 }
12136
12137 // At this point, we have a multiversion function decl (in OldFD) AND an
12138 // appropriate attribute in the current function decl (unless it's allowed to
12139 // omit the attribute). Resolve that these are still compatible with previous
12140 // declarations.
12141 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12142 NewCPUSpec, NewClones, Redeclaration,
12143 OldDecl, Previous);
12144}
12145
12147 bool IsPure = NewFD->hasAttr<PureAttr>();
12148 bool IsConst = NewFD->hasAttr<ConstAttr>();
12149
12150 // If there are no pure or const attributes, there's nothing to check.
12151 if (!IsPure && !IsConst)
12152 return;
12153
12154 // If the function is marked both pure and const, we retain the const
12155 // attribute because it makes stronger guarantees than the pure attribute, and
12156 // we drop the pure attribute explicitly to prevent later confusion about
12157 // semantics.
12158 if (IsPure && IsConst) {
12159 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12160 NewFD->dropAttrs<PureAttr>();
12161 }
12162
12163 // Constructors and destructors are functions which return void, so are
12164 // handled here as well.
12165 if (NewFD->getReturnType()->isVoidType()) {
12166 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12167 << IsConst;
12168 NewFD->dropAttrs<PureAttr, ConstAttr>();
12169 }
12170}
12171
12174 bool IsMemberSpecialization,
12175 bool DeclIsDefn) {
12176 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12177 "Variably modified return types are not handled here");
12178
12179 // Determine whether the type of this function should be merged with
12180 // a previous visible declaration. This never happens for functions in C++,
12181 // and always happens in C if the previous declaration was visible.
12182 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12183 !Previous.isShadowed();
12184
12185 bool Redeclaration = false;
12186 NamedDecl *OldDecl = nullptr;
12187 bool MayNeedOverloadableChecks = false;
12188
12190 // Merge or overload the declaration with an existing declaration of
12191 // the same name, if appropriate.
12192 if (!Previous.empty()) {
12193 // Determine whether NewFD is an overload of PrevDecl or
12194 // a declaration that requires merging. If it's an overload,
12195 // there's no more work to do here; we'll just add the new
12196 // function to the scope.
12198 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12199 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12200 Redeclaration = true;
12201 OldDecl = Candidate;
12202 }
12203 } else {
12204 MayNeedOverloadableChecks = true;
12205 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12206 /*NewIsUsingDecl*/ false)) {
12208 Redeclaration = true;
12209 break;
12210
12212 Redeclaration = true;
12213 break;
12214
12216 Redeclaration = false;
12217 break;
12218 }
12219 }
12220 }
12221
12222 // Check for a previous extern "C" declaration with this name.
12223 if (!Redeclaration &&
12225 if (!Previous.empty()) {
12226 // This is an extern "C" declaration with the same name as a previous
12227 // declaration, and thus redeclares that entity...
12228 Redeclaration = true;
12229 OldDecl = Previous.getFoundDecl();
12230 MergeTypeWithPrevious = false;
12231
12232 // ... except in the presence of __attribute__((overloadable)).
12233 if (OldDecl->hasAttr<OverloadableAttr>() ||
12234 NewFD->hasAttr<OverloadableAttr>()) {
12235 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12236 MayNeedOverloadableChecks = true;
12237 Redeclaration = false;
12238 OldDecl = nullptr;
12239 }
12240 }
12241 }
12242 }
12243
12244 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12245 return Redeclaration;
12246
12247 // PPC MMA non-pointer types are not allowed as function return types.
12248 if (Context.getTargetInfo().getTriple().isPPC64() &&
12249 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12250 NewFD->setInvalidDecl();
12251 }
12252
12253 CheckConstPureAttributesUsage(*this, NewFD);
12254
12255 // C++ [dcl.spec.auto.general]p12:
12256 // Return type deduction for a templated function with a placeholder in its
12257 // declared type occurs when the definition is instantiated even if the
12258 // function body contains a return statement with a non-type-dependent
12259 // operand.
12260 //
12261 // C++ [temp.dep.expr]p3:
12262 // An id-expression is type-dependent if it is a template-id that is not a
12263 // concept-id and is dependent; or if its terminal name is:
12264 // - [...]
12265 // - associated by name lookup with one or more declarations of member
12266 // functions of a class that is the current instantiation declared with a
12267 // return type that contains a placeholder type,
12268 // - [...]
12269 //
12270 // If this is a templated function with a placeholder in its return type,
12271 // make the placeholder type dependent since it won't be deduced until the
12272 // definition is instantiated. We do this here because it needs to happen
12273 // for implicitly instantiated member functions/member function templates.
12274 if (getLangOpts().CPlusPlus14 &&
12275 (NewFD->isDependentContext() &&
12276 NewFD->getReturnType()->isUndeducedType())) {
12277 const FunctionProtoType *FPT =
12278 NewFD->getType()->castAs<FunctionProtoType>();
12279 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12280 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12281 FPT->getExtProtoInfo()));
12282 }
12283
12284 // C++11 [dcl.constexpr]p8:
12285 // A constexpr specifier for a non-static member function that is not
12286 // a constructor declares that member function to be const.
12287 //
12288 // This needs to be delayed until we know whether this is an out-of-line
12289 // definition of a static member function.
12290 //
12291 // This rule is not present in C++1y, so we produce a backwards
12292 // compatibility warning whenever it happens in C++11.
12293 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12294 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12295 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12297 CXXMethodDecl *OldMD = nullptr;
12298 if (OldDecl)
12299 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12300 if (!OldMD || !OldMD->isStatic()) {
12301 const FunctionProtoType *FPT =
12304 EPI.TypeQuals.addConst();
12305 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12306 FPT->getParamTypes(), EPI));
12307
12308 // Warn that we did this, if we're not performing template instantiation.
12309 // In that case, we'll have warned already when the template was defined.
12310 if (!inTemplateInstantiation()) {
12311 SourceLocation AddConstLoc;
12314 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12315
12316 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12317 << FixItHint::CreateInsertion(AddConstLoc, " const");
12318 }
12319 }
12320 }
12321
12322 if (Redeclaration) {
12323 // NewFD and OldDecl represent declarations that need to be
12324 // merged.
12325 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12326 DeclIsDefn)) {
12327 NewFD->setInvalidDecl();
12328 return Redeclaration;
12329 }
12330
12331 Previous.clear();
12332 Previous.addDecl(OldDecl);
12333
12334 if (FunctionTemplateDecl *OldTemplateDecl =
12335 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12336 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12337 FunctionTemplateDecl *NewTemplateDecl
12339 assert(NewTemplateDecl && "Template/non-template mismatch");
12340
12341 // The call to MergeFunctionDecl above may have created some state in
12342 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12343 // can add it as a redeclaration.
12344 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12345
12346 NewFD->setPreviousDeclaration(OldFD);
12347 if (NewFD->isCXXClassMember()) {
12348 NewFD->setAccess(OldTemplateDecl->getAccess());
12349 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12350 }
12351
12352 // If this is an explicit specialization of a member that is a function
12353 // template, mark it as a member specialization.
12354 if (IsMemberSpecialization &&
12355 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12356 NewTemplateDecl->setMemberSpecialization();
12357 assert(OldTemplateDecl->isMemberSpecialization());
12358 // Explicit specializations of a member template do not inherit deleted
12359 // status from the parent member template that they are specializing.
12360 if (OldFD->isDeleted()) {
12361 // FIXME: This assert will not hold in the presence of modules.
12362 assert(OldFD->getCanonicalDecl() == OldFD);
12363 // FIXME: We need an update record for this AST mutation.
12364 OldFD->setDeletedAsWritten(false);
12365 }
12366 }
12367
12368 } else {
12369 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12370 auto *OldFD = cast<FunctionDecl>(OldDecl);
12371 // This needs to happen first so that 'inline' propagates.
12372 NewFD->setPreviousDeclaration(OldFD);
12373 if (NewFD->isCXXClassMember())
12374 NewFD->setAccess(OldFD->getAccess());
12375 }
12376 }
12377 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12378 !NewFD->getAttr<OverloadableAttr>()) {
12379 assert((Previous.empty() ||
12380 llvm::any_of(Previous,
12381 [](const NamedDecl *ND) {
12382 return ND->hasAttr<OverloadableAttr>();
12383 })) &&
12384 "Non-redecls shouldn't happen without overloadable present");
12385
12386 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12387 const auto *FD = dyn_cast<FunctionDecl>(ND);
12388 return FD && !FD->hasAttr<OverloadableAttr>();
12389 });
12390
12391 if (OtherUnmarkedIter != Previous.end()) {
12392 Diag(NewFD->getLocation(),
12393 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12394 Diag((*OtherUnmarkedIter)->getLocation(),
12395 diag::note_attribute_overloadable_prev_overload)
12396 << false;
12397
12398 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12399 }
12400 }
12401
12402 if (LangOpts.OpenMP)
12404
12405 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12407
12408 if (NewFD->hasAttr<SYCLExternalAttr>())
12410
12411 // Semantic checking for this function declaration (in isolation).
12412
12413 if (getLangOpts().CPlusPlus) {
12414 // C++-specific checks.
12415 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12417 } else if (CXXDestructorDecl *Destructor =
12418 dyn_cast<CXXDestructorDecl>(NewFD)) {
12419 // We check here for invalid destructor names.
12420 // If we have a friend destructor declaration that is dependent, we can't
12421 // diagnose right away because cases like this are still valid:
12422 // template <class T> struct A { friend T::X::~Y(); };
12423 // struct B { struct Y { ~Y(); }; using X = Y; };
12424 // template struct A<B>;
12426 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12427 CanQualType ClassType =
12428 Context.getCanonicalTagType(Destructor->getParent());
12429
12430 DeclarationName Name =
12431 Context.DeclarationNames.getCXXDestructorName(ClassType);
12432 if (NewFD->getDeclName() != Name) {
12433 Diag(NewFD->getLocation(), diag::err_destructor_name);
12434 NewFD->setInvalidDecl();
12435 return Redeclaration;
12436 }
12437 }
12438 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12439 if (auto *TD = Guide->getDescribedFunctionTemplate())
12441
12442 // A deduction guide is not on the list of entities that can be
12443 // explicitly specialized.
12444 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12445 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12446 << /*explicit specialization*/ 1;
12447 }
12448
12449 // Find any virtual functions that this function overrides.
12450 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12451 if (!Method->isFunctionTemplateSpecialization() &&
12452 !Method->getDescribedFunctionTemplate() &&
12453 Method->isCanonicalDecl()) {
12454 AddOverriddenMethods(Method->getParent(), Method);
12455 }
12456 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12457 // C++2a [class.virtual]p6
12458 // A virtual method shall not have a requires-clause.
12460 diag::err_constrained_virtual_method);
12461
12462 if (Method->isStatic())
12464 }
12465
12466 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12467 ActOnConversionDeclarator(Conversion);
12468
12469 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12470 if (NewFD->isOverloadedOperator() &&
12472 NewFD->setInvalidDecl();
12473 return Redeclaration;
12474 }
12475
12476 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12477 if (NewFD->getLiteralIdentifier() &&
12479 NewFD->setInvalidDecl();
12480 return Redeclaration;
12481 }
12482
12483 // In C++, check default arguments now that we have merged decls. Unless
12484 // the lexical context is the class, because in this case this is done
12485 // during delayed parsing anyway.
12486 if (!CurContext->isRecord())
12488
12489 // If this function is declared as being extern "C", then check to see if
12490 // the function returns a UDT (class, struct, or union type) that is not C
12491 // compatible, and if it does, warn the user.
12492 // But, issue any diagnostic on the first declaration only.
12493 if (Previous.empty() && NewFD->isExternC()) {
12494 QualType R = NewFD->getReturnType();
12495 if (R->isIncompleteType() && !R->isVoidType())
12496 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12497 << NewFD << R;
12498 else if (!R.isPODType(Context) && !R->isVoidType() &&
12500 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12501 }
12502
12503 // C++1z [dcl.fct]p6:
12504 // [...] whether the function has a non-throwing exception-specification
12505 // [is] part of the function type
12506 //
12507 // This results in an ABI break between C++14 and C++17 for functions whose
12508 // declared type includes an exception-specification in a parameter or
12509 // return type. (Exception specifications on the function itself are OK in
12510 // most cases, and exception specifications are not permitted in most other
12511 // contexts where they could make it into a mangling.)
12512 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12513 auto HasNoexcept = [&](QualType T) -> bool {
12514 // Strip off declarator chunks that could be between us and a function
12515 // type. We don't need to look far, exception specifications are very
12516 // restricted prior to C++17.
12517 if (auto *RT = T->getAs<ReferenceType>())
12518 T = RT->getPointeeType();
12519 else if (T->isAnyPointerType())
12520 T = T->getPointeeType();
12521 else if (auto *MPT = T->getAs<MemberPointerType>())
12522 T = MPT->getPointeeType();
12523 if (auto *FPT = T->getAs<FunctionProtoType>())
12524 if (FPT->isNothrow())
12525 return true;
12526 return false;
12527 };
12528
12529 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12530 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12531 for (QualType T : FPT->param_types())
12532 AnyNoexcept |= HasNoexcept(T);
12533 if (AnyNoexcept)
12534 Diag(NewFD->getLocation(),
12535 diag::warn_cxx17_compat_exception_spec_in_signature)
12536 << NewFD;
12537 }
12538
12539 if (!Redeclaration && LangOpts.CUDA) {
12540 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12541 for (auto *Parm : NewFD->parameters()) {
12542 if (!Parm->getType()->isDependentType() &&
12543 Parm->hasAttr<CUDAGridConstantAttr>() &&
12544 !(IsKernel && Parm->getType().isConstQualified()))
12545 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12546 diag::err_cuda_grid_constant_not_allowed);
12547 }
12549 }
12550 }
12551
12552 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12554
12555 return Redeclaration;
12556}
12557
12559 // [basic.start.main]p3
12560 // The main function shall not be declared with C linkage-specification.
12561 if (FD->isExternCContext())
12562 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12563
12564 // C++11 [basic.start.main]p3:
12565 // A program that [...] declares main to be inline, static or
12566 // constexpr is ill-formed.
12567 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12568 // appear in a declaration of main.
12569 // static main is not an error under C99, but we should warn about it.
12570 // We accept _Noreturn main as an extension.
12571 if (FD->getStorageClass() == SC_Static)
12573 ? diag::err_static_main : diag::warn_static_main)
12575 if (FD->isInlineSpecified())
12576 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12578 if (DS.isNoreturnSpecified()) {
12579 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12580 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12581 Diag(NoreturnLoc, diag::ext_noreturn_main);
12582 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12583 << FixItHint::CreateRemoval(NoreturnRange);
12584 }
12585 if (FD->isConstexpr()) {
12586 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12587 << FD->isConsteval()
12590 }
12591
12592 if (getLangOpts().OpenCL) {
12593 Diag(FD->getLocation(), diag::err_opencl_no_main)
12594 << FD->hasAttr<DeviceKernelAttr>();
12595 FD->setInvalidDecl();
12596 return;
12597 }
12598
12599 if (FD->hasAttr<SYCLExternalAttr>()) {
12600 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12601 << FD->getAttr<SYCLExternalAttr>();
12602 FD->setInvalidDecl();
12603 return;
12604 }
12605
12606 // Functions named main in hlsl are default entries, but don't have specific
12607 // signatures they are required to conform to.
12608 if (getLangOpts().HLSL)
12609 return;
12610
12611 QualType T = FD->getType();
12612 assert(T->isFunctionType() && "function decl is not of function type");
12613 const FunctionType* FT = T->castAs<FunctionType>();
12614
12615 // Set default calling convention for main()
12616 if (FT->getCallConv() != CC_C) {
12617 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12618 FD->setType(QualType(FT, 0));
12619 T = Context.getCanonicalType(FD->getType());
12620 }
12621
12623 // In C with GNU extensions we allow main() to have non-integer return
12624 // type, but we should warn about the extension, and we disable the
12625 // implicit-return-zero rule.
12626
12627 // GCC in C mode accepts qualified 'int'.
12628 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12629 FD->setHasImplicitReturnZero(true);
12630 else {
12631 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12632 SourceRange RTRange = FD->getReturnTypeSourceRange();
12633 if (RTRange.isValid())
12634 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12635 << FixItHint::CreateReplacement(RTRange, "int");
12636 }
12637 } else {
12638 // In C and C++, main magically returns 0 if you fall off the end;
12639 // set the flag which tells us that.
12640 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12641
12642 // All the standards say that main() should return 'int'.
12643 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12644 FD->setHasImplicitReturnZero(true);
12645 else {
12646 // Otherwise, this is just a flat-out error.
12647 SourceRange RTRange = FD->getReturnTypeSourceRange();
12648 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12649 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12650 : FixItHint());
12651 FD->setInvalidDecl(true);
12652 }
12653
12654 // [basic.start.main]p3:
12655 // A program that declares a function main that belongs to the global scope
12656 // and is attached to a named module is ill-formed.
12657 if (FD->isInNamedModule()) {
12658 const SourceLocation start = FD->getTypeSpecStartLoc();
12659 Diag(start, diag::warn_main_in_named_module)
12660 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12661 }
12662 }
12663
12664 // Treat protoless main() as nullary.
12665 if (isa<FunctionNoProtoType>(FT)) return;
12666
12668 unsigned nparams = FTP->getNumParams();
12669 assert(FD->getNumParams() == nparams);
12670
12671 bool HasExtraParameters = (nparams > 3);
12672
12673 if (FTP->isVariadic()) {
12674 Diag(FD->getLocation(), diag::ext_variadic_main);
12675 // FIXME: if we had information about the location of the ellipsis, we
12676 // could add a FixIt hint to remove it as a parameter.
12677 }
12678
12679 // Darwin passes an undocumented fourth argument of type char**. If
12680 // other platforms start sprouting these, the logic below will start
12681 // getting shifty.
12682 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12683 HasExtraParameters = false;
12684
12685 if (HasExtraParameters) {
12686 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12687 FD->setInvalidDecl(true);
12688 nparams = 3;
12689 }
12690
12691 // FIXME: a lot of the following diagnostics would be improved
12692 // if we had some location information about types.
12693
12694 QualType CharPP =
12695 Context.getPointerType(Context.getPointerType(Context.CharTy));
12696 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12697
12698 for (unsigned i = 0; i < nparams; ++i) {
12699 QualType AT = FTP->getParamType(i);
12700
12701 bool mismatch = true;
12702
12703 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12704 mismatch = false;
12705 else if (Expected[i] == CharPP) {
12706 // As an extension, the following forms are okay:
12707 // char const **
12708 // char const * const *
12709 // char * const *
12710
12712 const PointerType* PT;
12713 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12714 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12715 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12716 Context.CharTy)) {
12717 qs.removeConst();
12718 mismatch = !qs.empty();
12719 }
12720 }
12721
12722 if (mismatch) {
12723 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12724 // TODO: suggest replacing given type with expected type
12725 FD->setInvalidDecl(true);
12726 }
12727 }
12728
12729 if (nparams == 1 && !FD->isInvalidDecl()) {
12730 Diag(FD->getLocation(), diag::warn_main_one_arg);
12731 }
12732
12733 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12734 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12735 FD->setInvalidDecl();
12736 }
12737}
12738
12739static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12740
12741 // Default calling convention for main and wmain is __cdecl
12742 if (FD->getName() == "main" || FD->getName() == "wmain")
12743 return false;
12744
12745 // Default calling convention for MinGW and Cygwin is __cdecl
12746 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12747 if (T.isOSCygMing())
12748 return false;
12749
12750 // Default calling convention for WinMain, wWinMain and DllMain
12751 // is __stdcall on 32 bit Windows
12752 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12753 return true;
12754
12755 return false;
12756}
12757
12759 QualType T = FD->getType();
12760 assert(T->isFunctionType() && "function decl is not of function type");
12761 const FunctionType *FT = T->castAs<FunctionType>();
12762
12763 // Set an implicit return of 'zero' if the function can return some integral,
12764 // enumeration, pointer or nullptr type.
12768 // DllMain is exempt because a return value of zero means it failed.
12769 if (FD->getName() != "DllMain")
12770 FD->setHasImplicitReturnZero(true);
12771
12772 // Explicitly specified calling conventions are applied to MSVC entry points
12773 if (!hasExplicitCallingConv(T)) {
12774 if (isDefaultStdCall(FD, *this)) {
12775 if (FT->getCallConv() != CC_X86StdCall) {
12776 FT = Context.adjustFunctionType(
12778 FD->setType(QualType(FT, 0));
12779 }
12780 } else if (FT->getCallConv() != CC_C) {
12781 FT = Context.adjustFunctionType(FT,
12783 FD->setType(QualType(FT, 0));
12784 }
12785 }
12786
12787 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12788 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12789 FD->setInvalidDecl();
12790 }
12791}
12792
12794 // FIXME: Need strict checking. In C89, we need to check for
12795 // any assignment, increment, decrement, function-calls, or
12796 // commas outside of a sizeof. In C99, it's the same list,
12797 // except that the aforementioned are allowed in unevaluated
12798 // expressions. Everything else falls under the
12799 // "may accept other forms of constant expressions" exception.
12800 //
12801 // Regular C++ code will not end up here (exceptions: language extensions,
12802 // OpenCL C++ etc), so the constant expression rules there don't matter.
12803 if (Init->isValueDependent()) {
12804 assert(Init->containsErrors() &&
12805 "Dependent code should only occur in error-recovery path.");
12806 return true;
12807 }
12808 const Expr *Culprit;
12809 if (Init->isConstantInitializer(Context, false, &Culprit))
12810 return false;
12811 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12812 return true;
12813}
12814
12815namespace {
12816 // Visits an initialization expression to see if OrigDecl is evaluated in
12817 // its own initialization and throws a warning if it does.
12818 class SelfReferenceChecker
12819 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12820 Sema &S;
12821 Decl *OrigDecl;
12822 bool isRecordType;
12823 bool isPODType;
12824 bool isReferenceType;
12825 bool isInCXXOperatorCall;
12826
12827 bool isInitList;
12828 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12829
12830 public:
12832
12833 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12834 S(S), OrigDecl(OrigDecl) {
12835 isPODType = false;
12836 isRecordType = false;
12837 isReferenceType = false;
12838 isInCXXOperatorCall = false;
12839 isInitList = false;
12840 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12841 isPODType = VD->getType().isPODType(S.Context);
12842 isRecordType = VD->getType()->isRecordType();
12843 isReferenceType = VD->getType()->isReferenceType();
12844 }
12845 }
12846
12847 // For most expressions, just call the visitor. For initializer lists,
12848 // track the index of the field being initialized since fields are
12849 // initialized in order allowing use of previously initialized fields.
12850 void CheckExpr(Expr *E) {
12851 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12852 if (!InitList) {
12853 Visit(E);
12854 return;
12855 }
12856
12857 // Track and increment the index here.
12858 isInitList = true;
12859 InitFieldIndex.push_back(0);
12860 for (auto *Child : InitList->children()) {
12861 CheckExpr(cast<Expr>(Child));
12862 ++InitFieldIndex.back();
12863 }
12864 InitFieldIndex.pop_back();
12865 }
12866
12867 // Returns true if MemberExpr is checked and no further checking is needed.
12868 // Returns false if additional checking is required.
12869 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12870 llvm::SmallVector<FieldDecl*, 4> Fields;
12871 Expr *Base = E;
12872 bool ReferenceField = false;
12873
12874 // Get the field members used.
12875 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12876 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12877 if (!FD)
12878 return false;
12879 Fields.push_back(FD);
12880 if (FD->getType()->isReferenceType())
12881 ReferenceField = true;
12882 Base = ME->getBase()->IgnoreParenImpCasts();
12883 }
12884
12885 // Keep checking only if the base Decl is the same.
12886 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12887 if (!DRE || DRE->getDecl() != OrigDecl)
12888 return false;
12889
12890 // A reference field can be bound to an unininitialized field.
12891 if (CheckReference && !ReferenceField)
12892 return true;
12893
12894 // Convert FieldDecls to their index number.
12895 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12896 for (const FieldDecl *I : llvm::reverse(Fields))
12897 UsedFieldIndex.push_back(I->getFieldIndex());
12898
12899 // See if a warning is needed by checking the first difference in index
12900 // numbers. If field being used has index less than the field being
12901 // initialized, then the use is safe.
12902 for (auto UsedIter = UsedFieldIndex.begin(),
12903 UsedEnd = UsedFieldIndex.end(),
12904 OrigIter = InitFieldIndex.begin(),
12905 OrigEnd = InitFieldIndex.end();
12906 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12907 if (*UsedIter < *OrigIter)
12908 return true;
12909 if (*UsedIter > *OrigIter)
12910 break;
12911 }
12912
12913 // TODO: Add a different warning which will print the field names.
12914 HandleDeclRefExpr(DRE);
12915 return true;
12916 }
12917
12918 // For most expressions, the cast is directly above the DeclRefExpr.
12919 // For conditional operators, the cast can be outside the conditional
12920 // operator if both expressions are DeclRefExpr's.
12921 void HandleValue(Expr *E) {
12922 E = E->IgnoreParens();
12923 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12924 HandleDeclRefExpr(DRE);
12925 return;
12926 }
12927
12928 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12929 Visit(CO->getCond());
12930 HandleValue(CO->getTrueExpr());
12931 HandleValue(CO->getFalseExpr());
12932 return;
12933 }
12934
12935 if (BinaryConditionalOperator *BCO =
12936 dyn_cast<BinaryConditionalOperator>(E)) {
12937 Visit(BCO->getCond());
12938 HandleValue(BCO->getFalseExpr());
12939 return;
12940 }
12941
12942 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12943 if (Expr *SE = OVE->getSourceExpr())
12944 HandleValue(SE);
12945 return;
12946 }
12947
12948 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12949 if (BO->getOpcode() == BO_Comma) {
12950 Visit(BO->getLHS());
12951 HandleValue(BO->getRHS());
12952 return;
12953 }
12954 }
12955
12956 if (isa<MemberExpr>(E)) {
12957 if (isInitList) {
12958 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12959 false /*CheckReference*/))
12960 return;
12961 }
12962
12963 Expr *Base = E->IgnoreParenImpCasts();
12964 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12965 // Check for static member variables and don't warn on them.
12966 if (!isa<FieldDecl>(ME->getMemberDecl()))
12967 return;
12968 Base = ME->getBase()->IgnoreParenImpCasts();
12969 }
12970 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12971 HandleDeclRefExpr(DRE);
12972 return;
12973 }
12974
12975 Visit(E);
12976 }
12977
12978 // Reference types not handled in HandleValue are handled here since all
12979 // uses of references are bad, not just r-value uses.
12980 void VisitDeclRefExpr(DeclRefExpr *E) {
12981 if (isReferenceType)
12982 HandleDeclRefExpr(E);
12983 }
12984
12985 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12986 if (E->getCastKind() == CK_LValueToRValue) {
12987 HandleValue(E->getSubExpr());
12988 return;
12989 }
12990
12991 Inherited::VisitImplicitCastExpr(E);
12992 }
12993
12994 void VisitMemberExpr(MemberExpr *E) {
12995 if (isInitList) {
12996 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12997 return;
12998 }
12999
13000 // Don't warn on arrays since they can be treated as pointers.
13001 if (E->getType()->canDecayToPointerType()) return;
13002
13003 // Warn when a non-static method call is followed by non-static member
13004 // field accesses, which is followed by a DeclRefExpr.
13005 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
13006 bool Warn = (MD && !MD->isStatic());
13007 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13008 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13009 if (!isa<FieldDecl>(ME->getMemberDecl()))
13010 Warn = false;
13011 Base = ME->getBase()->IgnoreParenImpCasts();
13012 }
13013
13014 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
13015 if (Warn)
13016 HandleDeclRefExpr(DRE);
13017 return;
13018 }
13019
13020 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13021 // Visit that expression.
13022 Visit(Base);
13023 }
13024
13025 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13026 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13027 Expr *Callee = E->getCallee();
13028
13029 if (isa<UnresolvedLookupExpr>(Callee))
13030 return Inherited::VisitCXXOperatorCallExpr(E);
13031
13032 Visit(Callee);
13033 for (auto Arg: E->arguments())
13034 HandleValue(Arg->IgnoreParenImpCasts());
13035 }
13036
13037 void VisitLambdaExpr(LambdaExpr *E) {
13038 if (!isInCXXOperatorCall) {
13039 Inherited::VisitLambdaExpr(E);
13040 return;
13041 }
13042
13043 for (Expr *Init : E->capture_inits())
13044 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13045 HandleDeclRefExpr(DRE);
13046 else if (Init)
13047 Visit(Init);
13048 }
13049
13050 void VisitUnaryOperator(UnaryOperator *E) {
13051 // For POD record types, addresses of its own members are well-defined.
13052 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13054 if (!isPODType)
13055 HandleValue(E->getSubExpr());
13056 return;
13057 }
13058
13059 if (E->isIncrementDecrementOp()) {
13060 HandleValue(E->getSubExpr());
13061 return;
13062 }
13063
13064 Inherited::VisitUnaryOperator(E);
13065 }
13066
13067 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13068
13069 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13070 if (E->getConstructor()->isCopyConstructor()) {
13071 Expr *ArgExpr = E->getArg(0);
13072 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13073 if (ILE->getNumInits() == 1)
13074 ArgExpr = ILE->getInit(0);
13075 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13076 if (ICE->getCastKind() == CK_NoOp)
13077 ArgExpr = ICE->getSubExpr();
13078 HandleValue(ArgExpr);
13079 return;
13080 }
13081 Inherited::VisitCXXConstructExpr(E);
13082 }
13083
13084 void VisitCallExpr(CallExpr *E) {
13085 // Treat std::move as a use.
13086 if (E->isCallToStdMove()) {
13087 HandleValue(E->getArg(0));
13088 return;
13089 }
13090
13091 Inherited::VisitCallExpr(E);
13092 }
13093
13094 void VisitBinaryOperator(BinaryOperator *E) {
13095 if (E->isCompoundAssignmentOp()) {
13096 HandleValue(E->getLHS());
13097 Visit(E->getRHS());
13098 return;
13099 }
13100
13101 Inherited::VisitBinaryOperator(E);
13102 }
13103
13104 // A custom visitor for BinaryConditionalOperator is needed because the
13105 // regular visitor would check the condition and true expression separately
13106 // but both point to the same place giving duplicate diagnostics.
13107 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13108 Visit(E->getCond());
13109 Visit(E->getFalseExpr());
13110 }
13111
13112 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13113 Decl* ReferenceDecl = DRE->getDecl();
13114 if (OrigDecl != ReferenceDecl) return;
13115 unsigned diag;
13116 if (isReferenceType) {
13117 diag = diag::warn_uninit_self_reference_in_reference_init;
13118 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13119 diag = diag::warn_static_self_reference_in_init;
13120 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13121 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13122 DRE->getDecl()->getType()->isRecordType()) {
13123 diag = diag::warn_uninit_self_reference_in_init;
13124 } else {
13125 // Local variables will be handled by the CFG analysis.
13126 return;
13127 }
13128
13129 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13130 S.PDiag(diag)
13131 << DRE->getDecl() << OrigDecl->getLocation()
13132 << DRE->getSourceRange());
13133 }
13134 };
13135
13136 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13137 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13138 bool DirectInit) {
13139 // Parameters arguments are occassionially constructed with itself,
13140 // for instance, in recursive functions. Skip them.
13141 if (isa<ParmVarDecl>(OrigDecl))
13142 return;
13143
13144 // Skip checking for file-scope constexpr variables - constant evaluation
13145 // will produce appropriate errors without needing runtime diagnostics.
13146 // Local constexpr should still emit runtime warnings.
13147 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);
13148 VD && VD->isConstexpr() && VD->isFileVarDecl())
13149 return;
13150
13151 E = E->IgnoreParens();
13152
13153 // Skip checking T a = a where T is not a record or reference type.
13154 // Doing so is a way to silence uninitialized warnings.
13155 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13156 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13157 if (ICE->getCastKind() == CK_LValueToRValue)
13158 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13159 if (DRE->getDecl() == OrigDecl)
13160 return;
13161
13162 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13163 }
13164} // end anonymous namespace
13165
13166namespace {
13167 // Simple wrapper to add the name of a variable or (if no variable is
13168 // available) a DeclarationName into a diagnostic.
13169 struct VarDeclOrName {
13170 VarDecl *VDecl;
13171 DeclarationName Name;
13172
13173 friend const Sema::SemaDiagnosticBuilder &
13174 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13175 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13176 }
13177 };
13178} // end anonymous namespace
13179
13182 TypeSourceInfo *TSI,
13183 SourceRange Range, bool DirectInit,
13184 Expr *Init) {
13185 bool IsInitCapture = !VDecl;
13186 assert((!VDecl || !VDecl->isInitCapture()) &&
13187 "init captures are expected to be deduced prior to initialization");
13188
13189 VarDeclOrName VN{VDecl, Name};
13190
13191 DeducedType *Deduced = Type->getContainedDeducedType();
13192 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13193
13194 // Diagnose auto array declarations in C23, unless it's a supported extension.
13195 if (getLangOpts().C23 && Type->isArrayType() &&
13196 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13197 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13198 << (int)Deduced->getContainedAutoType()->getKeyword()
13199 << /*in array decl*/ 23 << Range;
13200 return QualType();
13201 }
13202
13203 // C++11 [dcl.spec.auto]p3
13204 if (!Init) {
13205 assert(VDecl && "no init for init capture deduction?");
13206
13207 // Except for class argument deduction, and then for an initializing
13208 // declaration only, i.e. no static at class scope or extern.
13210 VDecl->hasExternalStorage() ||
13211 VDecl->isStaticDataMember()) {
13212 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13213 << VDecl->getDeclName() << Type;
13214 return QualType();
13215 }
13216 }
13217
13218 ArrayRef<Expr*> DeduceInits;
13219 if (Init)
13220 DeduceInits = Init;
13221
13222 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13223 if (DirectInit && PL)
13224 DeduceInits = PL->exprs();
13225
13227 assert(VDecl && "non-auto type for init capture deduction?");
13230 VDecl->getLocation(), DirectInit, Init);
13231 // FIXME: Initialization should not be taking a mutable list of inits.
13232 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13233 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13234 InitsCopy);
13235 }
13236
13237 if (DirectInit) {
13238 if (auto *IL = dyn_cast<InitListExpr>(Init))
13239 DeduceInits = IL->inits();
13240 }
13241
13242 // Deduction only works if we have exactly one source expression.
13243 if (DeduceInits.empty()) {
13244 // It isn't possible to write this directly, but it is possible to
13245 // end up in this situation with "auto x(some_pack...);"
13246 Diag(Init->getBeginLoc(), IsInitCapture
13247 ? diag::err_init_capture_no_expression
13248 : diag::err_auto_var_init_no_expression)
13249 << VN << Type << Range;
13250 return QualType();
13251 }
13252
13253 if (DeduceInits.size() > 1) {
13254 Diag(DeduceInits[1]->getBeginLoc(),
13255 IsInitCapture ? diag::err_init_capture_multiple_expressions
13256 : diag::err_auto_var_init_multiple_expressions)
13257 << VN << Type << Range;
13258 return QualType();
13259 }
13260
13261 Expr *DeduceInit = DeduceInits[0];
13262 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13263 Diag(Init->getBeginLoc(), IsInitCapture
13264 ? diag::err_init_capture_paren_braces
13265 : diag::err_auto_var_init_paren_braces)
13266 << isa<InitListExpr>(Init) << VN << Type << Range;
13267 return QualType();
13268 }
13269
13270 // Expressions default to 'id' when we're in a debugger.
13271 bool DefaultedAnyToId = false;
13272 if (getLangOpts().DebuggerCastResultToId &&
13273 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13275 if (Result.isInvalid()) {
13276 return QualType();
13277 }
13278 Init = Result.get();
13279 DefaultedAnyToId = true;
13280 }
13281
13282 // C++ [dcl.decomp]p1:
13283 // If the assignment-expression [...] has array type A and no ref-qualifier
13284 // is present, e has type cv A
13285 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13286 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13287 DeduceInit->getType()->isConstantArrayType())
13288 return Context.getQualifiedType(DeduceInit->getType(),
13289 Type.getQualifiers());
13290
13291 QualType DeducedType;
13292 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13294 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13297 if (!IsInitCapture)
13298 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13299 else if (isa<InitListExpr>(Init))
13300 Diag(Range.getBegin(),
13301 diag::err_init_capture_deduction_failure_from_init_list)
13302 << VN
13303 << (DeduceInit->getType().isNull() ? TSI->getType()
13304 : DeduceInit->getType())
13305 << DeduceInit->getSourceRange();
13306 else
13307 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13308 << VN << TSI->getType()
13309 << (DeduceInit->getType().isNull() ? TSI->getType()
13310 : DeduceInit->getType())
13311 << DeduceInit->getSourceRange();
13312 }
13313
13314 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13315 // 'id' instead of a specific object type prevents most of our usual
13316 // checks.
13317 // We only want to warn outside of template instantiations, though:
13318 // inside a template, the 'id' could have come from a parameter.
13319 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13320 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13321 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13322 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13323 }
13324
13325 return DeducedType;
13326}
13327
13329 Expr *Init) {
13330 assert(!Init || !Init->containsErrors());
13332 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13333 VDecl->getSourceRange(), DirectInit, Init);
13334 if (DeducedType.isNull()) {
13335 VDecl->setInvalidDecl();
13336 return true;
13337 }
13338
13339 VDecl->setType(DeducedType);
13340 assert(VDecl->isLinkageValid());
13341
13342 // In ARC, infer lifetime.
13343 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13344 VDecl->setInvalidDecl();
13345
13346 if (getLangOpts().OpenCL)
13348
13349 if (getLangOpts().HLSL)
13350 HLSL().deduceAddressSpace(VDecl);
13351
13352 // If this is a redeclaration, check that the type we just deduced matches
13353 // the previously declared type.
13354 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13355 // We never need to merge the type, because we cannot form an incomplete
13356 // array of auto, nor deduce such a type.
13357 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13358 }
13359
13360 // Check the deduced type is valid for a variable declaration.
13362 return VDecl->isInvalidDecl();
13363}
13364
13366 SourceLocation Loc) {
13367 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13368 Init = EWC->getSubExpr();
13369
13370 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13371 Init = CE->getSubExpr();
13372
13373 QualType InitType = Init->getType();
13376 "shouldn't be called if type doesn't have a non-trivial C struct");
13377 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13378 for (auto *I : ILE->inits()) {
13379 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13380 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13381 continue;
13382 SourceLocation SL = I->getExprLoc();
13383 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13384 }
13385 return;
13386 }
13387
13390 checkNonTrivialCUnion(InitType, Loc,
13392 NTCUK_Init);
13393 } else {
13394 // Assume all other explicit initializers involving copying some existing
13395 // object.
13396 // TODO: ignore any explicit initializers where we can guarantee
13397 // copy-elision.
13400 NTCUK_Copy);
13401 }
13402}
13403
13404namespace {
13405
13406bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13407 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13408 // in the source code or implicitly by the compiler if it is in a union
13409 // defined in a system header and has non-trivial ObjC ownership
13410 // qualifications. We don't want those fields to participate in determining
13411 // whether the containing union is non-trivial.
13412 return FD->hasAttr<UnavailableAttr>();
13413}
13414
13415struct DiagNonTrivalCUnionDefaultInitializeVisitor
13416 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13417 void> {
13418 using Super =
13419 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13420 void>;
13421
13422 DiagNonTrivalCUnionDefaultInitializeVisitor(
13423 QualType OrigTy, SourceLocation OrigLoc,
13424 NonTrivialCUnionContext UseContext, Sema &S)
13425 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13426
13427 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13428 const FieldDecl *FD, bool InNonTrivialUnion) {
13429 if (const auto *AT = S.Context.getAsArrayType(QT))
13430 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13431 InNonTrivialUnion);
13432 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13433 }
13434
13435 void visitARCStrong(QualType QT, const FieldDecl *FD,
13436 bool InNonTrivialUnion) {
13437 if (InNonTrivialUnion)
13438 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13439 << 1 << 0 << QT << FD->getName();
13440 }
13441
13442 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13443 if (InNonTrivialUnion)
13444 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13445 << 1 << 0 << QT << FD->getName();
13446 }
13447
13448 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13449 const auto *RD = QT->castAsRecordDecl();
13450 if (RD->isUnion()) {
13451 if (OrigLoc.isValid()) {
13452 bool IsUnion = false;
13453 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13454 IsUnion = OrigRD->isUnion();
13455 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13456 << 0 << OrigTy << IsUnion << UseContext;
13457 // Reset OrigLoc so that this diagnostic is emitted only once.
13458 OrigLoc = SourceLocation();
13459 }
13460 InNonTrivialUnion = true;
13461 }
13462
13463 if (InNonTrivialUnion)
13464 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13465 << 0 << 0 << QT.getUnqualifiedType() << "";
13466
13467 for (const FieldDecl *FD : RD->fields())
13468 if (!shouldIgnoreForRecordTriviality(FD))
13469 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13470 }
13471
13472 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13473
13474 // The non-trivial C union type or the struct/union type that contains a
13475 // non-trivial C union.
13476 QualType OrigTy;
13477 SourceLocation OrigLoc;
13478 NonTrivialCUnionContext UseContext;
13479 Sema &S;
13480};
13481
13482struct DiagNonTrivalCUnionDestructedTypeVisitor
13483 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13484 using Super =
13485 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13486
13487 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13488 SourceLocation OrigLoc,
13489 NonTrivialCUnionContext UseContext,
13490 Sema &S)
13491 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13492
13493 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13494 const FieldDecl *FD, bool InNonTrivialUnion) {
13495 if (const auto *AT = S.Context.getAsArrayType(QT))
13496 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13497 InNonTrivialUnion);
13498 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13499 }
13500
13501 void visitARCStrong(QualType QT, const FieldDecl *FD,
13502 bool InNonTrivialUnion) {
13503 if (InNonTrivialUnion)
13504 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13505 << 1 << 1 << QT << FD->getName();
13506 }
13507
13508 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13509 if (InNonTrivialUnion)
13510 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13511 << 1 << 1 << QT << FD->getName();
13512 }
13513
13514 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13515 const auto *RD = QT->castAsRecordDecl();
13516 if (RD->isUnion()) {
13517 if (OrigLoc.isValid()) {
13518 bool IsUnion = false;
13519 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13520 IsUnion = OrigRD->isUnion();
13521 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13522 << 1 << OrigTy << IsUnion << UseContext;
13523 // Reset OrigLoc so that this diagnostic is emitted only once.
13524 OrigLoc = SourceLocation();
13525 }
13526 InNonTrivialUnion = true;
13527 }
13528
13529 if (InNonTrivialUnion)
13530 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13531 << 0 << 1 << QT.getUnqualifiedType() << "";
13532
13533 for (const FieldDecl *FD : RD->fields())
13534 if (!shouldIgnoreForRecordTriviality(FD))
13535 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13536 }
13537
13538 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13539 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13540 bool InNonTrivialUnion) {}
13541
13542 // The non-trivial C union type or the struct/union type that contains a
13543 // non-trivial C union.
13544 QualType OrigTy;
13545 SourceLocation OrigLoc;
13546 NonTrivialCUnionContext UseContext;
13547 Sema &S;
13548};
13549
13550struct DiagNonTrivalCUnionCopyVisitor
13551 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13552 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13553
13554 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13555 NonTrivialCUnionContext UseContext, Sema &S)
13556 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13557
13558 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13559 const FieldDecl *FD, bool InNonTrivialUnion) {
13560 if (const auto *AT = S.Context.getAsArrayType(QT))
13561 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13562 InNonTrivialUnion);
13563 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13564 }
13565
13566 void visitARCStrong(QualType QT, const FieldDecl *FD,
13567 bool InNonTrivialUnion) {
13568 if (InNonTrivialUnion)
13569 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13570 << 1 << 2 << QT << FD->getName();
13571 }
13572
13573 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13574 if (InNonTrivialUnion)
13575 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13576 << 1 << 2 << QT << FD->getName();
13577 }
13578
13579 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13580 const auto *RD = QT->castAsRecordDecl();
13581 if (RD->isUnion()) {
13582 if (OrigLoc.isValid()) {
13583 bool IsUnion = false;
13584 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13585 IsUnion = OrigRD->isUnion();
13586 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13587 << 2 << OrigTy << IsUnion << UseContext;
13588 // Reset OrigLoc so that this diagnostic is emitted only once.
13589 OrigLoc = SourceLocation();
13590 }
13591 InNonTrivialUnion = true;
13592 }
13593
13594 if (InNonTrivialUnion)
13595 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13596 << 0 << 2 << QT.getUnqualifiedType() << "";
13597
13598 for (const FieldDecl *FD : RD->fields())
13599 if (!shouldIgnoreForRecordTriviality(FD))
13600 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13601 }
13602
13603 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13604 if (InNonTrivialUnion)
13605 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13606 << 1 << 2 << QT << FD->getName();
13607 }
13608
13609 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13610 const FieldDecl *FD, bool InNonTrivialUnion) {}
13611 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13612 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13613 bool InNonTrivialUnion) {}
13614
13615 // The non-trivial C union type or the struct/union type that contains a
13616 // non-trivial C union.
13617 QualType OrigTy;
13618 SourceLocation OrigLoc;
13619 NonTrivialCUnionContext UseContext;
13620 Sema &S;
13621};
13622
13623} // namespace
13624
13626 NonTrivialCUnionContext UseContext,
13627 unsigned NonTrivialKind) {
13631 "shouldn't be called if type doesn't have a non-trivial C union");
13632
13633 if ((NonTrivialKind & NTCUK_Init) &&
13635 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13636 .visit(QT, nullptr, false);
13637 if ((NonTrivialKind & NTCUK_Destruct) &&
13639 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13640 .visit(QT, nullptr, false);
13641 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13642 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13643 .visit(QT, nullptr, false);
13644}
13645
13647 const VarDecl *Dcl) {
13648 if (!getLangOpts().CPlusPlus)
13649 return false;
13650
13651 // We only need to warn if the definition is in a header file, so wait to
13652 // diagnose until we've seen the definition.
13653 if (!Dcl->isThisDeclarationADefinition())
13654 return false;
13655
13656 // If an object is defined in a source file, its definition can't get
13657 // duplicated since it will never appear in more than one TU.
13659 return false;
13660
13661 // If the variable we're looking at is a static local, then we actually care
13662 // about the properties of the function containing it.
13663 const ValueDecl *Target = Dcl;
13664 // VarDecls and FunctionDecls have different functions for checking
13665 // inline-ness, and whether they were originally templated, so we have to
13666 // call the appropriate functions manually.
13667 bool TargetIsInline = Dcl->isInline();
13668 bool TargetWasTemplated =
13670
13671 // Update the Target and TargetIsInline property if necessary
13672 if (Dcl->isStaticLocal()) {
13673 const DeclContext *Ctx = Dcl->getDeclContext();
13674 if (!Ctx)
13675 return false;
13676
13677 const FunctionDecl *FunDcl =
13678 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
13679 if (!FunDcl)
13680 return false;
13681
13682 Target = FunDcl;
13683 // IsInlined() checks for the C++ inline property
13684 TargetIsInline = FunDcl->isInlined();
13685 TargetWasTemplated =
13687 }
13688
13689 // Non-inline functions/variables can only legally appear in one TU
13690 // unless they were part of a template. Unfortunately, making complex
13691 // template instantiations visible is infeasible in practice, since
13692 // everything the template depends on also has to be visible. To avoid
13693 // giving impractical-to-fix warnings, don't warn if we're inside
13694 // something that was templated, even on inline stuff.
13695 if (!TargetIsInline || TargetWasTemplated)
13696 return false;
13697
13698 // If the object isn't hidden, the dynamic linker will prevent duplication.
13699 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13700
13701 // The target is "hidden" (from the dynamic linker) if:
13702 // 1. On posix, it has hidden visibility, or
13703 // 2. On windows, it has no import/export annotation, and neither does the
13704 // class which directly contains it.
13705 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13706 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13707 return false;
13708
13709 // If the variable isn't directly annotated, check to see if it's a member
13710 // of an annotated class.
13711 const CXXRecordDecl *Ctx =
13712 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
13713 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13714 return false;
13715
13716 } else if (Lnk.getVisibility() != HiddenVisibility) {
13717 // Posix case
13718 return false;
13719 }
13720
13721 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13723 return false;
13724
13725 return true;
13726}
13727
13728// Determine whether the object seems mutable for the purpose of diagnosing
13729// possible unique object duplication, i.e. non-const-qualified, and
13730// not an always-constant type like a function.
13731// Not perfect: doesn't account for mutable members, for example, or
13732// elements of container types.
13733// For nested pointers, any individual level being non-const is sufficient.
13734static bool looksMutable(QualType T, const ASTContext &Ctx) {
13735 T = T.getNonReferenceType();
13736 if (T->isFunctionType())
13737 return false;
13738 if (!T.isConstant(Ctx))
13739 return true;
13740 if (T->isPointerType())
13741 return looksMutable(T->getPointeeType(), Ctx);
13742 return false;
13743}
13744
13746 // If this object has external linkage and hidden visibility, it might be
13747 // duplicated when built into a shared library, which causes problems if it's
13748 // mutable (since the copies won't be in sync) or its initialization has side
13749 // effects (since it will run once per copy instead of once globally).
13750
13751 // Don't diagnose if we're inside a template, because it's not practical to
13752 // fix the warning in most cases.
13753 if (!VD->isTemplated() &&
13755
13756 QualType Type = VD->getType();
13757 if (looksMutable(Type, VD->getASTContext())) {
13758 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13759 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13760 }
13761
13762 // To keep false positives low, only warn if we're certain that the
13763 // initializer has side effects. Don't warn on operator new, since a mutable
13764 // pointer will trigger the previous warning, and an immutable pointer
13765 // getting duplicated just results in a little extra memory usage.
13766 const Expr *Init = VD->getAnyInitializer();
13767 if (Init &&
13768 Init->HasSideEffects(VD->getASTContext(),
13769 /*IncludePossibleEffects=*/false) &&
13770 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
13771 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13772 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13773 }
13774 }
13775}
13776
13778 auto ResetDeclForInitializer = llvm::make_scope_exit([this]() {
13779 if (this->ExprEvalContexts.empty())
13780 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13781 });
13782
13783 // If there is no declaration, there was an error parsing it. Just ignore
13784 // the initializer.
13785 if (!RealDecl) {
13786 return;
13787 }
13788
13789 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13790 if (!Method->isInvalidDecl()) {
13791 // Pure-specifiers are handled in ActOnPureSpecifier.
13792 Diag(Method->getLocation(), diag::err_member_function_initialization)
13793 << Method->getDeclName() << Init->getSourceRange();
13794 Method->setInvalidDecl();
13795 }
13796 return;
13797 }
13798
13799 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13800 if (!VDecl) {
13801 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13802 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13803 RealDecl->setInvalidDecl();
13804 return;
13805 }
13806
13807 if (VDecl->isInvalidDecl()) {
13808 ExprResult Recovery =
13809 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13810 if (Expr *E = Recovery.get())
13811 VDecl->setInit(E);
13812 return;
13813 }
13814
13815 // WebAssembly tables can't be used to initialise a variable.
13816 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13817 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13818 VDecl->setInvalidDecl();
13819 return;
13820 }
13821
13822 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13823 if (VDecl->getType()->isUndeducedType()) {
13824 if (Init->containsErrors()) {
13825 // Invalidate the decl as we don't know the type for recovery-expr yet.
13826 RealDecl->setInvalidDecl();
13827 VDecl->setInit(Init);
13828 return;
13829 }
13830
13832 return;
13833 }
13834
13835 this->CheckAttributesOnDeducedType(RealDecl);
13836
13837 // dllimport cannot be used on variable definitions.
13838 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13839 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13840 VDecl->setInvalidDecl();
13841 return;
13842 }
13843
13844 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13845 // the identifier has external or internal linkage, the declaration shall
13846 // have no initializer for the identifier.
13847 // C++14 [dcl.init]p5 is the same restriction for C++.
13848 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13849 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13850 VDecl->setInvalidDecl();
13851 return;
13852 }
13853
13854 if (!VDecl->getType()->isDependentType()) {
13855 // A definition must end up with a complete type, which means it must be
13856 // complete with the restriction that an array type might be completed by
13857 // the initializer; note that later code assumes this restriction.
13858 QualType BaseDeclType = VDecl->getType();
13859 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13860 BaseDeclType = Array->getElementType();
13861 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13862 diag::err_typecheck_decl_incomplete_type)) {
13863 RealDecl->setInvalidDecl();
13864 return;
13865 }
13866
13867 // The variable can not have an abstract class type.
13868 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13869 diag::err_abstract_type_in_decl,
13871 VDecl->setInvalidDecl();
13872 }
13873
13874 // C++ [module.import/6]
13875 // ...
13876 // A header unit shall not contain a definition of a non-inline function or
13877 // variable whose name has external linkage.
13878 //
13879 // We choose to allow weak & selectany definitions, as they are common in
13880 // headers, and have semantics similar to inline definitions which are allowed
13881 // in header units.
13882 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13883 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13884 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13885 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13887 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
13888 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13889 VDecl->setInvalidDecl();
13890 }
13891
13892 // If adding the initializer will turn this declaration into a definition,
13893 // and we already have a definition for this variable, diagnose or otherwise
13894 // handle the situation.
13895 if (VarDecl *Def = VDecl->getDefinition())
13896 if (Def != VDecl &&
13897 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13899 checkVarDeclRedefinition(Def, VDecl))
13900 return;
13901
13902 if (getLangOpts().CPlusPlus) {
13903 // C++ [class.static.data]p4
13904 // If a static data member is of const integral or const
13905 // enumeration type, its declaration in the class definition can
13906 // specify a constant-initializer which shall be an integral
13907 // constant expression (5.19). In that case, the member can appear
13908 // in integral constant expressions. The member shall still be
13909 // defined in a namespace scope if it is used in the program and the
13910 // namespace scope definition shall not contain an initializer.
13911 //
13912 // We already performed a redefinition check above, but for static
13913 // data members we also need to check whether there was an in-class
13914 // declaration with an initializer.
13915 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13916 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13917 << VDecl->getDeclName();
13918 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13919 diag::note_previous_initializer)
13920 << 0;
13921 return;
13922 }
13923
13925 VDecl->setInvalidDecl();
13926 return;
13927 }
13928 }
13929
13930 // If the variable has an initializer and local storage, check whether
13931 // anything jumps over the initialization.
13932 if (VDecl->hasLocalStorage())
13934
13935 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13936 // a kernel function cannot be initialized."
13937 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13938 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13939 VDecl->setInvalidDecl();
13940 return;
13941 }
13942
13943 // The LoaderUninitialized attribute acts as a definition (of undef).
13944 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13945 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13946 VDecl->setInvalidDecl();
13947 return;
13948 }
13949
13950 if (getLangOpts().HLSL)
13951 if (!HLSL().handleInitialization(VDecl, Init))
13952 return;
13953
13954 // Get the decls type and save a reference for later, since
13955 // CheckInitializerTypes may change it.
13956 QualType DclT = VDecl->getType(), SavT = DclT;
13957
13958 // Expressions default to 'id' when we're in a debugger
13959 // and we are assigning it to a variable of Objective-C pointer type.
13960 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13961 Init->getType() == Context.UnknownAnyTy) {
13963 if (!Result.isUsable()) {
13964 VDecl->setInvalidDecl();
13965 return;
13966 }
13967 Init = Result.get();
13968 }
13969
13970 // Perform the initialization.
13971 bool InitializedFromParenListExpr = false;
13972 bool IsParenListInit = false;
13973 if (!VDecl->isInvalidDecl()) {
13976 VDecl->getLocation(), DirectInit, Init);
13977
13978 MultiExprArg Args = Init;
13979 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
13980 Args =
13981 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
13982 InitializedFromParenListExpr = true;
13983 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
13984 Args = CXXDirectInit->getInitExprs();
13985 InitializedFromParenListExpr = true;
13986 }
13987
13988 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13989 /*TopLevelOfInitList=*/false,
13990 /*TreatUnavailableAsInvalid=*/false);
13991 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13992 if (!Result.isUsable()) {
13993 // If the provided initializer fails to initialize the var decl,
13994 // we attach a recovery expr for better recovery.
13995 auto RecoveryExpr =
13996 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13997 if (RecoveryExpr.get())
13998 VDecl->setInit(RecoveryExpr.get());
13999 // In general, for error recovery purposes, the initializer doesn't play
14000 // part in the valid bit of the declaration. There are a few exceptions:
14001 // 1) if the var decl has a deduced auto type, and the type cannot be
14002 // deduced by an invalid initializer;
14003 // 2) if the var decl is a decomposition decl with a non-deduced type,
14004 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14005 // Case 1) was already handled elsewhere.
14006 if (isa<DecompositionDecl>(VDecl)) // Case 2)
14007 VDecl->setInvalidDecl();
14008 return;
14009 }
14010
14011 Init = Result.getAs<Expr>();
14012 IsParenListInit = !InitSeq.steps().empty() &&
14013 InitSeq.step_begin()->Kind ==
14015 QualType VDeclType = VDecl->getType();
14016 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14017 !VDeclType->isDependentType() &&
14018 Context.getAsIncompleteArrayType(VDeclType) &&
14019 Context.getAsIncompleteArrayType(Init->getType())) {
14020 // Bail out if it is not possible to deduce array size from the
14021 // initializer.
14022 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
14023 << VDeclType;
14024 VDecl->setInvalidDecl();
14025 return;
14026 }
14027 }
14028
14029 // Check for self-references within variable initializers.
14030 // Variables declared within a function/method body (except for references)
14031 // are handled by a dataflow analysis.
14032 // This is undefined behavior in C++, but valid in C.
14033 if (getLangOpts().CPlusPlus)
14034 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14035 VDecl->getType()->isReferenceType())
14036 CheckSelfReference(*this, RealDecl, Init, DirectInit);
14037
14038 // If the type changed, it means we had an incomplete type that was
14039 // completed by the initializer. For example:
14040 // int ary[] = { 1, 3, 5 };
14041 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14042 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14043 VDecl->setType(DclT);
14044
14045 if (!VDecl->isInvalidDecl()) {
14046 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
14047
14048 if (VDecl->hasAttr<BlocksAttr>())
14049 ObjC().checkRetainCycles(VDecl, Init);
14050
14051 // It is safe to assign a weak reference into a strong variable.
14052 // Although this code can still have problems:
14053 // id x = self.weakProp;
14054 // id y = self.weakProp;
14055 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14056 // paths through the function. This should be revisited if
14057 // -Wrepeated-use-of-weak is made flow-sensitive.
14058 if (FunctionScopeInfo *FSI = getCurFunction())
14059 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14061 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14062 Init->getBeginLoc()))
14063 FSI->markSafeWeakUse(Init);
14064 }
14065
14066 // The initialization is usually a full-expression.
14067 //
14068 // FIXME: If this is a braced initialization of an aggregate, it is not
14069 // an expression, and each individual field initializer is a separate
14070 // full-expression. For instance, in:
14071 //
14072 // struct Temp { ~Temp(); };
14073 // struct S { S(Temp); };
14074 // struct T { S a, b; } t = { Temp(), Temp() }
14075 //
14076 // we should destroy the first Temp before constructing the second.
14079 /*DiscardedValue*/ false, VDecl->isConstexpr());
14080 if (!Result.isUsable()) {
14081 VDecl->setInvalidDecl();
14082 return;
14083 }
14084 Init = Result.get();
14085
14086 // Attach the initializer to the decl.
14087 VDecl->setInit(Init);
14088
14089 if (VDecl->isLocalVarDecl()) {
14090 // Don't check the initializer if the declaration is malformed.
14091 if (VDecl->isInvalidDecl()) {
14092 // do nothing
14093
14094 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14095 // This is true even in C++ for OpenCL.
14096 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14098
14099 // Otherwise, C++ does not restrict the initializer.
14100 } else if (getLangOpts().CPlusPlus) {
14101 // do nothing
14102
14103 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14104 // static storage duration shall be constant expressions or string literals.
14105 } else if (VDecl->getStorageClass() == SC_Static) {
14107
14108 // C89 is stricter than C99 for aggregate initializers.
14109 // C89 6.5.7p3: All the expressions [...] in an initializer list
14110 // for an object that has aggregate or union type shall be
14111 // constant expressions.
14112 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14114 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14115 }
14116
14117 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14118 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14119 if (VDecl->hasLocalStorage())
14120 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14121 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14122 VDecl->getLexicalDeclContext()->isRecord()) {
14123 // This is an in-class initialization for a static data member, e.g.,
14124 //
14125 // struct S {
14126 // static const int value = 17;
14127 // };
14128
14129 // C++ [class.mem]p4:
14130 // A member-declarator can contain a constant-initializer only
14131 // if it declares a static member (9.4) of const integral or
14132 // const enumeration type, see 9.4.2.
14133 //
14134 // C++11 [class.static.data]p3:
14135 // If a non-volatile non-inline const static data member is of integral
14136 // or enumeration type, its declaration in the class definition can
14137 // specify a brace-or-equal-initializer in which every initializer-clause
14138 // that is an assignment-expression is a constant expression. A static
14139 // data member of literal type can be declared in the class definition
14140 // with the constexpr specifier; if so, its declaration shall specify a
14141 // brace-or-equal-initializer in which every initializer-clause that is
14142 // an assignment-expression is a constant expression.
14143
14144 // Do nothing on dependent types.
14145 if (DclT->isDependentType()) {
14146
14147 // Allow any 'static constexpr' members, whether or not they are of literal
14148 // type. We separately check that every constexpr variable is of literal
14149 // type.
14150 } else if (VDecl->isConstexpr()) {
14151
14152 // Require constness.
14153 } else if (!DclT.isConstQualified()) {
14154 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14155 << Init->getSourceRange();
14156 VDecl->setInvalidDecl();
14157
14158 // We allow integer constant expressions in all cases.
14159 } else if (DclT->isIntegralOrEnumerationType()) {
14161 // In C++11, a non-constexpr const static data member with an
14162 // in-class initializer cannot be volatile.
14163 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14164
14165 // We allow foldable floating-point constants as an extension.
14166 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14167 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14168 // it anyway and provide a fixit to add the 'constexpr'.
14169 if (getLangOpts().CPlusPlus11) {
14170 Diag(VDecl->getLocation(),
14171 diag::ext_in_class_initializer_float_type_cxx11)
14172 << DclT << Init->getSourceRange();
14173 Diag(VDecl->getBeginLoc(),
14174 diag::note_in_class_initializer_float_type_cxx11)
14175 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14176 } else {
14177 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14178 << DclT << Init->getSourceRange();
14179
14180 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14181 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14182 << Init->getSourceRange();
14183 VDecl->setInvalidDecl();
14184 }
14185 }
14186
14187 // Suggest adding 'constexpr' in C++11 for literal types.
14188 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14189 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14190 << DclT << Init->getSourceRange()
14191 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14192 VDecl->setConstexpr(true);
14193
14194 } else {
14195 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14196 << DclT << Init->getSourceRange();
14197 VDecl->setInvalidDecl();
14198 }
14199 } else if (VDecl->isFileVarDecl()) {
14200 // In C, extern is typically used to avoid tentative definitions when
14201 // declaring variables in headers, but adding an initializer makes it a
14202 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14203 // In C++, extern is often used to give implicitly static const variables
14204 // external linkage, so don't warn in that case. If selectany is present,
14205 // this might be header code intended for C and C++ inclusion, so apply the
14206 // C++ rules.
14207 if (VDecl->getStorageClass() == SC_Extern &&
14208 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14209 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14210 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14212 Diag(VDecl->getLocation(), diag::warn_extern_init);
14213
14214 // In Microsoft C++ mode, a const variable defined in namespace scope has
14215 // external linkage by default if the variable is declared with
14216 // __declspec(dllexport).
14217 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14219 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14220 VDecl->setStorageClass(SC_Extern);
14221
14222 // C99 6.7.8p4. All file scoped initializers need to be constant.
14223 // Avoid duplicate diagnostics for constexpr variables.
14224 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14225 !VDecl->isConstexpr())
14227 }
14228
14229 QualType InitType = Init->getType();
14230 if (!InitType.isNull() &&
14234
14235 // We will represent direct-initialization similarly to copy-initialization:
14236 // int x(1); -as-> int x = 1;
14237 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14238 //
14239 // Clients that want to distinguish between the two forms, can check for
14240 // direct initializer using VarDecl::getInitStyle().
14241 // A major benefit is that clients that don't particularly care about which
14242 // exactly form was it (like the CodeGen) can handle both cases without
14243 // special case code.
14244
14245 // C++ 8.5p11:
14246 // The form of initialization (using parentheses or '=') matters
14247 // when the entity being initialized has class type.
14248 if (InitializedFromParenListExpr) {
14249 assert(DirectInit && "Call-style initializer must be direct init.");
14250 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14252 } else if (DirectInit) {
14253 // This must be list-initialization. No other way is direct-initialization.
14255 }
14256
14257 if (LangOpts.OpenMP &&
14258 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14259 VDecl->isFileVarDecl())
14260 DeclsToCheckForDeferredDiags.insert(VDecl);
14262
14263 if (LangOpts.OpenACC && !InitType.isNull())
14264 OpenACC().ActOnVariableInit(VDecl, InitType);
14265}
14266
14268 // Our main concern here is re-establishing invariants like "a
14269 // variable's type is either dependent or complete".
14270 if (!D || D->isInvalidDecl()) return;
14271
14272 VarDecl *VD = dyn_cast<VarDecl>(D);
14273 if (!VD) return;
14274
14275 // Bindings are not usable if we can't make sense of the initializer.
14276 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14277 for (auto *BD : DD->bindings())
14278 BD->setInvalidDecl();
14279
14280 // Auto types are meaningless if we can't make sense of the initializer.
14281 if (VD->getType()->isUndeducedType()) {
14282 D->setInvalidDecl();
14283 return;
14284 }
14285
14286 QualType Ty = VD->getType();
14287 if (Ty->isDependentType()) return;
14288
14289 // Require a complete type.
14291 Context.getBaseElementType(Ty),
14292 diag::err_typecheck_decl_incomplete_type)) {
14293 VD->setInvalidDecl();
14294 return;
14295 }
14296
14297 // Require a non-abstract type.
14298 if (RequireNonAbstractType(VD->getLocation(), Ty,
14299 diag::err_abstract_type_in_decl,
14301 VD->setInvalidDecl();
14302 return;
14303 }
14304
14305 // Don't bother complaining about constructors or destructors,
14306 // though.
14307}
14308
14310 // If there is no declaration, there was an error parsing it. Just ignore it.
14311 if (!RealDecl)
14312 return;
14313
14314 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14315 QualType Type = Var->getType();
14316
14317 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14318 if (isa<DecompositionDecl>(RealDecl)) {
14319 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14320 Var->setInvalidDecl();
14321 return;
14322 }
14323
14324 if (Type->isUndeducedType() &&
14325 DeduceVariableDeclarationType(Var, false, nullptr))
14326 return;
14327
14328 this->CheckAttributesOnDeducedType(RealDecl);
14329
14330 // C++11 [class.static.data]p3: A static data member can be declared with
14331 // the constexpr specifier; if so, its declaration shall specify
14332 // a brace-or-equal-initializer.
14333 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14334 // the definition of a variable [...] or the declaration of a static data
14335 // member.
14336 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14337 !Var->isThisDeclarationADemotedDefinition()) {
14338 if (Var->isStaticDataMember()) {
14339 // C++1z removes the relevant rule; the in-class declaration is always
14340 // a definition there.
14341 if (!getLangOpts().CPlusPlus17 &&
14342 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14343 Diag(Var->getLocation(),
14344 diag::err_constexpr_static_mem_var_requires_init)
14345 << Var;
14346 Var->setInvalidDecl();
14347 return;
14348 }
14349 } else {
14350 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14351 Var->setInvalidDecl();
14352 return;
14353 }
14354 }
14355
14356 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14357 // be initialized.
14358 if (!Var->isInvalidDecl() &&
14359 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14360 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14361 bool HasConstExprDefaultConstructor = false;
14362 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14363 for (auto *Ctor : RD->ctors()) {
14364 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14365 Ctor->getMethodQualifiers().getAddressSpace() ==
14367 HasConstExprDefaultConstructor = true;
14368 }
14369 }
14370 }
14371 if (!HasConstExprDefaultConstructor) {
14372 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14373 Var->setInvalidDecl();
14374 return;
14375 }
14376 }
14377
14378 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14379 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14380 Diag(Var->getLocation(), diag::err_specialization_const);
14381 Var->setInvalidDecl();
14382 return;
14383 }
14384
14385 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14386 if (Var->getStorageClass() == SC_Extern) {
14387 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14388 << Var;
14389 Var->setInvalidDecl();
14390 return;
14391 }
14392 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14393 diag::err_typecheck_decl_incomplete_type)) {
14394 Var->setInvalidDecl();
14395 return;
14396 }
14397 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14398 if (!RD->hasTrivialDefaultConstructor()) {
14399 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14400 Var->setInvalidDecl();
14401 return;
14402 }
14403 }
14404 // The declaration is uninitialized, no need for further checks.
14405 return;
14406 }
14407
14408 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14409 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14410 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14411 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14413 NTCUK_Init);
14414
14415 switch (DefKind) {
14417 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14418 break;
14419
14420 // We have an out-of-line definition of a static data member
14421 // that has an in-class initializer, so we type-check this like
14422 // a declaration.
14423 //
14424 [[fallthrough]];
14425
14427 // It's only a declaration.
14428
14429 // Block scope. C99 6.7p7: If an identifier for an object is
14430 // declared with no linkage (C99 6.2.2p6), the type for the
14431 // object shall be complete.
14432 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14433 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14434 RequireCompleteType(Var->getLocation(), Type,
14435 diag::err_typecheck_decl_incomplete_type))
14436 Var->setInvalidDecl();
14437
14438 // Make sure that the type is not abstract.
14439 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14440 RequireNonAbstractType(Var->getLocation(), Type,
14441 diag::err_abstract_type_in_decl,
14443 Var->setInvalidDecl();
14444 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14445 Var->getStorageClass() == SC_PrivateExtern) {
14446 Diag(Var->getLocation(), diag::warn_private_extern);
14447 Diag(Var->getLocation(), diag::note_private_extern);
14448 }
14449
14450 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14451 !Var->isInvalidDecl())
14452 ExternalDeclarations.push_back(Var);
14453
14454 return;
14455
14457 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14458 // object that has file scope without an initializer, and without a
14459 // storage-class specifier or with the storage-class specifier "static",
14460 // constitutes a tentative definition. Note: A tentative definition with
14461 // external linkage is valid (C99 6.2.2p5).
14462 if (!Var->isInvalidDecl()) {
14463 if (const IncompleteArrayType *ArrayT
14464 = Context.getAsIncompleteArrayType(Type)) {
14466 Var->getLocation(), ArrayT->getElementType(),
14467 diag::err_array_incomplete_or_sizeless_type))
14468 Var->setInvalidDecl();
14469 }
14470 if (Var->getStorageClass() == SC_Static) {
14471 // C99 6.9.2p3: If the declaration of an identifier for an object is
14472 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14473 // declared type shall not be an incomplete type.
14474 // NOTE: code such as the following
14475 // static struct s;
14476 // struct s { int a; };
14477 // is accepted by gcc. Hence here we issue a warning instead of
14478 // an error and we do not invalidate the static declaration.
14479 // NOTE: to avoid multiple warnings, only check the first declaration.
14480 if (Var->isFirstDecl())
14481 RequireCompleteType(Var->getLocation(), Type,
14482 diag::ext_typecheck_decl_incomplete_type,
14483 Type->isArrayType());
14484 }
14485 }
14486
14487 // Record the tentative definition; we're done.
14488 if (!Var->isInvalidDecl())
14489 TentativeDefinitions.push_back(Var);
14490 return;
14491 }
14492
14493 // Provide a specific diagnostic for uninitialized variable definitions
14494 // with incomplete array type, unless it is a global unbounded HLSL resource
14495 // array.
14496 if (Type->isIncompleteArrayType() &&
14497 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14499 if (Var->isConstexpr())
14500 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14501 << Var;
14502 else
14503 Diag(Var->getLocation(),
14504 diag::err_typecheck_incomplete_array_needs_initializer);
14505 Var->setInvalidDecl();
14506 return;
14507 }
14508
14509 // Provide a specific diagnostic for uninitialized variable
14510 // definitions with reference type.
14511 if (Type->isReferenceType()) {
14512 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14513 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14514 return;
14515 }
14516
14517 // Do not attempt to type-check the default initializer for a
14518 // variable with dependent type.
14519 if (Type->isDependentType())
14520 return;
14521
14522 if (Var->isInvalidDecl())
14523 return;
14524
14525 if (!Var->hasAttr<AliasAttr>()) {
14526 if (RequireCompleteType(Var->getLocation(),
14527 Context.getBaseElementType(Type),
14528 diag::err_typecheck_decl_incomplete_type)) {
14529 Var->setInvalidDecl();
14530 return;
14531 }
14532 } else {
14533 return;
14534 }
14535
14536 // The variable can not have an abstract class type.
14537 if (RequireNonAbstractType(Var->getLocation(), Type,
14538 diag::err_abstract_type_in_decl,
14540 Var->setInvalidDecl();
14541 return;
14542 }
14543
14544 // In C, if the definition is const-qualified and has no initializer, it
14545 // is left uninitialized unless it has static or thread storage duration.
14546 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14547 unsigned DiagID = diag::warn_default_init_const_unsafe;
14548 if (Var->getStorageDuration() == SD_Static ||
14549 Var->getStorageDuration() == SD_Thread)
14550 DiagID = diag::warn_default_init_const;
14551
14552 bool EmitCppCompat = !Diags.isIgnored(
14553 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14554 Var->getLocation());
14555
14556 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14557 }
14558
14559 // Check for jumps past the implicit initializer. C++0x
14560 // clarifies that this applies to a "variable with automatic
14561 // storage duration", not a "local variable".
14562 // C++11 [stmt.dcl]p3
14563 // A program that jumps from a point where a variable with automatic
14564 // storage duration is not in scope to a point where it is in scope is
14565 // ill-formed unless the variable has scalar type, class type with a
14566 // trivial default constructor and a trivial destructor, a cv-qualified
14567 // version of one of these types, or an array of one of the preceding
14568 // types and is declared without an initializer.
14569 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14570 if (const auto *CXXRecord =
14571 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14572 // Mark the function (if we're in one) for further checking even if the
14573 // looser rules of C++11 do not require such checks, so that we can
14574 // diagnose incompatibilities with C++98.
14575 if (!CXXRecord->isPOD())
14577 }
14578 }
14579 // In OpenCL, we can't initialize objects in the __local address space,
14580 // even implicitly, so don't synthesize an implicit initializer.
14581 if (getLangOpts().OpenCL &&
14582 Var->getType().getAddressSpace() == LangAS::opencl_local)
14583 return;
14584
14585 // Handle HLSL uninitialized decls
14586 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14587 return;
14588
14589 // HLSL input variables are expected to be externally initialized, even
14590 // when marked `static`.
14591 if (getLangOpts().HLSL &&
14592 Var->getType().getAddressSpace() == LangAS::hlsl_input)
14593 return;
14594
14595 // C++03 [dcl.init]p9:
14596 // If no initializer is specified for an object, and the
14597 // object is of (possibly cv-qualified) non-POD class type (or
14598 // array thereof), the object shall be default-initialized; if
14599 // the object is of const-qualified type, the underlying class
14600 // type shall have a user-declared default
14601 // constructor. Otherwise, if no initializer is specified for
14602 // a non- static object, the object and its subobjects, if
14603 // any, have an indeterminate initial value); if the object
14604 // or any of its subobjects are of const-qualified type, the
14605 // program is ill-formed.
14606 // C++0x [dcl.init]p11:
14607 // If no initializer is specified for an object, the object is
14608 // default-initialized; [...].
14611 = InitializationKind::CreateDefault(Var->getLocation());
14612
14613 InitializationSequence InitSeq(*this, Entity, Kind, {});
14614 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14615
14616 if (Init.get()) {
14617 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14618 // This is important for template substitution.
14619 Var->setInitStyle(VarDecl::CallInit);
14620 } else if (Init.isInvalid()) {
14621 // If default-init fails, attach a recovery-expr initializer to track
14622 // that initialization was attempted and failed.
14623 auto RecoveryExpr =
14624 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14625 if (RecoveryExpr.get())
14626 Var->setInit(RecoveryExpr.get());
14627 }
14628
14630 }
14631}
14632
14634 // If there is no declaration, there was an error parsing it. Ignore it.
14635 if (!D)
14636 return;
14637
14638 VarDecl *VD = dyn_cast<VarDecl>(D);
14639 if (!VD) {
14640 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14641 D->setInvalidDecl();
14642 return;
14643 }
14644
14645 VD->setCXXForRangeDecl(true);
14646
14647 // for-range-declaration cannot be given a storage class specifier.
14648 int Error = -1;
14649 switch (VD->getStorageClass()) {
14650 case SC_None:
14651 break;
14652 case SC_Extern:
14653 Error = 0;
14654 break;
14655 case SC_Static:
14656 Error = 1;
14657 break;
14658 case SC_PrivateExtern:
14659 Error = 2;
14660 break;
14661 case SC_Auto:
14662 Error = 3;
14663 break;
14664 case SC_Register:
14665 Error = 4;
14666 break;
14667 }
14668
14669 // for-range-declaration cannot be given a storage class specifier con't.
14670 switch (VD->getTSCSpec()) {
14671 case TSCS_thread_local:
14672 Error = 6;
14673 break;
14674 case TSCS___thread:
14675 case TSCS__Thread_local:
14676 case TSCS_unspecified:
14677 break;
14678 }
14679
14680 if (Error != -1) {
14681 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14682 << VD << Error;
14683 D->setInvalidDecl();
14684 }
14685}
14686
14688 IdentifierInfo *Ident,
14689 ParsedAttributes &Attrs) {
14690 // C++1y [stmt.iter]p1:
14691 // A range-based for statement of the form
14692 // for ( for-range-identifier : for-range-initializer ) statement
14693 // is equivalent to
14694 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14695 DeclSpec DS(Attrs.getPool().getFactory());
14696
14697 const char *PrevSpec;
14698 unsigned DiagID;
14699 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14701
14703 D.SetIdentifier(Ident, IdentLoc);
14704 D.takeAttributesAppending(Attrs);
14705
14706 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14707 IdentLoc);
14708 Decl *Var = ActOnDeclarator(S, D);
14709 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14711 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14712 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14713 : IdentLoc);
14714}
14715
14717 if (var->isInvalidDecl()) return;
14718
14720
14721 if (getLangOpts().OpenCL) {
14722 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14723 // initialiser
14724 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14725 !var->hasInit()) {
14726 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14727 << 1 /*Init*/;
14728 var->setInvalidDecl();
14729 return;
14730 }
14731 }
14732
14733 // In Objective-C, don't allow jumps past the implicit initialization of a
14734 // local retaining variable.
14735 if (getLangOpts().ObjC &&
14736 var->hasLocalStorage()) {
14737 switch (var->getType().getObjCLifetime()) {
14741 break;
14742
14746 break;
14747 }
14748 }
14749
14750 if (var->hasLocalStorage() &&
14751 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14753
14754 // Warn about externally-visible variables being defined without a
14755 // prior declaration. We only want to do this for global
14756 // declarations, but we also specifically need to avoid doing it for
14757 // class members because the linkage of an anonymous class can
14758 // change if it's later given a typedef name.
14759 if (var->isThisDeclarationADefinition() &&
14760 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14761 var->isExternallyVisible() && var->hasLinkage() &&
14762 !var->isInline() && !var->getDescribedVarTemplate() &&
14763 var->getStorageClass() != SC_Register &&
14765 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14766 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14767 var->getLocation())) {
14768 // Find a previous declaration that's not a definition.
14769 VarDecl *prev = var->getPreviousDecl();
14770 while (prev && prev->isThisDeclarationADefinition())
14771 prev = prev->getPreviousDecl();
14772
14773 if (!prev) {
14774 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14775 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14776 << /* variable */ 0;
14777 }
14778 }
14779
14780 // Cache the result of checking for constant initialization.
14781 std::optional<bool> CacheHasConstInit;
14782 const Expr *CacheCulprit = nullptr;
14783 auto checkConstInit = [&]() mutable {
14784 const Expr *Init = var->getInit();
14785 if (Init->isInstantiationDependent())
14786 return true;
14787
14788 if (!CacheHasConstInit)
14789 CacheHasConstInit = var->getInit()->isConstantInitializer(
14790 Context, var->getType()->isReferenceType(), &CacheCulprit);
14791 return *CacheHasConstInit;
14792 };
14793
14794 if (var->getTLSKind() == VarDecl::TLS_Static) {
14795 if (var->getType().isDestructedType()) {
14796 // GNU C++98 edits for __thread, [basic.start.term]p3:
14797 // The type of an object with thread storage duration shall not
14798 // have a non-trivial destructor.
14799 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14801 Diag(var->getLocation(), diag::note_use_thread_local);
14802 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14803 if (!checkConstInit()) {
14804 // GNU C++98 edits for __thread, [basic.start.init]p4:
14805 // An object of thread storage duration shall not require dynamic
14806 // initialization.
14807 // FIXME: Need strict checking here.
14808 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14809 << CacheCulprit->getSourceRange();
14811 Diag(var->getLocation(), diag::note_use_thread_local);
14812 }
14813 }
14814 }
14815
14816
14817 if (!var->getType()->isStructureType() && var->hasInit() &&
14818 isa<InitListExpr>(var->getInit())) {
14819 const auto *ILE = cast<InitListExpr>(var->getInit());
14820 unsigned NumInits = ILE->getNumInits();
14821 if (NumInits > 2)
14822 for (unsigned I = 0; I < NumInits; ++I) {
14823 const auto *Init = ILE->getInit(I);
14824 if (!Init)
14825 break;
14826 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14827 if (!SL)
14828 break;
14829
14830 unsigned NumConcat = SL->getNumConcatenated();
14831 // Diagnose missing comma in string array initialization.
14832 // Do not warn when all the elements in the initializer are concatenated
14833 // together. Do not warn for macros too.
14834 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14835 bool OnlyOneMissingComma = true;
14836 for (unsigned J = I + 1; J < NumInits; ++J) {
14837 const auto *Init = ILE->getInit(J);
14838 if (!Init)
14839 break;
14840 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14841 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14842 OnlyOneMissingComma = false;
14843 break;
14844 }
14845 }
14846
14847 if (OnlyOneMissingComma) {
14849 for (unsigned i = 0; i < NumConcat - 1; ++i)
14850 Hints.push_back(FixItHint::CreateInsertion(
14851 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14852
14853 Diag(SL->getStrTokenLoc(1),
14854 diag::warn_concatenated_literal_array_init)
14855 << Hints;
14856 Diag(SL->getBeginLoc(),
14857 diag::note_concatenated_string_literal_silence);
14858 }
14859 // In any case, stop now.
14860 break;
14861 }
14862 }
14863 }
14864
14865
14866 QualType type = var->getType();
14867
14868 if (var->hasAttr<BlocksAttr>())
14870
14871 Expr *Init = var->getInit();
14872 bool GlobalStorage = var->hasGlobalStorage();
14873 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14874 QualType baseType = Context.getBaseElementType(type);
14875 bool HasConstInit = true;
14876
14877 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14878 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14879 << var;
14880
14881 // Check whether the initializer is sufficiently constant.
14882 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14883 !type->isDependentType() && Init && !Init->isValueDependent() &&
14884 (GlobalStorage || var->isConstexpr() ||
14885 var->mightBeUsableInConstantExpressions(Context))) {
14886 // If this variable might have a constant initializer or might be usable in
14887 // constant expressions, check whether or not it actually is now. We can't
14888 // do this lazily, because the result might depend on things that change
14889 // later, such as which constexpr functions happen to be defined.
14891 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14892 // Prior to C++11, in contexts where a constant initializer is required,
14893 // the set of valid constant initializers is described by syntactic rules
14894 // in [expr.const]p2-6.
14895 // FIXME: Stricter checking for these rules would be useful for constinit /
14896 // -Wglobal-constructors.
14897 HasConstInit = checkConstInit();
14898
14899 // Compute and cache the constant value, and remember that we have a
14900 // constant initializer.
14901 if (HasConstInit) {
14902 if (var->isStaticDataMember() && !var->isInline() &&
14903 var->getLexicalDeclContext()->isRecord() &&
14904 type->isIntegralOrEnumerationType()) {
14905 // In C++98, in-class initialization for a static data member must
14906 // be an integer constant expression.
14907 if (!Init->isIntegerConstantExpr(Context)) {
14908 Diag(Init->getExprLoc(),
14909 diag::ext_in_class_initializer_non_constant)
14910 << Init->getSourceRange();
14911 }
14912 }
14913 (void)var->checkForConstantInitialization(Notes);
14914 Notes.clear();
14915 } else if (CacheCulprit) {
14916 Notes.emplace_back(CacheCulprit->getExprLoc(),
14917 PDiag(diag::note_invalid_subexpr_in_const_expr));
14918 Notes.back().second << CacheCulprit->getSourceRange();
14919 }
14920 } else {
14921 // Evaluate the initializer to see if it's a constant initializer.
14922 HasConstInit = var->checkForConstantInitialization(Notes);
14923 }
14924
14925 if (HasConstInit) {
14926 // FIXME: Consider replacing the initializer with a ConstantExpr.
14927 } else if (var->isConstexpr()) {
14928 SourceLocation DiagLoc = var->getLocation();
14929 // If the note doesn't add any useful information other than a source
14930 // location, fold it into the primary diagnostic.
14931 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14932 diag::note_invalid_subexpr_in_const_expr) {
14933 DiagLoc = Notes[0].first;
14934 Notes.clear();
14935 }
14936 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14937 << var << Init->getSourceRange();
14938 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14939 Diag(Notes[I].first, Notes[I].second);
14940 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14941 auto *Attr = var->getAttr<ConstInitAttr>();
14942 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14943 << Init->getSourceRange();
14944 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14945 << Attr->getRange() << Attr->isConstinit();
14946 for (auto &it : Notes)
14947 Diag(it.first, it.second);
14948 } else if (var->isStaticDataMember() && !var->isInline() &&
14949 var->getLexicalDeclContext()->isRecord()) {
14950 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
14951 << Init->getSourceRange();
14952 for (auto &it : Notes)
14953 Diag(it.first, it.second);
14954 var->setInvalidDecl();
14955 } else if (IsGlobal &&
14956 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14957 var->getLocation())) {
14958 // Warn about globals which don't have a constant initializer. Don't
14959 // warn about globals with a non-trivial destructor because we already
14960 // warned about them.
14961 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14962 if (!(RD && !RD->hasTrivialDestructor())) {
14963 // checkConstInit() here permits trivial default initialization even in
14964 // C++11 onwards, where such an initializer is not a constant initializer
14965 // but nonetheless doesn't require a global constructor.
14966 if (!checkConstInit())
14967 Diag(var->getLocation(), diag::warn_global_constructor)
14968 << Init->getSourceRange();
14969 }
14970 }
14971 }
14972
14973 // Apply section attributes and pragmas to global variables.
14974 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14976 PragmaStack<StringLiteral *> *Stack = nullptr;
14977 int SectionFlags = ASTContext::PSF_Read;
14978 bool MSVCEnv =
14979 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14980 std::optional<QualType::NonConstantStorageReason> Reason;
14981 if (HasConstInit &&
14982 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14983 Stack = &ConstSegStack;
14984 } else {
14985 SectionFlags |= ASTContext::PSF_Write;
14986 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14987 }
14988 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14989 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14990 SectionFlags |= ASTContext::PSF_Implicit;
14991 UnifySection(SA->getName(), SectionFlags, var);
14992 } else if (Stack->CurrentValue) {
14993 if (Stack != &ConstSegStack && MSVCEnv &&
14994 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14995 var->getType().isConstQualified()) {
14996 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14997 NonConstNonReferenceType) &&
14998 "This case should've already been handled elsewhere");
14999 Diag(var->getLocation(), diag::warn_section_msvc_compat)
15000 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15002 : *Reason);
15003 }
15004 SectionFlags |= ASTContext::PSF_Implicit;
15005 auto SectionName = Stack->CurrentValue->getString();
15006 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
15007 Stack->CurrentPragmaLocation,
15008 SectionAttr::Declspec_allocate));
15009 if (UnifySection(SectionName, SectionFlags, var))
15010 var->dropAttr<SectionAttr>();
15011 }
15012
15013 // Apply the init_seg attribute if this has an initializer. If the
15014 // initializer turns out to not be dynamic, we'll end up ignoring this
15015 // attribute.
15016 if (CurInitSeg && var->getInit())
15017 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
15018 CurInitSegLoc));
15019 }
15020
15021 // All the following checks are C++ only.
15022 if (!getLangOpts().CPlusPlus) {
15023 // If this variable must be emitted, add it as an initializer for the
15024 // current module.
15025 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15026 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15027 return;
15028 }
15029
15031
15032 // Require the destructor.
15033 if (!type->isDependentType())
15034 if (auto *RD = baseType->getAsCXXRecordDecl())
15036
15037 // If this variable must be emitted, add it as an initializer for the current
15038 // module.
15039 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15040 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15041
15042 // Build the bindings if this is a structured binding declaration.
15043 if (auto *DD = dyn_cast<DecompositionDecl>(var))
15045}
15046
15048 assert(VD->isStaticLocal());
15049
15050 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15051
15052 // Find outermost function when VD is in lambda function.
15053 while (FD && !getDLLAttr(FD) &&
15054 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15055 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15056 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15057 }
15058
15059 if (!FD)
15060 return;
15061
15062 // Static locals inherit dll attributes from their function.
15063 if (Attr *A = getDLLAttr(FD)) {
15064 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15065 NewAttr->setInherited(true);
15066 VD->addAttr(NewAttr);
15067 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15068 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15069 NewAttr->setInherited(true);
15070 VD->addAttr(NewAttr);
15071
15072 // Export this function to enforce exporting this static variable even
15073 // if it is not used in this compilation unit.
15074 if (!FD->hasAttr<DLLExportAttr>())
15075 FD->addAttr(NewAttr);
15076
15077 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15078 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15079 NewAttr->setInherited(true);
15080 VD->addAttr(NewAttr);
15081 }
15082}
15083
15085 assert(VD->getTLSKind());
15086
15087 // Perform TLS alignment check here after attributes attached to the variable
15088 // which may affect the alignment have been processed. Only perform the check
15089 // if the target has a maximum TLS alignment (zero means no constraints).
15090 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15091 // Protect the check so that it's not performed on dependent types and
15092 // dependent alignments (we can't determine the alignment in that case).
15093 if (!VD->hasDependentAlignment()) {
15094 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15095 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15096 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15097 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15098 << (unsigned)MaxAlignChars.getQuantity();
15099 }
15100 }
15101 }
15102}
15103
15105 // Note that we are no longer parsing the initializer for this declaration.
15106 ParsingInitForAutoVars.erase(ThisDecl);
15107
15108 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15109 if (!VD)
15110 return;
15111
15112 // Emit any deferred warnings for the variable's initializer, even if the
15113 // variable is invalid
15114 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15115
15116 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15118 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15119 if (PragmaClangBSSSection.Valid)
15120 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15121 Context, PragmaClangBSSSection.SectionName,
15122 PragmaClangBSSSection.PragmaLocation));
15123 if (PragmaClangDataSection.Valid)
15124 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15125 Context, PragmaClangDataSection.SectionName,
15126 PragmaClangDataSection.PragmaLocation));
15127 if (PragmaClangRodataSection.Valid)
15128 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15129 Context, PragmaClangRodataSection.SectionName,
15130 PragmaClangRodataSection.PragmaLocation));
15131 if (PragmaClangRelroSection.Valid)
15132 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15133 Context, PragmaClangRelroSection.SectionName,
15134 PragmaClangRelroSection.PragmaLocation));
15135 }
15136
15137 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15138 for (auto *BD : DD->bindings()) {
15140 }
15141 }
15142
15143 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15145
15146 checkAttributesAfterMerging(*this, *VD);
15147
15148 if (VD->isStaticLocal())
15150
15151 if (VD->getTLSKind())
15153
15154 // Perform check for initializers of device-side global variables.
15155 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15156 // 7.5). We must also apply the same checks to all __shared__
15157 // variables whether they are local or not. CUDA also allows
15158 // constant initializers for __constant__ and __device__ variables.
15159 if (getLangOpts().CUDA)
15161
15162 // Grab the dllimport or dllexport attribute off of the VarDecl.
15163 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15164
15165 // Imported static data members cannot be defined out-of-line.
15166 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15167 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15169 // We allow definitions of dllimport class template static data members
15170 // with a warning.
15173 bool IsClassTemplateMember =
15175 Context->getDescribedClassTemplate();
15176
15177 Diag(VD->getLocation(),
15178 IsClassTemplateMember
15179 ? diag::warn_attribute_dllimport_static_field_definition
15180 : diag::err_attribute_dllimport_static_field_definition);
15181 Diag(IA->getLocation(), diag::note_attribute);
15182 if (!IsClassTemplateMember)
15183 VD->setInvalidDecl();
15184 }
15185 }
15186
15187 // dllimport/dllexport variables cannot be thread local, their TLS index
15188 // isn't exported with the variable.
15189 if (DLLAttr && VD->getTLSKind()) {
15190 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15191 if (F && getDLLAttr(F)) {
15192 assert(VD->isStaticLocal());
15193 // But if this is a static local in a dlimport/dllexport function, the
15194 // function will never be inlined, which means the var would never be
15195 // imported, so having it marked import/export is safe.
15196 } else {
15197 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15198 << DLLAttr;
15199 VD->setInvalidDecl();
15200 }
15201 }
15202
15203 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15204 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15205 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15206 << Attr;
15207 VD->dropAttr<UsedAttr>();
15208 }
15209 }
15210 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15211 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15212 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15213 << Attr;
15214 VD->dropAttr<RetainAttr>();
15215 }
15216 }
15217
15218 const DeclContext *DC = VD->getDeclContext();
15219 // If there's a #pragma GCC visibility in scope, and this isn't a class
15220 // member, set the visibility of this variable.
15223
15224 // FIXME: Warn on unused var template partial specializations.
15227
15228 // Now we have parsed the initializer and can update the table of magic
15229 // tag values.
15230 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15232 return;
15233
15234 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15235 const Expr *MagicValueExpr = VD->getInit();
15236 if (!MagicValueExpr) {
15237 continue;
15238 }
15239 std::optional<llvm::APSInt> MagicValueInt;
15240 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15241 Diag(I->getRange().getBegin(),
15242 diag::err_type_tag_for_datatype_not_ice)
15243 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15244 continue;
15245 }
15246 if (MagicValueInt->getActiveBits() > 64) {
15247 Diag(I->getRange().getBegin(),
15248 diag::err_type_tag_for_datatype_too_large)
15249 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15250 continue;
15251 }
15252 uint64_t MagicValue = MagicValueInt->getZExtValue();
15253 RegisterTypeTagForDatatype(I->getArgumentKind(),
15254 MagicValue,
15255 I->getMatchingCType(),
15256 I->getLayoutCompatible(),
15257 I->getMustBeNull());
15258 }
15259}
15260
15262 auto *VD = dyn_cast<VarDecl>(DD);
15263 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15264}
15265
15267 ArrayRef<Decl *> Group) {
15269
15270 if (DS.isTypeSpecOwned())
15271 Decls.push_back(DS.getRepAsDecl());
15272
15273 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15274 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15275 bool DiagnosedMultipleDecomps = false;
15276 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15277 bool DiagnosedNonDeducedAuto = false;
15278
15279 for (Decl *D : Group) {
15280 if (!D)
15281 continue;
15282 // Check if the Decl has been declared in '#pragma omp declare target'
15283 // directive and has static storage duration.
15284 if (auto *VD = dyn_cast<VarDecl>(D);
15285 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15286 VD->hasGlobalStorage())
15288 // For declarators, there are some additional syntactic-ish checks we need
15289 // to perform.
15290 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15291 if (!FirstDeclaratorInGroup)
15292 FirstDeclaratorInGroup = DD;
15293 if (!FirstDecompDeclaratorInGroup)
15294 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15295 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15296 !hasDeducedAuto(DD))
15297 FirstNonDeducedAutoInGroup = DD;
15298
15299 if (FirstDeclaratorInGroup != DD) {
15300 // A decomposition declaration cannot be combined with any other
15301 // declaration in the same group.
15302 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15303 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15304 diag::err_decomp_decl_not_alone)
15305 << FirstDeclaratorInGroup->getSourceRange()
15306 << DD->getSourceRange();
15307 DiagnosedMultipleDecomps = true;
15308 }
15309
15310 // A declarator that uses 'auto' in any way other than to declare a
15311 // variable with a deduced type cannot be combined with any other
15312 // declarator in the same group.
15313 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15314 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15315 diag::err_auto_non_deduced_not_alone)
15316 << FirstNonDeducedAutoInGroup->getType()
15318 << FirstDeclaratorInGroup->getSourceRange()
15319 << DD->getSourceRange();
15320 DiagnosedNonDeducedAuto = true;
15321 }
15322 }
15323 }
15324
15325 Decls.push_back(D);
15326 }
15327
15329 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15330 handleTagNumbering(Tag, S);
15331 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15333 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15334 }
15335 }
15336
15337 return BuildDeclaratorGroup(Decls);
15338}
15339
15342 // C++14 [dcl.spec.auto]p7: (DR1347)
15343 // If the type that replaces the placeholder type is not the same in each
15344 // deduction, the program is ill-formed.
15345 if (Group.size() > 1) {
15346 QualType Deduced;
15347 VarDecl *DeducedDecl = nullptr;
15348 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15349 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15350 if (!D || D->isInvalidDecl())
15351 break;
15352 DeducedType *DT = D->getType()->getContainedDeducedType();
15353 if (!DT || DT->getDeducedType().isNull())
15354 continue;
15355 if (Deduced.isNull()) {
15356 Deduced = DT->getDeducedType();
15357 DeducedDecl = D;
15358 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15359 auto *AT = dyn_cast<AutoType>(DT);
15360 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15361 diag::err_auto_different_deductions)
15362 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15363 << DeducedDecl->getDeclName() << DT->getDeducedType()
15364 << D->getDeclName();
15365 if (DeducedDecl->hasInit())
15366 Dia << DeducedDecl->getInit()->getSourceRange();
15367 if (D->getInit())
15368 Dia << D->getInit()->getSourceRange();
15369 D->setInvalidDecl();
15370 break;
15371 }
15372 }
15373 }
15374
15376
15377 return DeclGroupPtrTy::make(
15378 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15379}
15380
15384
15386 // Don't parse the comment if Doxygen diagnostics are ignored.
15387 if (Group.empty() || !Group[0])
15388 return;
15389
15390 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15391 Group[0]->getLocation()) &&
15392 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15393 Group[0]->getLocation()))
15394 return;
15395
15396 if (Group.size() >= 2) {
15397 // This is a decl group. Normally it will contain only declarations
15398 // produced from declarator list. But in case we have any definitions or
15399 // additional declaration references:
15400 // 'typedef struct S {} S;'
15401 // 'typedef struct S *S;'
15402 // 'struct S *pS;'
15403 // FinalizeDeclaratorGroup adds these as separate declarations.
15404 Decl *MaybeTagDecl = Group[0];
15405 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15406 Group = Group.slice(1);
15407 }
15408 }
15409
15410 // FIMXE: We assume every Decl in the group is in the same file.
15411 // This is false when preprocessor constructs the group from decls in
15412 // different files (e. g. macros or #include).
15413 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15414}
15415
15417 // Check that there are no default arguments inside the type of this
15418 // parameter.
15419 if (getLangOpts().CPlusPlus)
15421
15422 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15423 if (D.getCXXScopeSpec().isSet()) {
15424 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15425 << D.getCXXScopeSpec().getRange();
15426 }
15427
15428 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15429 // simple identifier except [...irrelevant cases...].
15430 switch (D.getName().getKind()) {
15432 break;
15433
15441 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15443 break;
15444
15447 // GetNameForDeclarator would not produce a useful name in this case.
15448 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15449 break;
15450 }
15451}
15452
15454 // This only matters in C.
15455 if (getLangOpts().CPlusPlus)
15456 return;
15457
15458 // This only matters if the declaration has a type.
15459 const auto *VD = dyn_cast<ValueDecl>(D);
15460 if (!VD)
15461 return;
15462
15463 // Get the type, this only matters for tag types.
15464 QualType QT = VD->getType();
15465 const auto *TD = QT->getAsTagDecl();
15466 if (!TD)
15467 return;
15468
15469 // Check if the tag declaration is lexically declared somewhere different
15470 // from the lexical declaration of the given object, then it will be hidden
15471 // in C++ and we should warn on it.
15472 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15473 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15474 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15475 Diag(TD->getLocation(), diag::note_declared_at);
15476 }
15477}
15478
15480 SourceLocation ExplicitThisLoc) {
15481 if (!ExplicitThisLoc.isValid())
15482 return;
15483 assert(S.getLangOpts().CPlusPlus &&
15484 "explicit parameter in non-cplusplus mode");
15485 if (!S.getLangOpts().CPlusPlus23)
15486 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15487 << P->getSourceRange();
15488
15489 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15490 // parameter pack.
15491 if (P->isParameterPack()) {
15492 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15493 << P->getSourceRange();
15494 return;
15495 }
15496 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15497 if (LambdaScopeInfo *LSI = S.getCurLambda())
15498 LSI->ExplicitObjectParameter = P;
15499}
15500
15502 SourceLocation ExplicitThisLoc) {
15503 const DeclSpec &DS = D.getDeclSpec();
15504
15505 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15506 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15507 // except for the special case of a single unnamed parameter of type void
15508 // with no storage class specifier, no type qualifier, and no following
15509 // ellipsis terminator.
15510 // Clang applies the C2y rules for 'register void' in all C language modes,
15511 // same as GCC, because it's questionable what that could possibly mean.
15512
15513 // C++03 [dcl.stc]p2 also permits 'auto'.
15514 StorageClass SC = SC_None;
15516 SC = SC_Register;
15517 // In C++11, the 'register' storage class specifier is deprecated.
15518 // In C++17, it is not allowed, but we tolerate it as an extension.
15519 if (getLangOpts().CPlusPlus11) {
15521 ? diag::ext_register_storage_class
15522 : diag::warn_deprecated_register)
15524 } else if (!getLangOpts().CPlusPlus &&
15526 D.getNumTypeObjects() == 0) {
15528 diag::err_invalid_storage_class_in_func_decl)
15531 }
15532 } else if (getLangOpts().CPlusPlus &&
15534 SC = SC_Auto;
15537 diag::err_invalid_storage_class_in_func_decl);
15539 }
15540
15542 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15544 if (DS.isInlineSpecified())
15545 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15546 << getLangOpts().CPlusPlus17;
15547 if (DS.hasConstexprSpecifier())
15548 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15549 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15550
15552
15554
15556 QualType parmDeclType = TInfo->getType();
15557
15558 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15559 const IdentifierInfo *II = D.getIdentifier();
15560 if (II) {
15563 LookupName(R, S);
15564 if (!R.empty()) {
15565 NamedDecl *PrevDecl = *R.begin();
15566 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15567 // Maybe we will complain about the shadowed template parameter.
15569 // Just pretend that we didn't see the previous declaration.
15570 PrevDecl = nullptr;
15571 }
15572 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15573 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15574 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15575 // Recover by removing the name
15576 II = nullptr;
15577 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15578 D.setInvalidType(true);
15579 }
15580 }
15581 }
15582
15583 // Incomplete resource arrays are not allowed as function parameters in HLSL
15584 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15585 parmDeclType->isHLSLResourceRecordArray()) {
15587 diag::err_hlsl_incomplete_resource_array_in_function_param);
15588 D.setInvalidType(true);
15589 }
15590
15591 // Temporarily put parameter variables in the translation unit, not
15592 // the enclosing context. This prevents them from accidentally
15593 // looking like class members in C++.
15594 ParmVarDecl *New =
15595 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15596 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15597
15598 if (D.isInvalidType())
15599 New->setInvalidDecl();
15600
15601 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15602
15603 assert(S->isFunctionPrototypeScope());
15604 assert(S->getFunctionPrototypeDepth() >= 1);
15605 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15607
15609
15610 // Add the parameter declaration into this scope.
15611 S->AddDecl(New);
15612 if (II)
15613 IdResolver.AddDecl(New);
15614
15616
15618 Diag(New->getLocation(), diag::err_module_private_local)
15621
15622 if (New->hasAttr<BlocksAttr>()) {
15623 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15624 }
15625
15626 if (getLangOpts().OpenCL)
15628
15629 return New;
15630}
15631
15633 SourceLocation Loc,
15634 QualType T) {
15635 /* FIXME: setting StartLoc == Loc.
15636 Would it be worth to modify callers so as to provide proper source
15637 location for the unnamed parameters, embedding the parameter's type? */
15638 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15639 T, Context.getTrivialTypeSourceInfo(T, Loc),
15640 SC_None, nullptr);
15641 Param->setImplicit();
15642 return Param;
15643}
15644
15646 // Don't diagnose unused-parameter errors in template instantiations; we
15647 // will already have done so in the template itself.
15649 return;
15650
15651 for (const ParmVarDecl *Parameter : Parameters) {
15652 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15653 !Parameter->hasAttr<UnusedAttr>() &&
15654 !Parameter->getIdentifier()->isPlaceholder()) {
15655 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15656 << Parameter->getDeclName();
15657 }
15658 }
15659}
15660
15662 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15663 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15664 return;
15665
15666 // Warn if the return value is pass-by-value and larger than the specified
15667 // threshold.
15668 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15669 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15670 if (Size > LangOpts.NumLargeByValueCopy)
15671 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15672 }
15673
15674 // Warn if any parameter is pass-by-value and larger than the specified
15675 // threshold.
15676 for (const ParmVarDecl *Parameter : Parameters) {
15677 QualType T = Parameter->getType();
15678 if (T->isDependentType() || !T.isPODType(Context))
15679 continue;
15680 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15681 if (Size > LangOpts.NumLargeByValueCopy)
15682 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15683 << Parameter << Size;
15684 }
15685}
15686
15688 SourceLocation NameLoc,
15689 const IdentifierInfo *Name, QualType T,
15690 TypeSourceInfo *TSInfo, StorageClass SC) {
15691 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15692 if (getLangOpts().ObjCAutoRefCount &&
15693 T.getObjCLifetime() == Qualifiers::OCL_None &&
15694 T->isObjCLifetimeType()) {
15695
15696 Qualifiers::ObjCLifetime lifetime;
15697
15698 // Special cases for arrays:
15699 // - if it's const, use __unsafe_unretained
15700 // - otherwise, it's an error
15701 if (T->isArrayType()) {
15702 if (!T.isConstQualified()) {
15706 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15707 else
15708 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15709 << TSInfo->getTypeLoc().getSourceRange();
15710 }
15712 } else {
15713 lifetime = T->getObjCARCImplicitLifetime();
15714 }
15715 T = Context.getLifetimeQualifiedType(T, lifetime);
15716 }
15717
15718 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15719 Context.getAdjustedParameterType(T),
15720 TSInfo, SC, nullptr);
15721
15722 // Make a note if we created a new pack in the scope of a lambda, so that
15723 // we know that references to that pack must also be expanded within the
15724 // lambda scope.
15725 if (New->isParameterPack())
15726 if (auto *CSI = getEnclosingLambdaOrBlock())
15727 CSI->LocalPacks.push_back(New);
15728
15729 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15730 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15731 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15734
15735 // Parameter declarators cannot be interface types. All ObjC objects are
15736 // passed by reference.
15737 if (T->isObjCObjectType()) {
15738 SourceLocation TypeEndLoc =
15740 Diag(NameLoc,
15741 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15742 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15743 T = Context.getObjCObjectPointerType(T);
15744 New->setType(T);
15745 }
15746
15747 // __ptrauth is forbidden on parameters.
15748 if (T.getPointerAuth()) {
15749 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
15750 New->setInvalidDecl();
15751 }
15752
15753 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15754 // duration shall not be qualified by an address-space qualifier."
15755 // Since all parameters have automatic store duration, they can not have
15756 // an address space.
15757 if (T.getAddressSpace() != LangAS::Default &&
15758 // OpenCL allows function arguments declared to be an array of a type
15759 // to be qualified with an address space.
15760 !(getLangOpts().OpenCL &&
15761 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15762 // WebAssembly allows reference types as parameters. Funcref in particular
15763 // lives in a different address space.
15764 !(T->isFunctionPointerType() &&
15765 T.getAddressSpace() == LangAS::wasm_funcref)) {
15766 Diag(NameLoc, diag::err_arg_with_address_space);
15767 New->setInvalidDecl();
15768 }
15769
15770 // PPC MMA non-pointer types are not allowed as function argument types.
15771 if (Context.getTargetInfo().getTriple().isPPC64() &&
15772 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15773 New->setInvalidDecl();
15774 }
15775
15776 return New;
15777}
15778
15780 SourceLocation LocAfterDecls) {
15782
15783 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15784 // in the declaration list shall have at least one declarator, those
15785 // declarators shall only declare identifiers from the identifier list, and
15786 // every identifier in the identifier list shall be declared.
15787 //
15788 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15789 // identifiers it names shall be declared in the declaration list."
15790 //
15791 // This is why we only diagnose in C99 and later. Note, the other conditions
15792 // listed are checked elsewhere.
15793 if (!FTI.hasPrototype) {
15794 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15795 --i;
15796 if (FTI.Params[i].Param == nullptr) {
15797 if (getLangOpts().C99) {
15798 SmallString<256> Code;
15799 llvm::raw_svector_ostream(Code)
15800 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15801 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15802 << FTI.Params[i].Ident
15803 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15804 }
15805
15806 // Implicitly declare the argument as type 'int' for lack of a better
15807 // type.
15808 AttributeFactory attrs;
15809 DeclSpec DS(attrs);
15810 const char* PrevSpec; // unused
15811 unsigned DiagID; // unused
15812 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15813 DiagID, Context.getPrintingPolicy());
15814 // Use the identifier location for the type source range.
15815 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15816 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15819 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15820 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15821 }
15822 }
15823 }
15824}
15825
15826Decl *
15828 MultiTemplateParamsArg TemplateParameterLists,
15829 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15830 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15831 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15832 Scope *ParentScope = FnBodyScope->getParent();
15833
15834 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15835 // we define a non-templated function definition, we will create a declaration
15836 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15837 // The base function declaration will have the equivalent of an `omp declare
15838 // variant` annotation which specifies the mangled definition as a
15839 // specialization function under the OpenMP context defined as part of the
15840 // `omp begin declare variant`.
15842 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15844 ParentScope, D, TemplateParameterLists, Bases);
15845
15847 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15848 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15849
15850 if (!Bases.empty())
15852 Bases);
15853
15854 return Dcl;
15855}
15856
15858 Consumer.HandleInlineFunctionDefinition(D);
15859}
15860
15862 const FunctionDecl *&PossiblePrototype) {
15863 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15864 Prev = Prev->getPreviousDecl()) {
15865 // Ignore any declarations that occur in function or method
15866 // scope, because they aren't visible from the header.
15867 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15868 continue;
15869
15870 PossiblePrototype = Prev;
15871 return Prev->getType()->isFunctionProtoType();
15872 }
15873 return false;
15874}
15875
15876static bool
15878 const FunctionDecl *&PossiblePrototype) {
15879 // Don't warn about invalid declarations.
15880 if (FD->isInvalidDecl())
15881 return false;
15882
15883 // Or declarations that aren't global.
15884 if (!FD->isGlobal())
15885 return false;
15886
15887 // Don't warn about C++ member functions.
15888 if (isa<CXXMethodDecl>(FD))
15889 return false;
15890
15891 // Don't warn about 'main'.
15893 if (IdentifierInfo *II = FD->getIdentifier())
15894 if (II->isStr("main") || II->isStr("efi_main"))
15895 return false;
15896
15897 if (FD->isMSVCRTEntryPoint())
15898 return false;
15899
15900 // Don't warn about inline functions.
15901 if (FD->isInlined())
15902 return false;
15903
15904 // Don't warn about function templates.
15906 return false;
15907
15908 // Don't warn about function template specializations.
15910 return false;
15911
15912 // Don't warn for OpenCL kernels.
15913 if (FD->hasAttr<DeviceKernelAttr>())
15914 return false;
15915
15916 // Don't warn on explicitly deleted functions.
15917 if (FD->isDeleted())
15918 return false;
15919
15920 // Don't warn on implicitly local functions (such as having local-typed
15921 // parameters).
15922 if (!FD->isExternallyVisible())
15923 return false;
15924
15925 // If we were able to find a potential prototype, don't warn.
15926 if (FindPossiblePrototype(FD, PossiblePrototype))
15927 return false;
15928
15929 return true;
15930}
15931
15932void
15934 const FunctionDecl *EffectiveDefinition,
15935 SkipBodyInfo *SkipBody) {
15936 const FunctionDecl *Definition = EffectiveDefinition;
15937 if (!Definition &&
15938 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15939 return;
15940
15941 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15942 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15943 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15944 // A merged copy of the same function, instantiated as a member of
15945 // the same class, is OK.
15946 if (declaresSameEntity(OrigFD, OrigDef) &&
15947 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15949 return;
15950 }
15951 }
15952 }
15953
15955 return;
15956
15957 // Don't emit an error when this is redefinition of a typo-corrected
15958 // definition.
15960 return;
15961
15962 bool DefinitionVisible = false;
15963 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&
15964 (Definition->getFormalLinkage() == Linkage::Internal ||
15965 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15966 Definition->getNumTemplateParameterLists())) {
15967 SkipBody->ShouldSkip = true;
15968 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15969 if (!DefinitionVisible) {
15970 if (auto *TD = Definition->getDescribedFunctionTemplate())
15973 }
15974 return;
15975 }
15976
15977 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15978 Definition->getStorageClass() == SC_Extern)
15979 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15980 << FD << getLangOpts().CPlusPlus;
15981 else
15982 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15983
15984 Diag(Definition->getLocation(), diag::note_previous_definition);
15985 FD->setInvalidDecl();
15986}
15987
15989 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15990
15992 LSI->CallOperator = CallOperator;
15993 LSI->Lambda = LambdaClass;
15994 LSI->ReturnType = CallOperator->getReturnType();
15995 // When this function is called in situation where the context of the call
15996 // operator is not entered, we set AfterParameterList to false, so that
15997 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15998 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
15999 // where we would set the CurContext to the lambda operator before
16000 // substituting into it. In this case the flag needs to be true such that
16001 // tryCaptureVariable can correctly handle potential captures thereof.
16002 LSI->AfterParameterList = CurContext == CallOperator;
16003
16004 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16005 // used at the point of dealing with potential captures.
16006 //
16007 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16008 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16009 // associated. (Technically, we could recover that list from their
16010 // instantiation patterns, but for now, the GLTemplateParameterList seems
16011 // unnecessary in these cases.)
16012 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16013 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16014 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16015
16016 if (LCD == LCD_None)
16018 else if (LCD == LCD_ByCopy)
16020 else if (LCD == LCD_ByRef)
16022 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16023
16025 LSI->Mutable = !CallOperator->isConst();
16026 if (CallOperator->isExplicitObjectMemberFunction())
16027 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
16028
16029 // Add the captures to the LSI so they can be noted as already
16030 // captured within tryCaptureVar.
16031 auto I = LambdaClass->field_begin();
16032 for (const auto &C : LambdaClass->captures()) {
16033 if (C.capturesVariable()) {
16034 ValueDecl *VD = C.getCapturedVar();
16035 if (VD->isInitCapture())
16036 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
16037 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16038 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
16039 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
16040 /*EllipsisLoc*/C.isPackExpansion()
16041 ? C.getEllipsisLoc() : SourceLocation(),
16042 I->getType(), /*Invalid*/false);
16043
16044 } else if (C.capturesThis()) {
16045 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
16046 C.getCaptureKind() == LCK_StarThis);
16047 } else {
16048 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
16049 I->getType());
16050 }
16051 ++I;
16052 }
16053 return LSI;
16054}
16055
16057 SkipBodyInfo *SkipBody,
16058 FnBodyKind BodyKind) {
16059 if (!D) {
16060 // Parsing the function declaration failed in some way. Push on a fake scope
16061 // anyway so we can try to parse the function body.
16064 return D;
16065 }
16066
16067 FunctionDecl *FD = nullptr;
16068
16069 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16070 FD = FunTmpl->getTemplatedDecl();
16071 else
16072 FD = cast<FunctionDecl>(D);
16073
16074 // Do not push if it is a lambda because one is already pushed when building
16075 // the lambda in ActOnStartOfLambdaDefinition().
16076 if (!isLambdaCallOperator(FD))
16078 FD);
16079
16080 // Check for defining attributes before the check for redefinition.
16081 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16082 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16083 FD->dropAttr<AliasAttr>();
16084 FD->setInvalidDecl();
16085 }
16086 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16087 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16088 FD->dropAttr<IFuncAttr>();
16089 FD->setInvalidDecl();
16090 }
16091 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16092 if (Context.getTargetInfo().getTriple().isAArch64() &&
16093 !Context.getTargetInfo().hasFeature("fmv") &&
16094 !Attr->isDefaultVersion()) {
16095 // If function multi versioning disabled skip parsing function body
16096 // defined with non-default target_version attribute
16097 if (SkipBody)
16098 SkipBody->ShouldSkip = true;
16099 return nullptr;
16100 }
16101 }
16102
16103 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16104 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16105 Ctor->isDefaultConstructor() &&
16106 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16107 // If this is an MS ABI dllexport default constructor, instantiate any
16108 // default arguments.
16110 }
16111 }
16112
16113 // See if this is a redefinition. If 'will have body' (or similar) is already
16114 // set, then these checks were already performed when it was set.
16115 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16117 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16118
16119 // If we're skipping the body, we're done. Don't enter the scope.
16120 if (SkipBody && SkipBody->ShouldSkip)
16121 return D;
16122 }
16123
16124 // Mark this function as "will have a body eventually". This lets users to
16125 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16126 // this function.
16127 FD->setWillHaveBody();
16128
16129 // If we are instantiating a generic lambda call operator, push
16130 // a LambdaScopeInfo onto the function stack. But use the information
16131 // that's already been calculated (ActOnLambdaExpr) to prime the current
16132 // LambdaScopeInfo.
16133 // When the template operator is being specialized, the LambdaScopeInfo,
16134 // has to be properly restored so that tryCaptureVariable doesn't try
16135 // and capture any new variables. In addition when calculating potential
16136 // captures during transformation of nested lambdas, it is necessary to
16137 // have the LSI properly restored.
16139 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16140 // instantiated, explicitly specialized.
16143 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
16144 FD->setInvalidDecl();
16146 } else {
16147 assert(inTemplateInstantiation() &&
16148 "There should be an active template instantiation on the stack "
16149 "when instantiating a generic lambda!");
16151 }
16152 } else {
16153 // Enter a new function scope
16155 }
16156
16157 // Builtin functions cannot be defined.
16158 if (unsigned BuiltinID = FD->getBuiltinID()) {
16159 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16160 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16161 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16162 FD->setInvalidDecl();
16163 }
16164 }
16165
16166 // The return type of a function definition must be complete (C99 6.9.1p3).
16167 // C++23 [dcl.fct.def.general]/p2
16168 // The type of [...] the return for a function definition
16169 // shall not be a (possibly cv-qualified) class type that is incomplete
16170 // or abstract within the function body unless the function is deleted.
16171 QualType ResultType = FD->getReturnType();
16172 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16173 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16174 (RequireCompleteType(FD->getLocation(), ResultType,
16175 diag::err_func_def_incomplete_result) ||
16177 diag::err_abstract_type_in_decl,
16179 FD->setInvalidDecl();
16180
16181 if (FnBodyScope)
16182 PushDeclContext(FnBodyScope, FD);
16183
16184 // Check the validity of our function parameters
16185 if (BodyKind != FnBodyKind::Delete)
16187 /*CheckParameterNames=*/true);
16188
16189 // Add non-parameter declarations already in the function to the current
16190 // scope.
16191 if (FnBodyScope) {
16192 for (Decl *NPD : FD->decls()) {
16193 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16194 if (!NonParmDecl)
16195 continue;
16196 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16197 "parameters should not be in newly created FD yet");
16198
16199 // If the decl has a name, make it accessible in the current scope.
16200 if (NonParmDecl->getDeclName())
16201 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16202
16203 // Similarly, dive into enums and fish their constants out, making them
16204 // accessible in this scope.
16205 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16206 for (auto *EI : ED->enumerators())
16207 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16208 }
16209 }
16210 }
16211
16212 // Introduce our parameters into the function scope
16213 for (auto *Param : FD->parameters()) {
16214 Param->setOwningFunction(FD);
16215
16216 // If this has an identifier, add it to the scope stack.
16217 if (Param->getIdentifier() && FnBodyScope) {
16218 CheckShadow(FnBodyScope, Param);
16219
16220 PushOnScopeChains(Param, FnBodyScope);
16221 }
16222 }
16223
16224 // C++ [module.import/6]
16225 // ...
16226 // A header unit shall not contain a definition of a non-inline function or
16227 // variable whose name has external linkage.
16228 //
16229 // Deleted and Defaulted functions are implicitly inline (but the
16230 // inline state is not set at this point, so check the BodyKind explicitly).
16231 // We choose to allow weak & selectany definitions, as they are common in
16232 // headers, and have semantics similar to inline definitions which are allowed
16233 // in header units.
16234 // FIXME: Consider an alternate location for the test where the inlined()
16235 // state is complete.
16236 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16237 !FD->isInvalidDecl() && !FD->isInlined() &&
16238 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16239 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16240 !FD->isTemplateInstantiation() &&
16241 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16242 assert(FD->isThisDeclarationADefinition());
16243 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16244 FD->setInvalidDecl();
16245 }
16246
16247 // Ensure that the function's exception specification is instantiated.
16248 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16250
16251 // dllimport cannot be applied to non-inline function definitions.
16252 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16253 !FD->isTemplateInstantiation()) {
16254 assert(!FD->hasAttr<DLLExportAttr>());
16255 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16256 FD->setInvalidDecl();
16257 return D;
16258 }
16259
16260 // Some function attributes (like OptimizeNoneAttr) need actions before
16261 // parsing body started.
16263
16264 // We want to attach documentation to original Decl (which might be
16265 // a function template).
16267 if (getCurLexicalContext()->isObjCContainer() &&
16268 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16269 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16270 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16271
16273
16274 return D;
16275}
16276
16278 if (!FD || FD->isInvalidDecl())
16279 return;
16280 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16281 FD = TD->getTemplatedDecl();
16282 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16285 CurFPFeatures.applyChanges(FPO);
16286 FpPragmaStack.CurrentValue =
16287 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16288 }
16289}
16290
16292 ReturnStmt **Returns = Scope->Returns.data();
16293
16294 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16295 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16296 if (!NRVOCandidate->isNRVOVariable()) {
16297 Diag(Returns[I]->getRetValue()->getExprLoc(),
16298 diag::warn_not_eliding_copy_on_return);
16299 Returns[I]->setNRVOCandidate(nullptr);
16300 }
16301 }
16302 }
16303}
16304
16306 // We can't delay parsing the body of a constexpr function template (yet).
16308 return false;
16309
16310 // We can't delay parsing the body of a function template with a deduced
16311 // return type (yet).
16312 if (D.getDeclSpec().hasAutoTypeSpec()) {
16313 // If the placeholder introduces a non-deduced trailing return type,
16314 // we can still delay parsing it.
16315 if (D.getNumTypeObjects()) {
16316 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16317 if (Outer.Kind == DeclaratorChunk::Function &&
16318 Outer.Fun.hasTrailingReturnType()) {
16319 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16320 return Ty.isNull() || !Ty->isUndeducedType();
16321 }
16322 }
16323 return false;
16324 }
16325
16326 return true;
16327}
16328
16330 // We cannot skip the body of a function (or function template) which is
16331 // constexpr, since we may need to evaluate its body in order to parse the
16332 // rest of the file.
16333 // We cannot skip the body of a function with an undeduced return type,
16334 // because any callers of that function need to know the type.
16335 if (const FunctionDecl *FD = D->getAsFunction()) {
16336 if (FD->isConstexpr())
16337 return false;
16338 // We can't simply call Type::isUndeducedType here, because inside template
16339 // auto can be deduced to a dependent type, which is not considered
16340 // "undeduced".
16341 if (FD->getReturnType()->getContainedDeducedType())
16342 return false;
16343 }
16344 return Consumer.shouldSkipFunctionBody(D);
16345}
16346
16348 if (!Decl)
16349 return nullptr;
16350 if (FunctionDecl *FD = Decl->getAsFunction())
16351 FD->setHasSkippedBody();
16352 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16353 MD->setHasSkippedBody();
16354 return Decl;
16355}
16356
16357/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16358/// body.
16360public:
16361 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16363 if (!IsLambda)
16364 S.PopExpressionEvaluationContext();
16365 }
16366
16367private:
16368 Sema &S;
16369 bool IsLambda = false;
16370};
16371
16373 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16374
16375 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16376 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16377 if (!Inserted)
16378 return It->second;
16379
16380 bool R = false;
16381 const BlockDecl *CurBD = BD;
16382
16383 do {
16384 R = !CurBD->doesNotEscape();
16385 if (R)
16386 break;
16387 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16388 } while (CurBD);
16389
16390 return It->second = R;
16391 };
16392
16393 // If the location where 'self' is implicitly retained is inside a escaping
16394 // block, emit a diagnostic.
16395 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16397 if (IsOrNestedInEscapingBlock(P.second))
16398 S.Diag(P.first, diag::warn_implicitly_retains_self)
16399 << FixItHint::CreateInsertion(P.first, "self->");
16400}
16401
16402static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16403 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16404 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16405}
16406
16408 return methodHasName(FD, "get_return_object");
16409}
16410
16412 return FD->isStatic() &&
16413 methodHasName(FD, "get_return_object_on_allocation_failure");
16414}
16415
16418 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16419 return;
16420 // Allow some_promise_type::get_return_object().
16422 return;
16423 if (!FD->hasAttr<CoroWrapperAttr>())
16424 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16425}
16426
16427Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16428 bool RetainFunctionScopeInfo) {
16430 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16431
16432 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16433 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16434
16435 SourceLocation AnalysisLoc;
16436 if (Body)
16437 AnalysisLoc = Body->getEndLoc();
16438 else if (FD)
16439 AnalysisLoc = FD->getEndLoc();
16441 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16442 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16443
16444 // If we skip function body, we can't tell if a function is a coroutine.
16445 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16446 if (FSI->isCoroutine())
16448 else
16450 }
16451
16452 // Diagnose invalid SYCL kernel entry point function declarations
16453 // and build SYCLKernelCallStmts for valid ones.
16454 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16455 SYCLKernelEntryPointAttr *SKEPAttr =
16456 FD->getAttr<SYCLKernelEntryPointAttr>();
16457 if (FD->isDefaulted()) {
16458 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16459 << SKEPAttr << /*defaulted function*/ 3;
16460 SKEPAttr->setInvalidAttr();
16461 } else if (FD->isDeleted()) {
16462 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16463 << SKEPAttr << /*deleted function*/ 2;
16464 SKEPAttr->setInvalidAttr();
16465 } else if (FSI->isCoroutine()) {
16466 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16467 << SKEPAttr << /*coroutine*/ 7;
16468 SKEPAttr->setInvalidAttr();
16469 } else if (Body && isa<CXXTryStmt>(Body)) {
16470 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16471 << SKEPAttr << /*function defined with a function try block*/ 8;
16472 SKEPAttr->setInvalidAttr();
16473 }
16474
16475 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
16476 StmtResult SR =
16478 if (SR.isInvalid())
16479 return nullptr;
16480 Body = SR.get();
16481 }
16482 }
16483
16484 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16485 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16486 if (FD->isDeletedAsWritten())
16487 Diag(SEAttr->getLocation(),
16488 diag::err_sycl_external_invalid_deleted_function)
16489 << SEAttr;
16490 }
16491
16492 {
16493 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16494 // one is already popped when finishing the lambda in BuildLambdaExpr().
16495 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16496 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16497 if (FD) {
16498 // The function body and the DefaultedOrDeletedInfo, if present, use
16499 // the same storage; don't overwrite the latter if the former is null
16500 // (the body is initialised to null anyway, so even if the latter isn't
16501 // present, this would still be a no-op).
16502 if (Body)
16503 FD->setBody(Body);
16504 FD->setWillHaveBody(false);
16505
16506 if (getLangOpts().CPlusPlus14) {
16507 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16508 FD->getReturnType()->isUndeducedType()) {
16509 // For a function with a deduced result type to return void,
16510 // the result type as written must be 'auto' or 'decltype(auto)',
16511 // possibly cv-qualified or constrained, but not ref-qualified.
16512 if (!FD->getReturnType()->getAs<AutoType>()) {
16513 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16514 << FD->getReturnType();
16515 FD->setInvalidDecl();
16516 } else {
16517 // Falling off the end of the function is the same as 'return;'.
16518 Expr *Dummy = nullptr;
16520 FD, dcl->getLocation(), Dummy,
16521 FD->getReturnType()->getAs<AutoType>()))
16522 FD->setInvalidDecl();
16523 }
16524 }
16525 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16526 // In C++11, we don't use 'auto' deduction rules for lambda call
16527 // operators because we don't support return type deduction.
16528 auto *LSI = getCurLambda();
16529 if (LSI->HasImplicitReturnType) {
16531
16532 // C++11 [expr.prim.lambda]p4:
16533 // [...] if there are no return statements in the compound-statement
16534 // [the deduced type is] the type void
16535 QualType RetType =
16536 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16537
16538 // Update the return type to the deduced type.
16539 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16540 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16541 Proto->getExtProtoInfo()));
16542 }
16543 }
16544
16545 // If the function implicitly returns zero (like 'main') or is naked,
16546 // don't complain about missing return statements.
16547 // Clang implicitly returns 0 in C89 mode, but that's considered an
16548 // extension. The check is necessary to ensure the expected extension
16549 // warning is emitted in C89 mode.
16550 if ((FD->hasImplicitReturnZero() &&
16551 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16552 FD->hasAttr<NakedAttr>())
16554
16555 // MSVC permits the use of pure specifier (=0) on function definition,
16556 // defined at class scope, warn about this non-standard construct.
16557 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16558 !FD->isOutOfLine())
16559 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16560
16561 if (!FD->isInvalidDecl()) {
16562 // Don't diagnose unused parameters of defaulted, deleted or naked
16563 // functions.
16564 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16565 !FD->hasAttr<NakedAttr>())
16568 FD->getReturnType(), FD);
16569
16570 // If this is a structor, we need a vtable.
16571 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16572 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16573 else if (CXXDestructorDecl *Destructor =
16574 dyn_cast<CXXDestructorDecl>(FD))
16575 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16576
16577 // Try to apply the named return value optimization. We have to check
16578 // if we can do this here because lambdas keep return statements around
16579 // to deduce an implicit return type.
16580 if (FD->getReturnType()->isRecordType() &&
16582 computeNRVO(Body, FSI);
16583 }
16584
16585 // GNU warning -Wmissing-prototypes:
16586 // Warn if a global function is defined without a previous
16587 // prototype declaration. This warning is issued even if the
16588 // definition itself provides a prototype. The aim is to detect
16589 // global functions that fail to be declared in header files.
16590 const FunctionDecl *PossiblePrototype = nullptr;
16591 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16592 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16593
16594 if (PossiblePrototype) {
16595 // We found a declaration that is not a prototype,
16596 // but that could be a zero-parameter prototype
16597 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16598 TypeLoc TL = TI->getTypeLoc();
16600 Diag(PossiblePrototype->getLocation(),
16601 diag::note_declaration_not_a_prototype)
16602 << (FD->getNumParams() != 0)
16604 FTL.getRParenLoc(), "void")
16605 : FixItHint{});
16606 }
16607 } else {
16608 // Returns true if the token beginning at this Loc is `const`.
16609 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16610 const LangOptions &LangOpts) {
16611 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16612 if (LocInfo.first.isInvalid())
16613 return false;
16614
16615 bool Invalid = false;
16616 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16617 if (Invalid)
16618 return false;
16619
16620 if (LocInfo.second > Buffer.size())
16621 return false;
16622
16623 const char *LexStart = Buffer.data() + LocInfo.second;
16624 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16625
16626 return StartTok.consume_front("const") &&
16627 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16628 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16629 };
16630
16631 auto findBeginLoc = [&]() {
16632 // If the return type has `const` qualifier, we want to insert
16633 // `static` before `const` (and not before the typename).
16634 if ((FD->getReturnType()->isAnyPointerType() &&
16637 // But only do this if we can determine where the `const` is.
16638
16639 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16640 getLangOpts()))
16641
16642 return FD->getBeginLoc();
16643 }
16644 return FD->getTypeSpecStartLoc();
16645 };
16647 diag::note_static_for_internal_linkage)
16648 << /* function */ 1
16649 << (FD->getStorageClass() == SC_None
16650 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16651 : FixItHint{});
16652 }
16653 }
16654
16655 // We might not have found a prototype because we didn't wish to warn on
16656 // the lack of a missing prototype. Try again without the checks for
16657 // whether we want to warn on the missing prototype.
16658 if (!PossiblePrototype)
16659 (void)FindPossiblePrototype(FD, PossiblePrototype);
16660
16661 // If the function being defined does not have a prototype, then we may
16662 // need to diagnose it as changing behavior in C23 because we now know
16663 // whether the function accepts arguments or not. This only handles the
16664 // case where the definition has no prototype but does have parameters
16665 // and either there is no previous potential prototype, or the previous
16666 // potential prototype also has no actual prototype. This handles cases
16667 // like:
16668 // void f(); void f(a) int a; {}
16669 // void g(a) int a; {}
16670 // See MergeFunctionDecl() for other cases of the behavior change
16671 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16672 // type without a prototype.
16673 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16674 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16675 !PossiblePrototype->isImplicit()))) {
16676 // The function definition has parameters, so this will change behavior
16677 // in C23. If there is a possible prototype, it comes before the
16678 // function definition.
16679 // FIXME: The declaration may have already been diagnosed as being
16680 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16681 // there's no way to test for the "changes behavior" condition in
16682 // SemaType.cpp when forming the declaration's function type. So, we do
16683 // this awkward dance instead.
16684 //
16685 // If we have a possible prototype and it declares a function with a
16686 // prototype, we don't want to diagnose it; if we have a possible
16687 // prototype and it has no prototype, it may have already been
16688 // diagnosed in SemaType.cpp as deprecated depending on whether
16689 // -Wstrict-prototypes is enabled. If we already warned about it being
16690 // deprecated, add a note that it also changes behavior. If we didn't
16691 // warn about it being deprecated (because the diagnostic is not
16692 // enabled), warn now that it is deprecated and changes behavior.
16693
16694 // This K&R C function definition definitely changes behavior in C23,
16695 // so diagnose it.
16696 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16697 << /*definition*/ 1 << /* not supported in C23 */ 0;
16698
16699 // If we have a possible prototype for the function which is a user-
16700 // visible declaration, we already tested that it has no prototype.
16701 // This will change behavior in C23. This gets a warning rather than a
16702 // note because it's the same behavior-changing problem as with the
16703 // definition.
16704 if (PossiblePrototype)
16705 Diag(PossiblePrototype->getLocation(),
16706 diag::warn_non_prototype_changes_behavior)
16707 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16708 << /*definition*/ 1;
16709 }
16710
16711 // Warn on CPUDispatch with an actual body.
16712 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16713 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16714 if (!CmpndBody->body_empty())
16715 Diag(CmpndBody->body_front()->getBeginLoc(),
16716 diag::warn_dispatch_body_ignored);
16717
16718 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16719 const CXXMethodDecl *KeyFunction;
16720 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16721 MD->isVirtual() &&
16722 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16723 MD == KeyFunction->getCanonicalDecl()) {
16724 // Update the key-function state if necessary for this ABI.
16725 if (FD->isInlined() &&
16726 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16727 Context.setNonKeyFunction(MD);
16728
16729 // If the newly-chosen key function is already defined, then we
16730 // need to mark the vtable as used retroactively.
16731 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16732 const FunctionDecl *Definition;
16733 if (KeyFunction && KeyFunction->isDefined(Definition))
16734 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16735 } else {
16736 // We just defined they key function; mark the vtable as used.
16737 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16738 }
16739 }
16740 }
16741
16742 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16743 "Function parsing confused");
16744 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16745 assert(MD == getCurMethodDecl() && "Method parsing confused");
16746 MD->setBody(Body);
16747 if (!MD->isInvalidDecl()) {
16749 MD->getReturnType(), MD);
16750
16751 if (Body)
16752 computeNRVO(Body, FSI);
16753 }
16754 if (FSI->ObjCShouldCallSuper) {
16755 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16756 << MD->getSelector().getAsString();
16757 FSI->ObjCShouldCallSuper = false;
16758 }
16760 const ObjCMethodDecl *InitMethod = nullptr;
16761 bool isDesignated =
16762 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16763 assert(isDesignated && InitMethod);
16764 (void)isDesignated;
16765
16766 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16767 auto IFace = MD->getClassInterface();
16768 if (!IFace)
16769 return false;
16770 auto SuperD = IFace->getSuperClass();
16771 if (!SuperD)
16772 return false;
16773 return SuperD->getIdentifier() ==
16774 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16775 };
16776 // Don't issue this warning for unavailable inits or direct subclasses
16777 // of NSObject.
16778 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16779 Diag(MD->getLocation(),
16780 diag::warn_objc_designated_init_missing_super_call);
16781 Diag(InitMethod->getLocation(),
16782 diag::note_objc_designated_init_marked_here);
16783 }
16785 }
16786 if (FSI->ObjCWarnForNoInitDelegation) {
16787 // Don't issue this warning for unavailable inits.
16788 if (!MD->isUnavailable())
16789 Diag(MD->getLocation(),
16790 diag::warn_objc_secondary_init_missing_init_call);
16791 FSI->ObjCWarnForNoInitDelegation = false;
16792 }
16793
16795 } else {
16796 // Parsing the function declaration failed in some way. Pop the fake scope
16797 // we pushed on.
16798 PopFunctionScopeInfo(ActivePolicy, dcl);
16799 return nullptr;
16800 }
16801
16802 if (Body && FSI->HasPotentialAvailabilityViolations)
16804
16805 assert(!FSI->ObjCShouldCallSuper &&
16806 "This should only be set for ObjC methods, which should have been "
16807 "handled in the block above.");
16808
16809 // Verify and clean out per-function state.
16810 if (Body && (!FD || !FD->isDefaulted())) {
16811 // C++ constructors that have function-try-blocks can't have return
16812 // statements in the handlers of that block. (C++ [except.handle]p14)
16813 // Verify this.
16814 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16816
16817 // Verify that gotos and switch cases don't jump into scopes illegally.
16818 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16820
16821 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16822 if (!Destructor->getParent()->isDependentType())
16824
16826 Destructor->getParent());
16827 }
16828
16829 // If any errors have occurred, clear out any temporaries that may have
16830 // been leftover. This ensures that these temporaries won't be picked up
16831 // for deletion in some later function.
16834 getDiagnostics().getSuppressAllDiagnostics()) {
16836 }
16838 // Since the body is valid, issue any analysis-based warnings that are
16839 // enabled.
16840 ActivePolicy = &WP;
16841 }
16842
16843 if (!IsInstantiation && FD &&
16844 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16845 !FD->isInvalidDecl() &&
16847 FD->setInvalidDecl();
16848
16849 if (FD && FD->hasAttr<NakedAttr>()) {
16850 for (const Stmt *S : Body->children()) {
16851 // Allow local register variables without initializer as they don't
16852 // require prologue.
16853 bool RegisterVariables = false;
16854 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16855 for (const auto *Decl : DS->decls()) {
16856 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16857 RegisterVariables =
16858 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16859 if (!RegisterVariables)
16860 break;
16861 }
16862 }
16863 }
16864 if (RegisterVariables)
16865 continue;
16866 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16867 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16868 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16869 FD->setInvalidDecl();
16870 break;
16871 }
16872 }
16873 }
16874
16875 assert(ExprCleanupObjects.size() ==
16876 ExprEvalContexts.back().NumCleanupObjects &&
16877 "Leftover temporaries in function");
16878 assert(!Cleanup.exprNeedsCleanups() &&
16879 "Unaccounted cleanups in function");
16880 assert(MaybeODRUseExprs.empty() &&
16881 "Leftover expressions for odr-use checking");
16882 }
16883 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16884 // the declaration context below. Otherwise, we're unable to transform
16885 // 'this' expressions when transforming immediate context functions.
16886
16887 if (FD)
16889
16890 if (!IsInstantiation)
16892
16893 if (!RetainFunctionScopeInfo)
16894 PopFunctionScopeInfo(ActivePolicy, dcl);
16895 // If any errors have occurred, clear out any temporaries that may have
16896 // been leftover. This ensures that these temporaries won't be picked up for
16897 // deletion in some later function.
16900 }
16901
16902 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
16903 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
16904 auto ES = getEmissionStatus(FD);
16908 }
16909
16910 if (FD && !FD->isDeleted())
16911 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16912
16913 return dcl;
16914}
16915
16916/// When we finish delayed parsing of an attribute, we must attach it to the
16917/// relevant Decl.
16919 ParsedAttributes &Attrs) {
16920 // Always attach attributes to the underlying decl.
16921 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16922 D = TD->getTemplatedDecl();
16923 ProcessDeclAttributeList(S, D, Attrs);
16924 ProcessAPINotes(D);
16925
16926 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16927 if (Method->isStatic())
16929}
16930
16932 IdentifierInfo &II, Scope *S) {
16933 // It is not valid to implicitly define a function in C23.
16934 assert(LangOpts.implicitFunctionsAllowed() &&
16935 "Implicit function declarations aren't allowed in this language mode");
16936
16937 // Find the scope in which the identifier is injected and the corresponding
16938 // DeclContext.
16939 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16940 // In that case, we inject the declaration into the translation unit scope
16941 // instead.
16942 Scope *BlockScope = S;
16943 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16944 BlockScope = BlockScope->getParent();
16945
16946 // Loop until we find a DeclContext that is either a function/method or the
16947 // translation unit, which are the only two valid places to implicitly define
16948 // a function. This avoids accidentally defining the function within a tag
16949 // declaration, for example.
16950 Scope *ContextScope = BlockScope;
16951 while (!ContextScope->getEntity() ||
16952 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16953 !ContextScope->getEntity()->isTranslationUnit()))
16954 ContextScope = ContextScope->getParent();
16955 ContextRAII SavedContext(*this, ContextScope->getEntity());
16956
16957 // Before we produce a declaration for an implicitly defined
16958 // function, see whether there was a locally-scoped declaration of
16959 // this name as a function or variable. If so, use that
16960 // (non-visible) declaration, and complain about it.
16961 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16962 if (ExternCPrev) {
16963 // We still need to inject the function into the enclosing block scope so
16964 // that later (non-call) uses can see it.
16965 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16966
16967 // C89 footnote 38:
16968 // If in fact it is not defined as having type "function returning int",
16969 // the behavior is undefined.
16970 if (!isa<FunctionDecl>(ExternCPrev) ||
16971 !Context.typesAreCompatible(
16972 cast<FunctionDecl>(ExternCPrev)->getType(),
16973 Context.getFunctionNoProtoType(Context.IntTy))) {
16974 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16975 << ExternCPrev << !getLangOpts().C99;
16976 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16977 return ExternCPrev;
16978 }
16979 }
16980
16981 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16982 unsigned diag_id;
16983 if (II.getName().starts_with("__builtin_"))
16984 diag_id = diag::warn_builtin_unknown;
16985 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16986 else if (getLangOpts().C99)
16987 diag_id = diag::ext_implicit_function_decl_c99;
16988 else
16989 diag_id = diag::warn_implicit_function_decl;
16990
16991 TypoCorrection Corrected;
16992 // Because typo correction is expensive, only do it if the implicit
16993 // function declaration is going to be treated as an error.
16994 //
16995 // Perform the correction before issuing the main diagnostic, as some
16996 // consumers use typo-correction callbacks to enhance the main diagnostic.
16997 if (S && !ExternCPrev &&
16998 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
17000 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
17001 S, nullptr, CCC, CorrectTypoKind::NonError);
17002 }
17003
17004 Diag(Loc, diag_id) << &II;
17005 if (Corrected) {
17006 // If the correction is going to suggest an implicitly defined function,
17007 // skip the correction as not being a particularly good idea.
17008 bool Diagnose = true;
17009 if (const auto *D = Corrected.getCorrectionDecl())
17010 Diagnose = !D->isImplicit();
17011 if (Diagnose)
17012 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
17013 /*ErrorRecovery*/ false);
17014 }
17015
17016 // If we found a prior declaration of this function, don't bother building
17017 // another one. We've already pushed that one into scope, so there's nothing
17018 // more to do.
17019 if (ExternCPrev)
17020 return ExternCPrev;
17021
17022 // Set a Declarator for the implicit definition: int foo();
17023 const char *Dummy;
17024 AttributeFactory attrFactory;
17025 DeclSpec DS(attrFactory);
17026 unsigned DiagID;
17027 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
17028 Context.getPrintingPolicy());
17029 (void)Error; // Silence warning.
17030 assert(!Error && "Error setting up implicit decl!");
17031 SourceLocation NoLoc;
17033 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
17034 /*IsAmbiguous=*/false,
17035 /*LParenLoc=*/NoLoc,
17036 /*Params=*/nullptr,
17037 /*NumParams=*/0,
17038 /*EllipsisLoc=*/NoLoc,
17039 /*RParenLoc=*/NoLoc,
17040 /*RefQualifierIsLvalueRef=*/true,
17041 /*RefQualifierLoc=*/NoLoc,
17042 /*MutableLoc=*/NoLoc, EST_None,
17043 /*ESpecRange=*/SourceRange(),
17044 /*Exceptions=*/nullptr,
17045 /*ExceptionRanges=*/nullptr,
17046 /*NumExceptions=*/0,
17047 /*NoexceptExpr=*/nullptr,
17048 /*ExceptionSpecTokens=*/nullptr,
17049 /*DeclsInPrototype=*/{}, Loc, Loc,
17050 D),
17051 std::move(DS.getAttributes()), SourceLocation());
17052 D.SetIdentifier(&II, Loc);
17053
17054 // Insert this function into the enclosing block scope.
17055 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
17056 FD->setImplicit();
17057
17059
17060 return FD;
17061}
17062
17064 FunctionDecl *FD) {
17065 if (FD->isInvalidDecl())
17066 return;
17067
17068 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17069 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17070 return;
17071
17072 UnsignedOrNone AlignmentParam = std::nullopt;
17073 bool IsNothrow = false;
17074 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17075 return;
17076
17077 // C++2a [basic.stc.dynamic.allocation]p4:
17078 // An allocation function that has a non-throwing exception specification
17079 // indicates failure by returning a null pointer value. Any other allocation
17080 // function never returns a null pointer value and indicates failure only by
17081 // throwing an exception [...]
17082 //
17083 // However, -fcheck-new invalidates this possible assumption, so don't add
17084 // NonNull when that is enabled.
17085 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17086 !getLangOpts().CheckNew)
17087 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17088
17089 // C++2a [basic.stc.dynamic.allocation]p2:
17090 // An allocation function attempts to allocate the requested amount of
17091 // storage. [...] If the request succeeds, the value returned by a
17092 // replaceable allocation function is a [...] pointer value p0 different
17093 // from any previously returned value p1 [...]
17094 //
17095 // However, this particular information is being added in codegen,
17096 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17097
17098 // C++2a [basic.stc.dynamic.allocation]p2:
17099 // An allocation function attempts to allocate the requested amount of
17100 // storage. If it is successful, it returns the address of the start of a
17101 // block of storage whose length in bytes is at least as large as the
17102 // requested size.
17103 if (!FD->hasAttr<AllocSizeAttr>()) {
17104 FD->addAttr(AllocSizeAttr::CreateImplicit(
17105 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17106 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17107 }
17108
17109 // C++2a [basic.stc.dynamic.allocation]p3:
17110 // For an allocation function [...], the pointer returned on a successful
17111 // call shall represent the address of storage that is aligned as follows:
17112 // (3.1) If the allocation function takes an argument of type
17113 // std​::​align_­val_­t, the storage will have the alignment
17114 // specified by the value of this argument.
17115 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17116 FD->addAttr(AllocAlignAttr::CreateImplicit(
17117 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17118 }
17119
17120 // FIXME:
17121 // C++2a [basic.stc.dynamic.allocation]p3:
17122 // For an allocation function [...], the pointer returned on a successful
17123 // call shall represent the address of storage that is aligned as follows:
17124 // (3.2) Otherwise, if the allocation function is named operator new[],
17125 // the storage is aligned for any object that does not have
17126 // new-extended alignment ([basic.align]) and is no larger than the
17127 // requested size.
17128 // (3.3) Otherwise, the storage is aligned for any object that does not
17129 // have new-extended alignment and is of the requested size.
17130}
17131
17133 if (FD->isInvalidDecl())
17134 return;
17135
17136 // If this is a built-in function, map its builtin attributes to
17137 // actual attributes.
17138 if (unsigned BuiltinID = FD->getBuiltinID()) {
17139 // Handle printf-formatting attributes.
17140 unsigned FormatIdx;
17141 bool HasVAListArg;
17142 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17143 if (!FD->hasAttr<FormatAttr>()) {
17144 const char *fmt = "printf";
17145 unsigned int NumParams = FD->getNumParams();
17146 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17147 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17148 fmt = "NSString";
17149 FD->addAttr(FormatAttr::CreateImplicit(Context,
17150 &Context.Idents.get(fmt),
17151 FormatIdx+1,
17152 HasVAListArg ? 0 : FormatIdx+2,
17153 FD->getLocation()));
17154 }
17155 }
17156 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17157 HasVAListArg)) {
17158 if (!FD->hasAttr<FormatAttr>())
17159 FD->addAttr(FormatAttr::CreateImplicit(Context,
17160 &Context.Idents.get("scanf"),
17161 FormatIdx+1,
17162 HasVAListArg ? 0 : FormatIdx+2,
17163 FD->getLocation()));
17164 }
17165
17166 // Handle automatically recognized callbacks.
17167 SmallVector<int, 4> Encoding;
17168 if (!FD->hasAttr<CallbackAttr>() &&
17169 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17170 FD->addAttr(CallbackAttr::CreateImplicit(
17171 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17172
17173 // Mark const if we don't care about errno and/or floating point exceptions
17174 // that are the only thing preventing the function from being const. This
17175 // allows IRgen to use LLVM intrinsics for such functions.
17176 bool NoExceptions =
17178 bool ConstWithoutErrnoAndExceptions =
17179 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17180 bool ConstWithoutExceptions =
17181 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17182 if (!FD->hasAttr<ConstAttr>() &&
17183 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17184 (!ConstWithoutErrnoAndExceptions ||
17185 (!getLangOpts().MathErrno && NoExceptions)) &&
17186 (!ConstWithoutExceptions || NoExceptions))
17187 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17188
17189 // We make "fma" on GNU or Windows const because we know it does not set
17190 // errno in those environments even though it could set errno based on the
17191 // C standard.
17192 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17193 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17194 !FD->hasAttr<ConstAttr>()) {
17195 switch (BuiltinID) {
17196 case Builtin::BI__builtin_fma:
17197 case Builtin::BI__builtin_fmaf:
17198 case Builtin::BI__builtin_fmal:
17199 case Builtin::BIfma:
17200 case Builtin::BIfmaf:
17201 case Builtin::BIfmal:
17202 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17203 break;
17204 default:
17205 break;
17206 }
17207 }
17208
17209 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17210 !FD->hasAttr<ReturnsTwiceAttr>())
17211 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17212 FD->getLocation()));
17213 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17214 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17215 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17216 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17217 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17218 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17219 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17220 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17221 // Add the appropriate attribute, depending on the CUDA compilation mode
17222 // and which target the builtin belongs to. For example, during host
17223 // compilation, aux builtins are __device__, while the rest are __host__.
17224 if (getLangOpts().CUDAIsDevice !=
17225 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17226 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17227 else
17228 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17229 }
17230
17231 // Add known guaranteed alignment for allocation functions.
17232 switch (BuiltinID) {
17233 case Builtin::BImemalign:
17234 case Builtin::BIaligned_alloc:
17235 if (!FD->hasAttr<AllocAlignAttr>())
17236 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17237 FD->getLocation()));
17238 break;
17239 default:
17240 break;
17241 }
17242
17243 // Add allocsize attribute for allocation functions.
17244 switch (BuiltinID) {
17245 case Builtin::BIcalloc:
17246 FD->addAttr(AllocSizeAttr::CreateImplicit(
17247 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17248 break;
17249 case Builtin::BImemalign:
17250 case Builtin::BIaligned_alloc:
17251 case Builtin::BIrealloc:
17252 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17253 ParamIdx(), FD->getLocation()));
17254 break;
17255 case Builtin::BImalloc:
17256 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17257 ParamIdx(), FD->getLocation()));
17258 break;
17259 default:
17260 break;
17261 }
17262 }
17263
17268
17269 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17270 // throw, add an implicit nothrow attribute to any extern "C" function we come
17271 // across.
17272 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17273 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17274 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17275 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17276 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17277 }
17278
17279 IdentifierInfo *Name = FD->getIdentifier();
17280 if (!Name)
17281 return;
17284 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17286 // Okay: this could be a libc/libm/Objective-C function we know
17287 // about.
17288 } else
17289 return;
17290
17291 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17292 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17293 // target-specific builtins, perhaps?
17294 if (!FD->hasAttr<FormatAttr>())
17295 FD->addAttr(FormatAttr::CreateImplicit(Context,
17296 &Context.Idents.get("printf"), 2,
17297 Name->isStr("vasprintf") ? 0 : 3,
17298 FD->getLocation()));
17299 }
17300
17301 if (Name->isStr("__CFStringMakeConstantString")) {
17302 // We already have a __builtin___CFStringMakeConstantString,
17303 // but builds that use -fno-constant-cfstrings don't go through that.
17304 if (!FD->hasAttr<FormatArgAttr>())
17305 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17306 FD->getLocation()));
17307 }
17308}
17309
17311 TypeSourceInfo *TInfo) {
17312 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17313 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17314
17315 if (!TInfo) {
17316 assert(D.isInvalidType() && "no declarator info for valid type");
17317 TInfo = Context.getTrivialTypeSourceInfo(T);
17318 }
17319
17320 // Scope manipulation handled by caller.
17321 TypedefDecl *NewTD =
17323 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17324
17325 // Bail out immediately if we have an invalid declaration.
17326 if (D.isInvalidType()) {
17327 NewTD->setInvalidDecl();
17328 return NewTD;
17329 }
17330
17332 if (CurContext->isFunctionOrMethod())
17333 Diag(NewTD->getLocation(), diag::err_module_private_local)
17334 << 2 << NewTD
17338 else
17339 NewTD->setModulePrivate();
17340 }
17341
17342 // C++ [dcl.typedef]p8:
17343 // If the typedef declaration defines an unnamed class (or
17344 // enum), the first typedef-name declared by the declaration
17345 // to be that class type (or enum type) is used to denote the
17346 // class type (or enum type) for linkage purposes only.
17347 // We need to check whether the type was declared in the declaration.
17348 switch (D.getDeclSpec().getTypeSpecType()) {
17349 case TST_enum:
17350 case TST_struct:
17351 case TST_interface:
17352 case TST_union:
17353 case TST_class: {
17354 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17355 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17356 break;
17357 }
17358
17359 default:
17360 break;
17361 }
17362
17363 return NewTD;
17364}
17365
17367 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17368 QualType T = TI->getType();
17369
17370 if (T->isDependentType())
17371 return false;
17372
17373 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17374 // integral type; any cv-qualification is ignored.
17375 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17376 // non-atomic version of the type specified by the type specifiers in the
17377 // specifier qualifier list.
17378 // Because of how odd C's rule is, we'll let the user know that operations
17379 // involving the enumeration type will be non-atomic.
17380 if (T->isAtomicType())
17381 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17382
17383 Qualifiers Q = T.getQualifiers();
17384 std::optional<unsigned> QualSelect;
17385 if (Q.hasConst() && Q.hasVolatile())
17386 QualSelect = diag::CVQualList::Both;
17387 else if (Q.hasConst())
17388 QualSelect = diag::CVQualList::Const;
17389 else if (Q.hasVolatile())
17390 QualSelect = diag::CVQualList::Volatile;
17391
17392 if (QualSelect)
17393 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17394
17395 T = T.getAtomicUnqualifiedType();
17396
17397 // This doesn't use 'isIntegralType' despite the error message mentioning
17398 // integral type because isIntegralType would also allow enum types in C.
17399 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17400 if (BT->isInteger())
17401 return false;
17402
17403 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17404 << T << T->isBitIntType();
17405}
17406
17408 QualType EnumUnderlyingTy, bool IsFixed,
17409 const EnumDecl *Prev) {
17410 if (IsScoped != Prev->isScoped()) {
17411 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17412 << Prev->isScoped();
17413 Diag(Prev->getLocation(), diag::note_previous_declaration);
17414 return true;
17415 }
17416
17417 if (IsFixed && Prev->isFixed()) {
17418 if (!EnumUnderlyingTy->isDependentType() &&
17419 !Prev->getIntegerType()->isDependentType() &&
17420 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17421 Prev->getIntegerType())) {
17422 // TODO: Highlight the underlying type of the redeclaration.
17423 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17424 << EnumUnderlyingTy << Prev->getIntegerType();
17425 Diag(Prev->getLocation(), diag::note_previous_declaration)
17426 << Prev->getIntegerTypeRange();
17427 return true;
17428 }
17429 } else if (IsFixed != Prev->isFixed()) {
17430 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17431 << Prev->isFixed();
17432 Diag(Prev->getLocation(), diag::note_previous_declaration);
17433 return true;
17434 }
17435
17436 return false;
17437}
17438
17439/// Get diagnostic %select index for tag kind for
17440/// redeclaration diagnostic message.
17441/// WARNING: Indexes apply to particular diagnostics only!
17442///
17443/// \returns diagnostic %select index.
17445 switch (Tag) {
17447 return 0;
17449 return 1;
17450 case TagTypeKind::Class:
17451 return 2;
17452 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17453 }
17454}
17455
17456/// Determine if tag kind is a class-key compatible with
17457/// class for redeclaration (class, struct, or __interface).
17458///
17459/// \returns true iff the tag kind is compatible.
17461{
17462 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17464}
17465
17467 if (isa<TypedefDecl>(PrevDecl))
17468 return NonTagKind::Typedef;
17469 else if (isa<TypeAliasDecl>(PrevDecl))
17470 return NonTagKind::TypeAlias;
17471 else if (isa<ClassTemplateDecl>(PrevDecl))
17472 return NonTagKind::Template;
17473 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17475 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17477 switch (TTK) {
17480 case TagTypeKind::Class:
17481 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17483 case TagTypeKind::Union:
17484 return NonTagKind::NonUnion;
17485 case TagTypeKind::Enum:
17486 return NonTagKind::NonEnum;
17487 }
17488 llvm_unreachable("invalid TTK");
17489}
17490
17492 TagTypeKind NewTag, bool isDefinition,
17493 SourceLocation NewTagLoc,
17494 const IdentifierInfo *Name) {
17495 // C++ [dcl.type.elab]p3:
17496 // The class-key or enum keyword present in the
17497 // elaborated-type-specifier shall agree in kind with the
17498 // declaration to which the name in the elaborated-type-specifier
17499 // refers. This rule also applies to the form of
17500 // elaborated-type-specifier that declares a class-name or
17501 // friend class since it can be construed as referring to the
17502 // definition of the class. Thus, in any
17503 // elaborated-type-specifier, the enum keyword shall be used to
17504 // refer to an enumeration (7.2), the union class-key shall be
17505 // used to refer to a union (clause 9), and either the class or
17506 // struct class-key shall be used to refer to a class (clause 9)
17507 // declared using the class or struct class-key.
17508 TagTypeKind OldTag = Previous->getTagKind();
17509 if (OldTag != NewTag &&
17511 return false;
17512
17513 // Tags are compatible, but we might still want to warn on mismatched tags.
17514 // Non-class tags can't be mismatched at this point.
17516 return true;
17517
17518 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17519 // by our warning analysis. We don't want to warn about mismatches with (eg)
17520 // declarations in system headers that are designed to be specialized, but if
17521 // a user asks us to warn, we should warn if their code contains mismatched
17522 // declarations.
17523 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17524 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17525 Loc);
17526 };
17527 if (IsIgnoredLoc(NewTagLoc))
17528 return true;
17529
17530 auto IsIgnored = [&](const TagDecl *Tag) {
17531 return IsIgnoredLoc(Tag->getLocation());
17532 };
17533 while (IsIgnored(Previous)) {
17534 Previous = Previous->getPreviousDecl();
17535 if (!Previous)
17536 return true;
17537 OldTag = Previous->getTagKind();
17538 }
17539
17540 bool isTemplate = false;
17541 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17542 isTemplate = Record->getDescribedClassTemplate();
17543
17545 if (OldTag != NewTag) {
17546 // In a template instantiation, do not offer fix-its for tag mismatches
17547 // since they usually mess up the template instead of fixing the problem.
17548 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17550 << getRedeclDiagFromTagKind(OldTag);
17551 // FIXME: Note previous location?
17552 }
17553 return true;
17554 }
17555
17556 if (isDefinition) {
17557 // On definitions, check all previous tags and issue a fix-it for each
17558 // one that doesn't match the current tag.
17559 if (Previous->getDefinition()) {
17560 // Don't suggest fix-its for redefinitions.
17561 return true;
17562 }
17563
17564 bool previousMismatch = false;
17565 for (const TagDecl *I : Previous->redecls()) {
17566 if (I->getTagKind() != NewTag) {
17567 // Ignore previous declarations for which the warning was disabled.
17568 if (IsIgnored(I))
17569 continue;
17570
17571 if (!previousMismatch) {
17572 previousMismatch = true;
17573 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17575 << getRedeclDiagFromTagKind(I->getTagKind());
17576 }
17577 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17579 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17581 }
17582 }
17583 return true;
17584 }
17585
17586 // Identify the prevailing tag kind: this is the kind of the definition (if
17587 // there is a non-ignored definition), or otherwise the kind of the prior
17588 // (non-ignored) declaration.
17589 const TagDecl *PrevDef = Previous->getDefinition();
17590 if (PrevDef && IsIgnored(PrevDef))
17591 PrevDef = nullptr;
17592 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17593 if (Redecl->getTagKind() != NewTag) {
17594 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17596 << getRedeclDiagFromTagKind(OldTag);
17597 Diag(Redecl->getLocation(), diag::note_previous_use);
17598
17599 // If there is a previous definition, suggest a fix-it.
17600 if (PrevDef) {
17601 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17605 }
17606 }
17607
17608 return true;
17609}
17610
17611/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17612/// from an outer enclosing namespace or file scope inside a friend declaration.
17613/// This should provide the commented out code in the following snippet:
17614/// namespace N {
17615/// struct X;
17616/// namespace M {
17617/// struct Y { friend struct /*N::*/ X; };
17618/// }
17619/// }
17621 SourceLocation NameLoc) {
17622 // While the decl is in a namespace, do repeated lookup of that name and see
17623 // if we get the same namespace back. If we do not, continue until
17624 // translation unit scope, at which point we have a fully qualified NNS.
17627 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17628 // This tag should be declared in a namespace, which can only be enclosed by
17629 // other namespaces. Bail if there's an anonymous namespace in the chain.
17630 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17631 if (!Namespace || Namespace->isAnonymousNamespace())
17632 return FixItHint();
17633 IdentifierInfo *II = Namespace->getIdentifier();
17634 Namespaces.push_back(II);
17635 NamedDecl *Lookup = SemaRef.LookupSingleName(
17636 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17637 if (Lookup == Namespace)
17638 break;
17639 }
17640
17641 // Once we have all the namespaces, reverse them to go outermost first, and
17642 // build an NNS.
17643 SmallString<64> Insertion;
17644 llvm::raw_svector_ostream OS(Insertion);
17645 if (DC->isTranslationUnit())
17646 OS << "::";
17647 std::reverse(Namespaces.begin(), Namespaces.end());
17648 for (auto *II : Namespaces)
17649 OS << II->getName() << "::";
17650 return FixItHint::CreateInsertion(NameLoc, Insertion);
17651}
17652
17653/// Determine whether a tag originally declared in context \p OldDC can
17654/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17655/// found a declaration in \p OldDC as a previous decl, perhaps through a
17656/// using-declaration).
17658 DeclContext *NewDC) {
17659 OldDC = OldDC->getRedeclContext();
17660 NewDC = NewDC->getRedeclContext();
17661
17662 if (OldDC->Equals(NewDC))
17663 return true;
17664
17665 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17666 // encloses the other).
17667 if (S.getLangOpts().MSVCCompat &&
17668 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17669 return true;
17670
17671 return false;
17672}
17673
17675Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17676 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17677 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17678 SourceLocation ModulePrivateLoc,
17679 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17680 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17681 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17682 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17683 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17684 // If this is not a definition, it must have a name.
17685 IdentifierInfo *OrigName = Name;
17686 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17687 "Nameless record must be a definition!");
17688 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17689
17690 OwnedDecl = false;
17692 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17693
17694 // FIXME: Check member specializations more carefully.
17695 bool isMemberSpecialization = false;
17696 bool IsInjectedClassName = false;
17697 bool Invalid = false;
17698
17699 // We only need to do this matching if we have template parameters
17700 // or a scope specifier, which also conveniently avoids this work
17701 // for non-C++ cases.
17702 if (TemplateParameterLists.size() > 0 ||
17703 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17704 TemplateParameterList *TemplateParams =
17706 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17707 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17708
17709 // C++23 [dcl.type.elab] p2:
17710 // If an elaborated-type-specifier is the sole constituent of a
17711 // declaration, the declaration is ill-formed unless it is an explicit
17712 // specialization, an explicit instantiation or it has one of the
17713 // following forms: [...]
17714 // C++23 [dcl.enum] p1:
17715 // If the enum-head-name of an opaque-enum-declaration contains a
17716 // nested-name-specifier, the declaration shall be an explicit
17717 // specialization.
17718 //
17719 // FIXME: Class template partial specializations can be forward declared
17720 // per CWG2213, but the resolution failed to allow qualified forward
17721 // declarations. This is almost certainly unintentional, so we allow them.
17722 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17723 !isMemberSpecialization)
17724 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17726
17727 if (TemplateParams) {
17728 if (Kind == TagTypeKind::Enum) {
17729 Diag(KWLoc, diag::err_enum_template);
17730 return true;
17731 }
17732
17733 if (TemplateParams->size() > 0) {
17734 // This is a declaration or definition of a class template (which may
17735 // be a member of another template).
17736
17737 if (Invalid)
17738 return true;
17739
17740 OwnedDecl = false;
17742 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17743 AS, ModulePrivateLoc,
17744 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17745 TemplateParameterLists.data(), SkipBody);
17746 return Result.get();
17747 } else {
17748 // The "template<>" header is extraneous.
17749 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17750 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17751 isMemberSpecialization = true;
17752 }
17753 }
17754
17755 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17756 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17757 return true;
17758 }
17759
17760 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17761 // C++23 [dcl.type.elab]p4:
17762 // If an elaborated-type-specifier appears with the friend specifier as
17763 // an entire member-declaration, the member-declaration shall have one
17764 // of the following forms:
17765 // friend class-key nested-name-specifier(opt) identifier ;
17766 // friend class-key simple-template-id ;
17767 // friend class-key nested-name-specifier template(opt)
17768 // simple-template-id ;
17769 //
17770 // Since enum is not a class-key, so declarations like "friend enum E;"
17771 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17772 // invalid, most implementations accept so we issue a pedantic warning.
17773 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17774 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17775 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17776 Diag(KWLoc, diag::note_enum_friend)
17777 << (ScopedEnum + ScopedEnumUsesClassTag);
17778 }
17779
17780 // Figure out the underlying type if this a enum declaration. We need to do
17781 // this early, because it's needed to detect if this is an incompatible
17782 // redeclaration.
17783 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17784 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17785
17786 if (Kind == TagTypeKind::Enum) {
17787 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17788 // No underlying type explicitly specified, or we failed to parse the
17789 // type, default to int.
17790 EnumUnderlying = Context.IntTy.getTypePtr();
17791 } else if (UnderlyingType.get()) {
17792 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17793 // integral type; any cv-qualification is ignored.
17794 // C23 6.7.3.3p5: The underlying type of the enumeration is the
17795 // unqualified, non-atomic version of the type specified by the type
17796 // specifiers in the specifier qualifier list.
17797 TypeSourceInfo *TI = nullptr;
17798 GetTypeFromParser(UnderlyingType.get(), &TI);
17799 EnumUnderlying = TI;
17800
17802 // Recover by falling back to int.
17803 EnumUnderlying = Context.IntTy.getTypePtr();
17804
17807 EnumUnderlying = Context.IntTy.getTypePtr();
17808
17809 // If the underlying type is atomic, we need to adjust the type before
17810 // continuing. This only happens in the case we stored a TypeSourceInfo
17811 // into EnumUnderlying because the other cases are error recovery up to
17812 // this point. But because it's not possible to gin up a TypeSourceInfo
17813 // for a non-atomic type from an atomic one, we'll store into the Type
17814 // field instead. FIXME: it would be nice to have an easy way to get a
17815 // derived TypeSourceInfo which strips qualifiers including the weird
17816 // ones like _Atomic where it forms a different type.
17817 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
17818 TI && TI->getType()->isAtomicType())
17819 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
17820
17821 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17822 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17823 // of 'int'. However, if this is an unfixed forward declaration, don't set
17824 // the underlying type unless the user enables -fms-compatibility. This
17825 // makes unfixed forward declared enums incomplete and is more conforming.
17826 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17827 EnumUnderlying = Context.IntTy.getTypePtr();
17828 }
17829 }
17830
17831 DeclContext *SearchDC = CurContext;
17832 DeclContext *DC = CurContext;
17833 bool isStdBadAlloc = false;
17834 bool isStdAlignValT = false;
17835
17837 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17839
17840 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17841 /// implemented asks for structural equivalence checking, the returned decl
17842 /// here is passed back to the parser, allowing the tag body to be parsed.
17843 auto createTagFromNewDecl = [&]() -> TagDecl * {
17844 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17845 // If there is an identifier, use the location of the identifier as the
17846 // location of the decl, otherwise use the location of the struct/union
17847 // keyword.
17848 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17849 TagDecl *New = nullptr;
17850
17851 if (Kind == TagTypeKind::Enum) {
17852 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17853 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17854 // If this is an undefined enum, bail.
17855 if (TUK != TagUseKind::Definition && !Invalid)
17856 return nullptr;
17857 if (EnumUnderlying) {
17859 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17861 else
17862 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17863 QualType EnumTy = ED->getIntegerType();
17864 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17865 ? Context.getPromotedIntegerType(EnumTy)
17866 : EnumTy);
17867 }
17868 } else { // struct/union
17869 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17870 nullptr);
17871 }
17872
17873 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17874 // Add alignment attributes if necessary; these attributes are checked
17875 // when the ASTContext lays out the structure.
17876 //
17877 // It is important for implementing the correct semantics that this
17878 // happen here (in ActOnTag). The #pragma pack stack is
17879 // maintained as a result of parser callbacks which can occur at
17880 // many points during the parsing of a struct declaration (because
17881 // the #pragma tokens are effectively skipped over during the
17882 // parsing of the struct).
17883 if (TUK == TagUseKind::Definition &&
17884 (!SkipBody || !SkipBody->ShouldSkip)) {
17885 if (LangOpts.HLSL)
17886 RD->addAttr(PackedAttr::CreateImplicit(Context));
17889 }
17890 }
17891 New->setLexicalDeclContext(CurContext);
17892 return New;
17893 };
17894
17895 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17896 if (Name && SS.isNotEmpty()) {
17897 // We have a nested-name tag ('struct foo::bar').
17898
17899 // Check for invalid 'foo::'.
17900 if (SS.isInvalid()) {
17901 Name = nullptr;
17902 goto CreateNewDecl;
17903 }
17904
17905 // If this is a friend or a reference to a class in a dependent
17906 // context, don't try to make a decl for it.
17907 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17908 DC = computeDeclContext(SS, false);
17909 if (!DC) {
17910 IsDependent = true;
17911 return true;
17912 }
17913 } else {
17914 DC = computeDeclContext(SS, true);
17915 if (!DC) {
17916 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17917 << SS.getRange();
17918 return true;
17919 }
17920 }
17921
17922 if (RequireCompleteDeclContext(SS, DC))
17923 return true;
17924
17925 SearchDC = DC;
17926 // Look-up name inside 'foo::'.
17928
17929 if (Previous.isAmbiguous())
17930 return true;
17931
17932 if (Previous.empty()) {
17933 // Name lookup did not find anything. However, if the
17934 // nested-name-specifier refers to the current instantiation,
17935 // and that current instantiation has any dependent base
17936 // classes, we might find something at instantiation time: treat
17937 // this as a dependent elaborated-type-specifier.
17938 // But this only makes any sense for reference-like lookups.
17939 if (Previous.wasNotFoundInCurrentInstantiation() &&
17940 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17941 IsDependent = true;
17942 return true;
17943 }
17944
17945 // A tag 'foo::bar' must already exist.
17946 Diag(NameLoc, diag::err_not_tag_in_scope)
17947 << Kind << Name << DC << SS.getRange();
17948 Name = nullptr;
17949 Invalid = true;
17950 goto CreateNewDecl;
17951 }
17952 } else if (Name) {
17953 // C++14 [class.mem]p14:
17954 // If T is the name of a class, then each of the following shall have a
17955 // name different from T:
17956 // -- every member of class T that is itself a type
17957 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17958 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17959 return true;
17960
17961 // If this is a named struct, check to see if there was a previous forward
17962 // declaration or definition.
17963 // FIXME: We're looking into outer scopes here, even when we
17964 // shouldn't be. Doing so can result in ambiguities that we
17965 // shouldn't be diagnosing.
17966 LookupName(Previous, S);
17967
17968 // When declaring or defining a tag, ignore ambiguities introduced
17969 // by types using'ed into this scope.
17970 if (Previous.isAmbiguous() &&
17972 LookupResult::Filter F = Previous.makeFilter();
17973 while (F.hasNext()) {
17974 NamedDecl *ND = F.next();
17975 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17976 SearchDC->getRedeclContext()))
17977 F.erase();
17978 }
17979 F.done();
17980 }
17981
17982 // C++11 [namespace.memdef]p3:
17983 // If the name in a friend declaration is neither qualified nor
17984 // a template-id and the declaration is a function or an
17985 // elaborated-type-specifier, the lookup to determine whether
17986 // the entity has been previously declared shall not consider
17987 // any scopes outside the innermost enclosing namespace.
17988 //
17989 // MSVC doesn't implement the above rule for types, so a friend tag
17990 // declaration may be a redeclaration of a type declared in an enclosing
17991 // scope. They do implement this rule for friend functions.
17992 //
17993 // Does it matter that this should be by scope instead of by
17994 // semantic context?
17995 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17996 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17997 LookupResult::Filter F = Previous.makeFilter();
17998 bool FriendSawTagOutsideEnclosingNamespace = false;
17999 while (F.hasNext()) {
18000 NamedDecl *ND = F.next();
18002 if (DC->isFileContext() &&
18003 !EnclosingNS->Encloses(ND->getDeclContext())) {
18004 if (getLangOpts().MSVCCompat)
18005 FriendSawTagOutsideEnclosingNamespace = true;
18006 else
18007 F.erase();
18008 }
18009 }
18010 F.done();
18011
18012 // Diagnose this MSVC extension in the easy case where lookup would have
18013 // unambiguously found something outside the enclosing namespace.
18014 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18015 NamedDecl *ND = Previous.getFoundDecl();
18016 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
18017 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
18018 }
18019 }
18020
18021 // Note: there used to be some attempt at recovery here.
18022 if (Previous.isAmbiguous())
18023 return true;
18024
18025 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18026 // FIXME: This makes sure that we ignore the contexts associated
18027 // with C structs, unions, and enums when looking for a matching
18028 // tag declaration or definition. See the similar lookup tweak
18029 // in Sema::LookupName; is there a better way to deal with this?
18031 SearchDC = SearchDC->getParent();
18032 } else if (getLangOpts().CPlusPlus) {
18033 // Inside ObjCContainer want to keep it as a lexical decl context but go
18034 // past it (most often to TranslationUnit) to find the semantic decl
18035 // context.
18036 while (isa<ObjCContainerDecl>(SearchDC))
18037 SearchDC = SearchDC->getParent();
18038 }
18039 } else if (getLangOpts().CPlusPlus) {
18040 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18041 // TagDecl the same way as we skip it for named TagDecl.
18042 while (isa<ObjCContainerDecl>(SearchDC))
18043 SearchDC = SearchDC->getParent();
18044 }
18045
18046 if (Previous.isSingleResult() &&
18047 Previous.getFoundDecl()->isTemplateParameter()) {
18048 // Maybe we will complain about the shadowed template parameter.
18049 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
18050 // Just pretend that we didn't see the previous declaration.
18051 Previous.clear();
18052 }
18053
18054 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18055 DC->Equals(getStdNamespace())) {
18056 if (Name->isStr("bad_alloc")) {
18057 // This is a declaration of or a reference to "std::bad_alloc".
18058 isStdBadAlloc = true;
18059
18060 // If std::bad_alloc has been implicitly declared (but made invisible to
18061 // name lookup), fill in this implicit declaration as the previous
18062 // declaration, so that the declarations get chained appropriately.
18063 if (Previous.empty() && StdBadAlloc)
18064 Previous.addDecl(getStdBadAlloc());
18065 } else if (Name->isStr("align_val_t")) {
18066 isStdAlignValT = true;
18067 if (Previous.empty() && StdAlignValT)
18068 Previous.addDecl(getStdAlignValT());
18069 }
18070 }
18071
18072 // If we didn't find a previous declaration, and this is a reference
18073 // (or friend reference), move to the correct scope. In C++, we
18074 // also need to do a redeclaration lookup there, just in case
18075 // there's a shadow friend decl.
18076 if (Name && Previous.empty() &&
18077 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18078 IsTemplateParamOrArg)) {
18079 if (Invalid) goto CreateNewDecl;
18080 assert(SS.isEmpty());
18081
18082 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18083 // C++ [basic.scope.pdecl]p5:
18084 // -- for an elaborated-type-specifier of the form
18085 //
18086 // class-key identifier
18087 //
18088 // if the elaborated-type-specifier is used in the
18089 // decl-specifier-seq or parameter-declaration-clause of a
18090 // function defined in namespace scope, the identifier is
18091 // declared as a class-name in the namespace that contains
18092 // the declaration; otherwise, except as a friend
18093 // declaration, the identifier is declared in the smallest
18094 // non-class, non-function-prototype scope that contains the
18095 // declaration.
18096 //
18097 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18098 // C structs and unions.
18099 //
18100 // It is an error in C++ to declare (rather than define) an enum
18101 // type, including via an elaborated type specifier. We'll
18102 // diagnose that later; for now, declare the enum in the same
18103 // scope as we would have picked for any other tag type.
18104 //
18105 // GNU C also supports this behavior as part of its incomplete
18106 // enum types extension, while GNU C++ does not.
18107 //
18108 // Find the context where we'll be declaring the tag.
18109 // FIXME: We would like to maintain the current DeclContext as the
18110 // lexical context,
18111 SearchDC = getTagInjectionContext(SearchDC);
18112
18113 // Find the scope where we'll be declaring the tag.
18115 } else {
18116 assert(TUK == TagUseKind::Friend);
18117 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18118
18119 // C++ [namespace.memdef]p3:
18120 // If a friend declaration in a non-local class first declares a
18121 // class or function, the friend class or function is a member of
18122 // the innermost enclosing namespace.
18123 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18124 : SearchDC->getEnclosingNamespaceContext();
18125 }
18126
18127 // In C++, we need to do a redeclaration lookup to properly
18128 // diagnose some problems.
18129 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18130 // hidden declaration so that we don't get ambiguity errors when using a
18131 // type declared by an elaborated-type-specifier. In C that is not correct
18132 // and we should instead merge compatible types found by lookup.
18133 if (getLangOpts().CPlusPlus) {
18134 // FIXME: This can perform qualified lookups into function contexts,
18135 // which are meaningless.
18136 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18137 LookupQualifiedName(Previous, SearchDC);
18138 } else {
18139 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18140 LookupName(Previous, S);
18141 }
18142 }
18143
18144 // If we have a known previous declaration to use, then use it.
18145 if (Previous.empty() && SkipBody && SkipBody->Previous)
18146 Previous.addDecl(SkipBody->Previous);
18147
18148 if (!Previous.empty()) {
18149 NamedDecl *PrevDecl = Previous.getFoundDecl();
18150 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18151
18152 // It's okay to have a tag decl in the same scope as a typedef
18153 // which hides a tag decl in the same scope. Finding this
18154 // with a redeclaration lookup can only actually happen in C++.
18155 //
18156 // This is also okay for elaborated-type-specifiers, which is
18157 // technically forbidden by the current standard but which is
18158 // okay according to the likely resolution of an open issue;
18159 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18160 if (getLangOpts().CPlusPlus) {
18161 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18162 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18163 if (Tag->getDeclName() == Name &&
18164 Tag->getDeclContext()->getRedeclContext()
18165 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18166 PrevDecl = Tag;
18167 Previous.clear();
18168 Previous.addDecl(Tag);
18169 Previous.resolveKind();
18170 }
18171 }
18172 } else if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18173 TUK == TagUseKind::Reference && RD &&
18174 RD->isInjectedClassName()) {
18175 // If lookup found the injected class name, the previous declaration is
18176 // the class being injected into.
18177 PrevDecl = cast<TagDecl>(RD->getDeclContext());
18178 Previous.clear();
18179 Previous.addDecl(PrevDecl);
18180 Previous.resolveKind();
18181 IsInjectedClassName = true;
18182 }
18183 }
18184
18185 // If this is a redeclaration of a using shadow declaration, it must
18186 // declare a tag in the same context. In MSVC mode, we allow a
18187 // redefinition if either context is within the other.
18188 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18189 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18190 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18191 TUK != TagUseKind::Friend &&
18192 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18193 !(OldTag && isAcceptableTagRedeclContext(
18194 *this, OldTag->getDeclContext(), SearchDC))) {
18195 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18196 Diag(Shadow->getTargetDecl()->getLocation(),
18197 diag::note_using_decl_target);
18198 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18199 << 0;
18200 // Recover by ignoring the old declaration.
18201 Previous.clear();
18202 goto CreateNewDecl;
18203 }
18204 }
18205
18206 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18207 // If this is a use of a previous tag, or if the tag is already declared
18208 // in the same scope (so that the definition/declaration completes or
18209 // rementions the tag), reuse the decl.
18210 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18211 isDeclInScope(DirectPrevDecl, SearchDC, S,
18212 SS.isNotEmpty() || isMemberSpecialization)) {
18213 // Make sure that this wasn't declared as an enum and now used as a
18214 // struct or something similar.
18215 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18216 TUK == TagUseKind::Definition, KWLoc,
18217 Name)) {
18218 bool SafeToContinue =
18219 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18220 Kind != TagTypeKind::Enum);
18221 if (SafeToContinue)
18222 Diag(KWLoc, diag::err_use_with_wrong_tag)
18223 << Name
18225 PrevTagDecl->getKindName());
18226 else
18227 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18228 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18229
18230 if (SafeToContinue)
18231 Kind = PrevTagDecl->getTagKind();
18232 else {
18233 // Recover by making this an anonymous redefinition.
18234 Name = nullptr;
18235 Previous.clear();
18236 Invalid = true;
18237 }
18238 }
18239
18240 if (Kind == TagTypeKind::Enum &&
18241 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18242 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18243 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18244 return PrevTagDecl;
18245
18246 QualType EnumUnderlyingTy;
18247 if (TypeSourceInfo *TI =
18248 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18249 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18250 else if (const Type *T =
18251 dyn_cast_if_present<const Type *>(EnumUnderlying))
18252 EnumUnderlyingTy = QualType(T, 0);
18253
18254 // All conflicts with previous declarations are recovered by
18255 // returning the previous declaration, unless this is a definition,
18256 // in which case we want the caller to bail out.
18257 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18258 ScopedEnum, EnumUnderlyingTy,
18259 IsFixed, PrevEnum))
18260 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18261 }
18262
18263 // C++11 [class.mem]p1:
18264 // A member shall not be declared twice in the member-specification,
18265 // except that a nested class or member class template can be declared
18266 // and then later defined.
18267 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18268 S->isDeclScope(PrevDecl)) {
18269 Diag(NameLoc, diag::ext_member_redeclared);
18270 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18271 }
18272
18273 if (!Invalid) {
18274 // If this is a use, just return the declaration we found, unless
18275 // we have attributes.
18276 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18277 if (!Attrs.empty()) {
18278 // FIXME: Diagnose these attributes. For now, we create a new
18279 // declaration to hold them.
18280 } else if (TUK == TagUseKind::Reference &&
18281 (PrevTagDecl->getFriendObjectKind() ==
18283 PrevDecl->getOwningModule() != getCurrentModule()) &&
18284 SS.isEmpty()) {
18285 // This declaration is a reference to an existing entity, but
18286 // has different visibility from that entity: it either makes
18287 // a friend visible or it makes a type visible in a new module.
18288 // In either case, create a new declaration. We only do this if
18289 // the declaration would have meant the same thing if no prior
18290 // declaration were found, that is, if it was found in the same
18291 // scope where we would have injected a declaration.
18292 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18293 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18294 return PrevTagDecl;
18295 // This is in the injected scope, create a new declaration in
18296 // that scope.
18298 } else {
18299 return PrevTagDecl;
18300 }
18301 }
18302
18303 // Diagnose attempts to redefine a tag.
18304 if (TUK == TagUseKind::Definition) {
18305 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18306 // If the type is currently being defined, complain
18307 // about a nested redefinition.
18308 if (Def->isBeingDefined()) {
18309 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18310 Diag(PrevTagDecl->getLocation(),
18311 diag::note_previous_definition);
18312 Name = nullptr;
18313 Previous.clear();
18314 Invalid = true;
18315 } else {
18316 // If we're defining a specialization and the previous
18317 // definition is from an implicit instantiation, don't emit an
18318 // error here; we'll catch this in the general case below.
18319 bool IsExplicitSpecializationAfterInstantiation = false;
18320 if (isMemberSpecialization) {
18321 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18322 IsExplicitSpecializationAfterInstantiation =
18323 RD->getTemplateSpecializationKind() !=
18325 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18326 IsExplicitSpecializationAfterInstantiation =
18327 ED->getTemplateSpecializationKind() !=
18329 }
18330
18331 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18332 // do not keep more that one definition around (merge them).
18333 // However, ensure the decl passes the structural compatibility
18334 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18335 NamedDecl *Hidden = nullptr;
18336 bool HiddenDefVisible = false;
18337 if (SkipBody &&
18338 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||
18339 getLangOpts().C23)) {
18340 // There is a definition of this tag, but it is not visible.
18341 // We explicitly make use of C++'s one definition rule here,
18342 // and assume that this definition is identical to the hidden
18343 // one we already have. Make the existing definition visible
18344 // and use it in place of this one.
18345 if (!getLangOpts().CPlusPlus) {
18346 // Postpone making the old definition visible until after we
18347 // complete parsing the new one and do the structural
18348 // comparison.
18349 SkipBody->CheckSameAsPrevious = true;
18350 SkipBody->New = createTagFromNewDecl();
18351 SkipBody->Previous = Def;
18352
18353 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18354 return Def;
18355 }
18356
18357 SkipBody->ShouldSkip = true;
18358 SkipBody->Previous = Def;
18359 if (!HiddenDefVisible && Hidden)
18361 // Carry on and handle it like a normal definition. We'll
18362 // skip starting the definition later.
18363
18364 } else if (!IsExplicitSpecializationAfterInstantiation) {
18365 // A redeclaration in function prototype scope in C isn't
18366 // visible elsewhere, so merely issue a warning.
18367 if (!getLangOpts().CPlusPlus &&
18369 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18370 << Name;
18371 else
18372 Diag(NameLoc, diag::err_redefinition) << Name;
18374 NameLoc.isValid() ? NameLoc : KWLoc);
18375 // If this is a redefinition, recover by making this
18376 // struct be anonymous, which will make any later
18377 // references get the previous definition.
18378 Name = nullptr;
18379 Previous.clear();
18380 Invalid = true;
18381 }
18382 }
18383 }
18384
18385 // Okay, this is definition of a previously declared or referenced
18386 // tag. We're going to create a new Decl for it.
18387 }
18388
18389 // Okay, we're going to make a redeclaration. If this is some kind
18390 // of reference, make sure we build the redeclaration in the same DC
18391 // as the original, and ignore the current access specifier.
18392 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18393 SearchDC = PrevTagDecl->getDeclContext();
18394 AS = AS_none;
18395 }
18396 }
18397 // If we get here we have (another) forward declaration or we
18398 // have a definition. Just create a new decl.
18399
18400 } else {
18401 // If we get here, this is a definition of a new tag type in a nested
18402 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18403 // new decl/type. We set PrevDecl to NULL so that the entities
18404 // have distinct types.
18405 Previous.clear();
18406 }
18407 // If we get here, we're going to create a new Decl. If PrevDecl
18408 // is non-NULL, it's a definition of the tag declared by
18409 // PrevDecl. If it's NULL, we have a new definition.
18410
18411 // Otherwise, PrevDecl is not a tag, but was found with tag
18412 // lookup. This is only actually possible in C++, where a few
18413 // things like templates still live in the tag namespace.
18414 } else {
18415 // Use a better diagnostic if an elaborated-type-specifier
18416 // found the wrong kind of type on the first
18417 // (non-redeclaration) lookup.
18418 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18419 !Previous.isForRedeclaration()) {
18420 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18421 Diag(NameLoc, diag::err_tag_reference_non_tag)
18422 << PrevDecl << NTK << Kind;
18423 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18424 Invalid = true;
18425
18426 // Otherwise, only diagnose if the declaration is in scope.
18427 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18428 SS.isNotEmpty() || isMemberSpecialization)) {
18429 // do nothing
18430
18431 // Diagnose implicit declarations introduced by elaborated types.
18432 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18433 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18434 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18435 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18436 Invalid = true;
18437
18438 // Otherwise it's a declaration. Call out a particularly common
18439 // case here.
18440 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18441 unsigned Kind = 0;
18442 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18443 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18444 << Name << Kind << TND->getUnderlyingType();
18445 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18446 Invalid = true;
18447
18448 // Otherwise, diagnose.
18449 } else {
18450 // The tag name clashes with something else in the target scope,
18451 // issue an error and recover by making this tag be anonymous.
18452 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18453 notePreviousDefinition(PrevDecl, NameLoc);
18454 Name = nullptr;
18455 Invalid = true;
18456 }
18457
18458 // The existing declaration isn't relevant to us; we're in a
18459 // new scope, so clear out the previous declaration.
18460 Previous.clear();
18461 }
18462 }
18463
18464CreateNewDecl:
18465
18466 TagDecl *PrevDecl = nullptr;
18467 if (Previous.isSingleResult())
18468 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18469
18470 // If there is an identifier, use the location of the identifier as the
18471 // location of the decl, otherwise use the location of the struct/union
18472 // keyword.
18473 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18474
18475 // Otherwise, create a new declaration. If there is a previous
18476 // declaration of the same entity, the two will be linked via
18477 // PrevDecl.
18478 TagDecl *New;
18479
18480 if (Kind == TagTypeKind::Enum) {
18481 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18482 // enum X { A, B, C } D; D should chain to X.
18483 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18484 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18485 ScopedEnumUsesClassTag, IsFixed);
18486
18487 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18489
18490 // If this is an undefined enum, warn.
18491 if (TUK != TagUseKind::Definition && !Invalid) {
18492 TagDecl *Def;
18493 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
18494 // C++0x: 7.2p2: opaque-enum-declaration.
18495 // Conflicts are diagnosed above. Do nothing.
18496 }
18497 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18498 Diag(Loc, diag::ext_forward_ref_enum_def)
18499 << New;
18500 Diag(Def->getLocation(), diag::note_previous_definition);
18501 } else {
18502 unsigned DiagID = diag::ext_forward_ref_enum;
18503 if (getLangOpts().MSVCCompat)
18504 DiagID = diag::ext_ms_forward_ref_enum;
18505 else if (getLangOpts().CPlusPlus)
18506 DiagID = diag::err_forward_ref_enum;
18507 Diag(Loc, DiagID);
18508 }
18509 }
18510
18511 if (EnumUnderlying) {
18513 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18515 else
18516 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18517 QualType EnumTy = ED->getIntegerType();
18518 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18519 ? Context.getPromotedIntegerType(EnumTy)
18520 : EnumTy);
18521 assert(ED->isComplete() && "enum with type should be complete");
18522 }
18523 } else {
18524 // struct/union/class
18525
18526 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18527 // struct X { int A; } D; D should chain to X.
18528 if (getLangOpts().CPlusPlus) {
18529 // FIXME: Look for a way to use RecordDecl for simple structs.
18530 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18531 cast_or_null<CXXRecordDecl>(PrevDecl));
18532
18533 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18535 } else
18536 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18537 cast_or_null<RecordDecl>(PrevDecl));
18538 }
18539
18540 // Only C23 and later allow defining new types in 'offsetof()'.
18541 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18543 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18544 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18545
18546 // C++11 [dcl.type]p3:
18547 // A type-specifier-seq shall not define a class or enumeration [...].
18548 if (!Invalid && getLangOpts().CPlusPlus &&
18549 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18550 TUK == TagUseKind::Definition) {
18551 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18552 << Context.getCanonicalTagType(New);
18553 Invalid = true;
18554 }
18555
18557 DC->getDeclKind() == Decl::Enum) {
18558 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18559 << Context.getCanonicalTagType(New);
18560 Invalid = true;
18561 }
18562
18563 // Maybe add qualifier info.
18564 if (SS.isNotEmpty()) {
18565 if (SS.isSet()) {
18566 // If this is either a declaration or a definition, check the
18567 // nested-name-specifier against the current context.
18568 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18569 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18570 /*TemplateId=*/nullptr,
18571 isMemberSpecialization))
18572 Invalid = true;
18573
18574 New->setQualifierInfo(SS.getWithLocInContext(Context));
18575 if (TemplateParameterLists.size() > 0) {
18576 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18577 }
18578 }
18579 else
18580 Invalid = true;
18581 }
18582
18583 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18584 // Add alignment attributes if necessary; these attributes are checked when
18585 // the ASTContext lays out the structure.
18586 //
18587 // It is important for implementing the correct semantics that this
18588 // happen here (in ActOnTag). The #pragma pack stack is
18589 // maintained as a result of parser callbacks which can occur at
18590 // many points during the parsing of a struct declaration (because
18591 // the #pragma tokens are effectively skipped over during the
18592 // parsing of the struct).
18593 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18594 if (LangOpts.HLSL)
18595 RD->addAttr(PackedAttr::CreateImplicit(Context));
18598 }
18599 }
18600
18601 if (ModulePrivateLoc.isValid()) {
18602 if (isMemberSpecialization)
18603 Diag(New->getLocation(), diag::err_module_private_specialization)
18604 << 2
18605 << FixItHint::CreateRemoval(ModulePrivateLoc);
18606 // __module_private__ does not apply to local classes. However, we only
18607 // diagnose this as an error when the declaration specifiers are
18608 // freestanding. Here, we just ignore the __module_private__.
18609 else if (!SearchDC->isFunctionOrMethod())
18610 New->setModulePrivate();
18611 }
18612
18613 // If this is a specialization of a member class (of a class template),
18614 // check the specialization.
18615 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18616 Invalid = true;
18617
18618 // If we're declaring or defining a tag in function prototype scope in C,
18619 // note that this type can only be used within the function and add it to
18620 // the list of decls to inject into the function definition scope. However,
18621 // in C23 and later, while the type is only visible within the function, the
18622 // function can be called with a compatible type defined in the same TU, so
18623 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18624 if ((Name || Kind == TagTypeKind::Enum) &&
18625 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18626 if (getLangOpts().CPlusPlus) {
18627 // C++ [dcl.fct]p6:
18628 // Types shall not be defined in return or parameter types.
18629 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18630 Diag(Loc, diag::err_type_defined_in_param_type)
18631 << Name;
18632 Invalid = true;
18633 }
18634 if (TUK == TagUseKind::Declaration)
18635 Invalid = true;
18636 } else if (!PrevDecl) {
18637 // In C23 mode, if the declaration is complete, we do not want to
18638 // diagnose.
18639 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18640 Diag(Loc, diag::warn_decl_in_param_list)
18641 << Context.getCanonicalTagType(New);
18642 }
18643 }
18644
18645 if (Invalid)
18646 New->setInvalidDecl();
18647
18648 // Set the lexical context. If the tag has a C++ scope specifier, the
18649 // lexical context will be different from the semantic context.
18650 New->setLexicalDeclContext(CurContext);
18651
18652 // Mark this as a friend decl if applicable.
18653 // In Microsoft mode, a friend declaration also acts as a forward
18654 // declaration so we always pass true to setObjectOfFriendDecl to make
18655 // the tag name visible.
18656 if (TUK == TagUseKind::Friend)
18657 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18658
18659 // Set the access specifier.
18660 if (!Invalid && SearchDC->isRecord())
18661 SetMemberAccessSpecifier(New, PrevDecl, AS);
18662
18663 if (PrevDecl)
18665
18666 if (TUK == TagUseKind::Definition) {
18667 if (!SkipBody || !SkipBody->ShouldSkip) {
18668 New->startDefinition();
18669 } else {
18670 New->setCompleteDefinition();
18671 New->demoteThisDefinitionToDeclaration();
18672 }
18673 }
18674
18675 ProcessDeclAttributeList(S, New, Attrs);
18677
18678 // If this has an identifier, add it to the scope stack.
18679 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18680 // We might be replacing an existing declaration in the lookup tables;
18681 // if so, borrow its access specifier.
18682 if (PrevDecl)
18683 New->setAccess(PrevDecl->getAccess());
18684
18685 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18687 if (Name) // can be null along some error paths
18688 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18689 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18690 } else if (Name) {
18691 S = getNonFieldDeclScope(S);
18692 PushOnScopeChains(New, S, true);
18693 } else {
18694 CurContext->addDecl(New);
18695 }
18696
18697 // If this is the C FILE type, notify the AST context.
18698 if (IdentifierInfo *II = New->getIdentifier())
18699 if (!New->isInvalidDecl() &&
18700 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18701 II->isStr("FILE"))
18702 Context.setFILEDecl(New);
18703
18704 if (PrevDecl)
18705 mergeDeclAttributes(New, PrevDecl);
18706
18707 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18710 }
18711
18712 // If there's a #pragma GCC visibility in scope, set the visibility of this
18713 // record.
18715
18716 // If this is not a definition, process API notes for it now.
18717 if (TUK != TagUseKind::Definition)
18719
18720 if (isMemberSpecialization && !New->isInvalidDecl())
18722
18723 OwnedDecl = true;
18724 // In C++, don't return an invalid declaration. We can't recover well from
18725 // the cases where we make the type anonymous.
18726 if (Invalid && getLangOpts().CPlusPlus) {
18727 if (New->isBeingDefined())
18728 if (auto RD = dyn_cast<RecordDecl>(New))
18729 RD->completeDefinition();
18730 return true;
18731 } else if (SkipBody && SkipBody->ShouldSkip) {
18732 return SkipBody->Previous;
18733 } else {
18734 return New;
18735 }
18736}
18737
18740 TagDecl *Tag = cast<TagDecl>(TagD);
18741
18742 // Enter the tag context.
18743 PushDeclContext(S, Tag);
18744
18746
18747 // If there's a #pragma GCC visibility in scope, set the visibility of this
18748 // record.
18750}
18751
18753 SkipBodyInfo &SkipBody) {
18754 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18755 return false;
18756
18757 // Make the previous decl visible.
18759 CleanupMergedEnum(S, SkipBody.New);
18760 return true;
18761}
18762
18764 Scope *S, Decl *TagD, SourceLocation FinalLoc, bool IsFinalSpelledSealed,
18765 bool IsAbstract, SourceLocation TriviallyRelocatable,
18766 SourceLocation Replaceable, SourceLocation LBraceLoc) {
18769
18770 FieldCollector->StartClass();
18771
18772 if (!Record->getIdentifier())
18773 return;
18774
18775 if (IsAbstract)
18776 Record->markAbstract();
18777
18778 if (FinalLoc.isValid()) {
18779 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18780 IsFinalSpelledSealed
18781 ? FinalAttr::Keyword_sealed
18782 : FinalAttr::Keyword_final));
18783 }
18784
18785 if (TriviallyRelocatable.isValid())
18786 Record->addAttr(
18787 TriviallyRelocatableAttr::Create(Context, TriviallyRelocatable));
18788
18789 if (Replaceable.isValid())
18790 Record->addAttr(ReplaceableAttr::Create(Context, Replaceable));
18791
18792 // C++ [class]p2:
18793 // [...] The class-name is also inserted into the scope of the
18794 // class itself; this is known as the injected-class-name. For
18795 // purposes of access checking, the injected-class-name is treated
18796 // as if it were a public member name.
18797 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18798 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18799 Record->getLocation(), Record->getIdentifier());
18800 InjectedClassName->setImplicit();
18801 InjectedClassName->setAccess(AS_public);
18802 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18803 InjectedClassName->setDescribedClassTemplate(Template);
18804
18805 PushOnScopeChains(InjectedClassName, S);
18806 assert(InjectedClassName->isInjectedClassName() &&
18807 "Broken injected-class-name");
18808}
18809
18811 SourceRange BraceRange) {
18813 TagDecl *Tag = cast<TagDecl>(TagD);
18814 Tag->setBraceRange(BraceRange);
18815
18816 // Make sure we "complete" the definition even it is invalid.
18817 if (Tag->isBeingDefined()) {
18818 assert(Tag->isInvalidDecl() && "We should already have completed it");
18819 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18820 RD->completeDefinition();
18821 }
18822
18823 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18824 FieldCollector->FinishClass();
18825 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18826 auto *Def = RD->getDefinition();
18827 assert(Def && "The record is expected to have a completed definition");
18828 unsigned NumInitMethods = 0;
18829 for (auto *Method : Def->methods()) {
18830 if (!Method->getIdentifier())
18831 continue;
18832 if (Method->getName() == "__init")
18833 NumInitMethods++;
18834 }
18835 if (NumInitMethods > 1 || !Def->hasInitMethod())
18836 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18837 }
18838
18839 // If we're defining a dynamic class in a module interface unit, we always
18840 // need to produce the vtable for it, even if the vtable is not used in the
18841 // current TU.
18842 //
18843 // The case where the current class is not dynamic is handled in
18844 // MarkVTableUsed.
18845 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18846 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18847 }
18848
18849 // Exit this scope of this tag's definition.
18851
18852 if (getCurLexicalContext()->isObjCContainer() &&
18853 Tag->getDeclContext()->isFileContext())
18854 Tag->setTopLevelDeclInObjCContainer();
18855
18856 // Notify the consumer that we've defined a tag.
18857 if (!Tag->isInvalidDecl())
18858 Consumer.HandleTagDeclDefinition(Tag);
18859
18860 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18861 // from XLs and instead matches the XL #pragma pack(1) behavior.
18862 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18863 AlignPackStack.hasValue()) {
18864 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18865 // Only diagnose #pragma align(packed).
18866 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18867 return;
18868 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18869 if (!RD)
18870 return;
18871 // Only warn if there is at least 1 bitfield member.
18872 if (llvm::any_of(RD->fields(),
18873 [](const FieldDecl *FD) { return FD->isBitField(); }))
18874 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18875 }
18876}
18877
18880 TagDecl *Tag = cast<TagDecl>(TagD);
18881 Tag->setInvalidDecl();
18882
18883 // Make sure we "complete" the definition even it is invalid.
18884 if (Tag->isBeingDefined()) {
18885 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18886 RD->completeDefinition();
18887 }
18888
18889 // We're undoing ActOnTagStartDefinition here, not
18890 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18891 // the FieldCollector.
18892
18894}
18895
18896// Note that FieldName may be null for anonymous bitfields.
18898 const IdentifierInfo *FieldName,
18899 QualType FieldTy, bool IsMsStruct,
18900 Expr *BitWidth) {
18901 assert(BitWidth);
18902 if (BitWidth->containsErrors())
18903 return ExprError();
18904
18905 // C99 6.7.2.1p4 - verify the field type.
18906 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18907 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18908 // Handle incomplete and sizeless types with a specific error.
18909 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18910 diag::err_field_incomplete_or_sizeless))
18911 return ExprError();
18912 if (FieldName)
18913 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18914 << FieldName << FieldTy << BitWidth->getSourceRange();
18915 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18916 << FieldTy << BitWidth->getSourceRange();
18918 return ExprError();
18919
18920 // If the bit-width is type- or value-dependent, don't try to check
18921 // it now.
18922 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18923 return BitWidth;
18924
18925 llvm::APSInt Value;
18926 ExprResult ICE =
18928 if (ICE.isInvalid())
18929 return ICE;
18930 BitWidth = ICE.get();
18931
18932 // Zero-width bitfield is ok for anonymous field.
18933 if (Value == 0 && FieldName)
18934 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18935 << FieldName << BitWidth->getSourceRange();
18936
18937 if (Value.isSigned() && Value.isNegative()) {
18938 if (FieldName)
18939 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18940 << FieldName << toString(Value, 10);
18941 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18942 << toString(Value, 10);
18943 }
18944
18945 // The size of the bit-field must not exceed our maximum permitted object
18946 // size.
18947 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18948 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18949 << !FieldName << FieldName << toString(Value, 10);
18950 }
18951
18952 if (!FieldTy->isDependentType()) {
18953 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18954 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18955 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18956
18957 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18958 // ABI.
18959 bool CStdConstraintViolation =
18960 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18961 bool MSBitfieldViolation =
18962 Value.ugt(TypeStorageSize) &&
18963 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18964 if (CStdConstraintViolation || MSBitfieldViolation) {
18965 unsigned DiagWidth =
18966 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18967 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18968 << (bool)FieldName << FieldName << toString(Value, 10)
18969 << !CStdConstraintViolation << DiagWidth;
18970 }
18971
18972 // Warn on types where the user might conceivably expect to get all
18973 // specified bits as value bits: that's all integral types other than
18974 // 'bool'.
18975 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18976 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18977 << FieldName << Value << (unsigned)TypeWidth;
18978 }
18979 }
18980
18981 if (isa<ConstantExpr>(BitWidth))
18982 return BitWidth;
18983 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
18984}
18985
18987 Declarator &D, Expr *BitfieldWidth) {
18988 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18989 D, BitfieldWidth,
18990 /*InitStyle=*/ICIS_NoInit, AS_public);
18991 return Res;
18992}
18993
18995 SourceLocation DeclStart,
18996 Declarator &D, Expr *BitWidth,
18997 InClassInitStyle InitStyle,
18998 AccessSpecifier AS) {
18999 if (D.isDecompositionDeclarator()) {
19001 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
19002 << Decomp.getSourceRange();
19003 return nullptr;
19004 }
19005
19006 const IdentifierInfo *II = D.getIdentifier();
19007 SourceLocation Loc = DeclStart;
19008 if (II) Loc = D.getIdentifierLoc();
19009
19011 QualType T = TInfo->getType();
19012 if (getLangOpts().CPlusPlus) {
19014
19017 D.setInvalidType();
19018 T = Context.IntTy;
19019 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19020 }
19021 }
19022
19024
19026 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19027 << getLangOpts().CPlusPlus17;
19030 diag::err_invalid_thread)
19032
19033 // Check to see if this name was declared as a member previously
19034 NamedDecl *PrevDecl = nullptr;
19035 LookupResult Previous(*this, II, Loc, LookupMemberName,
19037 LookupName(Previous, S);
19038 switch (Previous.getResultKind()) {
19041 PrevDecl = Previous.getAsSingle<NamedDecl>();
19042 break;
19043
19045 PrevDecl = Previous.getRepresentativeDecl();
19046 break;
19047
19051 break;
19052 }
19053 Previous.suppressDiagnostics();
19054
19055 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19056 // Maybe we will complain about the shadowed template parameter.
19058 // Just pretend that we didn't see the previous declaration.
19059 PrevDecl = nullptr;
19060 }
19061
19062 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19063 PrevDecl = nullptr;
19064
19065 bool Mutable
19066 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19067 SourceLocation TSSL = D.getBeginLoc();
19068 FieldDecl *NewFD
19069 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
19070 TSSL, AS, PrevDecl, &D);
19071
19072 if (NewFD->isInvalidDecl())
19073 Record->setInvalidDecl();
19074
19076 NewFD->setModulePrivate();
19077
19078 if (NewFD->isInvalidDecl() && PrevDecl) {
19079 // Don't introduce NewFD into scope; there's already something
19080 // with the same name in the same scope.
19081 } else if (II) {
19082 PushOnScopeChains(NewFD, S);
19083 } else
19084 Record->addDecl(NewFD);
19085
19086 return NewFD;
19087}
19088
19090 TypeSourceInfo *TInfo,
19092 bool Mutable, Expr *BitWidth,
19093 InClassInitStyle InitStyle,
19094 SourceLocation TSSL,
19095 AccessSpecifier AS, NamedDecl *PrevDecl,
19096 Declarator *D) {
19097 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19098 bool InvalidDecl = false;
19099 if (D) InvalidDecl = D->isInvalidType();
19100
19101 // If we receive a broken type, recover by assuming 'int' and
19102 // marking this declaration as invalid.
19103 if (T.isNull() || T->containsErrors()) {
19104 InvalidDecl = true;
19105 T = Context.IntTy;
19106 }
19107
19108 QualType EltTy = Context.getBaseElementType(T);
19109 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19110 bool isIncomplete =
19111 LangOpts.HLSL // HLSL allows sizeless builtin types
19112 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19113 : RequireCompleteSizedType(Loc, EltTy,
19114 diag::err_field_incomplete_or_sizeless);
19115 if (isIncomplete) {
19116 // Fields of incomplete type force their record to be invalid.
19117 Record->setInvalidDecl();
19118 InvalidDecl = true;
19119 } else {
19120 NamedDecl *Def;
19121 EltTy->isIncompleteType(&Def);
19122 if (Def && Def->isInvalidDecl()) {
19123 Record->setInvalidDecl();
19124 InvalidDecl = true;
19125 }
19126 }
19127 }
19128
19129 // TR 18037 does not allow fields to be declared with address space
19130 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19131 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19132 Diag(Loc, diag::err_field_with_address_space);
19133 Record->setInvalidDecl();
19134 InvalidDecl = true;
19135 }
19136
19137 if (LangOpts.OpenCL) {
19138 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19139 // used as structure or union field: image, sampler, event or block types.
19140 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19141 T->isBlockPointerType()) {
19142 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19143 Record->setInvalidDecl();
19144 InvalidDecl = true;
19145 }
19146 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19147 // is enabled.
19148 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19149 "__cl_clang_bitfields", LangOpts)) {
19150 Diag(Loc, diag::err_opencl_bitfields);
19151 InvalidDecl = true;
19152 }
19153 }
19154
19155 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19156 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19157 T.hasQualifiers()) {
19158 InvalidDecl = true;
19159 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19160 }
19161
19162 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19163 // than a variably modified type.
19164 if (!InvalidDecl && T->isVariablyModifiedType()) {
19166 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19167 InvalidDecl = true;
19168 }
19169
19170 // Fields can not have abstract class types
19171 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19172 diag::err_abstract_type_in_decl,
19174 InvalidDecl = true;
19175
19176 if (InvalidDecl)
19177 BitWidth = nullptr;
19178 // If this is declared as a bit-field, check the bit-field.
19179 if (BitWidth) {
19180 BitWidth =
19181 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19182 if (!BitWidth) {
19183 InvalidDecl = true;
19184 BitWidth = nullptr;
19185 }
19186 }
19187
19188 // Check that 'mutable' is consistent with the type of the declaration.
19189 if (!InvalidDecl && Mutable) {
19190 unsigned DiagID = 0;
19191 if (T->isReferenceType())
19192 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19193 : diag::err_mutable_reference;
19194 else if (T.isConstQualified())
19195 DiagID = diag::err_mutable_const;
19196
19197 if (DiagID) {
19198 SourceLocation ErrLoc = Loc;
19199 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19200 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19201 Diag(ErrLoc, DiagID);
19202 if (DiagID != diag::ext_mutable_reference) {
19203 Mutable = false;
19204 InvalidDecl = true;
19205 }
19206 }
19207 }
19208
19209 // C++11 [class.union]p8 (DR1460):
19210 // At most one variant member of a union may have a
19211 // brace-or-equal-initializer.
19212 if (InitStyle != ICIS_NoInit)
19214
19215 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19216 BitWidth, Mutable, InitStyle);
19217 if (InvalidDecl)
19218 NewFD->setInvalidDecl();
19219
19220 if (!InvalidDecl)
19222
19223 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19224 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19225 Diag(Loc, diag::err_duplicate_member) << II;
19226 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19227 NewFD->setInvalidDecl();
19228 }
19229
19230 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19231 if (Record->isUnion()) {
19232 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19233 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19234
19235 // C++ [class.union]p1: An object of a class with a non-trivial
19236 // constructor, a non-trivial copy constructor, a non-trivial
19237 // destructor, or a non-trivial copy assignment operator
19238 // cannot be a member of a union, nor can an array of such
19239 // objects.
19240 if (CheckNontrivialField(NewFD))
19241 NewFD->setInvalidDecl();
19242 }
19243
19244 // C++ [class.union]p1: If a union contains a member of reference type,
19245 // the program is ill-formed, except when compiling with MSVC extensions
19246 // enabled.
19247 if (EltTy->isReferenceType()) {
19248 const bool HaveMSExt =
19249 getLangOpts().MicrosoftExt &&
19251
19252 Diag(NewFD->getLocation(),
19253 HaveMSExt ? diag::ext_union_member_of_reference_type
19254 : diag::err_union_member_of_reference_type)
19255 << NewFD->getDeclName() << EltTy;
19256 if (!HaveMSExt)
19257 NewFD->setInvalidDecl();
19258 }
19259 }
19260 }
19261
19262 // FIXME: We need to pass in the attributes given an AST
19263 // representation, not a parser representation.
19264 if (D) {
19265 // FIXME: The current scope is almost... but not entirely... correct here.
19266 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19267
19268 if (NewFD->hasAttrs())
19270 }
19271
19272 // In auto-retain/release, infer strong retension for fields of
19273 // retainable type.
19274 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19275 NewFD->setInvalidDecl();
19276
19277 if (T.isObjCGCWeak())
19278 Diag(Loc, diag::warn_attribute_weak_on_field);
19279
19280 // PPC MMA non-pointer types are not allowed as field types.
19281 if (Context.getTargetInfo().getTriple().isPPC64() &&
19282 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19283 NewFD->setInvalidDecl();
19284
19285 NewFD->setAccess(AS);
19286 return NewFD;
19287}
19288
19290 assert(FD);
19291 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19292
19293 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19294 return false;
19295
19296 QualType EltTy = Context.getBaseElementType(FD->getType());
19297 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19298 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19299 // We check for copy constructors before constructors
19300 // because otherwise we'll never get complaints about
19301 // copy constructors.
19302
19304 // We're required to check for any non-trivial constructors. Since the
19305 // implicit default constructor is suppressed if there are any
19306 // user-declared constructors, we just need to check that there is a
19307 // trivial default constructor and a trivial copy constructor. (We don't
19308 // worry about move constructors here, since this is a C++98 check.)
19309 if (RDecl->hasNonTrivialCopyConstructor())
19311 else if (!RDecl->hasTrivialDefaultConstructor())
19313 else if (RDecl->hasNonTrivialCopyAssignment())
19315 else if (RDecl->hasNonTrivialDestructor())
19317
19318 if (member != CXXSpecialMemberKind::Invalid) {
19319 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19320 RDecl->hasObjectMember()) {
19321 // Objective-C++ ARC: it is an error to have a non-trivial field of
19322 // a union. However, system headers in Objective-C programs
19323 // occasionally have Objective-C lifetime objects within unions,
19324 // and rather than cause the program to fail, we make those
19325 // members unavailable.
19326 SourceLocation Loc = FD->getLocation();
19327 if (getSourceManager().isInSystemHeader(Loc)) {
19328 if (!FD->hasAttr<UnavailableAttr>())
19329 FD->addAttr(UnavailableAttr::CreateImplicit(
19330 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19331 return false;
19332 }
19333 }
19334
19335 Diag(FD->getLocation(),
19337 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19338 : diag::err_illegal_union_or_anon_struct_member)
19339 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19340 DiagnoseNontrivial(RDecl, member);
19341 return !getLangOpts().CPlusPlus11;
19342 }
19343 }
19344
19345 return false;
19346}
19347
19349 SmallVectorImpl<Decl *> &AllIvarDecls) {
19350 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19351 return;
19352
19353 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19354 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19355
19356 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19357 return;
19358 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19359 if (!ID) {
19360 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19361 if (!CD->IsClassExtension())
19362 return;
19363 }
19364 // No need to add this to end of @implementation.
19365 else
19366 return;
19367 }
19368 // All conditions are met. Add a new bitfield to the tail end of ivars.
19369 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19370 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19371 Expr *BitWidth =
19372 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19373
19374 Ivar = ObjCIvarDecl::Create(
19375 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19376 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19377 ObjCIvarDecl::Private, BitWidth, true);
19378 AllIvarDecls.push_back(Ivar);
19379}
19380
19381/// [class.dtor]p4:
19382/// At the end of the definition of a class, overload resolution is
19383/// performed among the prospective destructors declared in that class with
19384/// an empty argument list to select the destructor for the class, also
19385/// known as the selected destructor.
19386///
19387/// We do the overload resolution here, then mark the selected constructor in the AST.
19388/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19390 if (!Record->hasUserDeclaredDestructor()) {
19391 return;
19392 }
19393
19394 SourceLocation Loc = Record->getLocation();
19396
19397 for (auto *Decl : Record->decls()) {
19398 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19399 if (DD->isInvalidDecl())
19400 continue;
19401 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19402 OCS);
19403 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19404 }
19405 }
19406
19407 if (OCS.empty()) {
19408 return;
19409 }
19411 unsigned Msg = 0;
19412 OverloadCandidateDisplayKind DisplayKind;
19413
19414 switch (OCS.BestViableFunction(S, Loc, Best)) {
19415 case OR_Success:
19416 case OR_Deleted:
19417 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19418 break;
19419
19420 case OR_Ambiguous:
19421 Msg = diag::err_ambiguous_destructor;
19422 DisplayKind = OCD_AmbiguousCandidates;
19423 break;
19424
19426 Msg = diag::err_no_viable_destructor;
19427 DisplayKind = OCD_AllCandidates;
19428 break;
19429 }
19430
19431 if (Msg) {
19432 // OpenCL have got their own thing going with destructors. It's slightly broken,
19433 // but we allow it.
19434 if (!S.LangOpts.OpenCL) {
19435 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19436 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19437 Record->setInvalidDecl();
19438 }
19439 // It's a bit hacky: At this point we've raised an error but we want the
19440 // rest of the compiler to continue somehow working. However almost
19441 // everything we'll try to do with the class will depend on there being a
19442 // destructor. So let's pretend the first one is selected and hope for the
19443 // best.
19444 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19445 }
19446}
19447
19448/// [class.mem.special]p5
19449/// Two special member functions are of the same kind if:
19450/// - they are both default constructors,
19451/// - they are both copy or move constructors with the same first parameter
19452/// type, or
19453/// - they are both copy or move assignment operators with the same first
19454/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19456 CXXMethodDecl *M1,
19457 CXXMethodDecl *M2,
19459 // We don't want to compare templates to non-templates: See
19460 // https://github.com/llvm/llvm-project/issues/59206
19462 return bool(M1->getDescribedFunctionTemplate()) ==
19464 // FIXME: better resolve CWG
19465 // https://cplusplus.github.io/CWG/issues/2787.html
19466 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19467 M2->getNonObjectParameter(0)->getType()))
19468 return false;
19469 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
19471 return false;
19472
19473 return true;
19474}
19475
19476/// [class.mem.special]p6:
19477/// An eligible special member function is a special member function for which:
19478/// - the function is not deleted,
19479/// - the associated constraints, if any, are satisfied, and
19480/// - no special member function of the same kind whose associated constraints
19481/// [CWG2595], if any, are satisfied is more constrained.
19485 SmallVector<bool, 4> SatisfactionStatus;
19486
19487 for (CXXMethodDecl *Method : Methods) {
19488 if (!Method->getTrailingRequiresClause())
19489 SatisfactionStatus.push_back(true);
19490 else {
19491 ConstraintSatisfaction Satisfaction;
19492 if (S.CheckFunctionConstraints(Method, Satisfaction))
19493 SatisfactionStatus.push_back(false);
19494 else
19495 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19496 }
19497 }
19498
19499 for (size_t i = 0; i < Methods.size(); i++) {
19500 if (!SatisfactionStatus[i])
19501 continue;
19502 CXXMethodDecl *Method = Methods[i];
19503 CXXMethodDecl *OrigMethod = Method;
19504 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19505 OrigMethod = cast<CXXMethodDecl>(MF);
19506
19508 bool AnotherMethodIsMoreConstrained = false;
19509 for (size_t j = 0; j < Methods.size(); j++) {
19510 if (i == j || !SatisfactionStatus[j])
19511 continue;
19512 CXXMethodDecl *OtherMethod = Methods[j];
19513 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19514 OtherMethod = cast<CXXMethodDecl>(MF);
19515
19516 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19517 CSM))
19518 continue;
19519
19521 if (!Other)
19522 continue;
19523 if (!Orig) {
19524 AnotherMethodIsMoreConstrained = true;
19525 break;
19526 }
19527 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
19528 AnotherMethodIsMoreConstrained)) {
19529 // There was an error with the constraints comparison. Exit the loop
19530 // and don't consider this function eligible.
19531 AnotherMethodIsMoreConstrained = true;
19532 }
19533 if (AnotherMethodIsMoreConstrained)
19534 break;
19535 }
19536 // FIXME: Do not consider deleted methods as eligible after implementing
19537 // DR1734 and DR1496.
19538 if (!AnotherMethodIsMoreConstrained) {
19539 Method->setIneligibleOrNotSelected(false);
19540 Record->addedEligibleSpecialMemberFunction(Method,
19541 1 << llvm::to_underlying(CSM));
19542 }
19543 }
19544}
19545
19548 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19549 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19550 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19551 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19552 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19553
19554 for (auto *Decl : Record->decls()) {
19555 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19556 if (!MD) {
19557 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19558 if (FTD)
19559 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19560 }
19561 if (!MD)
19562 continue;
19563 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19564 if (CD->isInvalidDecl())
19565 continue;
19566 if (CD->isDefaultConstructor())
19567 DefaultConstructors.push_back(MD);
19568 else if (CD->isCopyConstructor())
19569 CopyConstructors.push_back(MD);
19570 else if (CD->isMoveConstructor())
19571 MoveConstructors.push_back(MD);
19572 } else if (MD->isCopyAssignmentOperator()) {
19573 CopyAssignmentOperators.push_back(MD);
19574 } else if (MD->isMoveAssignmentOperator()) {
19575 MoveAssignmentOperators.push_back(MD);
19576 }
19577 }
19578
19579 SetEligibleMethods(S, Record, DefaultConstructors,
19581 SetEligibleMethods(S, Record, CopyConstructors,
19583 SetEligibleMethods(S, Record, MoveConstructors,
19585 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19587 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19589}
19590
19591bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19592 // Check to see if a FieldDecl is a pointer to a function.
19593 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19594 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19595 if (!FD) {
19596 // Check whether this is a forward declaration that was inserted by
19597 // Clang. This happens when a non-forward declared / defined type is
19598 // used, e.g.:
19599 //
19600 // struct foo {
19601 // struct bar *(*f)();
19602 // struct bar *(*g)();
19603 // };
19604 //
19605 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19606 // incomplete definition.
19607 if (const auto *TD = dyn_cast<TagDecl>(D))
19608 return !TD->isCompleteDefinition();
19609 return false;
19610 }
19611 QualType FieldType = FD->getType().getDesugaredType(Context);
19612 if (isa<PointerType>(FieldType)) {
19613 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19614 return PointeeType.getDesugaredType(Context)->isFunctionType();
19615 }
19616 // If a member is a struct entirely of function pointers, that counts too.
19617 if (const auto *Record = FieldType->getAsRecordDecl();
19618 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19619 return true;
19620 return false;
19621 };
19622
19623 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
19624}
19625
19626void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19627 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19628 SourceLocation RBrac,
19629 const ParsedAttributesView &Attrs) {
19630 assert(EnclosingDecl && "missing record or interface decl");
19631
19632 // If this is an Objective-C @implementation or category and we have
19633 // new fields here we should reset the layout of the interface since
19634 // it will now change.
19635 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19636 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19637 switch (DC->getKind()) {
19638 default: break;
19639 case Decl::ObjCCategory:
19640 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19641 break;
19642 case Decl::ObjCImplementation:
19643 Context.
19644 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19645 break;
19646 }
19647 }
19648
19649 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19650 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19651
19652 // Start counting up the number of named members; make sure to include
19653 // members of anonymous structs and unions in the total.
19654 unsigned NumNamedMembers = 0;
19655 if (Record) {
19656 for (const auto *I : Record->decls()) {
19657 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19658 if (IFD->getDeclName())
19659 ++NumNamedMembers;
19660 }
19661 }
19662
19663 // Verify that all the fields are okay.
19665 const FieldDecl *PreviousField = nullptr;
19666 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19667 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
19668 FieldDecl *FD = cast<FieldDecl>(*i);
19669
19670 // Get the type for the field.
19671 const Type *FDTy = FD->getType().getTypePtr();
19672
19673 if (!FD->isAnonymousStructOrUnion()) {
19674 // Remember all fields written by the user.
19675 RecFields.push_back(FD);
19676 }
19677
19678 // If the field is already invalid for some reason, don't emit more
19679 // diagnostics about it.
19680 if (FD->isInvalidDecl()) {
19681 EnclosingDecl->setInvalidDecl();
19682 continue;
19683 }
19684
19685 // C99 6.7.2.1p2:
19686 // A structure or union shall not contain a member with
19687 // incomplete or function type (hence, a structure shall not
19688 // contain an instance of itself, but may contain a pointer to
19689 // an instance of itself), except that the last member of a
19690 // structure with more than one named member may have incomplete
19691 // array type; such a structure (and any union containing,
19692 // possibly recursively, a member that is such a structure)
19693 // shall not be a member of a structure or an element of an
19694 // array.
19695 bool IsLastField = (i + 1 == Fields.end());
19696 if (FDTy->isFunctionType()) {
19697 // Field declared as a function.
19698 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19699 << FD->getDeclName();
19700 FD->setInvalidDecl();
19701 EnclosingDecl->setInvalidDecl();
19702 continue;
19703 } else if (FDTy->isIncompleteArrayType() &&
19704 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19705 if (Record) {
19706 // Flexible array member.
19707 // Microsoft and g++ is more permissive regarding flexible array.
19708 // It will accept flexible array in union and also
19709 // as the sole element of a struct/class.
19710 unsigned DiagID = 0;
19711 if (!Record->isUnion() && !IsLastField) {
19712 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19713 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19714 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19715 FD->setInvalidDecl();
19716 EnclosingDecl->setInvalidDecl();
19717 continue;
19718 } else if (Record->isUnion())
19719 DiagID = getLangOpts().MicrosoftExt
19720 ? diag::ext_flexible_array_union_ms
19721 : diag::ext_flexible_array_union_gnu;
19722 else if (NumNamedMembers < 1)
19723 DiagID = getLangOpts().MicrosoftExt
19724 ? diag::ext_flexible_array_empty_aggregate_ms
19725 : diag::ext_flexible_array_empty_aggregate_gnu;
19726
19727 if (DiagID)
19728 Diag(FD->getLocation(), DiagID)
19729 << FD->getDeclName() << Record->getTagKind();
19730 // While the layout of types that contain virtual bases is not specified
19731 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19732 // virtual bases after the derived members. This would make a flexible
19733 // array member declared at the end of an object not adjacent to the end
19734 // of the type.
19735 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19736 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19737 << FD->getDeclName() << Record->getTagKind();
19738 if (!getLangOpts().C99)
19739 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19740 << FD->getDeclName() << Record->getTagKind();
19741
19742 // If the element type has a non-trivial destructor, we would not
19743 // implicitly destroy the elements, so disallow it for now.
19744 //
19745 // FIXME: GCC allows this. We should probably either implicitly delete
19746 // the destructor of the containing class, or just allow this.
19747 QualType BaseElem = Context.getBaseElementType(FD->getType());
19748 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19749 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19750 << FD->getDeclName() << FD->getType();
19751 FD->setInvalidDecl();
19752 EnclosingDecl->setInvalidDecl();
19753 continue;
19754 }
19755 // Okay, we have a legal flexible array member at the end of the struct.
19756 Record->setHasFlexibleArrayMember(true);
19757 } else {
19758 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19759 // unless they are followed by another ivar. That check is done
19760 // elsewhere, after synthesized ivars are known.
19761 }
19762 } else if (!FDTy->isDependentType() &&
19763 (LangOpts.HLSL // HLSL allows sizeless builtin types
19765 diag::err_incomplete_type)
19767 FD->getLocation(), FD->getType(),
19768 diag::err_field_incomplete_or_sizeless))) {
19769 // Incomplete type
19770 FD->setInvalidDecl();
19771 EnclosingDecl->setInvalidDecl();
19772 continue;
19773 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
19774 if (Record && RD->hasFlexibleArrayMember()) {
19775 // A type which contains a flexible array member is considered to be a
19776 // flexible array member.
19777 Record->setHasFlexibleArrayMember(true);
19778 if (!Record->isUnion()) {
19779 // If this is a struct/class and this is not the last element, reject
19780 // it. Note that GCC supports variable sized arrays in the middle of
19781 // structures.
19782 if (!IsLastField)
19783 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19784 << FD->getDeclName() << FD->getType();
19785 else {
19786 // We support flexible arrays at the end of structs in
19787 // other structs as an extension.
19788 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19789 << FD->getDeclName();
19790 }
19791 }
19792 }
19793 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19795 diag::err_abstract_type_in_decl,
19797 // Ivars can not have abstract class types
19798 FD->setInvalidDecl();
19799 }
19800 if (Record && RD->hasObjectMember())
19801 Record->setHasObjectMember(true);
19802 if (Record && RD->hasVolatileMember())
19803 Record->setHasVolatileMember(true);
19804 } else if (FDTy->isObjCObjectType()) {
19805 /// A field cannot be an Objective-c object
19806 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19808 QualType T = Context.getObjCObjectPointerType(FD->getType());
19809 FD->setType(T);
19810 } else if (Record && Record->isUnion() &&
19812 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19813 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19815 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19816 // For backward compatibility, fields of C unions declared in system
19817 // headers that have non-trivial ObjC ownership qualifications are marked
19818 // as unavailable unless the qualifier is explicit and __strong. This can
19819 // break ABI compatibility between programs compiled with ARC and MRR, but
19820 // is a better option than rejecting programs using those unions under
19821 // ARC.
19822 FD->addAttr(UnavailableAttr::CreateImplicit(
19823 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19824 FD->getLocation()));
19825 } else if (getLangOpts().ObjC &&
19826 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19827 !Record->hasObjectMember()) {
19828 if (FD->getType()->isObjCObjectPointerType() ||
19829 FD->getType().isObjCGCStrong())
19830 Record->setHasObjectMember(true);
19831 else if (Context.getAsArrayType(FD->getType())) {
19832 QualType BaseType = Context.getBaseElementType(FD->getType());
19833 if (const auto *RD = BaseType->getAsRecordDecl();
19834 RD && RD->hasObjectMember())
19835 Record->setHasObjectMember(true);
19836 else if (BaseType->isObjCObjectPointerType() ||
19837 BaseType.isObjCGCStrong())
19838 Record->setHasObjectMember(true);
19839 }
19840 }
19841
19842 if (Record && !getLangOpts().CPlusPlus &&
19843 !shouldIgnoreForRecordTriviality(FD)) {
19844 QualType FT = FD->getType();
19846 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19848 Record->isUnion())
19849 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19850 }
19853 Record->setNonTrivialToPrimitiveCopy(true);
19854 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19855 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19856 }
19857 if (FD->hasAttr<ExplicitInitAttr>())
19858 Record->setHasUninitializedExplicitInitFields(true);
19859 if (FT.isDestructedType()) {
19860 Record->setNonTrivialToPrimitiveDestroy(true);
19861 Record->setParamDestroyedInCallee(true);
19862 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19863 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19864 }
19865
19866 if (const auto *RD = FT->getAsRecordDecl()) {
19867 if (RD->getArgPassingRestrictions() ==
19869 Record->setArgPassingRestrictions(
19871 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
19872 Record->setArgPassingRestrictions(
19874 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
19875 Q && Q.isAddressDiscriminated()) {
19876 Record->setArgPassingRestrictions(
19878 Record->setNonTrivialToPrimitiveCopy(true);
19879 }
19880 }
19881
19882 if (Record && FD->getType().isVolatileQualified())
19883 Record->setHasVolatileMember(true);
19884 bool ReportMSBitfieldStoragePacking =
19885 Record && PreviousField &&
19886 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
19887 Record->getLocation());
19888 auto IsNonDependentBitField = [](const FieldDecl *FD) {
19889 return FD->isBitField() && !FD->getType()->isDependentType();
19890 };
19891
19892 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
19893 IsNonDependentBitField(PreviousField)) {
19894 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
19895 CharUnits PreviousFieldStorageSize =
19896 Context.getTypeSizeInChars(PreviousField->getType());
19897 if (FDStorageSize != PreviousFieldStorageSize) {
19898 Diag(FD->getLocation(),
19899 diag::warn_ms_bitfield_mismatched_storage_packing)
19900 << FD << FD->getType() << FDStorageSize.getQuantity()
19901 << PreviousFieldStorageSize.getQuantity();
19902 Diag(PreviousField->getLocation(),
19903 diag::note_ms_bitfield_mismatched_storage_size_previous)
19904 << PreviousField << PreviousField->getType();
19905 }
19906 }
19907 // Keep track of the number of named members.
19908 if (FD->getIdentifier())
19909 ++NumNamedMembers;
19910 }
19911
19912 // Okay, we successfully defined 'Record'.
19913 if (Record) {
19914 bool Completed = false;
19915 if (S) {
19916 Scope *Parent = S->getParent();
19917 if (Parent && Parent->isTypeAliasScope() &&
19918 Parent->isTemplateParamScope())
19919 Record->setInvalidDecl();
19920 }
19921
19922 if (CXXRecord) {
19923 if (!CXXRecord->isInvalidDecl()) {
19924 // Set access bits correctly on the directly-declared conversions.
19926 I = CXXRecord->conversion_begin(),
19927 E = CXXRecord->conversion_end(); I != E; ++I)
19928 I.setAccess((*I)->getAccess());
19929 }
19930
19931 // Add any implicitly-declared members to this class.
19933
19934 if (!CXXRecord->isDependentType()) {
19935 if (!CXXRecord->isInvalidDecl()) {
19936 // If we have virtual base classes, we may end up finding multiple
19937 // final overriders for a given virtual function. Check for this
19938 // problem now.
19939 if (CXXRecord->getNumVBases()) {
19940 CXXFinalOverriderMap FinalOverriders;
19941 CXXRecord->getFinalOverriders(FinalOverriders);
19942
19943 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19944 MEnd = FinalOverriders.end();
19945 M != MEnd; ++M) {
19946 for (OverridingMethods::iterator SO = M->second.begin(),
19947 SOEnd = M->second.end();
19948 SO != SOEnd; ++SO) {
19949 assert(SO->second.size() > 0 &&
19950 "Virtual function without overriding functions?");
19951 if (SO->second.size() == 1)
19952 continue;
19953
19954 // C++ [class.virtual]p2:
19955 // In a derived class, if a virtual member function of a base
19956 // class subobject has more than one final overrider the
19957 // program is ill-formed.
19958 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19959 << (const NamedDecl *)M->first << Record;
19960 Diag(M->first->getLocation(),
19961 diag::note_overridden_virtual_function);
19963 OM = SO->second.begin(),
19964 OMEnd = SO->second.end();
19965 OM != OMEnd; ++OM)
19966 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19967 << (const NamedDecl *)M->first << OM->Method->getParent();
19968
19969 Record->setInvalidDecl();
19970 }
19971 }
19972 CXXRecord->completeDefinition(&FinalOverriders);
19973 Completed = true;
19974 }
19975 }
19976 ComputeSelectedDestructor(*this, CXXRecord);
19978 }
19979 }
19980
19981 if (!Completed)
19982 Record->completeDefinition();
19983
19984 // Handle attributes before checking the layout.
19986
19987 // Maybe randomize the record's decls. We automatically randomize a record
19988 // of function pointers, unless it has the "no_randomize_layout" attribute.
19989 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
19990 !Record->isRandomized() && !Record->isUnion() &&
19991 (Record->hasAttr<RandomizeLayoutAttr>() ||
19992 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19993 EntirelyFunctionPointers(Record)))) {
19994 SmallVector<Decl *, 32> NewDeclOrdering;
19996 NewDeclOrdering))
19997 Record->reorderDecls(NewDeclOrdering);
19998 }
19999
20000 // We may have deferred checking for a deleted destructor. Check now.
20001 if (CXXRecord) {
20002 auto *Dtor = CXXRecord->getDestructor();
20003 if (Dtor && Dtor->isImplicit() &&
20005 CXXRecord->setImplicitDestructorIsDeleted();
20006 SetDeclDeleted(Dtor, CXXRecord->getLocation());
20007 }
20008 }
20009
20010 if (Record->hasAttrs()) {
20012
20013 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20015 IA->getRange(), IA->getBestCase(),
20016 IA->getInheritanceModel());
20017 }
20018
20019 // Check if the structure/union declaration is a type that can have zero
20020 // size in C. For C this is a language extension, for C++ it may cause
20021 // compatibility problems.
20022 bool CheckForZeroSize;
20023 if (!getLangOpts().CPlusPlus) {
20024 CheckForZeroSize = true;
20025 } else {
20026 // For C++ filter out types that cannot be referenced in C code.
20028 CheckForZeroSize =
20029 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20030 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20031 CXXRecord->isCLike();
20032 }
20033 if (CheckForZeroSize) {
20034 bool ZeroSize = true;
20035 bool IsEmpty = true;
20036 unsigned NonBitFields = 0;
20037 for (RecordDecl::field_iterator I = Record->field_begin(),
20038 E = Record->field_end();
20039 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20040 IsEmpty = false;
20041 if (I->isUnnamedBitField()) {
20042 if (!I->isZeroLengthBitField())
20043 ZeroSize = false;
20044 } else {
20045 ++NonBitFields;
20046 QualType FieldType = I->getType();
20047 if (FieldType->isIncompleteType() ||
20048 !Context.getTypeSizeInChars(FieldType).isZero())
20049 ZeroSize = false;
20050 }
20051 }
20052
20053 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20054 // allowed in C++, but warn if its declaration is inside
20055 // extern "C" block.
20056 if (ZeroSize) {
20057 Diag(RecLoc, getLangOpts().CPlusPlus ?
20058 diag::warn_zero_size_struct_union_in_extern_c :
20059 diag::warn_zero_size_struct_union_compat)
20060 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20061 }
20062
20063 // Structs without named members are extension in C (C99 6.7.2.1p7),
20064 // but are accepted by GCC. In C2y, this became implementation-defined
20065 // (C2y 6.7.3.2p10).
20066 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20067 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
20068 : diag::ext_no_named_members_in_struct_union)
20069 << Record->isUnion();
20070 }
20071 }
20072 } else {
20073 ObjCIvarDecl **ClsFields =
20074 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20075 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
20076 ID->setEndOfDefinitionLoc(RBrac);
20077 // Add ivar's to class's DeclContext.
20078 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20079 ClsFields[i]->setLexicalDeclContext(ID);
20080 ID->addDecl(ClsFields[i]);
20081 }
20082 // Must enforce the rule that ivars in the base classes may not be
20083 // duplicates.
20084 if (ID->getSuperClass())
20085 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
20086 } else if (ObjCImplementationDecl *IMPDecl =
20087 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
20088 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20089 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20090 // Ivar declared in @implementation never belongs to the implementation.
20091 // Only it is in implementation's lexical context.
20092 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20093 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20094 RBrac);
20095 IMPDecl->setIvarLBraceLoc(LBrac);
20096 IMPDecl->setIvarRBraceLoc(RBrac);
20097 } else if (ObjCCategoryDecl *CDecl =
20098 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20099 // case of ivars in class extension; all other cases have been
20100 // reported as errors elsewhere.
20101 // FIXME. Class extension does not have a LocEnd field.
20102 // CDecl->setLocEnd(RBrac);
20103 // Add ivar's to class extension's DeclContext.
20104 // Diagnose redeclaration of private ivars.
20105 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20106 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20107 if (IDecl) {
20108 if (const ObjCIvarDecl *ClsIvar =
20109 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20110 Diag(ClsFields[i]->getLocation(),
20111 diag::err_duplicate_ivar_declaration);
20112 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20113 continue;
20114 }
20115 for (const auto *Ext : IDecl->known_extensions()) {
20116 if (const ObjCIvarDecl *ClsExtIvar
20117 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20118 Diag(ClsFields[i]->getLocation(),
20119 diag::err_duplicate_ivar_declaration);
20120 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20121 continue;
20122 }
20123 }
20124 }
20125 ClsFields[i]->setLexicalDeclContext(CDecl);
20126 CDecl->addDecl(ClsFields[i]);
20127 }
20128 CDecl->setIvarLBraceLoc(LBrac);
20129 CDecl->setIvarRBraceLoc(RBrac);
20130 }
20131 }
20133}
20134
20135// Given an integral type, return the next larger integral type
20136// (or a NULL type of no such type exists).
20138 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20139 // enum checking below.
20140 assert((T->isIntegralType(Context) ||
20141 T->isEnumeralType()) && "Integral type required!");
20142 const unsigned NumTypes = 4;
20143 QualType SignedIntegralTypes[NumTypes] = {
20144 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20145 };
20146 QualType UnsignedIntegralTypes[NumTypes] = {
20147 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20148 Context.UnsignedLongLongTy
20149 };
20150
20151 unsigned BitWidth = Context.getTypeSize(T);
20152 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20153 : UnsignedIntegralTypes;
20154 for (unsigned I = 0; I != NumTypes; ++I)
20155 if (Context.getTypeSize(Types[I]) > BitWidth)
20156 return Types[I];
20157
20158 return QualType();
20159}
20160
20162 EnumConstantDecl *LastEnumConst,
20163 SourceLocation IdLoc,
20164 IdentifierInfo *Id,
20165 Expr *Val) {
20166 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20167 llvm::APSInt EnumVal(IntWidth);
20168 QualType EltTy;
20169
20171 Val = nullptr;
20172
20173 if (Val)
20174 Val = DefaultLvalueConversion(Val).get();
20175
20176 if (Val) {
20177 if (Enum->isDependentType() || Val->isTypeDependent() ||
20178 Val->containsErrors())
20179 EltTy = Context.DependentTy;
20180 else {
20181 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20182 // underlying type, but do allow it in all other contexts.
20183 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20184 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20185 // constant-expression in the enumerator-definition shall be a converted
20186 // constant expression of the underlying type.
20187 EltTy = Enum->getIntegerType();
20189 Val, EltTy, EnumVal, CCEKind::Enumerator);
20190 if (Converted.isInvalid())
20191 Val = nullptr;
20192 else
20193 Val = Converted.get();
20194 } else if (!Val->isValueDependent() &&
20195 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20197 .get())) {
20198 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20199 } else {
20200 if (Enum->isComplete()) {
20201 EltTy = Enum->getIntegerType();
20202
20203 // In Obj-C and Microsoft mode, require the enumeration value to be
20204 // representable in the underlying type of the enumeration. In C++11,
20205 // we perform a non-narrowing conversion as part of converted constant
20206 // expression checking.
20207 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20208 if (Context.getTargetInfo()
20209 .getTriple()
20210 .isWindowsMSVCEnvironment()) {
20211 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20212 } else {
20213 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20214 }
20215 }
20216
20217 // Cast to the underlying type.
20218 Val = ImpCastExprToType(Val, EltTy,
20219 EltTy->isBooleanType() ? CK_IntegralToBoolean
20220 : CK_IntegralCast)
20221 .get();
20222 } else if (getLangOpts().CPlusPlus) {
20223 // C++11 [dcl.enum]p5:
20224 // If the underlying type is not fixed, the type of each enumerator
20225 // is the type of its initializing value:
20226 // - If an initializer is specified for an enumerator, the
20227 // initializing value has the same type as the expression.
20228 EltTy = Val->getType();
20229 } else {
20230 // C99 6.7.2.2p2:
20231 // The expression that defines the value of an enumeration constant
20232 // shall be an integer constant expression that has a value
20233 // representable as an int.
20234
20235 // Complain if the value is not representable in an int.
20236 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20237 Diag(IdLoc, getLangOpts().C23
20238 ? diag::warn_c17_compat_enum_value_not_int
20239 : diag::ext_c23_enum_value_not_int)
20240 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20241 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20242 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20243 // Force the type of the expression to 'int'.
20244 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20245 }
20246 EltTy = Val->getType();
20247 }
20248 }
20249 }
20250 }
20251
20252 if (!Val) {
20253 if (Enum->isDependentType())
20254 EltTy = Context.DependentTy;
20255 else if (!LastEnumConst) {
20256 // C++0x [dcl.enum]p5:
20257 // If the underlying type is not fixed, the type of each enumerator
20258 // is the type of its initializing value:
20259 // - If no initializer is specified for the first enumerator, the
20260 // initializing value has an unspecified integral type.
20261 //
20262 // GCC uses 'int' for its unspecified integral type, as does
20263 // C99 6.7.2.2p3.
20264 if (Enum->isFixed()) {
20265 EltTy = Enum->getIntegerType();
20266 }
20267 else {
20268 EltTy = Context.IntTy;
20269 }
20270 } else {
20271 // Assign the last value + 1.
20272 EnumVal = LastEnumConst->getInitVal();
20273 ++EnumVal;
20274 EltTy = LastEnumConst->getType();
20275
20276 // Check for overflow on increment.
20277 if (EnumVal < LastEnumConst->getInitVal()) {
20278 // C++0x [dcl.enum]p5:
20279 // If the underlying type is not fixed, the type of each enumerator
20280 // is the type of its initializing value:
20281 //
20282 // - Otherwise the type of the initializing value is the same as
20283 // the type of the initializing value of the preceding enumerator
20284 // unless the incremented value is not representable in that type,
20285 // in which case the type is an unspecified integral type
20286 // sufficient to contain the incremented value. If no such type
20287 // exists, the program is ill-formed.
20289 if (T.isNull() || Enum->isFixed()) {
20290 // There is no integral type larger enough to represent this
20291 // value. Complain, then allow the value to wrap around.
20292 EnumVal = LastEnumConst->getInitVal();
20293 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20294 ++EnumVal;
20295 if (Enum->isFixed())
20296 // When the underlying type is fixed, this is ill-formed.
20297 Diag(IdLoc, diag::err_enumerator_wrapped)
20298 << toString(EnumVal, 10)
20299 << EltTy;
20300 else
20301 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20302 << toString(EnumVal, 10);
20303 } else {
20304 EltTy = T;
20305 }
20306
20307 // Retrieve the last enumerator's value, extent that type to the
20308 // type that is supposed to be large enough to represent the incremented
20309 // value, then increment.
20310 EnumVal = LastEnumConst->getInitVal();
20311 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20312 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20313 ++EnumVal;
20314
20315 // If we're not in C++, diagnose the overflow of enumerator values,
20316 // which in C99 means that the enumerator value is not representable in
20317 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20318 // are representable in some larger integral type and we allow it in
20319 // older language modes as an extension.
20320 // Exclude fixed enumerators since they are diagnosed with an error for
20321 // this case.
20322 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20323 Diag(IdLoc, getLangOpts().C23
20324 ? diag::warn_c17_compat_enum_value_not_int
20325 : diag::ext_c23_enum_value_not_int)
20326 << 1 << toString(EnumVal, 10) << 1;
20327 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20328 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20329 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20330 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20331 : diag::ext_c23_enum_value_not_int)
20332 << 1 << toString(EnumVal, 10) << 1;
20333 }
20334 }
20335 }
20336
20337 if (!EltTy->isDependentType()) {
20338 // Make the enumerator value match the signedness and size of the
20339 // enumerator's type.
20340 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20341 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20342 }
20343
20344 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20345 Val, EnumVal);
20346}
20347
20349 SourceLocation IILoc) {
20350 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20352 return SkipBodyInfo();
20353
20354 // We have an anonymous enum definition. Look up the first enumerator to
20355 // determine if we should merge the definition with an existing one and
20356 // skip the body.
20357 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20359 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20360 if (!PrevECD)
20361 return SkipBodyInfo();
20362
20363 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20364 NamedDecl *Hidden;
20365 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20367 Skip.Previous = Hidden;
20368 return Skip;
20369 }
20370
20371 return SkipBodyInfo();
20372}
20373
20374Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20375 SourceLocation IdLoc, IdentifierInfo *Id,
20376 const ParsedAttributesView &Attrs,
20377 SourceLocation EqualLoc, Expr *Val,
20378 SkipBodyInfo *SkipBody) {
20379 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20380 EnumConstantDecl *LastEnumConst =
20381 cast_or_null<EnumConstantDecl>(lastEnumConst);
20382
20383 // The scope passed in may not be a decl scope. Zip up the scope tree until
20384 // we find one that is.
20385 S = getNonFieldDeclScope(S);
20386
20387 // Verify that there isn't already something declared with this name in this
20388 // scope.
20389 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20391 LookupName(R, S);
20392 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20393
20394 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20395 // Maybe we will complain about the shadowed template parameter.
20396 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20397 // Just pretend that we didn't see the previous declaration.
20398 PrevDecl = nullptr;
20399 }
20400
20401 // C++ [class.mem]p15:
20402 // If T is the name of a class, then each of the following shall have a name
20403 // different from T:
20404 // - every enumerator of every member of class T that is an unscoped
20405 // enumerated type
20406 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20408 DeclarationNameInfo(Id, IdLoc)))
20409 return nullptr;
20410
20412 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20413 if (!New)
20414 return nullptr;
20415
20416 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20417 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20418 // Check for other kinds of shadowing not already handled.
20419 CheckShadow(New, PrevDecl, R);
20420 }
20421
20422 // When in C++, we may get a TagDecl with the same name; in this case the
20423 // enum constant will 'hide' the tag.
20424 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20425 "Received TagDecl when not in C++!");
20426 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20427 if (isa<EnumConstantDecl>(PrevDecl))
20428 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20429 else
20430 Diag(IdLoc, diag::err_redefinition) << Id;
20431 notePreviousDefinition(PrevDecl, IdLoc);
20432 return nullptr;
20433 }
20434 }
20435
20436 // Process attributes.
20437 ProcessDeclAttributeList(S, New, Attrs);
20440
20441 // Register this decl in the current scope stack.
20442 New->setAccess(TheEnumDecl->getAccess());
20444
20446
20447 return New;
20448}
20449
20450// Returns true when the enum initial expression does not trigger the
20451// duplicate enum warning. A few common cases are exempted as follows:
20452// Element2 = Element1
20453// Element2 = Element1 + 1
20454// Element2 = Element1 - 1
20455// Where Element2 and Element1 are from the same enum.
20457 Expr *InitExpr = ECD->getInitExpr();
20458 if (!InitExpr)
20459 return true;
20460 InitExpr = InitExpr->IgnoreImpCasts();
20461
20462 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20463 if (!BO->isAdditiveOp())
20464 return true;
20465 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20466 if (!IL)
20467 return true;
20468 if (IL->getValue() != 1)
20469 return true;
20470
20471 InitExpr = BO->getLHS();
20472 }
20473
20474 // This checks if the elements are from the same enum.
20475 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20476 if (!DRE)
20477 return true;
20478
20479 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20480 if (!EnumConstant)
20481 return true;
20482
20484 Enum)
20485 return true;
20486
20487 return false;
20488}
20489
20490// Emits a warning when an element is implicitly set a value that
20491// a previous element has already been set to.
20493 EnumDecl *Enum, QualType EnumType) {
20494 // Avoid anonymous enums
20495 if (!Enum->getIdentifier())
20496 return;
20497
20498 // Only check for small enums.
20499 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20500 return;
20501
20502 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20503 return;
20504
20505 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20506 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20507
20508 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20509
20510 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20511 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20512
20513 // Use int64_t as a key to avoid needing special handling for map keys.
20514 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20515 llvm::APSInt Val = D->getInitVal();
20516 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20517 };
20518
20519 DuplicatesVector DupVector;
20520 ValueToVectorMap EnumMap;
20521
20522 // Populate the EnumMap with all values represented by enum constants without
20523 // an initializer.
20524 for (auto *Element : Elements) {
20525 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20526
20527 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20528 // this constant. Skip this enum since it may be ill-formed.
20529 if (!ECD) {
20530 return;
20531 }
20532
20533 // Constants with initializers are handled in the next loop.
20534 if (ECD->getInitExpr())
20535 continue;
20536
20537 // Duplicate values are handled in the next loop.
20538 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20539 }
20540
20541 if (EnumMap.size() == 0)
20542 return;
20543
20544 // Create vectors for any values that has duplicates.
20545 for (auto *Element : Elements) {
20546 // The last loop returned if any constant was null.
20548 if (!ValidDuplicateEnum(ECD, Enum))
20549 continue;
20550
20551 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20552 if (Iter == EnumMap.end())
20553 continue;
20554
20555 DeclOrVector& Entry = Iter->second;
20556 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
20557 // Ensure constants are different.
20558 if (D == ECD)
20559 continue;
20560
20561 // Create new vector and push values onto it.
20562 auto Vec = std::make_unique<ECDVector>();
20563 Vec->push_back(D);
20564 Vec->push_back(ECD);
20565
20566 // Update entry to point to the duplicates vector.
20567 Entry = Vec.get();
20568
20569 // Store the vector somewhere we can consult later for quick emission of
20570 // diagnostics.
20571 DupVector.emplace_back(std::move(Vec));
20572 continue;
20573 }
20574
20575 ECDVector *Vec = cast<ECDVector *>(Entry);
20576 // Make sure constants are not added more than once.
20577 if (*Vec->begin() == ECD)
20578 continue;
20579
20580 Vec->push_back(ECD);
20581 }
20582
20583 // Emit diagnostics.
20584 for (const auto &Vec : DupVector) {
20585 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20586
20587 // Emit warning for one enum constant.
20588 auto *FirstECD = Vec->front();
20589 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20590 << FirstECD << toString(FirstECD->getInitVal(), 10)
20591 << FirstECD->getSourceRange();
20592
20593 // Emit one note for each of the remaining enum constants with
20594 // the same value.
20595 for (auto *ECD : llvm::drop_begin(*Vec))
20596 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20597 << ECD << toString(ECD->getInitVal(), 10)
20598 << ECD->getSourceRange();
20599 }
20600}
20601
20602bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20603 bool AllowMask) const {
20604 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20605 assert(ED->isCompleteDefinition() && "expected enum definition");
20606
20607 auto R = FlagBitsCache.try_emplace(ED);
20608 llvm::APInt &FlagBits = R.first->second;
20609
20610 if (R.second) {
20611 for (auto *E : ED->enumerators()) {
20612 const auto &EVal = E->getInitVal();
20613 // Only single-bit enumerators introduce new flag values.
20614 if (EVal.isPowerOf2())
20615 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20616 }
20617 }
20618
20619 // A value is in a flag enum if either its bits are a subset of the enum's
20620 // flag bits (the first condition) or we are allowing masks and the same is
20621 // true of its complement (the second condition). When masks are allowed, we
20622 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20623 //
20624 // While it's true that any value could be used as a mask, the assumption is
20625 // that a mask will have all of the insignificant bits set. Anything else is
20626 // likely a logic error.
20627 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20628 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20629}
20630
20631// Emits a warning when a suspicious comparison operator is used along side
20632// binary operators in enum initializers.
20634 const EnumDecl *Enum) {
20635 bool HasBitwiseOp = false;
20636 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20637
20638 // Iterate over all the enum values, gather suspisious comparison ops and
20639 // whether any enum initialisers contain a binary operator.
20640 for (const auto *ECD : Enum->enumerators()) {
20641 const Expr *InitExpr = ECD->getInitExpr();
20642 if (!InitExpr)
20643 continue;
20644
20645 const Expr *E = InitExpr->IgnoreParenImpCasts();
20646
20647 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
20648 BinaryOperatorKind Op = BinOp->getOpcode();
20649
20650 // Check for bitwise ops (<<, >>, &, |)
20651 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
20652 HasBitwiseOp = true;
20653 } else if (Op == BO_LT || Op == BO_GT) {
20654 // Check for the typo pattern (Comparison < or >)
20655 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
20656 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(LHS)) {
20657 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
20658 if (IntLiteral->getValue() == 1)
20659 SuspiciousCompares.push_back(BinOp);
20660 }
20661 }
20662 }
20663 }
20664
20665 // If we found a bitwise op and some sus compares, iterate over the compares
20666 // and warn.
20667 if (HasBitwiseOp) {
20668 for (const auto *BinOp : SuspiciousCompares) {
20669 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
20672 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
20673
20674 Sema.Diag(OperatorLoc, diag::warn_comparison_in_enum_initializer)
20675 << BinOp->getOpcodeStr() << SuggestedOp;
20676
20677 Sema.Diag(OperatorLoc, diag::note_enum_compare_typo_suggest)
20678 << SuggestedOp
20679 << FixItHint::CreateReplacement(OperatorLoc, SuggestedOp);
20680 }
20681 }
20682}
20683
20685 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20686 const ParsedAttributesView &Attrs) {
20687 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20688 CanQualType EnumType = Context.getCanonicalTagType(Enum);
20689
20690 ProcessDeclAttributeList(S, Enum, Attrs);
20692
20693 if (Enum->isDependentType()) {
20694 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20695 EnumConstantDecl *ECD =
20696 cast_or_null<EnumConstantDecl>(Elements[i]);
20697 if (!ECD) continue;
20698
20699 ECD->setType(EnumType);
20700 }
20701
20702 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20703 return;
20704 }
20705
20706 // Verify that all the values are okay, compute the size of the values, and
20707 // reverse the list.
20708 unsigned NumNegativeBits = 0;
20709 unsigned NumPositiveBits = 0;
20710 bool MembersRepresentableByInt =
20711 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
20712
20713 // Figure out the type that should be used for this enum.
20714 QualType BestType;
20715 unsigned BestWidth;
20716
20717 // C++0x N3000 [conv.prom]p3:
20718 // An rvalue of an unscoped enumeration type whose underlying
20719 // type is not fixed can be converted to an rvalue of the first
20720 // of the following types that can represent all the values of
20721 // the enumeration: int, unsigned int, long int, unsigned long
20722 // int, long long int, or unsigned long long int.
20723 // C99 6.4.4.3p2:
20724 // An identifier declared as an enumeration constant has type int.
20725 // The C99 rule is modified by C23.
20726 QualType BestPromotionType;
20727
20728 bool Packed = Enum->hasAttr<PackedAttr>();
20729 // -fshort-enums is the equivalent to specifying the packed attribute on all
20730 // enum definitions.
20731 if (LangOpts.ShortEnums)
20732 Packed = true;
20733
20734 // If the enum already has a type because it is fixed or dictated by the
20735 // target, promote that type instead of analyzing the enumerators.
20736 if (Enum->isComplete()) {
20737 BestType = Enum->getIntegerType();
20738 if (Context.isPromotableIntegerType(BestType))
20739 BestPromotionType = Context.getPromotedIntegerType(BestType);
20740 else
20741 BestPromotionType = BestType;
20742
20743 BestWidth = Context.getIntWidth(BestType);
20744 } else {
20745 bool EnumTooLarge = Context.computeBestEnumTypes(
20746 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20747 BestWidth = Context.getIntWidth(BestType);
20748 if (EnumTooLarge)
20749 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20750 }
20751
20752 // Loop over all of the enumerator constants, changing their types to match
20753 // the type of the enum if needed.
20754 for (auto *D : Elements) {
20755 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20756 if (!ECD) continue; // Already issued a diagnostic.
20757
20758 // C99 says the enumerators have int type, but we allow, as an
20759 // extension, the enumerators to be larger than int size. If each
20760 // enumerator value fits in an int, type it as an int, otherwise type it the
20761 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20762 // that X has type 'int', not 'unsigned'.
20763
20764 // Determine whether the value fits into an int.
20765 llvm::APSInt InitVal = ECD->getInitVal();
20766
20767 // If it fits into an integer type, force it. Otherwise force it to match
20768 // the enum decl type.
20769 QualType NewTy;
20770 unsigned NewWidth;
20771 bool NewSign;
20772 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20773 MembersRepresentableByInt) {
20774 // C23 6.7.3.3.3p15:
20775 // The enumeration member type for an enumerated type without fixed
20776 // underlying type upon completion is:
20777 // - int if all the values of the enumeration are representable as an
20778 // int; or,
20779 // - the enumerated type
20780 NewTy = Context.IntTy;
20781 NewWidth = Context.getTargetInfo().getIntWidth();
20782 NewSign = true;
20783 } else if (ECD->getType() == BestType) {
20784 // Already the right type!
20785 if (getLangOpts().CPlusPlus)
20786 // C++ [dcl.enum]p4: Following the closing brace of an
20787 // enum-specifier, each enumerator has the type of its
20788 // enumeration.
20789 ECD->setType(EnumType);
20790 continue;
20791 } else {
20792 NewTy = BestType;
20793 NewWidth = BestWidth;
20794 NewSign = BestType->isSignedIntegerOrEnumerationType();
20795 }
20796
20797 // Adjust the APSInt value.
20798 InitVal = InitVal.extOrTrunc(NewWidth);
20799 InitVal.setIsSigned(NewSign);
20800 ECD->setInitVal(Context, InitVal);
20801
20802 // Adjust the Expr initializer and type.
20803 if (ECD->getInitExpr() &&
20804 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20805 ECD->setInitExpr(ImplicitCastExpr::Create(
20806 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20807 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20808 if (getLangOpts().CPlusPlus)
20809 // C++ [dcl.enum]p4: Following the closing brace of an
20810 // enum-specifier, each enumerator has the type of its
20811 // enumeration.
20812 ECD->setType(EnumType);
20813 else
20814 ECD->setType(NewTy);
20815 }
20816
20817 Enum->completeDefinition(BestType, BestPromotionType,
20818 NumPositiveBits, NumNegativeBits);
20819
20820 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20822
20823 if (Enum->isClosedFlag()) {
20824 for (Decl *D : Elements) {
20825 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20826 if (!ECD) continue; // Already issued a diagnostic.
20827
20828 llvm::APSInt InitVal = ECD->getInitVal();
20829 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20830 !IsValueInFlagEnum(Enum, InitVal, true))
20831 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20832 << ECD << Enum;
20833 }
20834 }
20835
20836 // Now that the enum type is defined, ensure it's not been underaligned.
20837 if (Enum->hasAttrs())
20839}
20840
20842 SourceLocation EndLoc) {
20843
20845 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
20846 CurContext->addDecl(New);
20847 return New;
20848}
20849
20851 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20852 CurContext->addDecl(New);
20853 PushDeclContext(S, New);
20855 PushCompoundScope(false);
20856 return New;
20857}
20858
20860 if (Statement)
20861 D->setStmt(Statement);
20865}
20866
20868 IdentifierInfo* AliasName,
20869 SourceLocation PragmaLoc,
20870 SourceLocation NameLoc,
20871 SourceLocation AliasNameLoc) {
20872 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20874 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20876 AsmLabelAttr *Attr =
20877 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
20878
20879 // If a declaration that:
20880 // 1) declares a function or a variable
20881 // 2) has external linkage
20882 // already exists, add a label attribute to it.
20883 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20884 if (isDeclExternC(PrevDecl))
20885 PrevDecl->addAttr(Attr);
20886 else
20887 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20888 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20889 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20890 } else
20891 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20892}
20893
20895 SourceLocation PragmaLoc,
20896 SourceLocation NameLoc) {
20897 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20898
20899 if (PrevDecl) {
20900 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20901 } else {
20902 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20903 }
20904}
20905
20907 IdentifierInfo* AliasName,
20908 SourceLocation PragmaLoc,
20909 SourceLocation NameLoc,
20910 SourceLocation AliasNameLoc) {
20911 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20913 WeakInfo W = WeakInfo(Name, NameLoc);
20914
20915 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20916 if (!PrevDecl->hasAttr<AliasAttr>())
20917 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20919 } else {
20920 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20921 }
20922}
20923
20925 bool Final) {
20926 assert(FD && "Expected non-null FunctionDecl");
20927
20928 // SYCL functions can be template, so we check if they have appropriate
20929 // attribute prior to checking if it is a template.
20930 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20932
20933 // Templates are emitted when they're instantiated.
20934 if (FD->isDependentContext())
20936
20937 // Check whether this function is an externally visible definition.
20938 auto IsEmittedForExternalSymbol = [this, FD]() {
20939 // We have to check the GVA linkage of the function's *definition* -- if we
20940 // only have a declaration, we don't know whether or not the function will
20941 // be emitted, because (say) the definition could include "inline".
20942 const FunctionDecl *Def = FD->getDefinition();
20943
20944 // We can't compute linkage when we skip function bodies.
20945 return Def && !Def->hasSkippedBody() &&
20947 getASTContext().GetGVALinkageForFunction(Def));
20948 };
20949
20950 if (LangOpts.OpenMPIsTargetDevice) {
20951 // In OpenMP device mode we will not emit host only functions, or functions
20952 // we don't need due to their linkage.
20953 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20954 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20955 // DevTy may be changed later by
20956 // #pragma omp declare target to(*) device_type(*).
20957 // Therefore DevTy having no value does not imply host. The emission status
20958 // will be checked again at the end of compilation unit with Final = true.
20959 if (DevTy)
20960 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20962 // If we have an explicit value for the device type, or we are in a target
20963 // declare context, we need to emit all extern and used symbols.
20964 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20965 if (IsEmittedForExternalSymbol())
20967 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20968 // we'll omit it.
20969 if (Final)
20971 } else if (LangOpts.OpenMP > 45) {
20972 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20973 // function. In 5.0, no_host was introduced which might cause a function to
20974 // be omitted.
20975 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20976 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20977 if (DevTy)
20978 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20980 }
20981
20982 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20984
20985 if (LangOpts.CUDA) {
20986 // When compiling for device, host functions are never emitted. Similarly,
20987 // when compiling for host, device and global functions are never emitted.
20988 // (Technically, we do emit a host-side stub for global functions, but this
20989 // doesn't count for our purposes here.)
20991 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20993 if (!LangOpts.CUDAIsDevice &&
20996
20997 if (IsEmittedForExternalSymbol())
20999
21000 // If FD is a virtual destructor of an explicit instantiation
21001 // of a template class, return Emitted.
21002 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(FD)) {
21003 if (Destructor->isVirtual()) {
21004 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
21005 Destructor->getParent())) {
21007 Spec->getTemplateSpecializationKind();
21011 }
21012 }
21013 }
21014 }
21015
21016 // Otherwise, the function is known-emitted if it's in our set of
21017 // known-emitted functions.
21019}
21020
21022 // Host-side references to a __global__ function refer to the stub, so the
21023 // function itself is never emitted and therefore should not be marked.
21024 // If we have host fn calls kernel fn calls host+device, the HD function
21025 // does not get instantiated on the host. We model this by omitting at the
21026 // call to the kernel from the callgraph. This ensures that, when compiling
21027 // for host, only HD functions actually called from the host get marked as
21028 // known-emitted.
21029 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21031}
21032
21034 bool &Visible) {
21035 Visible = hasVisibleDefinition(D, Suggested);
21036 // The redefinition of D in the **current** TU is allowed if D is invisible or
21037 // D is defined in the global module of other module units. We didn't check if
21038 // it is in global module as, we'll check the redefinition in named module
21039 // later with better diagnostic message.
21040 return D->isInAnotherModuleUnit() || !Visible;
21041}
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:2234
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.
static const Decl * getCanonicalDecl(const Decl *D)
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition MachO.h:27
llvm::MachO::Record Record
Definition MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition Mangle.cpp:74
#define SM(sm)
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:187
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition SemaDecl.cpp:177
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:232
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:832
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:596
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:615
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:847
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 checkSelectAnyAttr(Sema &S, NamedDecl &ND)
static bool isImplicitInstantiation(NamedDecl *D)
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
static bool looksMutable(QualType T, const ASTContext &Ctx)
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From, F &&propagator)
static const NamedDecl * getDefinition(const Decl *D)
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static bool hasDeducedAuto(DeclaratorDecl *DD)
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
static QualType getCoreType(QualType Ty)
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, AvailabilityMergeKind AMK)
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a new function declaration being added to an existing multiversioned declaratio...
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
static void checkAliasAttr(Sema &S, NamedDecl &ND)
static void filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don't have linkage, but they still denote the same entity if their types are the...
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
static void checkWeakRefAttr(Sema &S, NamedDecl &ND)
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
static bool isAttributeTargetADefinition(Decl *D)
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualified na...
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to Wasm.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
@ GE_None
No error.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_type
Missing a type.
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
SourceManager & getSourceManager()
Definition ASTContext.h:837
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:776
const LangOptions & getLangOpts() const
Definition ASTContext.h:930
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:895
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:3489
Wrapper for source info for arrays.
Definition TypeLoc.h:1748
SourceLocation getLBracketLoc() const
Definition TypeLoc.h:1750
Expr * getSizeExpr() const
Definition TypeLoc.h:1770
TypeLoc getElementLoc() const
Definition TypeLoc.h:1778
SourceLocation getRBracketLoc() const
Definition TypeLoc.h:1758
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
QualType getElementType() const
Definition TypeBase.h:3734
Attr - This represents one attribute.
Definition Attr.h:45
attr::Kind getKind() const
Definition Attr.h:91
bool isInherited() const
Definition Attr.h:100
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition Attr.h:105
SourceLocation getLocation() const
Definition Attr.h:98
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
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4441
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4429
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
Expr * getLHS() const
Definition Expr.h:4022
StringRef getOpcodeStr() const
Definition Expr.h:4038
Expr * getRHS() const
Definition Expr.h:4024
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4113
A binding in a decomposition declaration.
Definition DeclCXX.h:4185
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4659
bool doesNotEscape() const
Definition Decl.h:4810
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:229
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:376
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:1691
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1611
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
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:3008
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:2968
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2943
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:3170
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:2367
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
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:3098
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:2129
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:2703
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition DeclCXX.cpp:2755
bool isVirtual() const
Definition DeclCXX.h:2184
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:2488
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2735
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2290
bool isConst() const
Definition DeclCXX.h:2181
bool isStatic() const
Definition DeclCXX.cpp:2401
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2714
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2225
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
base_class_iterator bases_end()
Definition DeclCXX.h:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1366
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1554
base_class_range bases()
Definition DeclCXX.h:608
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
base_class_iterator bases_begin()
Definition DeclCXX.h:615
capture_const_range captures() const
Definition DeclCXX.h:1097
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1148
bool hasDefinition() const
Definition DeclCXX.h:561
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2042
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2146
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1059
UnresolvedSetIterator conversion_iterator
Definition DeclCXX.h:1119
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2046
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:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:180
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:206
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:185
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:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
bool isSet() const
Deprecated.
Definition DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
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:183
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
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:3081
bool isCallToStdMove() const
Definition Expr.cpp:3619
Expr * getCallee()
Definition Expr.h:3024
arg_range arguments()
Definition Expr.h:3129
CastKind getCastKind() const
Definition Expr.h:3654
Expr * getSubExpr()
Definition Expr.h:3660
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:3760
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:214
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:254
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3816
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclListNode::iterator iterator
Definition DeclBase.h:1392
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isFileContext() const
Definition DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool isClosure() const
Definition DeclBase.h:2142
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
bool isNamespace() const
Definition DeclBase.h:2198
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
bool isTranslationUnit() const
Definition DeclBase.h:2185
bool isRecord() const
Definition DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2102
DeclContext * getNonTransparentContext()
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition DeclGroup.h:64
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
ValueDecl * getDecl()
Definition Expr.h:1338
SourceLocation getBeginLoc() const
Definition Expr.h:1349
Captures information about "declaration specifiers".
Definition DeclSpec.h:217
bool isVirtualSpecified() const
Definition DeclSpec.h:618
bool isModulePrivateSpecified() const
Definition DeclSpec.h:799
static const TST TST_typeof_unqualType
Definition DeclSpec.h:279
bool hasAutoTypeSpec() const
Definition DeclSpec.h:565
static const TST TST_typename
Definition DeclSpec.h:276
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:619
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:234
void ClearStorageClassSpecs()
Definition DeclSpec.h:485
bool isNoreturnSpecified() const
Definition DeclSpec.h:631
TST getTypeSpecType() const
Definition DeclSpec.h:507
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:480
SCS getStorageClassSpec() const
Definition DeclSpec.h:471
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:834
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:545
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:544
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:679
static const TST TST_interface
Definition DeclSpec.h:274
static const TST TST_typeofExpr
Definition DeclSpec.h:278
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:586
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:678
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:632
bool isExternInLinkageSpec() const
Definition DeclSpec.h:475
static const TST TST_union
Definition DeclSpec.h:272
SCS
storage-class-specifier
Definition DeclSpec.h:221
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:624
static const TST TST_int
Definition DeclSpec.h:255
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:800
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
ParsedType getRepAsType() const
Definition DeclSpec.h:517
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:758
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:472
ParsedAttributes & getAttributes()
Definition DeclSpec.h:843
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:596
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:587
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:625
Expr * getRepAsExpr() const
Definition DeclSpec.h:525
static const TST TST_enum
Definition DeclSpec.h:271
static const TST TST_decltype
Definition DeclSpec.h:281
static bool isDeclRep(TST T)
Definition DeclSpec.h:439
bool isInlineSpecified() const
Definition DeclSpec.h:607
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:588
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:280
static const TST TST_class
Definition DeclSpec.h:275
TypeSpecifierType TST
Definition DeclSpec.h:247
static const TST TST_void
Definition DeclSpec.h:249
void ClearConstexprSpec()
Definition DeclSpec.h:811
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:291
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:481
Decl * getRepAsDecl() const
Definition DeclSpec.h:521
static const TST TST_unspecified
Definition DeclSpec.h:248
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:590
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:619
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:806
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:552
void UpdateExprRep(Expr *Rep)
Definition DeclSpec.h:762
static const TSCS TSCS_thread_local
Definition DeclSpec.h:237
static const TST TST_error
Definition DeclSpec.h:298
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclSpec.h:614
bool isTypeSpecOwned() const
Definition DeclSpec.h:511
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:610
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:591
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:589
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:791
bool hasExplicitSpecifier() const
Definition DeclSpec.h:621
bool hasConstexprSpecifier() const
Definition DeclSpec.h:807
static const TST TST_typeofType
Definition DeclSpec.h:277
static const TST TST_auto
Definition DeclSpec.h:288
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:802
static const TST TST_struct
Definition DeclSpec.h:273
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1061
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1076
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:341
bool isInStdNamespace() const
Definition DeclBase.cpp:449
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:435
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
bool isFromGlobalModule() const
Whether this declaration comes from global module.
T * getAttr() const
Definition DeclBase.h:573
bool hasAttrs() const
Definition DeclBase.h:518
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
void setAttrs(const AttrVec &Attrs)
Definition DeclBase.h:520
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition DeclBase.h:771
bool isInNamedModule() const
Whether this declaration comes from a named module.
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition DeclBase.h:1151
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void setTopLevelDeclInObjCContainer(bool V=true)
Definition DeclBase.h:638
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:893
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1219
@ FOK_None
Not a friend object.
Definition DeclBase.h:1217
@ FOK_Declared
A friend of a previously-declared entity.
Definition DeclBase.h:1218
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:600
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
void dropAttrs()
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition DeclBase.h:210
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1180
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2793
bool isInvalidDecl() const
Definition DeclBase.h:588
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1169
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
void setImplicit(bool I=true)
Definition DeclBase.h:594
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:575
DeclContext * getDeclContext()
Definition DeclBase.h:448
attr_range attrs() const
Definition DeclBase.h:535
AccessSpecifier getAccess() const
Definition DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void dropAttr()
Definition DeclBase.h:556
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:382
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition Decl.cpp:1636
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1235
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:386
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isAnyOperatorNewOrDelete() const
bool isAnyOperatorDelete() const
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function),...
NameKind getNameKind() const
Determine what kind of name this is.
bool isEmpty() const
Evaluates true when this declaration name is empty.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:822
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition Decl.cpp:2055
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2095
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1993
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:2005
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:2039
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2430
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2372
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2021
Expr * getAsmLabel() const
Definition DeclSpec.h:2676
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2715
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2657
void setRedeclaration(bool Val)
Definition DeclSpec.h:2738
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2310
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2313
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2058
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2607
void takeAttributesAppending(ParsedAttributes &attrs)
takeAttributesAppending - Takes attributes from the given ParsedAttributes set and add them to this d...
Definition DeclSpec.h:2650
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2687
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition DeclSpec.h:2637
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2368
bool isRedeclaration() const
Definition DeclSpec.h:2739
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2660
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2042
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2057
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition DeclSpec.cpp:410
bool isFunctionDefinition() const
Definition DeclSpec.h:2711
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2040
bool hasInitializer() const
Definition DeclSpec.h:2720
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2707
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2036
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2327
bool isInvalidType() const
Definition DeclSpec.h:2688
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2056
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2300
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2723
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:2028
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2461
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2304
A decomposition declaration.
Definition DeclCXX.h:4249
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3629
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1762
SourceRange getSourceRange() const
Definition DeclSpec.h:1810
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1808
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2484
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2572
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2552
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2561
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
llvm::APSInt getInitVal() const
Definition Decl.h:3443
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5636
const Expr * getInitExpr() const
Definition Decl.h:3441
Represents an enum.
Definition Decl.h:4007
enumerator_range enumerators() const
Definition Decl.h:4144
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4216
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:4180
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:4183
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4230
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5006
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:5045
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4225
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:5020
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:4166
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4171
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
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:3085
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:3081
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:3065
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
bool isFPConstrained() const
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4709
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4694
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4755
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5769
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2000
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2689
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2189
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2476
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4199
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3727
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4192
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4187
void setIsPureVirtual(bool P=true)
Definition Decl.cpp:3292
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2314
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2701
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2680
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4018
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3756
param_iterator param_end()
Definition Decl.h:2787
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2921
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2695
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3700
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2389
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2377
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3608
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4307
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2448
void setWillHaveBody(bool V=true)
Definition Decl.h:2686
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition Decl.h:2594
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2443
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4317
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3741
param_iterator param_begin()
Definition Decl.h:2786
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2823
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2326
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2540
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3134
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3369
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4251
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2888
bool isStatic() const
Definition Decl.h:2929
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4520
void setTrivial(bool IT)
Definition Decl.h:2378
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4138
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
bool isDeletedAsWritten() const
Definition Decl.h:2544
redecl_iterator redecls_end() const
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2353
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3612
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2357
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2428
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2349
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2679
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2282
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3362
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:2916
bool param_empty() const
Definition Decl.h:2785
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3217
void setRangeEnd(SourceLocation E)
Definition Decl.h:2218
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3696
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2385
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2421
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4543
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2933
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4132
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2473
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4411
void setDefaulted(bool D=true)
Definition Decl.h:2386
bool isConsteval() const
Definition Decl.h:2482
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:2862
void setBody(Stmt *B)
Definition Decl.cpp:3285
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3626
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3163
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2459
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4159
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3820
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2211
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3193
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2435
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3240
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition Decl.h:2899
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3682
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2685
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5190
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5222
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5671
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5054
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
unsigned getNumParams() const
Definition TypeBase.h:5532
QualType getParamType(unsigned i) const
Definition TypeBase.h:5534
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5751
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5567
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5658
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5543
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5539
Declaration of a template function.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Wrapper for source info for functions.
Definition TypeLoc.h:1615
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4561
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4673
CallingConv getCC() const
Definition TypeBase.h:4620
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4639
unsigned getRegParm() const
Definition TypeBase.h:4613
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4609
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4632
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4653
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4667
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4450
ExtInfo getExtInfo() const
Definition TypeBase.h:4806
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3577
unsigned getRegParmType() const
Definition TypeBase.h:4793
CallingConv getCallConv() const
Definition TypeBase.h:4805
QualType getReturnType() const
Definition TypeBase.h:4790
bool getCmseNSCallAttr() const
Definition TypeBase.h:4804
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:2068
Represents a C array with an unspecified size.
Definition TypeBase.h:3909
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5663
void setInherited(bool I)
Definition Attr.h:157
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2575
child_range children()
Definition Expr.h:5432
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:971
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:2083
@ 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...
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
FPExceptionModeKind getDefaultExceptionMode() const
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
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:1377
Visibility getVisibility() const
Definition Visibility.h:89
Linkage getLinkage() const
Definition Visibility.h:88
Represents a linkage specification.
Definition DeclCXX.h:3015
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3200
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
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition Lookup.h:672
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
LookupResultKind getResultKind() const
Definition Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:265
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:3381
Expr * getBase() const
Definition Expr.h:3375
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
Describes a module or submodule.
Definition Module.h:144
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:150
Module * Parent
The parent of this module.
Definition Module.h:193
bool isPrivateModule() const
Definition Module.h:249
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:648
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:664
bool isModulePartition() const
Is this a module partition.
Definition Module.h:653
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:224
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:722
@ ClassId_NSObject
Definition NSAPI.h:30
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isLinkageValid() const
True if the computed linkage is valid.
Definition Decl.cpp:1085
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:444
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition Decl.h:479
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:429
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
bool declarationReplaces(const NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition Decl.cpp:1863
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:706
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1935
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:1274
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1284
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:1153
@ CSK_Normal
Normal lookup.
Definition Overload.h:1157
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1369
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:273
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1386
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1399
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1382
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3302
Represents a parameter to a function.
Definition Decl.h:1790
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1850
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1854
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1823
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1882
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2951
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2974
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:8096
Pointer-authentication qualifiers.
Definition TypeBase.h:152
bool isAddressDiscriminated() const
Definition TypeBase.h:265
TypeLoc getPointeeLoc() const
Definition TypeLoc.h:1465
Wrapper for source info for pointers.
Definition TypeLoc.h:1484
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1490
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
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:8362
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8356
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:1453
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:2920
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:109
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1214
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1296
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:2969
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8278
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8404
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:8318
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getCanonicalType() const
Definition TypeBase.h:8330
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8372
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:2953
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition TypeBase.h:1433
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8351
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1670
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isCanonical() const
Definition TypeBase.h:8335
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1309
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1442
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2694
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition TypeBase.h:1493
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition TypeBase.h:1498
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:8218
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8225
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4659
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:4312
field_range fields() const
Definition Decl.h:4515
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5164
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4512
field_iterator field_begin() const
Definition Decl.cpp:5207
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7389
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:5317
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3573
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3139
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:3182
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void setEntity(DeclContext *E)
Definition Scope.h:409
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:428
unsigned getDepth() const
Returns the depth of this scope. The translation-unit has scope depth 0.
Definition Scope.h:339
unsigned getNextFunctionPrototypeIndex()
Return the number of parameters declared in this function prototype, increasing it by one for the nex...
Definition Scope.h:349
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:291
void AddDecl(Decl *D)
Definition Scope.h:362
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
bool isTypeAliasScope() const
Determine whether this scope is a type alias scope.
Definition Scope.h:628
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:398
void RemoveDecl(Decl *D)
Definition Scope.h:370
void setLookupEntity(DeclContext *E)
Definition Scope.h:414
unsigned getMSLastManglingNumber() const
Definition Scope.h:386
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
unsigned getMSCurManglingNumber() const
Definition Scope.h:392
bool decl_empty() const
Definition Scope.h:360
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:481
unsigned getFunctionPrototypeDepth() const
Returns the number of function prototype scopes in this scope chain.
Definition Scope.h:343
Scope * getDeclParent()
Definition Scope.h:335
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition Scope.h:619
decl_range decls() const
Definition Scope.h:356
bool containedInPrototypeScope() const
containedInPrototypeScope - Return true if this or a parent scope is a FunctionPrototypeScope.
Definition Scope.cpp:106
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:487
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred within this scope.
Definition Scope.h:420
void applyNRVO()
Definition Scope.cpp:166
Scope * getTemplateParamParent()
Definition Scope.h:332
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
void CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition SemaARM.cpp:1417
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:90
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:757
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:212
void maybeAddHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition SemaCUDA.cpp:845
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:910
void CheckEntryPoint(FunctionDecl *FD)
Definition SemaHLSL.cpp:891
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:657
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:623
void deduceAddressSpace(VarDecl *Decl)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:726
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:693
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:637
void ActOnVariableDeclarator(VarDecl *VD)
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
void AddCFAuditedAttribute(Decl *D)
AddCFAuditedAttribute - Check whether we're currently within '#pragma clang arc_cf_code_audited' and,...
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void ActOnVariableDeclarator(VarDecl *VD)
Function called when a variable declarator is created, which lets us implement the 'routine' 'functio...
OpenACCRoutineDeclAttr * mergeRoutineDeclAttr(const OpenACCRoutineDeclAttr &Old)
void ActOnFunctionDeclarator(FunctionDecl *FD)
Called when a function decl is created, which lets us implement the 'routine' 'doesn't match next thi...
void ActOnVariableInit(VarDecl *VD, QualType InitType)
Called when a variable is initialized, so we can implement the 'routine 'doesn't match the next thing...
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Decl *D, SmallVectorImpl< FunctionDecl * > &Bases)
Register D as specialization of all base functions in Bases in the current omp begin/end declare vari...
void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl< FunctionDecl * > &Bases)
The declarator D defines a function in the scope S which is nested in an omp begin/end declare varian...
void ActOnOpenMPDeclareTargetInitializer(Decl *D)
Adds OMPDeclareTargetDeclAttr to referenced variables in declare target directive.
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D, const llvm::StringMap< bool > &FeatureMap)
void CheckSYCLExternalFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:253
StmtResult BuildSYCLKernelCallStmt(FunctionDecl *FD, CompoundStmt *Body)
Definition SemaSYCL.cpp:437
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:270
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition SemaSwift.cpp:26
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition SemaWasm.cpp:334
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition SemaWasm.cpp:313
bool IsAlignAttr() const
Definition Sema.h:1887
Mode getAlignMode() const
Definition Sema.h:1889
A RAII object to temporarily push a declaration context.
Definition Sema.h:3467
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1355
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1367
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:3681
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3691
static NameClassification Unknown()
Definition Sema.h:3661
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3665
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3709
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3697
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3671
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3703
static NameClassification UndeclaredNonType()
Definition Sema.h:3677
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3685
static NameClassification Error()
Definition Sema.h:3657
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12418
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12452
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition Sema.h:3559
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13012
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2537
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1120
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:8219
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6289
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9305
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9309
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9328
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9344
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9341
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9317
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9312
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.
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:1501
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1241
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:4731
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3541
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1813
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:6481
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:1441
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:277
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2440
Preprocessor & getPreprocessor() const
Definition Sema.h:924
void deduceOpenCLAddressSpace(ValueDecl *decl)
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2044
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2038
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:4132
@ Delete
deleted-function-body
Definition Sema.h:4138
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.
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)
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:1526
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:1651
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:673
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ASTContext & Context
Definition Sema.h:1283
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void * SkippedDefinitionContext
Definition Sema.h:4356
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1486
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:77
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2041
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:3549
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:925
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:2037
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:756
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:697
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
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:1191
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:1656
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:12118
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8337
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:795
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:2328
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:168
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition Sema.h:4569
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:920
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2346
void PopCompoundScope()
Definition Sema.cpp:2479
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:14343
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14346
@ UPPC_Initializer
An initializer.
Definition Sema.h:14358
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14352
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14331
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14370
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14355
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14334
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14337
const LangOptions & getLangOpts() const
Definition Sema.h:918
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)
SourceLocation CurInitSegLoc
Definition Sema.h:2077
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:220
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition Sema.h:3566
SemaOpenACC & OpenACC()
Definition Sema.h:1491
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:1282
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:2118
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:1281
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:2555
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15435
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1451
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:1814
SemaRISCV & RISCV()
Definition Sema.h:1516
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:15611
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:213
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:1531
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:2026
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:6945
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2036
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1124
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:896
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:4746
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1314
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2474
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:6942
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.
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:639
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:15429
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2076
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9835
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:1414
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SemaOpenCL & OpenCL()
Definition Sema.h:1496
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:1631
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:3563
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:13891
SourceManager & getSourceManager() const
Definition Sema.h:923
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:3516
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:1815
@ NTCUK_Destruct
Definition Sema.h:4071
@ NTCUK_Init
Definition Sema.h:4070
@ NTCUK_Copy
Definition Sema.h:4072
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1812
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:6742
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:224
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)
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:2495
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:6503
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:625
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3537
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:272
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:1284
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4632
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:6949
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1319
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1777
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9863
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....
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
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:1506
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition SemaStmt.cpp:75
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1246
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:3556
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:8292
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D)
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:1286
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:1285
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:919
FPOptions CurFPFeatures
Definition Sema.h:1279
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...
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2035
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:11550
@ TPC_ClassTemplateMember
Definition Sema.h:11548
@ TPC_FunctionTemplate
Definition Sema.h:11547
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11551
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:1556
bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl)
Certain globally-unique variables might be accidentally duplicated if built into multiple shared libr...
void DiagnoseUnusedDecl(const NamedDecl *ND)
void PopDeclContext()
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6519
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...
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, IdentifierInfo *IIEnvironment)
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:3531
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2101
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
PragmaClangSection PragmaClangBSSSection
Definition Sema.h:1811
Decl * ActOnDeclarator(Scope *S, Declarator &D)
@ AbstractVariableType
Definition Sema.h:6213
@ AbstractReturnType
Definition Sema.h:6211
@ AbstractFieldType
Definition Sema.h:6214
@ AbstractIvarType
Definition Sema.h:6215
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:8341
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:6400
void CheckVariableDeclarationType(VarDecl *NewVD)
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1275
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:3512
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:1541
IdentifierResolver IdResolver
Definition Sema.h:3460
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:2486
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition SemaDecl.cpp:716
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:145
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:8300
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1274
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:3804
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:1421
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:322
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation TriviallyRelocatable, SourceLocation Replaceable, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8631
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:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:362
child_range children()
Definition Stmt.cpp:299
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition Expr.h:1945
StringRef getString() const
Definition Expr.h:1867
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition Decl.h:3999
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition Decl.cpp:4923
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3807
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3793
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3812
bool isStruct() const
Definition Decl.h:3919
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:4895
bool isUnion() const
Definition Decl.h:3922
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:3944
TagKind getTagKind() const
Definition Decl.h:3911
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3857
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
virtual bool validateCpuSupports(StringRef Name) const
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation getRAngleLoc() const
SourceLocation getTemplateLoc() const
Token - This structure provides full information about a lexed token.
Definition Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:102
bool isOneOf(Ts... Ks) const
Definition Token.h:104
bool isNot(tok::TokenKind K) const
Definition Token.h:103
A declaration that models statements at global scope.
Definition Decl.h:4622
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition Decl.cpp:5787
void setStmt(Stmt *S)
Definition Decl.cpp:5807
Represents a declaration of a type.
Definition Decl.h:3513
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
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:1408
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:879
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:2706
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8249
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:8260
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isStructureType() const
Definition Type.cpp:678
bool isDependentSizedArrayType() const
Definition TypeBase.h:8634
bool isVoidType() const
Definition TypeBase.h:8871
bool isBooleanType() const
Definition TypeBase.h:9001
bool isFunctionReferenceType() const
Definition TypeBase.h:8589
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9051
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:2993
bool isIncompleteArrayType() const
Definition TypeBase.h:8622
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9167
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:8618
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9031
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8614
bool isFunctionPointerType() const
Definition TypeBase.h:8582
bool isPointerType() const
Definition TypeBase.h:8515
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9158
bool isReferenceType() const
Definition TypeBase.h:8539
bool isScalarType() const
Definition TypeBase.h:8973
bool isVariableArrayType() const
Definition TypeBase.h:8626
bool isClkEventT() const
Definition TypeBase.h:8757
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2103
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8989
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:8769
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2899
bool isPipeType() const
Definition TypeBase.h:8776
bool isOpenCLSpecificType() const
Definition TypeBase.h:8805
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2411
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isHalfType() const
Definition TypeBase.h:8875
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2056
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2557
bool containsErrors() const
Whether this type is an error type.
Definition TypeBase.h:2776
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9044
bool isAtomicType() const
Definition TypeBase.h:8697
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isObjCIdType() const
Definition TypeBase.h:8717
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
bool isObjCObjectType() const
Definition TypeBase.h:8688
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9007
bool isEventT() const
Definition TypeBase.h:8753
bool isPointerOrReferenceType() const
Definition TypeBase.h:8519
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2435
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition TypeBase.h:9108
bool isFunctionType() const
Definition TypeBase.h:8511
bool isObjCObjectPointerType() const
Definition TypeBase.h:8684
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8600
bool isFloatingType() const
Definition Type.cpp:2304
bool isAnyPointerType() const
Definition TypeBase.h:8523
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition Type.cpp:2061
bool isSamplerT() const
Definition TypeBase.h:8749
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isNullPtrType() const
Definition TypeBase.h:8908
bool isRecordType() const
Definition TypeBase.h:8642
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5366
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5014
bool isUnionType() const
Definition Type.cpp:718
bool isFunctionNoProtoType() const
Definition TypeBase.h:2600
bool isReserveIDT() const
Definition TypeBase.h:8765
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3667
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5686
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3612
QualType getUnderlyingType() const
Definition Decl.h:3617
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition Decl.h:3623
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
TypedefNameDecl * getDecl() const
Definition TypeBase.h:6099
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:2285
Opcode getOpcode() const
Definition Expr.h:2280
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2340
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1030
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1034
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1086
UnionParsedType ConstructorName
When Kind == IK_ConstructorName, the class-name of the type whose constructor is being referenced.
Definition DeclSpec.h:1038
SourceLocation EndLocation
The location of the last token that describes this unqualified-id.
Definition DeclSpec.h:1059
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1207
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1042
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1056
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1045
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1026
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1080
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1050
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3463
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3374
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:5518
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5512
Represents a variable declaration or definition.
Definition Decl.h:926
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2815
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2156
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1525
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1569
TLSKind getTLSKind() const
Definition Decl.cpp:2173
bool hasInit() const
Definition Decl.cpp:2403
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1452
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2265
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2195
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:2466
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2262
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1578
bool isCXXCondDecl() const
Definition Decl.h:1611
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:937
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition Decl.h:940
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:934
void setStorageClass(StorageClass SC)
Definition Decl.cpp:2168
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1593
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1226
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2371
void setInlineSpecified()
Definition Decl.h:1558
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1208
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2777
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1342
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1173
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1551
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1177
const Expr * getInit() const
Definition Decl.h:1368
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1217
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1184
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition Decl.cpp:2434
void setConstexpr(bool IC)
Definition Decl.h:1572
@ TLS_Static
TLS with a known-constant initializer.
Definition Decl.h:949
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:952
void setInit(Expr *I)
Definition Decl.cpp:2482
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition Decl.cpp:2350
@ TentativeDefinition
This declaration is a tentative definition.
Definition Decl.h:1298
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1295
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1301
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2820
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition Decl.cpp:2250
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1253
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1168
void setImplicitlyInline()
Definition Decl.h:1563
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition Decl.h:1476
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1588
VarDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition Decl.cpp:2711
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1262
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2784
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1358
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3966
Expr * getSizeExpr() const
Definition TypeBase.h:3980
Captures information about a #pragma weak directive.
Definition Weak.h:25
ValueDecl * getVariable() const
Definition ScopeInfo.h:675
bool isVariableCapture() const
Definition ScopeInfo.h:650
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:686
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:745
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:732
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:708
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:755
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition ScopeInfo.h:1096
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:737
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:498
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
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:884
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition ScopeInfo.h:915
ParmVarDecl * ExplicitObjectParameter
Definition ScopeInfo.h:881
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition ScopeInfo.h:948
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:871
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:874
bool Mutable
Whether this is a mutable lambda.
Definition ScopeInfo.h:896
Provides information about an attempted template argument deduction, whose success or failure was des...
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
Public enums and private classes that are part of the SourceManager implementation.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_struct
Definition Specifiers.h:81
@ TST_class
Definition Specifiers.h:82
@ TST_union
Definition Specifiers.h:80
@ TST_enum
Definition Specifiers.h:79
@ TST_interface
Definition Specifiers.h:83
ImplicitTypenameContext
Definition DeclSpec.h:1857
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:820
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:812
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:212
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ GVA_AvailableExternally
Definition Linkage.h:74
CUDAFunctionTarget
Definition Cuda.h:60
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
int hasAttribute(AttributeCommonInfo::Syntax Syntax, llvm::StringRef ScopeName, llvm::StringRef AttrName, const TargetInfo &Target, const LangOptions &LangOpts, bool CheckPlugins)
Return the version number associated with the attribute if we recognize and implement the attribute s...
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:35
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
std::pair< FileID, unsigned > FileIDAndOffset
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition Lambda.h:35
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:602
@ TemplateTemplateArgument
Definition Sema.h:611
NonTrivialCUnionContext
Definition Sema.h:530
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:626
@ None
Don't merge availability attributes at all.
Definition Sema.h:628
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:634
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:640
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:631
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:637
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:994
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:992
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:990
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:986
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:984
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:982
@ IK_Identifier
An identifier.
Definition DeclSpec.h:976
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:988
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:978
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:980
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_public
Definition Specifiers.h:124
@ AS_protected
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:127
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition Lookup.h:137
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition Linkage.h:63
@ CLanguageLinkage
Definition Linkage.h:64
@ CXXLanguageLinkage
Definition Linkage.h:65
StorageClass
Storage classes.
Definition Specifiers.h:248
@ SC_Auto
Definition Specifiers.h:256
@ SC_PrivateExtern
Definition Specifiers.h:253
@ SC_Extern
Definition Specifiers.h:251
@ SC_Register
Definition Specifiers.h:257
@ SC_Static
Definition Specifiers.h:252
@ SC_None
Definition Specifiers.h:250
@ TSCS_thread_local
C++11 thread_local.
Definition Specifiers.h:241
@ TSCS_unspecified
Definition Specifiers.h:236
@ TSCS__Thread_local
C11 _Thread_local.
Definition Specifiers.h:244
@ TSCS___thread
GNU __thread.
Definition Specifiers.h:238
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
llvm::Expected< Decl * > ExpectedDecl
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:342
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:908
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:614
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
const FunctionProtoType * T
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:319
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:449
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5878
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5883
@ Struct
The "struct" keyword.
Definition TypeBase.h:5880
@ Class
The "class" keyword.
Definition TypeBase.h:5889
@ Union
The "union" keyword.
Definition TypeBase.h:5886
@ Enum
The "enum" keyword.
Definition TypeBase.h:5892
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:4305
@ TU_Complete
The translation unit is a complete translation unit.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:425
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition Lambda.h:22
@ LCD_ByRef
Definition Lambda.h:25
@ LCD_None
Definition Lambda.h:23
@ LCD_ByCopy
Definition Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
MultiVersionKind
Definition Decl.h:1979
bool isExternalFormalLinkage(Linkage L)
Definition Linkage.h:117
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:367
@ Success
Template argument deduction was successful.
Definition Sema.h:369
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:421
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_X86StdCall
Definition Specifiers.h:280
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:826
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:5874
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5864
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5867
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5871
ReservedIdentifierStatus
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition Visibility.h:37
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition ASTLambda.h:60
const Expr * ConstraintExpr
Definition Decl.h:88
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword).
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1398
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition DeclSpec.h:1549
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1373
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1332
const IdentifierInfo * Ident
Definition DeclSpec.h:1304
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1221
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1633
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:1614
FunctionTypeInfo Fun
Definition DeclSpec.h:1612
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition DeclSpec.h:1657
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
Extra information about a function prototype.
Definition TypeBase.h:5339
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition TypeBase.h:5366
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:5917
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3240
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:2011
SourceLocation CurrentPragmaLocation
Definition Sema.h:2012
bool CheckSameAsPrevious
Definition Sema.h:353
NamedDecl * Previous
Definition Sema.h:354
NamedDecl * New
Definition Sema.h:355
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:1018
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1009