clang 20.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"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
37#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
38#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
39#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
40#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
42#include "clang/Sema/DeclSpec.h"
45#include "clang/Sema/Lookup.h"
47#include "clang/Sema/Scope.h"
49#include "clang/Sema/SemaCUDA.h"
50#include "clang/Sema/SemaHLSL.h"
52#include "clang/Sema/SemaObjC.h"
54#include "clang/Sema/SemaPPC.h"
57#include "clang/Sema/SemaWasm.h"
58#include "clang/Sema/Template.h"
59#include "llvm/ADT/STLForwardCompat.h"
60#include "llvm/ADT/SmallString.h"
61#include "llvm/ADT/StringExtras.h"
62#include "llvm/TargetParser/Triple.h"
63#include <algorithm>
64#include <cstring>
65#include <functional>
66#include <optional>
67#include <unordered_map>
68
69using namespace clang;
70using namespace sema;
71
73 if (OwnedType) {
74 Decl *Group[2] = { OwnedType, Ptr };
76 }
77
79}
80
81namespace {
82
83class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
84 public:
85 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
86 bool AllowTemplates = false,
87 bool AllowNonTemplates = true)
88 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
89 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
90 WantExpressionKeywords = false;
91 WantCXXNamedCasts = false;
92 WantRemainingKeywords = false;
93 }
94
95 bool ValidateCandidate(const TypoCorrection &candidate) override {
96 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
97 if (!AllowInvalidDecl && ND->isInvalidDecl())
98 return false;
99
100 if (getAsTypeTemplateDecl(ND))
101 return AllowTemplates;
102
103 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
104 if (!IsType)
105 return false;
106
107 if (AllowNonTemplates)
108 return true;
109
110 // An injected-class-name of a class template (specialization) is valid
111 // as a template or as a non-template.
112 if (AllowTemplates) {
113 auto *RD = dyn_cast<CXXRecordDecl>(ND);
114 if (!RD || !RD->isInjectedClassName())
115 return false;
116 RD = cast<CXXRecordDecl>(RD->getDeclContext());
117 return RD->getDescribedClassTemplate() ||
118 isa<ClassTemplateSpecializationDecl>(RD);
119 }
120
121 return false;
122 }
123
124 return !WantClassName && candidate.isKeyword();
125 }
126
127 std::unique_ptr<CorrectionCandidateCallback> clone() override {
128 return std::make_unique<TypeNameValidatorCCC>(*this);
129 }
130
131 private:
132 bool AllowInvalidDecl;
133 bool WantClassName;
134 bool AllowTemplates;
135 bool AllowNonTemplates;
136};
137
138} // end anonymous namespace
139
140namespace {
141enum class UnqualifiedTypeNameLookupResult {
142 NotFound,
143 FoundNonType,
144 FoundType
145};
146} // end anonymous namespace
147
148/// Tries to perform unqualified lookup of the type decls in bases for
149/// dependent class.
150/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
151/// type decl, \a FoundType if only type decls are found.
152static UnqualifiedTypeNameLookupResult
154 SourceLocation NameLoc,
155 const CXXRecordDecl *RD) {
156 if (!RD->hasDefinition())
157 return UnqualifiedTypeNameLookupResult::NotFound;
158 // Look for type decls in base classes.
159 UnqualifiedTypeNameLookupResult FoundTypeDecl =
160 UnqualifiedTypeNameLookupResult::NotFound;
161 for (const auto &Base : RD->bases()) {
162 const CXXRecordDecl *BaseRD = nullptr;
163 if (auto *BaseTT = Base.getType()->getAs<TagType>())
164 BaseRD = BaseTT->getAsCXXRecordDecl();
165 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
166 // Look for type decls in dependent base classes that have known primary
167 // templates.
168 if (!TST || !TST->isDependentType())
169 continue;
170 auto *TD = TST->getTemplateName().getAsTemplateDecl();
171 if (!TD)
172 continue;
173 if (auto *BasePrimaryTemplate =
174 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
175 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
176 BaseRD = BasePrimaryTemplate;
177 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
179 CTD->findPartialSpecialization(Base.getType()))
180 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
181 BaseRD = PS;
182 }
183 }
184 }
185 if (BaseRD) {
186 for (NamedDecl *ND : BaseRD->lookup(&II)) {
187 if (!isa<TypeDecl>(ND))
188 return UnqualifiedTypeNameLookupResult::FoundNonType;
189 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190 }
191 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
192 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
193 case UnqualifiedTypeNameLookupResult::FoundNonType:
194 return UnqualifiedTypeNameLookupResult::FoundNonType;
195 case UnqualifiedTypeNameLookupResult::FoundType:
196 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
197 break;
198 case UnqualifiedTypeNameLookupResult::NotFound:
199 break;
200 }
201 }
202 }
203 }
204
205 return FoundTypeDecl;
206}
207
209 const IdentifierInfo &II,
210 SourceLocation NameLoc) {
211 // Lookup in the parent class template context, if any.
212 const CXXRecordDecl *RD = nullptr;
213 UnqualifiedTypeNameLookupResult FoundTypeDecl =
214 UnqualifiedTypeNameLookupResult::NotFound;
215 for (DeclContext *DC = S.CurContext;
216 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
217 DC = DC->getParent()) {
218 // Look for type decls in dependent base classes that have known primary
219 // templates.
220 RD = dyn_cast<CXXRecordDecl>(DC);
221 if (RD && RD->getDescribedClassTemplate())
222 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
223 }
224 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
225 return nullptr;
226
227 // We found some types in dependent base classes. Recover as if the user
228 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
229 // lookup during template instantiation.
230 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
231
232 ASTContext &Context = S.Context;
233 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
234 cast<Type>(Context.getRecordType(RD)));
235 QualType T =
237
238 CXXScopeSpec SS;
239 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
240
241 TypeLocBuilder Builder;
242 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
243 DepTL.setNameLoc(NameLoc);
245 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
246 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
247}
248
249/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
251 SourceLocation NameLoc,
252 bool WantNontrivialTypeSourceInfo = true) {
253 switch (T->getTypeClass()) {
254 case Type::DeducedTemplateSpecialization:
255 case Type::Enum:
256 case Type::InjectedClassName:
257 case Type::Record:
258 case Type::Typedef:
259 case Type::UnresolvedUsing:
260 case Type::Using:
261 break;
262 // These can never be qualified so an ElaboratedType node
263 // would carry no additional meaning.
264 case Type::ObjCInterface:
265 case Type::ObjCTypeParam:
266 case Type::TemplateTypeParm:
267 return ParsedType::make(T);
268 default:
269 llvm_unreachable("Unexpected Type Class");
270 }
271
272 if (!SS || SS->isEmpty())
274 ElaboratedTypeKeyword::None, nullptr, T, nullptr));
275
277 if (!WantNontrivialTypeSourceInfo)
278 return ParsedType::make(ElTy);
279
280 TypeLocBuilder Builder;
281 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
282 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
285 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
286}
287
289 Scope *S, CXXScopeSpec *SS, bool isClassName,
290 bool HasTrailingDot, ParsedType ObjectTypePtr,
291 bool IsCtorOrDtorName,
292 bool WantNontrivialTypeSourceInfo,
293 bool IsClassTemplateDeductionContext,
294 ImplicitTypenameContext AllowImplicitTypename,
295 IdentifierInfo **CorrectedII) {
296 // FIXME: Consider allowing this outside C++1z mode as an extension.
297 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
298 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
299 !isClassName && !HasTrailingDot;
300
301 // Determine where we will perform name lookup.
302 DeclContext *LookupCtx = nullptr;
303 if (ObjectTypePtr) {
304 QualType ObjectType = ObjectTypePtr.get();
305 if (ObjectType->isRecordType())
306 LookupCtx = computeDeclContext(ObjectType);
307 } else if (SS && SS->isNotEmpty()) {
308 LookupCtx = computeDeclContext(*SS, false);
309
310 if (!LookupCtx) {
311 if (isDependentScopeSpecifier(*SS)) {
312 // C++ [temp.res]p3:
313 // A qualified-id that refers to a type and in which the
314 // nested-name-specifier depends on a template-parameter (14.6.2)
315 // shall be prefixed by the keyword typename to indicate that the
316 // qualified-id denotes a type, forming an
317 // elaborated-type-specifier (7.1.5.3).
318 //
319 // We therefore do not perform any name lookup if the result would
320 // refer to a member of an unknown specialization.
321 // In C++2a, in several contexts a 'typename' is not required. Also
322 // allow this as an extension.
323 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
324 !isClassName && !IsCtorOrDtorName)
325 return nullptr;
326 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
327 if (IsImplicitTypename) {
328 SourceLocation QualifiedLoc = SS->getRange().getBegin();
330 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
331 else
332 Diag(QualifiedLoc, diag::ext_implicit_typename)
333 << SS->getScopeRep() << II.getName()
334 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
335 }
336
337 // We know from the grammar that this name refers to a type,
338 // so build a dependent node to describe the type.
339 if (WantNontrivialTypeSourceInfo)
340 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
341 (ImplicitTypenameContext)IsImplicitTypename)
342 .get();
343
346 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
348 SourceLocation(), QualifierLoc, II, NameLoc);
349 return ParsedType::make(T);
350 }
351
352 return nullptr;
353 }
354
355 if (!LookupCtx->isDependentContext() &&
356 RequireCompleteDeclContext(*SS, LookupCtx))
357 return nullptr;
358 }
359
360 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
361 // lookup for class-names.
362 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
364 LookupResult Result(*this, &II, NameLoc, Kind);
365 if (LookupCtx) {
366 // Perform "qualified" name lookup into the declaration context we
367 // computed, which is either the type of the base of a member access
368 // expression or the declaration context associated with a prior
369 // nested-name-specifier.
370 LookupQualifiedName(Result, LookupCtx);
371
372 if (ObjectTypePtr && Result.empty()) {
373 // C++ [basic.lookup.classref]p3:
374 // If the unqualified-id is ~type-name, the type-name is looked up
375 // in the context of the entire postfix-expression. If the type T of
376 // the object expression is of a class type C, the type-name is also
377 // looked up in the scope of class C. At least one of the lookups shall
378 // find a name that refers to (possibly cv-qualified) T.
379 LookupName(Result, S);
380 }
381 } else {
382 // Perform unqualified name lookup.
383 LookupName(Result, S);
384
385 // For unqualified lookup in a class template in MSVC mode, look into
386 // dependent base classes where the primary class template is known.
387 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
388 if (ParsedType TypeInBase =
389 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
390 return TypeInBase;
391 }
392 }
393
394 NamedDecl *IIDecl = nullptr;
395 UsingShadowDecl *FoundUsingShadow = nullptr;
396 switch (Result.getResultKind()) {
398 if (CorrectedII) {
399 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
400 AllowDeducedTemplate);
401 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
402 S, SS, CCC, CTK_ErrorRecovery);
403 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
404 TemplateTy Template;
405 bool MemberOfUnknownSpecialization;
407 TemplateName.setIdentifier(NewII, NameLoc);
409 CXXScopeSpec NewSS, *NewSSPtr = SS;
410 if (SS && NNS) {
411 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
412 NewSSPtr = &NewSS;
413 }
414 if (Correction && (NNS || NewII != &II) &&
415 // Ignore a correction to a template type as the to-be-corrected
416 // identifier is not a template (typo correction for template names
417 // is handled elsewhere).
418 !(getLangOpts().CPlusPlus && NewSSPtr &&
419 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
420 Template, MemberOfUnknownSpecialization))) {
421 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
422 isClassName, HasTrailingDot, ObjectTypePtr,
423 IsCtorOrDtorName,
424 WantNontrivialTypeSourceInfo,
425 IsClassTemplateDeductionContext);
426 if (Ty) {
427 diagnoseTypo(Correction,
428 PDiag(diag::err_unknown_type_or_class_name_suggest)
429 << Result.getLookupName() << isClassName);
430 if (SS && NNS)
431 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
432 *CorrectedII = NewII;
433 return Ty;
434 }
435 }
436 }
437 Result.suppressDiagnostics();
438 return nullptr;
440 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
442 SS->getScopeRep(), &II);
443 TypeLocBuilder TLB;
447 TL.setNameLoc(NameLoc);
449 }
450 [[fallthrough]];
453 Result.suppressDiagnostics();
454 return nullptr;
455
457 // Recover from type-hiding ambiguities by hiding the type. We'll
458 // do the lookup again when looking for an object, and we can
459 // diagnose the error then. If we don't do this, then the error
460 // about hiding the type will be immediately followed by an error
461 // that only makes sense if the identifier was treated like a type.
462 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
463 Result.suppressDiagnostics();
464 return nullptr;
465 }
466
467 // Look to see if we have a type anywhere in the list of results.
468 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
469 Res != ResEnd; ++Res) {
470 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
471 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
472 RealRes) ||
473 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
474 if (!IIDecl ||
475 // Make the selection of the recovery decl deterministic.
476 RealRes->getLocation() < IIDecl->getLocation()) {
477 IIDecl = RealRes;
478 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
479 }
480 }
481 }
482
483 if (!IIDecl) {
484 // None of the entities we found is a type, so there is no way
485 // to even assume that the result is a type. In this case, don't
486 // complain about the ambiguity. The parser will either try to
487 // perform this lookup again (e.g., as an object name), which
488 // will produce the ambiguity, or will complain that it expected
489 // a type name.
490 Result.suppressDiagnostics();
491 return nullptr;
492 }
493
494 // We found a type within the ambiguous lookup; diagnose the
495 // ambiguity and then return that type. This might be the right
496 // answer, or it might not be, but it suppresses any attempt to
497 // perform the name lookup again.
498 break;
499
501 IIDecl = Result.getFoundDecl();
502 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
503 break;
504 }
505
506 assert(IIDecl && "Didn't find decl");
507
508 QualType T;
509 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
510 // C++ [class.qual]p2: A lookup that would find the injected-class-name
511 // instead names the constructors of the class, except when naming a class.
512 // This is ill-formed when we're not actually forming a ctor or dtor name.
513 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
514 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
515 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
516 FoundRD->isInjectedClassName() &&
517 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
518 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
519 << &II << /*Type*/1;
520
521 DiagnoseUseOfDecl(IIDecl, NameLoc);
522
524 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
525 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
526 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
527 if (!HasTrailingDot)
529 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
530 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
531 (void)DiagnoseUseOfDecl(UD, NameLoc);
532 // Recover with 'int'
534 } else if (AllowDeducedTemplate) {
535 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
536 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
538 SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false,
539 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
541 false);
542 // Don't wrap in a further UsingType.
543 FoundUsingShadow = nullptr;
544 }
545 }
546
547 if (T.isNull()) {
548 // If it's not plausibly a type, suppress diagnostics.
549 Result.suppressDiagnostics();
550 return nullptr;
551 }
552
553 if (FoundUsingShadow)
554 T = Context.getUsingType(FoundUsingShadow, T);
555
556 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
557}
558
559// Builds a fake NNS for the given decl context.
560static NestedNameSpecifier *
562 for (;; DC = DC->getLookupParent()) {
563 DC = DC->getPrimaryContext();
564 auto *ND = dyn_cast<NamespaceDecl>(DC);
565 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
566 return NestedNameSpecifier::Create(Context, nullptr, ND);
567 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
568 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
569 RD->getTypeForDecl());
570 else if (isa<TranslationUnitDecl>(DC))
572 }
573 llvm_unreachable("something isn't in TU scope?");
574}
575
576/// Find the parent class with dependent bases of the innermost enclosing method
577/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
578/// up allowing unqualified dependent type names at class-level, which MSVC
579/// correctly rejects.
580static const CXXRecordDecl *
582 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
583 DC = DC->getPrimaryContext();
584 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
585 if (MD->getParent()->hasAnyDependentBases())
586 return MD->getParent();
587 }
588 return nullptr;
589}
590
592 SourceLocation NameLoc,
593 bool IsTemplateTypeArg) {
594 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
595
596 NestedNameSpecifier *NNS = nullptr;
597 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
598 // If we weren't able to parse a default template argument, delay lookup
599 // until instantiation time by making a non-dependent DependentTypeName. We
600 // pretend we saw a NestedNameSpecifier referring to the current scope, and
601 // lookup is retried.
602 // FIXME: This hurts our diagnostic quality, since we get errors like "no
603 // type named 'Foo' in 'current_namespace'" when the user didn't write any
604 // name specifiers.
606 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
607 } else if (const CXXRecordDecl *RD =
609 // Build a DependentNameType that will perform lookup into RD at
610 // instantiation time.
611 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
612 RD->getTypeForDecl());
613
614 // Diagnose that this identifier was undeclared, and retry the lookup during
615 // template instantiation.
616 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
617 << RD;
618 } else {
619 // This is not a situation that we should recover from.
620 return ParsedType();
621 }
622
623 QualType T =
625
626 // Build type location information. We synthesized the qualifier, so we have
627 // to build a fake NestedNameSpecifierLoc.
628 NestedNameSpecifierLocBuilder NNSLocBuilder;
629 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
630 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
631
632 TypeLocBuilder Builder;
633 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
634 DepTL.setNameLoc(NameLoc);
636 DepTL.setQualifierLoc(QualifierLoc);
637 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
638}
639
641 // Do a tag name lookup in this scope.
642 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
643 LookupName(R, S, false);
646 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
647 switch (TD->getTagKind()) {
653 return DeclSpec::TST_union;
655 return DeclSpec::TST_class;
657 return DeclSpec::TST_enum;
658 }
659 }
660
662}
663
665 if (CurContext->isRecord()) {
667 return true;
668
669 const Type *Ty = SS->getScopeRep()->getAsType();
670
671 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
672 for (const auto &Base : RD->bases())
673 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
674 return true;
675 return S->isFunctionPrototypeScope();
676 }
677 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
678}
679
681 SourceLocation IILoc,
682 Scope *S,
683 CXXScopeSpec *SS,
684 ParsedType &SuggestedType,
685 bool IsTemplateName) {
686 // Don't report typename errors for editor placeholders.
687 if (II->isEditorPlaceholder())
688 return;
689 // We don't have anything to suggest (yet).
690 SuggestedType = nullptr;
691
692 // There may have been a typo in the name of the type. Look up typo
693 // results, in case we have something that we can suggest.
694 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
695 /*AllowTemplates=*/IsTemplateName,
696 /*AllowNonTemplates=*/!IsTemplateName);
697 if (TypoCorrection Corrected =
699 CCC, CTK_ErrorRecovery)) {
700 // FIXME: Support error recovery for the template-name case.
701 bool CanRecover = !IsTemplateName;
702 if (Corrected.isKeyword()) {
703 // We corrected to a keyword.
704 diagnoseTypo(Corrected,
705 PDiag(IsTemplateName ? diag::err_no_template_suggest
706 : diag::err_unknown_typename_suggest)
707 << II);
708 II = Corrected.getCorrectionAsIdentifierInfo();
709 } else {
710 // We found a similarly-named type or interface; suggest that.
711 if (!SS || !SS->isSet()) {
712 diagnoseTypo(Corrected,
713 PDiag(IsTemplateName ? diag::err_no_template_suggest
714 : diag::err_unknown_typename_suggest)
715 << II, CanRecover);
716 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
717 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
718 bool DroppedSpecifier =
719 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
720 diagnoseTypo(Corrected,
721 PDiag(IsTemplateName
722 ? diag::err_no_member_template_suggest
723 : diag::err_unknown_nested_typename_suggest)
724 << II << DC << DroppedSpecifier << SS->getRange(),
725 CanRecover);
726 } else {
727 llvm_unreachable("could not have corrected a typo here");
728 }
729
730 if (!CanRecover)
731 return;
732
733 CXXScopeSpec tmpSS;
734 if (Corrected.getCorrectionSpecifier())
735 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
736 SourceRange(IILoc));
737 // FIXME: Support class template argument deduction here.
738 SuggestedType =
739 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
740 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
741 /*IsCtorOrDtorName=*/false,
742 /*WantNontrivialTypeSourceInfo=*/true);
743 }
744 return;
745 }
746
747 if (getLangOpts().CPlusPlus && !IsTemplateName) {
748 // See if II is a class template that the user forgot to pass arguments to.
749 UnqualifiedId Name;
750 Name.setIdentifier(II, IILoc);
751 CXXScopeSpec EmptySS;
752 TemplateTy TemplateResult;
753 bool MemberOfUnknownSpecialization;
754 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
755 Name, nullptr, true, TemplateResult,
756 MemberOfUnknownSpecialization) == TNK_Type_template) {
757 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
758 return;
759 }
760 }
761
762 // FIXME: Should we move the logic that tries to recover from a missing tag
763 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
764
765 if (!SS || (!SS->isSet() && !SS->isInvalid()))
766 Diag(IILoc, IsTemplateName ? diag::err_no_template
767 : diag::err_unknown_typename)
768 << II;
769 else if (DeclContext *DC = computeDeclContext(*SS, false))
770 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
771 : diag::err_typename_nested_not_found)
772 << II << DC << SS->getRange();
773 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
774 SuggestedType =
775 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
776 } else if (isDependentScopeSpecifier(*SS)) {
777 unsigned DiagID = diag::err_typename_missing;
778 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
779 DiagID = diag::ext_typename_missing;
780
781 Diag(SS->getRange().getBegin(), DiagID)
782 << SS->getScopeRep() << II->getName()
783 << SourceRange(SS->getRange().getBegin(), IILoc)
784 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
785 SuggestedType = ActOnTypenameType(S, SourceLocation(),
786 *SS, *II, IILoc).get();
787 } else {
788 assert(SS && SS->isInvalid() &&
789 "Invalid scope specifier has already been diagnosed");
790 }
791}
792
793/// Determine whether the given result set contains either a type name
794/// or
795static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
796 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
797 NextToken.is(tok::less);
798
799 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
800 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
801 return true;
802
803 if (CheckTemplate && isa<TemplateDecl>(*I))
804 return true;
805 }
806
807 return false;
808}
809
811 Scope *S, CXXScopeSpec &SS,
812 IdentifierInfo *&Name,
813 SourceLocation NameLoc) {
814 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
815 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
816 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
817 StringRef FixItTagName;
818 switch (Tag->getTagKind()) {
820 FixItTagName = "class ";
821 break;
822
824 FixItTagName = "enum ";
825 break;
826
828 FixItTagName = "struct ";
829 break;
830
832 FixItTagName = "__interface ";
833 break;
834
836 FixItTagName = "union ";
837 break;
838 }
839
840 StringRef TagName = FixItTagName.drop_back();
841 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
842 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
843 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
844
845 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
846 I != IEnd; ++I)
847 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
848 << Name << TagName;
849
850 // Replace lookup results with just the tag decl.
852 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
853 return true;
854 }
855
856 return false;
857}
858
860 IdentifierInfo *&Name,
861 SourceLocation NameLoc,
862 const Token &NextToken,
864 DeclarationNameInfo NameInfo(Name, NameLoc);
865 ObjCMethodDecl *CurMethod = getCurMethodDecl();
866
867 assert(NextToken.isNot(tok::coloncolon) &&
868 "parse nested name specifiers before calling ClassifyName");
869 if (getLangOpts().CPlusPlus && SS.isSet() &&
870 isCurrentClassName(*Name, S, &SS)) {
871 // Per [class.qual]p2, this names the constructors of SS, not the
872 // injected-class-name. We don't have a classification for that.
873 // There's not much point caching this result, since the parser
874 // will reject it later.
876 }
877
878 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
879 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
880 /*AllowBuiltinCreation=*/!CurMethod);
881
882 if (SS.isInvalid())
884
885 // For unqualified lookup in a class template in MSVC mode, look into
886 // dependent base classes where the primary class template is known.
887 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
888 if (ParsedType TypeInBase =
889 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
890 return TypeInBase;
891 }
892
893 // Perform lookup for Objective-C instance variables (including automatically
894 // synthesized instance variables), if we're in an Objective-C method.
895 // FIXME: This lookup really, really needs to be folded in to the normal
896 // unqualified lookup mechanism.
897 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
898 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
899 if (Ivar.isInvalid())
901 if (Ivar.isUsable())
902 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
903
904 // We defer builtin creation until after ivar lookup inside ObjC methods.
905 if (Result.empty())
907 }
908
909 bool SecondTry = false;
910 bool IsFilteredTemplateName = false;
911
912Corrected:
913 switch (Result.getResultKind()) {
915 // If an unqualified-id is followed by a '(', then we have a function
916 // call.
917 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
918 // In C++, this is an ADL-only call.
919 // FIXME: Reference?
922
923 // C90 6.3.2.2:
924 // If the expression that precedes the parenthesized argument list in a
925 // function call consists solely of an identifier, and if no
926 // declaration is visible for this identifier, the identifier is
927 // implicitly declared exactly as if, in the innermost block containing
928 // the function call, the declaration
929 //
930 // extern int identifier ();
931 //
932 // appeared.
933 //
934 // We also allow this in C99 as an extension. However, this is not
935 // allowed in all language modes as functions without prototypes may not
936 // be supported.
937 if (getLangOpts().implicitFunctionsAllowed()) {
938 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
940 }
941 }
942
943 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
944 // In C++20 onwards, this could be an ADL-only call to a function
945 // template, and we're required to assume that this is a template name.
946 //
947 // FIXME: Find a way to still do typo correction in this case.
948 TemplateName Template =
951 }
952
953 // In C, we first see whether there is a tag type by the same name, in
954 // which case it's likely that the user just forgot to write "enum",
955 // "struct", or "union".
956 if (!getLangOpts().CPlusPlus && !SecondTry &&
957 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
958 break;
959 }
960
961 // Perform typo correction to determine if there is another name that is
962 // close to this name.
963 if (!SecondTry && CCC) {
964 SecondTry = true;
965 if (TypoCorrection Corrected =
966 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
967 &SS, *CCC, CTK_ErrorRecovery)) {
968 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
969 unsigned QualifiedDiag = diag::err_no_member_suggest;
970
971 NamedDecl *FirstDecl = Corrected.getFoundDecl();
972 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
973 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
974 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
975 UnqualifiedDiag = diag::err_no_template_suggest;
976 QualifiedDiag = diag::err_no_member_template_suggest;
977 } else if (UnderlyingFirstDecl &&
978 (isa<TypeDecl>(UnderlyingFirstDecl) ||
979 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
980 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
981 UnqualifiedDiag = diag::err_unknown_typename_suggest;
982 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
983 }
984
985 if (SS.isEmpty()) {
986 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
987 } else {// FIXME: is this even reachable? Test it.
988 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
989 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
990 Name->getName() == CorrectedStr;
991 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
992 << Name << computeDeclContext(SS, false)
993 << DroppedSpecifier << SS.getRange());
994 }
995
996 // Update the name, so that the caller has the new name.
997 Name = Corrected.getCorrectionAsIdentifierInfo();
998
999 // Typo correction corrected to a keyword.
1000 if (Corrected.isKeyword())
1001 return Name;
1002
1003 // Also update the LookupResult...
1004 // FIXME: This should probably go away at some point
1005 Result.clear();
1006 Result.setLookupName(Corrected.getCorrection());
1007 if (FirstDecl)
1008 Result.addDecl(FirstDecl);
1009
1010 // If we found an Objective-C instance variable, let
1011 // LookupInObjCMethod build the appropriate expression to
1012 // reference the ivar.
1013 // FIXME: This is a gross hack.
1014 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1015 DeclResult R =
1016 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1017 if (R.isInvalid())
1019 if (R.isUsable())
1020 return NameClassification::NonType(Ivar);
1021 }
1022
1023 goto Corrected;
1024 }
1025 }
1026
1027 // We failed to correct; just fall through and let the parser deal with it.
1028 Result.suppressDiagnostics();
1030
1032 // We performed name lookup into the current instantiation, and there were
1033 // dependent bases, so we treat this result the same way as any other
1034 // dependent nested-name-specifier.
1035
1036 // C++ [temp.res]p2:
1037 // A name used in a template declaration or definition and that is
1038 // dependent on a template-parameter is assumed not to name a type
1039 // unless the applicable name lookup finds a type name or the name is
1040 // qualified by the keyword typename.
1041 //
1042 // FIXME: If the next token is '<', we might want to ask the parser to
1043 // perform some heroics to see if we actually have a
1044 // template-argument-list, which would indicate a missing 'template'
1045 // keyword here.
1047 }
1048
1052 break;
1053
1055 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1056 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1057 /*AllowDependent=*/false)) {
1058 // C++ [temp.local]p3:
1059 // A lookup that finds an injected-class-name (10.2) can result in an
1060 // ambiguity in certain cases (for example, if it is found in more than
1061 // one base class). If all of the injected-class-names that are found
1062 // refer to specializations of the same class template, and if the name
1063 // is followed by a template-argument-list, the reference refers to the
1064 // class template itself and not a specialization thereof, and is not
1065 // ambiguous.
1066 //
1067 // This filtering can make an ambiguous result into an unambiguous one,
1068 // so try again after filtering out template names.
1070 if (!Result.isAmbiguous()) {
1071 IsFilteredTemplateName = true;
1072 break;
1073 }
1074 }
1075
1076 // Diagnose the ambiguity and return an error.
1078 }
1079
1080 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1081 (IsFilteredTemplateName ||
1083 Result, /*AllowFunctionTemplates=*/true,
1084 /*AllowDependent=*/false,
1085 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1087 // C++ [temp.names]p3:
1088 // After name lookup (3.4) finds that a name is a template-name or that
1089 // an operator-function-id or a literal- operator-id refers to a set of
1090 // overloaded functions any member of which is a function template if
1091 // this is followed by a <, the < is always taken as the delimiter of a
1092 // template-argument-list and never as the less-than operator.
1093 // C++2a [temp.names]p2:
1094 // A name is also considered to refer to a template if it is an
1095 // unqualified-id followed by a < and name lookup finds either one
1096 // or more functions or finds nothing.
1097 if (!IsFilteredTemplateName)
1099
1100 bool IsFunctionTemplate;
1101 bool IsVarTemplate;
1102 TemplateName Template;
1103 if (Result.end() - Result.begin() > 1) {
1104 IsFunctionTemplate = true;
1105 Template = Context.getOverloadedTemplateName(Result.begin(),
1106 Result.end());
1107 } else if (!Result.empty()) {
1108 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1109 *Result.begin(), /*AllowFunctionTemplates=*/true,
1110 /*AllowDependent=*/false));
1111 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1112 IsVarTemplate = isa<VarTemplateDecl>(TD);
1113
1114 UsingShadowDecl *FoundUsingShadow =
1115 dyn_cast<UsingShadowDecl>(*Result.begin());
1116 assert(!FoundUsingShadow ||
1117 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1119 SS.getScopeRep(),
1120 /*TemplateKeyword=*/false,
1121 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1122 } else {
1123 // All results were non-template functions. This is a function template
1124 // name.
1125 IsFunctionTemplate = true;
1126 Template = Context.getAssumedTemplateName(NameInfo.getName());
1127 }
1128
1129 if (IsFunctionTemplate) {
1130 // Function templates always go through overload resolution, at which
1131 // point we'll perform the various checks (e.g., accessibility) we need
1132 // to based on which function we selected.
1133 Result.suppressDiagnostics();
1134
1135 return NameClassification::FunctionTemplate(Template);
1136 }
1137
1138 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1140 }
1141
1142 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1144 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1145 T = Context.getUsingType(USD, T);
1146 return buildNamedType(*this, &SS, T, NameLoc);
1147 };
1148
1149 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1150 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1151 DiagnoseUseOfDecl(Type, NameLoc);
1152 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1153 return BuildTypeFor(Type, *Result.begin());
1154 }
1155
1156 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1157 if (!Class) {
1158 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1159 if (ObjCCompatibleAliasDecl *Alias =
1160 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1161 Class = Alias->getClassInterface();
1162 }
1163
1164 if (Class) {
1165 DiagnoseUseOfDecl(Class, NameLoc);
1166
1167 if (NextToken.is(tok::period)) {
1168 // Interface. <something> is parsed as a property reference expression.
1169 // Just return "unknown" as a fall-through for now.
1170 Result.suppressDiagnostics();
1172 }
1173
1175 return ParsedType::make(T);
1176 }
1177
1178 if (isa<ConceptDecl>(FirstDecl)) {
1179 // We want to preserve the UsingShadowDecl for concepts.
1180 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1183 TemplateName(cast<TemplateDecl>(FirstDecl)));
1184 }
1185
1186 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1187 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1189 }
1190
1191 // We can have a type template here if we're classifying a template argument.
1192 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1193 !isa<VarTemplateDecl>(FirstDecl))
1195 TemplateName(cast<TemplateDecl>(FirstDecl)));
1196
1197 // Check for a tag type hidden by a non-type decl in a few cases where it
1198 // seems likely a type is wanted instead of the non-type that was found.
1199 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1200 if ((NextToken.is(tok::identifier) ||
1201 (NextIsOp &&
1202 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1203 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1204 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1205 DiagnoseUseOfDecl(Type, NameLoc);
1206 return BuildTypeFor(Type, *Result.begin());
1207 }
1208
1209 // If we already know which single declaration is referenced, just annotate
1210 // that declaration directly. Defer resolving even non-overloaded class
1211 // member accesses, as we need to defer certain access checks until we know
1212 // the context.
1213 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1214 if (Result.isSingleResult() && !ADL &&
1215 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1216 return NameClassification::NonType(Result.getRepresentativeDecl());
1217
1218 // Otherwise, this is an overload set that we will need to resolve later.
1219 Result.suppressDiagnostics();
1221 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1222 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1223 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1224}
1225
1228 SourceLocation NameLoc) {
1229 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1230 CXXScopeSpec SS;
1231 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1232 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1233}
1234
1237 IdentifierInfo *Name,
1238 SourceLocation NameLoc,
1239 bool IsAddressOfOperand) {
1240 DeclarationNameInfo NameInfo(Name, NameLoc);
1241 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1242 NameInfo, IsAddressOfOperand,
1243 /*TemplateArgs=*/nullptr);
1244}
1245
1248 SourceLocation NameLoc,
1249 const Token &NextToken) {
1250 if (getCurMethodDecl() && SS.isEmpty())
1251 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1252 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1253
1254 // Reconstruct the lookup result.
1255 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1256 Result.addDecl(Found);
1257 Result.resolveKind();
1258
1259 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1260 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1261}
1262
1264 // For an implicit class member access, transform the result into a member
1265 // access expression if necessary.
1266 auto *ULE = cast<UnresolvedLookupExpr>(E);
1267 if ((*ULE->decls_begin())->isCXXClassMember()) {
1268 CXXScopeSpec SS;
1269 SS.Adopt(ULE->getQualifierLoc());
1270
1271 // Reconstruct the lookup result.
1272 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1274 Result.setNamingClass(ULE->getNamingClass());
1275 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1276 Result.addDecl(*I, I.getAccess());
1277 Result.resolveKind();
1279 nullptr, S);
1280 }
1281
1282 // Otherwise, this is already in the form we needed, and no further checks
1283 // are necessary.
1284 return ULE;
1285}
1286
1289 auto *TD = Name.getAsTemplateDecl();
1290 if (!TD)
1292 if (isa<ClassTemplateDecl>(TD))
1294 if (isa<FunctionTemplateDecl>(TD))
1296 if (isa<VarTemplateDecl>(TD))
1298 if (isa<TypeAliasTemplateDecl>(TD))
1300 if (isa<TemplateTemplateParmDecl>(TD))
1302 if (isa<ConceptDecl>(TD))
1305}
1306
1308 assert(DC->getLexicalParent() == CurContext &&
1309 "The next DeclContext should be lexically contained in the current one.");
1310 CurContext = DC;
1311 S->setEntity(DC);
1312}
1313
1315 assert(CurContext && "DeclContext imbalance!");
1316
1318 assert(CurContext && "Popped translation unit!");
1319}
1320
1322 Decl *D) {
1323 // Unlike PushDeclContext, the context to which we return is not necessarily
1324 // the containing DC of TD, because the new context will be some pre-existing
1325 // TagDecl definition instead of a fresh one.
1326 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1327 CurContext = cast<TagDecl>(D)->getDefinition();
1328 assert(CurContext && "skipping definition of undefined tag");
1329 // Start lookups from the parent of the current context; we don't want to look
1330 // into the pre-existing complete definition.
1331 S->setEntity(CurContext->getLookupParent());
1332 return Result;
1333}
1334
1336 CurContext = static_cast<decltype(CurContext)>(Context);
1337}
1338
1340 // C++0x [basic.lookup.unqual]p13:
1341 // A name used in the definition of a static data member of class
1342 // X (after the qualified-id of the static member) is looked up as
1343 // if the name was used in a member function of X.
1344 // C++0x [basic.lookup.unqual]p14:
1345 // If a variable member of a namespace is defined outside of the
1346 // scope of its namespace then any name used in the definition of
1347 // the variable member (after the declarator-id) is looked up as
1348 // if the definition of the variable member occurred in its
1349 // namespace.
1350 // Both of these imply that we should push a scope whose context
1351 // is the semantic context of the declaration. We can't use
1352 // PushDeclContext here because that context is not necessarily
1353 // lexically contained in the current context. Fortunately,
1354 // the containing scope should have the appropriate information.
1355
1356 assert(!S->getEntity() && "scope already has entity");
1357
1358#ifndef NDEBUG
1359 Scope *Ancestor = S->getParent();
1360 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1361 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1362#endif
1363
1364 CurContext = DC;
1365 S->setEntity(DC);
1366
1367 if (S->getParent()->isTemplateParamScope()) {
1368 // Also set the corresponding entities for all immediately-enclosing
1369 // template parameter scopes.
1370 EnterTemplatedContext(S->getParent(), DC);
1371 }
1372}
1373
1375 assert(S->getEntity() == CurContext && "Context imbalance!");
1376
1377 // Switch back to the lexical context. The safety of this is
1378 // enforced by an assert in EnterDeclaratorContext.
1379 Scope *Ancestor = S->getParent();
1380 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1381 CurContext = Ancestor->getEntity();
1382
1383 // We don't need to do anything with the scope, which is going to
1384 // disappear.
1385}
1386
1388 assert(S->isTemplateParamScope() &&
1389 "expected to be initializing a template parameter scope");
1390
1391 // C++20 [temp.local]p7:
1392 // In the definition of a member of a class template that appears outside
1393 // of the class template definition, the name of a member of the class
1394 // template hides the name of a template-parameter of any enclosing class
1395 // templates (but not a template-parameter of the member if the member is a
1396 // class or function template).
1397 // C++20 [temp.local]p9:
1398 // In the definition of a class template or in the definition of a member
1399 // of such a template that appears outside of the template definition, for
1400 // each non-dependent base class (13.8.2.1), if the name of the base class
1401 // or the name of a member of the base class is the same as the name of a
1402 // template-parameter, the base class name or member name hides the
1403 // template-parameter name (6.4.10).
1404 //
1405 // This means that a template parameter scope should be searched immediately
1406 // after searching the DeclContext for which it is a template parameter
1407 // scope. For example, for
1408 // template<typename T> template<typename U> template<typename V>
1409 // void N::A<T>::B<U>::f(...)
1410 // we search V then B<U> (and base classes) then U then A<T> (and base
1411 // classes) then T then N then ::.
1412 unsigned ScopeDepth = getTemplateDepth(S);
1413 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1414 DeclContext *SearchDCAfterScope = DC;
1415 for (; DC; DC = DC->getLookupParent()) {
1416 if (const TemplateParameterList *TPL =
1417 cast<Decl>(DC)->getDescribedTemplateParams()) {
1418 unsigned DCDepth = TPL->getDepth() + 1;
1419 if (DCDepth > ScopeDepth)
1420 continue;
1421 if (ScopeDepth == DCDepth)
1422 SearchDCAfterScope = DC = DC->getLookupParent();
1423 break;
1424 }
1425 }
1426 S->setLookupEntity(SearchDCAfterScope);
1427 }
1428}
1429
1431 // We assume that the caller has already called
1432 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1433 FunctionDecl *FD = D->getAsFunction();
1434 if (!FD)
1435 return;
1436
1437 // Same implementation as PushDeclContext, but enters the context
1438 // from the lexical parent, rather than the top-level class.
1439 assert(CurContext == FD->getLexicalParent() &&
1440 "The next DeclContext should be lexically contained in the current one.");
1441 CurContext = FD;
1442 S->setEntity(CurContext);
1443
1444 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1445 ParmVarDecl *Param = FD->getParamDecl(P);
1446 // If the parameter has an identifier, then add it to the scope
1447 if (Param->getIdentifier()) {
1448 S->AddDecl(Param);
1449 IdResolver.AddDecl(Param);
1450 }
1451 }
1452}
1453
1455 // Same implementation as PopDeclContext, but returns to the lexical parent,
1456 // rather than the top-level class.
1457 assert(CurContext && "DeclContext imbalance!");
1459 assert(CurContext && "Popped translation unit!");
1460}
1461
1462/// Determine whether overloading is allowed for a new function
1463/// declaration considering prior declarations of the same name.
1464///
1465/// This routine determines whether overloading is possible, not
1466/// whether a new declaration actually overloads a previous one.
1467/// It will return true in C++ (where overloads are always permitted)
1468/// or, as a C extension, when either the new declaration or a
1469/// previous one is declared with the 'overloadable' attribute.
1471 ASTContext &Context,
1472 const FunctionDecl *New) {
1473 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1474 return true;
1475
1476 // Multiversion function declarations are not overloads in the
1477 // usual sense of that term, but lookup will report that an
1478 // overload set was found if more than one multiversion function
1479 // declaration is present for the same name. It is therefore
1480 // inadequate to assume that some prior declaration(s) had
1481 // the overloadable attribute; checking is required. Since one
1482 // declaration is permitted to omit the attribute, it is necessary
1483 // to check at least two; hence the 'any_of' check below. Note that
1484 // the overloadable attribute is implicitly added to declarations
1485 // that were required to have it but did not.
1486 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1487 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1488 return ND->hasAttr<OverloadableAttr>();
1489 });
1490 } else if (Previous.getResultKind() == LookupResult::Found)
1491 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1492
1493 return false;
1494}
1495
1496void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1497 // Move up the scope chain until we find the nearest enclosing
1498 // non-transparent context. The declaration will be introduced into this
1499 // scope.
1500 while (S->getEntity() && S->getEntity()->isTransparentContext())
1501 S = S->getParent();
1502
1503 // Add scoped declarations into their context, so that they can be
1504 // found later. Declarations without a context won't be inserted
1505 // into any context.
1506 if (AddToContext)
1508
1509 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1510 // are function-local declarations.
1511 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1512 return;
1513
1514 // Template instantiations should also not be pushed into scope.
1515 if (isa<FunctionDecl>(D) &&
1516 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1517 return;
1518
1519 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1520 S->AddDecl(D);
1521 return;
1522 }
1523 // If this replaces anything in the current scope,
1524 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1525 IEnd = IdResolver.end();
1526 for (; I != IEnd; ++I) {
1527 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1528 S->RemoveDecl(*I);
1530
1531 // Should only need to replace one decl.
1532 break;
1533 }
1534 }
1535
1536 S->AddDecl(D);
1537
1538 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1539 // Implicitly-generated labels may end up getting generated in an order that
1540 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1541 // the label at the appropriate place in the identifier chain.
1542 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1543 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1544 if (IDC == CurContext) {
1545 if (!S->isDeclScope(*I))
1546 continue;
1547 } else if (IDC->Encloses(CurContext))
1548 break;
1549 }
1550
1552 } else {
1554 }
1556}
1557
1559 bool AllowInlineNamespace) const {
1560 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1561}
1562
1564 DeclContext *TargetDC = DC->getPrimaryContext();
1565 do {
1566 if (DeclContext *ScopeDC = S->getEntity())
1567 if (ScopeDC->getPrimaryContext() == TargetDC)
1568 return S;
1569 } while ((S = S->getParent()));
1570
1571 return nullptr;
1572}
1573
1575 DeclContext*,
1576 ASTContext&);
1577
1579 bool ConsiderLinkage,
1580 bool AllowInlineNamespace) {
1582 while (F.hasNext()) {
1583 NamedDecl *D = F.next();
1584
1585 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1586 continue;
1587
1588 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1589 continue;
1590
1591 F.erase();
1592 }
1593
1594 F.done();
1595}
1596
1598 // [module.interface]p7:
1599 // A declaration is attached to a module as follows:
1600 // - If the declaration is a non-dependent friend declaration that nominates a
1601 // function with a declarator-id that is a qualified-id or template-id or that
1602 // nominates a class other than with an elaborated-type-specifier with neither
1603 // a nested-name-specifier nor a simple-template-id, it is attached to the
1604 // module to which the friend is attached ([basic.link]).
1605 if (New->getFriendObjectKind() &&
1609 return false;
1610 }
1611
1612 Module *NewM = New->getOwningModule();
1613 Module *OldM = Old->getOwningModule();
1614
1615 if (NewM && NewM->isPrivateModule())
1616 NewM = NewM->Parent;
1617 if (OldM && OldM->isPrivateModule())
1618 OldM = OldM->Parent;
1619
1620 if (NewM == OldM)
1621 return false;
1622
1623 if (NewM && OldM) {
1624 // A module implementation unit has visibility of the decls in its
1625 // implicitly imported interface.
1626 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1627 return false;
1628
1629 // Partitions are part of the module, but a partition could import another
1630 // module, so verify that the PMIs agree.
1631 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1632 getASTContext().isInSameModule(NewM, OldM))
1633 return false;
1634 }
1635
1636 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1637 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1638 if (NewIsModuleInterface || OldIsModuleInterface) {
1639 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1640 // if a declaration of D [...] appears in the purview of a module, all
1641 // other such declarations shall appear in the purview of the same module
1642 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1643 << New
1644 << NewIsModuleInterface
1645 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1646 << OldIsModuleInterface
1647 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1648 Diag(Old->getLocation(), diag::note_previous_declaration);
1649 New->setInvalidDecl();
1650 return true;
1651 }
1652
1653 return false;
1654}
1655
1657 // [module.interface]p1:
1658 // An export-declaration shall inhabit a namespace scope.
1659 //
1660 // So it is meaningless to talk about redeclaration which is not at namespace
1661 // scope.
1662 if (!New->getLexicalDeclContext()
1664 ->isFileContext() ||
1665 !Old->getLexicalDeclContext()
1667 ->isFileContext())
1668 return false;
1669
1670 bool IsNewExported = New->isInExportDeclContext();
1671 bool IsOldExported = Old->isInExportDeclContext();
1672
1673 // It should be irrevelant if both of them are not exported.
1674 if (!IsNewExported && !IsOldExported)
1675 return false;
1676
1677 if (IsOldExported)
1678 return false;
1679
1680 // If the Old declaration are not attached to named modules
1681 // and the New declaration are attached to global module.
1682 // It should be fine to allow the export since it doesn't change
1683 // the linkage of declarations. See
1684 // https://github.com/llvm/llvm-project/issues/98583 for details.
1685 if (!Old->isInNamedModule() && New->getOwningModule() &&
1687 return false;
1688
1689 assert(IsNewExported);
1690
1691 auto Lk = Old->getFormalLinkage();
1692 int S = 0;
1693 if (Lk == Linkage::Internal)
1694 S = 1;
1695 else if (Lk == Linkage::Module)
1696 S = 2;
1697 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1698 Diag(Old->getLocation(), diag::note_previous_declaration);
1699 return true;
1700}
1701
1704 return true;
1705
1706 if (CheckRedeclarationExported(New, Old))
1707 return true;
1708
1709 return false;
1710}
1711
1713 const NamedDecl *Old) const {
1714 assert(getASTContext().isSameEntity(New, Old) &&
1715 "New and Old are not the same definition, we should diagnostic it "
1716 "immediately instead of checking it.");
1717 assert(const_cast<Sema *>(this)->isReachable(New) &&
1718 const_cast<Sema *>(this)->isReachable(Old) &&
1719 "We shouldn't see unreachable definitions here.");
1720
1721 Module *NewM = New->getOwningModule();
1722 Module *OldM = Old->getOwningModule();
1723
1724 // We only checks for named modules here. The header like modules is skipped.
1725 // FIXME: This is not right if we import the header like modules in the module
1726 // purview.
1727 //
1728 // For example, assuming "header.h" provides definition for `D`.
1729 // ```C++
1730 // //--- M.cppm
1731 // export module M;
1732 // import "header.h"; // or #include "header.h" but import it by clang modules
1733 // actually.
1734 //
1735 // //--- Use.cpp
1736 // import M;
1737 // import "header.h"; // or uses clang modules.
1738 // ```
1739 //
1740 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1741 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1742 // reject it. But the current implementation couldn't detect the case since we
1743 // don't record the information about the importee modules.
1744 //
1745 // But this might not be painful in practice. Since the design of C++20 Named
1746 // Modules suggests us to use headers in global module fragment instead of
1747 // module purview.
1748 if (NewM && NewM->isHeaderLikeModule())
1749 NewM = nullptr;
1750 if (OldM && OldM->isHeaderLikeModule())
1751 OldM = nullptr;
1752
1753 if (!NewM && !OldM)
1754 return true;
1755
1756 // [basic.def.odr]p14.3
1757 // Each such definition shall not be attached to a named module
1758 // ([module.unit]).
1759 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1760 return true;
1761
1762 // Then New and Old lives in the same TU if their share one same module unit.
1763 if (NewM)
1764 NewM = NewM->getTopLevelModule();
1765 if (OldM)
1766 OldM = OldM->getTopLevelModule();
1767 return OldM == NewM;
1768}
1769
1771 if (D->getDeclContext()->isFileContext())
1772 return false;
1773
1774 return isa<UsingShadowDecl>(D) ||
1775 isa<UnresolvedUsingTypenameDecl>(D) ||
1776 isa<UnresolvedUsingValueDecl>(D);
1777}
1778
1779/// Removes using shadow declarations not at class scope from the lookup
1780/// results.
1783 while (F.hasNext())
1785 F.erase();
1786
1787 F.done();
1788}
1789
1790/// Check for this common pattern:
1791/// @code
1792/// class S {
1793/// S(const S&); // DO NOT IMPLEMENT
1794/// void operator=(const S&); // DO NOT IMPLEMENT
1795/// };
1796/// @endcode
1798 // FIXME: Should check for private access too but access is set after we get
1799 // the decl here.
1800 if (D->doesThisDeclarationHaveABody())
1801 return false;
1802
1803 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1804 return CD->isCopyConstructor();
1805 return D->isCopyAssignmentOperator();
1806}
1807
1808bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1809 const DeclContext *DC = D->getDeclContext();
1810 while (!DC->isTranslationUnit()) {
1811 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1812 if (!RD->hasNameForLinkage())
1813 return true;
1814 }
1815 DC = DC->getParent();
1816 }
1817
1818 return !D->isExternallyVisible();
1819}
1820
1821// FIXME: This needs to be refactored; some other isInMainFile users want
1822// these semantics.
1823static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1825 return false;
1826 return S.SourceMgr.isInMainFile(Loc);
1827}
1828
1830 assert(D);
1831
1832 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1833 return false;
1834
1835 // Ignore all entities declared within templates, and out-of-line definitions
1836 // of members of class templates.
1839 return false;
1840
1841 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1842 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1843 return false;
1844 // A non-out-of-line declaration of a member specialization was implicitly
1845 // instantiated; it's the out-of-line declaration that we're interested in.
1846 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1847 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1848 return false;
1849
1850 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1851 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1852 return false;
1853 } else {
1854 // 'static inline' functions are defined in headers; don't warn.
1855 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1856 return false;
1857 }
1858
1859 if (FD->doesThisDeclarationHaveABody() &&
1861 return false;
1862 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1863 // Constants and utility variables are defined in headers with internal
1864 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1865 // like "inline".)
1866 if (!isMainFileLoc(*this, VD->getLocation()))
1867 return false;
1868
1869 if (Context.DeclMustBeEmitted(VD))
1870 return false;
1871
1872 if (VD->isStaticDataMember() &&
1873 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1874 return false;
1875 if (VD->isStaticDataMember() &&
1876 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1877 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1878 return false;
1879
1880 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1881 return false;
1882 } else {
1883 return false;
1884 }
1885
1886 // Only warn for unused decls internal to the translation unit.
1887 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1888 // for inline functions defined in the main source file, for instance.
1889 return mightHaveNonExternalLinkage(D);
1890}
1891
1893 if (!D)
1894 return;
1895
1896 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1897 const FunctionDecl *First = FD->getFirstDecl();
1899 return; // First should already be in the vector.
1900 }
1901
1902 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1903 const VarDecl *First = VD->getFirstDecl();
1905 return; // First should already be in the vector.
1906 }
1907
1910}
1911
1912static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1913 const NamedDecl *D) {
1914 if (D->isInvalidDecl())
1915 return false;
1916
1917 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1918 // For a decomposition declaration, warn if none of the bindings are
1919 // referenced, instead of if the variable itself is referenced (which
1920 // it is, by the bindings' expressions).
1921 bool IsAllPlaceholders = true;
1922 for (const auto *BD : DD->bindings()) {
1923 if (BD->isReferenced() || BD->hasAttr<UnusedAttr>())
1924 return false;
1925 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1926 }
1927 if (IsAllPlaceholders)
1928 return false;
1929 } else if (!D->getDeclName()) {
1930 return false;
1931 } else if (D->isReferenced() || D->isUsed()) {
1932 return false;
1933 }
1934
1935 if (D->isPlaceholderVar(LangOpts))
1936 return false;
1937
1938 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1939 D->hasAttr<CleanupAttr>())
1940 return false;
1941
1942 if (isa<LabelDecl>(D))
1943 return true;
1944
1945 // Except for labels, we only care about unused decls that are local to
1946 // functions.
1947 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1948 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1949 // For dependent types, the diagnostic is deferred.
1950 WithinFunction =
1951 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1952 if (!WithinFunction)
1953 return false;
1954
1955 if (isa<TypedefNameDecl>(D))
1956 return true;
1957
1958 // White-list anything that isn't a local variable.
1959 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1960 return false;
1961
1962 // Types of valid local variables should be complete, so this should succeed.
1963 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1964
1965 const Expr *Init = VD->getInit();
1966 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
1967 Init = Cleanups->getSubExpr();
1968
1969 const auto *Ty = VD->getType().getTypePtr();
1970
1971 // Only look at the outermost level of typedef.
1972 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1973 // Allow anything marked with __attribute__((unused)).
1974 if (TT->getDecl()->hasAttr<UnusedAttr>())
1975 return false;
1976 }
1977
1978 // Warn for reference variables whose initializtion performs lifetime
1979 // extension.
1980 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
1981 MTE && MTE->getExtendingDecl()) {
1982 Ty = VD->getType().getNonReferenceType().getTypePtr();
1983 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1984 }
1985
1986 // If we failed to complete the type for some reason, or if the type is
1987 // dependent, don't diagnose the variable.
1988 if (Ty->isIncompleteType() || Ty->isDependentType())
1989 return false;
1990
1991 // Look at the element type to ensure that the warning behaviour is
1992 // consistent for both scalars and arrays.
1993 Ty = Ty->getBaseElementTypeUnsafe();
1994
1995 if (const TagType *TT = Ty->getAs<TagType>()) {
1996 const TagDecl *Tag = TT->getDecl();
1997 if (Tag->hasAttr<UnusedAttr>())
1998 return false;
1999
2000 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2001 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2002 return false;
2003
2004 if (Init) {
2005 const auto *Construct =
2006 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2007 if (Construct && !Construct->isElidable()) {
2008 const CXXConstructorDecl *CD = Construct->getConstructor();
2009 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2010 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2011 return false;
2012 }
2013
2014 // Suppress the warning if we don't know how this is constructed, and
2015 // it could possibly be non-trivial constructor.
2016 if (Init->isTypeDependent()) {
2017 for (const CXXConstructorDecl *Ctor : RD->ctors())
2018 if (!Ctor->isTrivial())
2019 return false;
2020 }
2021
2022 // Suppress the warning if the constructor is unresolved because
2023 // its arguments are dependent.
2024 if (isa<CXXUnresolvedConstructExpr>(Init))
2025 return false;
2026 }
2027 }
2028 }
2029
2030 // TODO: __attribute__((unused)) templates?
2031 }
2032
2033 return true;
2034}
2035
2037 FixItHint &Hint) {
2038 if (isa<LabelDecl>(D)) {
2040 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2041 /*SkipTrailingWhitespaceAndNewline=*/false);
2042 if (AfterColon.isInvalid())
2043 return;
2046 }
2047}
2048
2051 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2052}
2053
2055 DiagReceiverTy DiagReceiver) {
2056 if (D->getTypeForDecl()->isDependentType())
2057 return;
2058
2059 for (auto *TmpD : D->decls()) {
2060 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2061 DiagnoseUnusedDecl(T, DiagReceiver);
2062 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2063 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2064 }
2065}
2066
2069 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2070}
2071
2074 return;
2075
2076 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2077 // typedefs can be referenced later on, so the diagnostics are emitted
2078 // at end-of-translation-unit.
2080 return;
2081 }
2082
2083 FixItHint Hint;
2085
2086 unsigned DiagID;
2087 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2088 DiagID = diag::warn_unused_exception_param;
2089 else if (isa<LabelDecl>(D))
2090 DiagID = diag::warn_unused_label;
2091 else
2092 DiagID = diag::warn_unused_variable;
2093
2094 SourceLocation DiagLoc = D->getLocation();
2095 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2096}
2097
2099 DiagReceiverTy DiagReceiver) {
2100 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2101 // it's not really unused.
2102 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2103 return;
2104
2105 // In C++, `_` variables behave as if they were maybe_unused
2106 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2107 return;
2108
2109 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2110
2111 if (Ty->isReferenceType() || Ty->isDependentType())
2112 return;
2113
2114 if (const TagType *TT = Ty->getAs<TagType>()) {
2115 const TagDecl *Tag = TT->getDecl();
2116 if (Tag->hasAttr<UnusedAttr>())
2117 return;
2118 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2119 // mimic gcc's behavior.
2120 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2121 RD && !RD->hasAttr<WarnUnusedAttr>())
2122 return;
2123 }
2124
2125 // Don't warn about __block Objective-C pointer variables, as they might
2126 // be assigned in the block but not used elsewhere for the purpose of lifetime
2127 // extension.
2128 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2129 return;
2130
2131 // Don't warn about Objective-C pointer variables with precise lifetime
2132 // semantics; they can be used to ensure ARC releases the object at a known
2133 // time, which may mean assignment but no other references.
2134 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2135 return;
2136
2137 auto iter = RefsMinusAssignments.find(VD);
2138 if (iter == RefsMinusAssignments.end())
2139 return;
2140
2141 assert(iter->getSecond() >= 0 &&
2142 "Found a negative number of references to a VarDecl");
2143 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2144 // Assume the given VarDecl is "used" if its ref count stored in
2145 // `RefMinusAssignments` is positive, with one exception.
2146 //
2147 // For a C++ variable whose decl (with initializer) entirely consist the
2148 // condition expression of a if/while/for construct,
2149 // Clang creates a DeclRefExpr for the condition expression rather than a
2150 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2151 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2152 // used in the body of the if/while/for construct.
2153 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2154 if (!UnusedCXXCondDecl)
2155 return;
2156 }
2157
2158 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2159 : diag::warn_unused_but_set_variable;
2160 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2161}
2162
2164 Sema::DiagReceiverTy DiagReceiver) {
2165 // Verify that we have no forward references left. If so, there was a goto
2166 // or address of a label taken, but no definition of it. Label fwd
2167 // definitions are indicated with a null substmt which is also not a resolved
2168 // MS inline assembly label name.
2169 bool Diagnose = false;
2170 if (L->isMSAsmLabel())
2171 Diagnose = !L->isResolvedMSAsmLabel();
2172 else
2173 Diagnose = L->getStmt() == nullptr;
2174 if (Diagnose)
2175 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2176 << L);
2177}
2178
2180 S->applyNRVO();
2181
2182 if (S->decl_empty()) return;
2183 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2184 "Scope shouldn't contain decls!");
2185
2186 /// We visit the decls in non-deterministic order, but we want diagnostics
2187 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2188 /// and sort the diagnostics before emitting them, after we visited all decls.
2189 struct LocAndDiag {
2191 std::optional<SourceLocation> PreviousDeclLoc;
2193 };
2195 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2196 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2197 };
2198 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2199 SourceLocation PreviousDeclLoc,
2200 PartialDiagnostic PD) {
2201 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2202 };
2203
2204 for (auto *TmpD : S->decls()) {
2205 assert(TmpD && "This decl didn't get pushed??");
2206
2207 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2208 NamedDecl *D = cast<NamedDecl>(TmpD);
2209
2210 // Diagnose unused variables in this scope.
2211 if (!S->hasUnrecoverableErrorOccurred()) {
2212 DiagnoseUnusedDecl(D, addDiag);
2213 if (const auto *RD = dyn_cast<RecordDecl>(D))
2214 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2215 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2216 DiagnoseUnusedButSetDecl(VD, addDiag);
2217 RefsMinusAssignments.erase(VD);
2218 }
2219 }
2220
2221 if (!D->getDeclName()) continue;
2222
2223 // If this was a forward reference to a label, verify it was defined.
2224 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2225 CheckPoppedLabel(LD, *this, addDiag);
2226
2227 // Partial translation units that are created in incremental processing must
2228 // not clean up the IdResolver because PTUs should take into account the
2229 // declarations that came from previous PTUs.
2233
2234 // Warn on it if we are shadowing a declaration.
2235 auto ShadowI = ShadowingDecls.find(D);
2236 if (ShadowI != ShadowingDecls.end()) {
2237 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2238 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2239 PDiag(diag::warn_ctor_parm_shadows_field)
2240 << D << FD << FD->getParent());
2241 }
2242 ShadowingDecls.erase(ShadowI);
2243 }
2244 }
2245
2246 llvm::sort(DeclDiags,
2247 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2248 // The particular order for diagnostics is not important, as long
2249 // as the order is deterministic. Using the raw location is going
2250 // to generally be in source order unless there are macro
2251 // expansions involved.
2252 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2253 });
2254 for (const LocAndDiag &D : DeclDiags) {
2255 Diag(D.Loc, D.PD);
2256 if (D.PreviousDeclLoc)
2257 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2258 }
2259}
2260
2262 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2263 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2264 (S->isClassScope() && !getLangOpts().CPlusPlus))
2265 S = S->getParent();
2266 return S;
2267}
2268
2269static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2271 switch (Error) {
2273 return "";
2275 return BuiltinInfo.getHeaderName(ID);
2277 return "stdio.h";
2279 return "setjmp.h";
2281 return "ucontext.h";
2282 }
2283 llvm_unreachable("unhandled error kind");
2284}
2285
2287 unsigned ID, SourceLocation Loc) {
2289
2290 if (getLangOpts().CPlusPlus) {
2293 CLinkageDecl->setImplicit();
2294 Parent->addDecl(CLinkageDecl);
2295 Parent = CLinkageDecl;
2296 }
2297
2300 assert(getLangOpts().CPlusPlus20 &&
2301 "consteval builtins should only be available in C++20 mode");
2302 ConstexprKind = ConstexprSpecKind::Consteval;
2303 }
2304
2306 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2307 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2308 Type->isFunctionProtoType(), ConstexprKind);
2309 New->setImplicit();
2310 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2311
2312 // Create Decl objects for each parameter, adding them to the
2313 // FunctionDecl.
2314 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2316 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2318 Context, New, SourceLocation(), SourceLocation(), nullptr,
2319 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2320 parm->setScopeInfo(0, i);
2321 Params.push_back(parm);
2322 }
2323 New->setParams(Params);
2324 }
2325
2327 return New;
2328}
2329
2331 Scope *S, bool ForRedeclaration,
2334
2336 QualType R = Context.GetBuiltinType(ID, Error);
2337 if (Error) {
2338 if (!ForRedeclaration)
2339 return nullptr;
2340
2341 // If we have a builtin without an associated type we should not emit a
2342 // warning when we were not able to find a type for it.
2343 if (Error == ASTContext::GE_Missing_type ||
2345 return nullptr;
2346
2347 // If we could not find a type for setjmp it is because the jmp_buf type was
2348 // not defined prior to the setjmp declaration.
2349 if (Error == ASTContext::GE_Missing_setjmp) {
2350 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2352 return nullptr;
2353 }
2354
2355 // Generally, we emit a warning that the declaration requires the
2356 // appropriate header.
2357 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2358 << getHeaderName(Context.BuiltinInfo, ID, Error)
2360 return nullptr;
2361 }
2362
2363 if (!ForRedeclaration &&
2366 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2367 : diag::ext_implicit_lib_function_decl)
2368 << Context.BuiltinInfo.getName(ID) << R;
2369 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2370 Diag(Loc, diag::note_include_header_or_declare)
2371 << Header << Context.BuiltinInfo.getName(ID);
2372 }
2373
2374 if (R.isNull())
2375 return nullptr;
2376
2377 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2379
2380 // TUScope is the translation-unit scope to insert this function into.
2381 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2382 // relate Scopes to DeclContexts, and probably eliminate CurContext
2383 // entirely, but we're not there yet.
2384 DeclContext *SavedContext = CurContext;
2385 CurContext = New->getDeclContext();
2387 CurContext = SavedContext;
2388 return New;
2389}
2390
2391/// Typedef declarations don't have linkage, but they still denote the same
2392/// entity if their types are the same.
2393/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2394/// isSameEntity.
2395static void
2398 // This is only interesting when modules are enabled.
2399 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2400 return;
2401
2402 // Empty sets are uninteresting.
2403 if (Previous.empty())
2404 return;
2405
2406 LookupResult::Filter Filter = Previous.makeFilter();
2407 while (Filter.hasNext()) {
2408 NamedDecl *Old = Filter.next();
2409
2410 // Non-hidden declarations are never ignored.
2411 if (S.isVisible(Old))
2412 continue;
2413
2414 // Declarations of the same entity are not ignored, even if they have
2415 // different linkages.
2416 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2417 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2418 Decl->getUnderlyingType()))
2419 continue;
2420
2421 // If both declarations give a tag declaration a typedef name for linkage
2422 // purposes, then they declare the same entity.
2423 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2424 Decl->getAnonDeclWithTypedefName())
2425 continue;
2426 }
2427
2428 Filter.erase();
2429 }
2430
2431 Filter.done();
2432}
2433
2435 QualType OldType;
2436 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2437 OldType = OldTypedef->getUnderlyingType();
2438 else
2439 OldType = Context.getTypeDeclType(Old);
2440 QualType NewType = New->getUnderlyingType();
2441
2442 if (NewType->isVariablyModifiedType()) {
2443 // Must not redefine a typedef with a variably-modified type.
2444 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2445 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2446 << Kind << NewType;
2447 if (Old->getLocation().isValid())
2449 New->setInvalidDecl();
2450 return true;
2451 }
2452
2453 if (OldType != NewType &&
2454 !OldType->isDependentType() &&
2455 !NewType->isDependentType() &&
2456 !Context.hasSameType(OldType, NewType)) {
2457 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2458 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2459 << Kind << NewType << OldType;
2460 if (Old->getLocation().isValid())
2462 New->setInvalidDecl();
2463 return true;
2464 }
2465 return false;
2466}
2467
2469 LookupResult &OldDecls) {
2470 // If the new decl is known invalid already, don't bother doing any
2471 // merging checks.
2472 if (New->isInvalidDecl()) return;
2473
2474 // Allow multiple definitions for ObjC built-in typedefs.
2475 // FIXME: Verify the underlying types are equivalent!
2476 if (getLangOpts().ObjC) {
2477 const IdentifierInfo *TypeID = New->getIdentifier();
2478 switch (TypeID->getLength()) {
2479 default: break;
2480 case 2:
2481 {
2482 if (!TypeID->isStr("id"))
2483 break;
2484 QualType T = New->getUnderlyingType();
2485 if (!T->isPointerType())
2486 break;
2487 if (!T->isVoidPointerType()) {
2489 if (!PT->isStructureType())
2490 break;
2491 }
2493 // Install the built-in type for 'id', ignoring the current definition.
2495 return;
2496 }
2497 case 5:
2498 if (!TypeID->isStr("Class"))
2499 break;
2501 // Install the built-in type for 'Class', ignoring the current definition.
2503 return;
2504 case 3:
2505 if (!TypeID->isStr("SEL"))
2506 break;
2508 // Install the built-in type for 'SEL', ignoring the current definition.
2510 return;
2511 }
2512 // Fall through - the typedef name was not a builtin type.
2513 }
2514
2515 // Verify the old decl was also a type.
2516 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2517 if (!Old) {
2518 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2519 << New->getDeclName();
2520
2521 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2522 if (OldD->getLocation().isValid())
2523 notePreviousDefinition(OldD, New->getLocation());
2524
2525 return New->setInvalidDecl();
2526 }
2527
2528 // If the old declaration is invalid, just give up here.
2529 if (Old->isInvalidDecl())
2530 return New->setInvalidDecl();
2531
2532 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2533 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2534 auto *NewTag = New->getAnonDeclWithTypedefName();
2535 NamedDecl *Hidden = nullptr;
2536 if (OldTag && NewTag &&
2537 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2538 !hasVisibleDefinition(OldTag, &Hidden)) {
2539 // There is a definition of this tag, but it is not visible. Use it
2540 // instead of our tag.
2541 New->setTypeForDecl(OldTD->getTypeForDecl());
2542 if (OldTD->isModed())
2543 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2544 OldTD->getUnderlyingType());
2545 else
2546 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2547
2548 // Make the old tag definition visible.
2550
2551 // If this was an unscoped enumeration, yank all of its enumerators
2552 // out of the scope.
2553 if (isa<EnumDecl>(NewTag)) {
2554 Scope *EnumScope = getNonFieldDeclScope(S);
2555 for (auto *D : NewTag->decls()) {
2556 auto *ED = cast<EnumConstantDecl>(D);
2557 assert(EnumScope->isDeclScope(ED));
2558 EnumScope->RemoveDecl(ED);
2560 ED->getLexicalDeclContext()->removeDecl(ED);
2561 }
2562 }
2563 }
2564 }
2565
2566 // If the typedef types are not identical, reject them in all languages and
2567 // with any extensions enabled.
2568 if (isIncompatibleTypedef(Old, New))
2569 return;
2570
2571 // The types match. Link up the redeclaration chain and merge attributes if
2572 // the old declaration was a typedef.
2573 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2574 New->setPreviousDecl(Typedef);
2575 mergeDeclAttributes(New, Old);
2576 }
2577
2578 if (getLangOpts().MicrosoftExt)
2579 return;
2580
2581 if (getLangOpts().CPlusPlus) {
2582 // C++ [dcl.typedef]p2:
2583 // In a given non-class scope, a typedef specifier can be used to
2584 // redefine the name of any type declared in that scope to refer
2585 // to the type to which it already refers.
2586 if (!isa<CXXRecordDecl>(CurContext))
2587 return;
2588
2589 // C++0x [dcl.typedef]p4:
2590 // In a given class scope, a typedef specifier can be used to redefine
2591 // any class-name declared in that scope that is not also a typedef-name
2592 // to refer to the type to which it already refers.
2593 //
2594 // This wording came in via DR424, which was a correction to the
2595 // wording in DR56, which accidentally banned code like:
2596 //
2597 // struct S {
2598 // typedef struct A { } A;
2599 // };
2600 //
2601 // in the C++03 standard. We implement the C++0x semantics, which
2602 // allow the above but disallow
2603 //
2604 // struct S {
2605 // typedef int I;
2606 // typedef int I;
2607 // };
2608 //
2609 // since that was the intent of DR56.
2610 if (!isa<TypedefNameDecl>(Old))
2611 return;
2612
2613 Diag(New->getLocation(), diag::err_redefinition)
2614 << New->getDeclName();
2616 return New->setInvalidDecl();
2617 }
2618
2619 // Modules always permit redefinition of typedefs, as does C11.
2620 if (getLangOpts().Modules || getLangOpts().C11)
2621 return;
2622
2623 // If we have a redefinition of a typedef in C, emit a warning. This warning
2624 // is normally mapped to an error, but can be controlled with
2625 // -Wtypedef-redefinition. If either the original or the redefinition is
2626 // in a system header, don't emit this for compatibility with GCC.
2627 if (getDiagnostics().getSuppressSystemWarnings() &&
2628 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2629 (Old->isImplicit() ||
2632 return;
2633
2634 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2635 << New->getDeclName();
2637}
2638
2639/// DeclhasAttr - returns true if decl Declaration already has the target
2640/// attribute.
2641static bool DeclHasAttr(const Decl *D, const Attr *A) {
2642 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2643 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2644 for (const auto *i : D->attrs())
2645 if (i->getKind() == A->getKind()) {
2646 if (Ann) {
2647 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2648 return true;
2649 continue;
2650 }
2651 // FIXME: Don't hardcode this check
2652 if (OA && isa<OwnershipAttr>(i))
2653 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2654 return true;
2655 }
2656
2657 return false;
2658}
2659
2661 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2662 return VD->isThisDeclarationADefinition();
2663 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2664 return TD->isCompleteDefinition() || TD->isBeingDefined();
2665 return true;
2666}
2667
2668/// Merge alignment attributes from \p Old to \p New, taking into account the
2669/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2670///
2671/// \return \c true if any attributes were added to \p New.
2672static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2673 // Look for alignas attributes on Old, and pick out whichever attribute
2674 // specifies the strictest alignment requirement.
2675 AlignedAttr *OldAlignasAttr = nullptr;
2676 AlignedAttr *OldStrictestAlignAttr = nullptr;
2677 unsigned OldAlign = 0;
2678 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2679 // FIXME: We have no way of representing inherited dependent alignments
2680 // in a case like:
2681 // template<int A, int B> struct alignas(A) X;
2682 // template<int A, int B> struct alignas(B) X {};
2683 // For now, we just ignore any alignas attributes which are not on the
2684 // definition in such a case.
2685 if (I->isAlignmentDependent())
2686 return false;
2687
2688 if (I->isAlignas())
2689 OldAlignasAttr = I;
2690
2691 unsigned Align = I->getAlignment(S.Context);
2692 if (Align > OldAlign) {
2693 OldAlign = Align;
2694 OldStrictestAlignAttr = I;
2695 }
2696 }
2697
2698 // Look for alignas attributes on New.
2699 AlignedAttr *NewAlignasAttr = nullptr;
2700 unsigned NewAlign = 0;
2701 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2702 if (I->isAlignmentDependent())
2703 return false;
2704
2705 if (I->isAlignas())
2706 NewAlignasAttr = I;
2707
2708 unsigned Align = I->getAlignment(S.Context);
2709 if (Align > NewAlign)
2710 NewAlign = Align;
2711 }
2712
2713 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2714 // Both declarations have 'alignas' attributes. We require them to match.
2715 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2716 // fall short. (If two declarations both have alignas, they must both match
2717 // every definition, and so must match each other if there is a definition.)
2718
2719 // If either declaration only contains 'alignas(0)' specifiers, then it
2720 // specifies the natural alignment for the type.
2721 if (OldAlign == 0 || NewAlign == 0) {
2722 QualType Ty;
2723 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2724 Ty = VD->getType();
2725 else
2726 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2727
2728 if (OldAlign == 0)
2729 OldAlign = S.Context.getTypeAlign(Ty);
2730 if (NewAlign == 0)
2731 NewAlign = S.Context.getTypeAlign(Ty);
2732 }
2733
2734 if (OldAlign != NewAlign) {
2735 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2738 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2739 }
2740 }
2741
2742 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2743 // C++11 [dcl.align]p6:
2744 // if any declaration of an entity has an alignment-specifier,
2745 // every defining declaration of that entity shall specify an
2746 // equivalent alignment.
2747 // C11 6.7.5/7:
2748 // If the definition of an object does not have an alignment
2749 // specifier, any other declaration of that object shall also
2750 // have no alignment specifier.
2751 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2752 << OldAlignasAttr;
2753 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2754 << OldAlignasAttr;
2755 }
2756
2757 bool AnyAdded = false;
2758
2759 // Ensure we have an attribute representing the strictest alignment.
2760 if (OldAlign > NewAlign) {
2761 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2762 Clone->setInherited(true);
2763 New->addAttr(Clone);
2764 AnyAdded = true;
2765 }
2766
2767 // Ensure we have an alignas attribute if the old declaration had one.
2768 if (OldAlignasAttr && !NewAlignasAttr &&
2769 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2770 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2771 Clone->setInherited(true);
2772 New->addAttr(Clone);
2773 AnyAdded = true;
2774 }
2775
2776 return AnyAdded;
2777}
2778
2779#define WANT_DECL_MERGE_LOGIC
2780#include "clang/Sema/AttrParsedAttrImpl.inc"
2781#undef WANT_DECL_MERGE_LOGIC
2782
2784 const InheritableAttr *Attr,
2786 // Diagnose any mutual exclusions between the attribute that we want to add
2787 // and attributes that already exist on the declaration.
2788 if (!DiagnoseMutualExclusions(S, D, Attr))
2789 return false;
2790
2791 // This function copies an attribute Attr from a previous declaration to the
2792 // new declaration D if the new declaration doesn't itself have that attribute
2793 // yet or if that attribute allows duplicates.
2794 // If you're adding a new attribute that requires logic different from
2795 // "use explicit attribute on decl if present, else use attribute from
2796 // previous decl", for example if the attribute needs to be consistent
2797 // between redeclarations, you need to call a custom merge function here.
2798 InheritableAttr *NewAttr = nullptr;
2799 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2800 NewAttr = S.mergeAvailabilityAttr(
2801 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2802 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2803 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2804 AA->getPriority(), AA->getEnvironment());
2805 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2806 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2807 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2808 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2809 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2810 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2811 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2812 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2813 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2814 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2815 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2816 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2817 FA->getFirstArg());
2818 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2819 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2820 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2821 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2822 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2823 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2824 IA->getInheritanceModel());
2825 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2826 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2827 &S.Context.Idents.get(AA->getSpelling()));
2828 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2829 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2830 isa<CUDAGlobalAttr>(Attr))) {
2831 // CUDA target attributes are part of function signature for
2832 // overloading purposes and must not be merged.
2833 return false;
2834 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2835 NewAttr = S.mergeMinSizeAttr(D, *MA);
2836 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2837 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2838 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2839 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2840 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2841 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2842 else if (isa<AlignedAttr>(Attr))
2843 // AlignedAttrs are handled separately, because we need to handle all
2844 // such attributes on a declaration at the same time.
2845 NewAttr = nullptr;
2846 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2847 (AMK == Sema::AMK_Override ||
2850 NewAttr = nullptr;
2851 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2852 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2853 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2854 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2855 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2856 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2857 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2858 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2859 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2860 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2861 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2862 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2863 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2864 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2865 NT->getZ());
2866 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2867 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2868 else if (isa<SuppressAttr>(Attr))
2869 // Do nothing. Each redeclaration should be suppressed separately.
2870 NewAttr = nullptr;
2871 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2872 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2873
2874 if (NewAttr) {
2875 NewAttr->setInherited(true);
2876 D->addAttr(NewAttr);
2877 if (isa<MSInheritanceAttr>(NewAttr))
2878 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2879 return true;
2880 }
2881
2882 return false;
2883}
2884
2885static const NamedDecl *getDefinition(const Decl *D) {
2886 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2887 return TD->getDefinition();
2888 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2889 const VarDecl *Def = VD->getDefinition();
2890 if (Def)
2891 return Def;
2892 return VD->getActingDefinition();
2893 }
2894 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2895 const FunctionDecl *Def = nullptr;
2896 if (FD->isDefined(Def, true))
2897 return Def;
2898 }
2899 return nullptr;
2900}
2901
2902static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2903 for (const auto *Attribute : D->attrs())
2904 if (Attribute->getKind() == Kind)
2905 return true;
2906 return false;
2907}
2908
2909/// checkNewAttributesAfterDef - If we already have a definition, check that
2910/// there are no new attributes in this declaration.
2911static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2912 if (!New->hasAttrs())
2913 return;
2914
2915 const NamedDecl *Def = getDefinition(Old);
2916 if (!Def || Def == New)
2917 return;
2918
2919 AttrVec &NewAttributes = New->getAttrs();
2920 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2921 const Attr *NewAttribute = NewAttributes[I];
2922
2923 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2924 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2925 SkipBodyInfo SkipBody;
2926 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2927
2928 // If we're skipping this definition, drop the "alias" attribute.
2929 if (SkipBody.ShouldSkip) {
2930 NewAttributes.erase(NewAttributes.begin() + I);
2931 --E;
2932 continue;
2933 }
2934 } else {
2935 VarDecl *VD = cast<VarDecl>(New);
2936 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2938 ? diag::err_alias_after_tentative
2939 : diag::err_redefinition;
2940 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2941 if (Diag == diag::err_redefinition)
2942 S.notePreviousDefinition(Def, VD->getLocation());
2943 else
2944 S.Diag(Def->getLocation(), diag::note_previous_definition);
2945 VD->setInvalidDecl();
2946 }
2947 ++I;
2948 continue;
2949 }
2950
2951 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2952 // Tentative definitions are only interesting for the alias check above.
2953 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2954 ++I;
2955 continue;
2956 }
2957 }
2958
2959 if (hasAttribute(Def, NewAttribute->getKind())) {
2960 ++I;
2961 continue; // regular attr merging will take care of validating this.
2962 }
2963
2964 if (isa<C11NoReturnAttr>(NewAttribute)) {
2965 // C's _Noreturn is allowed to be added to a function after it is defined.
2966 ++I;
2967 continue;
2968 } else if (isa<UuidAttr>(NewAttribute)) {
2969 // msvc will allow a subsequent definition to add an uuid to a class
2970 ++I;
2971 continue;
2972 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2973 if (AA->isAlignas()) {
2974 // C++11 [dcl.align]p6:
2975 // if any declaration of an entity has an alignment-specifier,
2976 // every defining declaration of that entity shall specify an
2977 // equivalent alignment.
2978 // C11 6.7.5/7:
2979 // If the definition of an object does not have an alignment
2980 // specifier, any other declaration of that object shall also
2981 // have no alignment specifier.
2982 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2983 << AA;
2984 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2985 << AA;
2986 NewAttributes.erase(NewAttributes.begin() + I);
2987 --E;
2988 continue;
2989 }
2990 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2991 // If there is a C definition followed by a redeclaration with this
2992 // attribute then there are two different definitions. In C++, prefer the
2993 // standard diagnostics.
2994 if (!S.getLangOpts().CPlusPlus) {
2995 S.Diag(NewAttribute->getLocation(),
2996 diag::err_loader_uninitialized_redeclaration);
2997 S.Diag(Def->getLocation(), diag::note_previous_definition);
2998 NewAttributes.erase(NewAttributes.begin() + I);
2999 --E;
3000 continue;
3001 }
3002 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3003 cast<VarDecl>(New)->isInline() &&
3004 !cast<VarDecl>(New)->isInlineSpecified()) {
3005 // Don't warn about applying selectany to implicitly inline variables.
3006 // Older compilers and language modes would require the use of selectany
3007 // to make such variables inline, and it would have no effect if we
3008 // honored it.
3009 ++I;
3010 continue;
3011 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3012 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3013 // declarations after definitions.
3014 ++I;
3015 continue;
3016 }
3017
3018 S.Diag(NewAttribute->getLocation(),
3019 diag::warn_attribute_precede_definition);
3020 S.Diag(Def->getLocation(), diag::note_previous_definition);
3021 NewAttributes.erase(NewAttributes.begin() + I);
3022 --E;
3023 }
3024}
3025
3026static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3027 const ConstInitAttr *CIAttr,
3028 bool AttrBeforeInit) {
3029 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3030
3031 // Figure out a good way to write this specifier on the old declaration.
3032 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3033 // enough of the attribute list spelling information to extract that without
3034 // heroics.
3035 std::string SuitableSpelling;
3036 if (S.getLangOpts().CPlusPlus20)
3037 SuitableSpelling = std::string(
3038 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3039 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3040 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3041 InsertLoc, {tok::l_square, tok::l_square,
3042 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3043 S.PP.getIdentifierInfo("require_constant_initialization"),
3044 tok::r_square, tok::r_square}));
3045 if (SuitableSpelling.empty())
3046 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3047 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3048 S.PP.getIdentifierInfo("require_constant_initialization"),
3049 tok::r_paren, tok::r_paren}));
3050 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3051 SuitableSpelling = "constinit";
3052 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3053 SuitableSpelling = "[[clang::require_constant_initialization]]";
3054 if (SuitableSpelling.empty())
3055 SuitableSpelling = "__attribute__((require_constant_initialization))";
3056 SuitableSpelling += " ";
3057
3058 if (AttrBeforeInit) {
3059 // extern constinit int a;
3060 // int a = 0; // error (missing 'constinit'), accepted as extension
3061 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3062 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3063 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3064 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3065 } else {
3066 // int a = 0;
3067 // constinit extern int a; // error (missing 'constinit')
3068 S.Diag(CIAttr->getLocation(),
3069 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3070 : diag::warn_require_const_init_added_too_late)
3071 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3072 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3073 << CIAttr->isConstinit()
3074 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3075 }
3076}
3077
3080 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3081 UsedAttr *NewAttr = OldAttr->clone(Context);
3082 NewAttr->setInherited(true);
3083 New->addAttr(NewAttr);
3084 }
3085 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3086 RetainAttr *NewAttr = OldAttr->clone(Context);
3087 NewAttr->setInherited(true);
3088 New->addAttr(NewAttr);
3089 }
3090
3091 if (!Old->hasAttrs() && !New->hasAttrs())
3092 return;
3093
3094 // [dcl.constinit]p1:
3095 // If the [constinit] specifier is applied to any declaration of a
3096 // variable, it shall be applied to the initializing declaration.
3097 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3098 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3099 if (bool(OldConstInit) != bool(NewConstInit)) {
3100 const auto *OldVD = cast<VarDecl>(Old);
3101 auto *NewVD = cast<VarDecl>(New);
3102
3103 // Find the initializing declaration. Note that we might not have linked
3104 // the new declaration into the redeclaration chain yet.
3105 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3106 if (!InitDecl &&
3107 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3108 InitDecl = NewVD;
3109
3110 if (InitDecl == NewVD) {
3111 // This is the initializing declaration. If it would inherit 'constinit',
3112 // that's ill-formed. (Note that we do not apply this to the attribute
3113 // form).
3114 if (OldConstInit && OldConstInit->isConstinit())
3115 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3116 /*AttrBeforeInit=*/true);
3117 } else if (NewConstInit) {
3118 // This is the first time we've been told that this declaration should
3119 // have a constant initializer. If we already saw the initializing
3120 // declaration, this is too late.
3121 if (InitDecl && InitDecl != NewVD) {
3122 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3123 /*AttrBeforeInit=*/false);
3124 NewVD->dropAttr<ConstInitAttr>();
3125 }
3126 }
3127 }
3128
3129 // Attributes declared post-definition are currently ignored.
3130 checkNewAttributesAfterDef(*this, New, Old);
3131
3132 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3133 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3134 if (!OldA->isEquivalent(NewA)) {
3135 // This redeclaration changes __asm__ label.
3136 Diag(New->getLocation(), diag::err_different_asm_label);
3137 Diag(OldA->getLocation(), diag::note_previous_declaration);
3138 }
3139 } else if (Old->isUsed()) {
3140 // This redeclaration adds an __asm__ label to a declaration that has
3141 // already been ODR-used.
3142 Diag(New->getLocation(), diag::err_late_asm_label_name)
3143 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3144 }
3145 }
3146
3147 // Re-declaration cannot add abi_tag's.
3148 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3149 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3150 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3151 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3152 Diag(NewAbiTagAttr->getLocation(),
3153 diag::err_new_abi_tag_on_redeclaration)
3154 << NewTag;
3155 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3156 }
3157 }
3158 } else {
3159 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3160 Diag(Old->getLocation(), diag::note_previous_declaration);
3161 }
3162 }
3163
3164 // This redeclaration adds a section attribute.
3165 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3166 if (auto *VD = dyn_cast<VarDecl>(New)) {
3167 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3168 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3169 Diag(Old->getLocation(), diag::note_previous_declaration);
3170 }
3171 }
3172 }
3173
3174 // Redeclaration adds code-seg attribute.
3175 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3176 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3177 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3178 Diag(New->getLocation(), diag::warn_mismatched_section)
3179 << 0 /*codeseg*/;
3180 Diag(Old->getLocation(), diag::note_previous_declaration);
3181 }
3182
3183 if (!Old->hasAttrs())
3184 return;
3185
3186 bool foundAny = New->hasAttrs();
3187
3188 // Ensure that any moving of objects within the allocated map is done before
3189 // we process them.
3190 if (!foundAny) New->setAttrs(AttrVec());
3191
3192 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3193 // Ignore deprecated/unavailable/availability attributes if requested.
3195 if (isa<DeprecatedAttr>(I) ||
3196 isa<UnavailableAttr>(I) ||
3197 isa<AvailabilityAttr>(I)) {
3198 switch (AMK) {
3199 case AMK_None:
3200 continue;
3201
3202 case AMK_Redeclaration:
3203 case AMK_Override:
3206 LocalAMK = AMK;
3207 break;
3208 }
3209 }
3210
3211 // Already handled.
3212 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3213 continue;
3214
3215 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3216 foundAny = true;
3217 }
3218
3219 if (mergeAlignedAttrs(*this, New, Old))
3220 foundAny = true;
3221
3222 if (!foundAny) New->dropAttrs();
3223}
3224
3225/// mergeParamDeclAttributes - Copy attributes from the old parameter
3226/// to the new one.
3228 const ParmVarDecl *oldDecl,
3229 Sema &S) {
3230 // C++11 [dcl.attr.depend]p2:
3231 // The first declaration of a function shall specify the
3232 // carries_dependency attribute for its declarator-id if any declaration
3233 // of the function specifies the carries_dependency attribute.
3234 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3235 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3236 S.Diag(CDA->getLocation(),
3237 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3238 // Find the first declaration of the parameter.
3239 // FIXME: Should we build redeclaration chains for function parameters?
3240 const FunctionDecl *FirstFD =
3241 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3242 const ParmVarDecl *FirstVD =
3243 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3244 S.Diag(FirstVD->getLocation(),
3245 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3246 }
3247
3248 // HLSL parameter declarations for inout and out must match between
3249 // declarations. In HLSL inout and out are ambiguous at the call site, but
3250 // have different calling behavior, so you cannot overload a method based on a
3251 // difference between inout and out annotations.
3252 if (S.getLangOpts().HLSL) {
3253 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3254 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3255 // We don't need to cover the case where one declaration doesn't have an
3256 // attribute. The only possible case there is if one declaration has an `in`
3257 // attribute and the other declaration has no attribute. This case is
3258 // allowed since parameters are `in` by default.
3259 if (NDAttr && ODAttr &&
3260 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3261 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3262 << NDAttr << newDecl;
3263 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3264 << ODAttr;
3265 }
3266 }
3267
3268 if (!oldDecl->hasAttrs())
3269 return;
3270
3271 bool foundAny = newDecl->hasAttrs();
3272
3273 // Ensure that any moving of objects within the allocated map is
3274 // done before we process them.
3275 if (!foundAny) newDecl->setAttrs(AttrVec());
3276
3277 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3278 if (!DeclHasAttr(newDecl, I)) {
3279 InheritableAttr *newAttr =
3280 cast<InheritableParamAttr>(I->clone(S.Context));
3281 newAttr->setInherited(true);
3282 newDecl->addAttr(newAttr);
3283 foundAny = true;
3284 }
3285 }
3286
3287 if (!foundAny) newDecl->dropAttrs();
3288}
3289
3291 const ASTContext &Ctx) {
3292
3293 auto NoSizeInfo = [&Ctx](QualType Ty) {
3294 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3295 return true;
3296 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3297 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3298 return false;
3299 };
3300
3301 // `type[]` is equivalent to `type *` and `type[*]`.
3302 if (NoSizeInfo(Old) && NoSizeInfo(New))
3303 return true;
3304
3305 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3306 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3307 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3308 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3309 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3310 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3311 return false;
3312 return true;
3313 }
3314
3315 // Only compare size, ignore Size modifiers and CVR.
3316 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3317 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3318 Ctx.getAsConstantArrayType(New)->getSize();
3319 }
3320
3321 // Don't try to compare dependent sized array
3323 return true;
3324 }
3325
3326 return Old == New;
3327}
3328
3329static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3330 const ParmVarDecl *OldParam,
3331 Sema &S) {
3332 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3333 if (auto Newnullability = NewParam->getType()->getNullability()) {
3334 if (*Oldnullability != *Newnullability) {
3335 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3337 *Newnullability,
3339 != 0))
3341 *Oldnullability,
3343 != 0));
3344 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3345 }
3346 } else {
3347 QualType NewT = NewParam->getType();
3348 NewT = S.Context.getAttributedType(
3350 NewT, NewT);
3351 NewParam->setType(NewT);
3352 }
3353 }
3354 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3355 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3356 if (OldParamDT && NewParamDT &&
3357 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3358 QualType OldParamOT = OldParamDT->getOriginalType();
3359 QualType NewParamOT = NewParamDT->getOriginalType();
3360 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3361 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3362 << NewParam << NewParamOT;
3363 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3364 << OldParamOT;
3365 }
3366 }
3367}
3368
3369namespace {
3370
3371/// Used in MergeFunctionDecl to keep track of function parameters in
3372/// C.
3373struct GNUCompatibleParamWarning {
3374 ParmVarDecl *OldParm;
3375 ParmVarDecl *NewParm;
3376 QualType PromotedType;
3377};
3378
3379} // end anonymous namespace
3380
3381// Determine whether the previous declaration was a definition, implicit
3382// declaration, or a declaration.
3383template <typename T>
3384static std::pair<diag::kind, SourceLocation>
3385getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3386 diag::kind PrevDiag;
3387 SourceLocation OldLocation = Old->getLocation();
3388 if (Old->isThisDeclarationADefinition())
3389 PrevDiag = diag::note_previous_definition;
3390 else if (Old->isImplicit()) {
3391 PrevDiag = diag::note_previous_implicit_declaration;
3392 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3393 if (FD->getBuiltinID())
3394 PrevDiag = diag::note_previous_builtin_declaration;
3395 }
3396 if (OldLocation.isInvalid())
3397 OldLocation = New->getLocation();
3398 } else
3399 PrevDiag = diag::note_previous_declaration;
3400 return std::make_pair(PrevDiag, OldLocation);
3401}
3402
3403/// canRedefineFunction - checks if a function can be redefined. Currently,
3404/// only extern inline functions can be redefined, and even then only in
3405/// GNU89 mode.
3406static bool canRedefineFunction(const FunctionDecl *FD,
3407 const LangOptions& LangOpts) {
3408 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3409 !LangOpts.CPlusPlus &&
3410 FD->isInlineSpecified() &&
3411 FD->getStorageClass() == SC_Extern);
3412}
3413
3415 const AttributedType *AT = T->getAs<AttributedType>();
3416 while (AT && !AT->isCallingConv())
3417 AT = AT->getModifiedType()->getAs<AttributedType>();
3418 return AT;
3419}
3420
3421template <typename T>
3422static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3423 const DeclContext *DC = Old->getDeclContext();
3424 if (DC->isRecord())
3425 return false;
3426
3427 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3428 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3429 return true;
3430 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3431 return true;
3432 return false;
3433}
3434
3435template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3436static bool isExternC(VarTemplateDecl *) { return false; }
3437static bool isExternC(FunctionTemplateDecl *) { return false; }
3438
3439/// Check whether a redeclaration of an entity introduced by a
3440/// using-declaration is valid, given that we know it's not an overload
3441/// (nor a hidden tag declaration).
3442template<typename ExpectedDecl>
3444 ExpectedDecl *New) {
3445 // C++11 [basic.scope.declarative]p4:
3446 // Given a set of declarations in a single declarative region, each of
3447 // which specifies the same unqualified name,
3448 // -- they shall all refer to the same entity, or all refer to functions
3449 // and function templates; or
3450 // -- exactly one declaration shall declare a class name or enumeration
3451 // name that is not a typedef name and the other declarations shall all
3452 // refer to the same variable or enumerator, or all refer to functions
3453 // and function templates; in this case the class name or enumeration
3454 // name is hidden (3.3.10).
3455
3456 // C++11 [namespace.udecl]p14:
3457 // If a function declaration in namespace scope or block scope has the
3458 // same name and the same parameter-type-list as a function introduced
3459 // by a using-declaration, and the declarations do not declare the same
3460 // function, the program is ill-formed.
3461
3462 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3463 if (Old &&
3464 !Old->getDeclContext()->getRedeclContext()->Equals(
3465 New->getDeclContext()->getRedeclContext()) &&
3466 !(isExternC(Old) && isExternC(New)))
3467 Old = nullptr;
3468
3469 if (!Old) {
3470 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3471 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3472 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3473 return true;
3474 }
3475 return false;
3476}
3477
3479 const FunctionDecl *B) {
3480 assert(A->getNumParams() == B->getNumParams());
3481
3482 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3483 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3484 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3485 if (AttrA == AttrB)
3486 return true;
3487 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3488 AttrA->isDynamic() == AttrB->isDynamic();
3489 };
3490
3491 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3492}
3493
3494/// If necessary, adjust the semantic declaration context for a qualified
3495/// declaration to name the correct inline namespace within the qualifier.
3497 DeclaratorDecl *OldD) {
3498 // The only case where we need to update the DeclContext is when
3499 // redeclaration lookup for a qualified name finds a declaration
3500 // in an inline namespace within the context named by the qualifier:
3501 //
3502 // inline namespace N { int f(); }
3503 // int ::f(); // Sema DC needs adjusting from :: to N::.
3504 //
3505 // For unqualified declarations, the semantic context *can* change
3506 // along the redeclaration chain (for local extern declarations,
3507 // extern "C" declarations, and friend declarations in particular).
3508 if (!NewD->getQualifier())
3509 return;
3510
3511 // NewD is probably already in the right context.
3512 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3513 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3514 if (NamedDC->Equals(SemaDC))
3515 return;
3516
3517 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3518 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3519 "unexpected context for redeclaration");
3520
3521 auto *LexDC = NewD->getLexicalDeclContext();
3522 auto FixSemaDC = [=](NamedDecl *D) {
3523 if (!D)
3524 return;
3525 D->setDeclContext(SemaDC);
3526 D->setLexicalDeclContext(LexDC);
3527 };
3528
3529 FixSemaDC(NewD);
3530 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3531 FixSemaDC(FD->getDescribedFunctionTemplate());
3532 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3533 FixSemaDC(VD->getDescribedVarTemplate());
3534}
3535
3537 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3538 // Verify the old decl was also a function.
3539 FunctionDecl *Old = OldD->getAsFunction();
3540 if (!Old) {
3541 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3542 if (New->getFriendObjectKind()) {
3543 Diag(New->getLocation(), diag::err_using_decl_friend);
3544 Diag(Shadow->getTargetDecl()->getLocation(),
3545 diag::note_using_decl_target);
3546 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3547 << 0;
3548 return true;
3549 }
3550
3551 // Check whether the two declarations might declare the same function or
3552 // function template.
3553 if (FunctionTemplateDecl *NewTemplate =
3555 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3556 NewTemplate))
3557 return true;
3558 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3559 ->getAsFunction();
3560 } else {
3561 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3562 return true;
3563 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3564 }
3565 } else {
3566 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3567 << New->getDeclName();
3568 notePreviousDefinition(OldD, New->getLocation());
3569 return true;
3570 }
3571 }
3572
3573 // If the old declaration was found in an inline namespace and the new
3574 // declaration was qualified, update the DeclContext to match.
3576
3577 // If the old declaration is invalid, just give up here.
3578 if (Old->isInvalidDecl())
3579 return true;
3580
3581 // Disallow redeclaration of some builtins.
3582 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3583 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3584 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3585 << Old << Old->getType();
3586 return true;
3587 }
3588
3589 diag::kind PrevDiag;
3590 SourceLocation OldLocation;
3591 std::tie(PrevDiag, OldLocation) =
3593
3594 // Don't complain about this if we're in GNU89 mode and the old function
3595 // is an extern inline function.
3596 // Don't complain about specializations. They are not supposed to have
3597 // storage classes.
3598 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3599 New->getStorageClass() == SC_Static &&
3600 Old->hasExternalFormalLinkage() &&
3603 if (getLangOpts().MicrosoftExt) {
3604 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3605 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3606 } else {
3607 Diag(New->getLocation(), diag::err_static_non_static) << New;
3608 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3609 return true;
3610 }
3611 }
3612
3613 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3614 if (!Old->hasAttr<InternalLinkageAttr>()) {
3615 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3616 << ILA;
3617 Diag(Old->getLocation(), diag::note_previous_declaration);
3618 New->dropAttr<InternalLinkageAttr>();
3619 }
3620
3621 if (auto *EA = New->getAttr<ErrorAttr>()) {
3622 if (!Old->hasAttr<ErrorAttr>()) {
3623 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3624 Diag(Old->getLocation(), diag::note_previous_declaration);
3625 New->dropAttr<ErrorAttr>();
3626 }
3627 }
3628
3629 if (CheckRedeclarationInModule(New, Old))
3630 return true;
3631
3632 if (!getLangOpts().CPlusPlus) {
3633 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3634 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3635 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3636 << New << OldOvl;
3637
3638 // Try our best to find a decl that actually has the overloadable
3639 // attribute for the note. In most cases (e.g. programs with only one
3640 // broken declaration/definition), this won't matter.
3641 //
3642 // FIXME: We could do this if we juggled some extra state in
3643 // OverloadableAttr, rather than just removing it.
3644 const Decl *DiagOld = Old;
3645 if (OldOvl) {
3646 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3647 const auto *A = D->getAttr<OverloadableAttr>();
3648 return A && !A->isImplicit();
3649 });
3650 // If we've implicitly added *all* of the overloadable attrs to this
3651 // chain, emitting a "previous redecl" note is pointless.
3652 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3653 }
3654
3655 if (DiagOld)
3656 Diag(DiagOld->getLocation(),
3657 diag::note_attribute_overloadable_prev_overload)
3658 << OldOvl;
3659
3660 if (OldOvl)
3661 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3662 else
3663 New->dropAttr<OverloadableAttr>();
3664 }
3665 }
3666
3667 // It is not permitted to redeclare an SME function with different SME
3668 // attributes.
3669 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3670 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3671 << New->getType() << Old->getType();
3672 Diag(OldLocation, diag::note_previous_declaration);
3673 return true;
3674 }
3675
3676 // If a function is first declared with a calling convention, but is later
3677 // declared or defined without one, all following decls assume the calling
3678 // convention of the first.
3679 //
3680 // It's OK if a function is first declared without a calling convention,
3681 // but is later declared or defined with the default calling convention.
3682 //
3683 // To test if either decl has an explicit calling convention, we look for
3684 // AttributedType sugar nodes on the type as written. If they are missing or
3685 // were canonicalized away, we assume the calling convention was implicit.
3686 //
3687 // Note also that we DO NOT return at this point, because we still have
3688 // other tests to run.
3689 QualType OldQType = Context.getCanonicalType(Old->getType());
3690 QualType NewQType = Context.getCanonicalType(New->getType());
3691 const FunctionType *OldType = cast<FunctionType>(OldQType);
3692 const FunctionType *NewType = cast<FunctionType>(NewQType);
3693 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3694 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3695 bool RequiresAdjustment = false;
3696
3697 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3699 const FunctionType *FT =
3700 First->getType().getCanonicalType()->castAs<FunctionType>();
3702 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3703 if (!NewCCExplicit) {
3704 // Inherit the CC from the previous declaration if it was specified
3705 // there but not here.
3706 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3707 RequiresAdjustment = true;
3708 } else if (Old->getBuiltinID()) {
3709 // Builtin attribute isn't propagated to the new one yet at this point,
3710 // so we check if the old one is a builtin.
3711
3712 // Calling Conventions on a Builtin aren't really useful and setting a
3713 // default calling convention and cdecl'ing some builtin redeclarations is
3714 // common, so warn and ignore the calling convention on the redeclaration.
3715 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3716 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3718 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3719 RequiresAdjustment = true;
3720 } else {
3721 // Calling conventions aren't compatible, so complain.
3722 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3723 Diag(New->getLocation(), diag::err_cconv_change)
3724 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3725 << !FirstCCExplicit
3726 << (!FirstCCExplicit ? "" :
3728
3729 // Put the note on the first decl, since it is the one that matters.
3730 Diag(First->getLocation(), diag::note_previous_declaration);
3731 return true;
3732 }
3733 }
3734
3735 // FIXME: diagnose the other way around?
3736 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3737 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3738 RequiresAdjustment = true;
3739 }
3740
3741 // Merge regparm attribute.
3742 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3743 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3744 if (NewTypeInfo.getHasRegParm()) {
3745 Diag(New->getLocation(), diag::err_regparm_mismatch)
3746 << NewType->getRegParmType()
3747 << OldType->getRegParmType();
3748 Diag(OldLocation, diag::note_previous_declaration);
3749 return true;
3750 }
3751
3752 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3753 RequiresAdjustment = true;
3754 }
3755
3756 // Merge ns_returns_retained attribute.
3757 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3758 if (NewTypeInfo.getProducesResult()) {
3759 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3760 << "'ns_returns_retained'";
3761 Diag(OldLocation, diag::note_previous_declaration);
3762 return true;
3763 }
3764
3765 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3766 RequiresAdjustment = true;
3767 }
3768
3769 if (OldTypeInfo.getNoCallerSavedRegs() !=
3770 NewTypeInfo.getNoCallerSavedRegs()) {
3771 if (NewTypeInfo.getNoCallerSavedRegs()) {
3772 AnyX86NoCallerSavedRegistersAttr *Attr =
3773 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3774 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3775 Diag(OldLocation, diag::note_previous_declaration);
3776 return true;
3777 }
3778
3779 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3780 RequiresAdjustment = true;
3781 }
3782
3783 if (RequiresAdjustment) {
3786 New->setType(QualType(AdjustedType, 0));
3787 NewQType = Context.getCanonicalType(New->getType());
3788 }
3789
3790 // If this redeclaration makes the function inline, we may need to add it to
3791 // UndefinedButUsed.
3792 if (!Old->isInlined() && New->isInlined() &&
3793 !New->hasAttr<GNUInlineAttr>() &&
3794 !getLangOpts().GNUInline &&
3795 Old->isUsed(false) &&
3796 !Old->isDefined() && !New->isThisDeclarationADefinition())
3797 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3798 SourceLocation()));
3799
3800 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3801 // about it.
3802 if (New->hasAttr<GNUInlineAttr>() &&
3803 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3804 UndefinedButUsed.erase(Old->getCanonicalDecl());
3805 }
3806
3807 // If pass_object_size params don't match up perfectly, this isn't a valid
3808 // redeclaration.
3809 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3811 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3812 << New->getDeclName();
3813 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3814 return true;
3815 }
3816
3817 QualType OldQTypeForComparison = OldQType;
3819 const auto OldFX = Old->getFunctionEffects();
3820 const auto NewFX = New->getFunctionEffects();
3821 if (OldFX != NewFX) {
3822 const auto Diffs = FunctionEffectDifferences(OldFX, NewFX);
3823 for (const auto &Diff : Diffs) {
3824 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3825 Diag(New->getLocation(),
3826 diag::warn_mismatched_func_effect_redeclaration)
3827 << Diff.effectName();
3828 Diag(Old->getLocation(), diag::note_previous_declaration);
3829 }
3830 }
3831 // Following a warning, we could skip merging effects from the previous
3832 // declaration, but that would trigger an additional "conflicting types"
3833 // error.
3834 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3836 FunctionEffectSet MergedFX =
3837 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3838 if (!MergeErrs.empty())
3840 Old->getLocation());
3841
3842 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3843 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3844 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
3845 NewFPT->getParamTypes(), EPI);
3846
3847 New->setType(ModQT);
3848 NewQType = New->getType();
3849
3850 // Revise OldQTForComparison to include the merged effects,
3851 // so as not to fail due to differences later.
3852 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3853 EPI = OldFPT->getExtProtoInfo();
3854 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3855 OldQTypeForComparison = Context.getFunctionType(
3856 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
3857 }
3858 }
3859 }
3860 }
3861
3862 if (getLangOpts().CPlusPlus) {
3863 OldQType = Context.getCanonicalType(Old->getType());
3864 NewQType = Context.getCanonicalType(New->getType());
3865
3866 // Go back to the type source info to compare the declared return types,
3867 // per C++1y [dcl.type.auto]p13:
3868 // Redeclarations or specializations of a function or function template
3869 // with a declared return type that uses a placeholder type shall also
3870 // use that placeholder, not a deduced type.
3871 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3872 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3873 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3874 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3875 OldDeclaredReturnType)) {
3876 QualType ResQT;
3877 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3878 OldDeclaredReturnType->isObjCObjectPointerType())
3879 // FIXME: This does the wrong thing for a deduced return type.
3880 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3881 if (ResQT.isNull()) {
3882 if (New->isCXXClassMember() && New->isOutOfLine())
3883 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3884 << New << New->getReturnTypeSourceRange();
3885 else
3886 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3887 << New->getReturnTypeSourceRange();
3888 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3889 << Old->getReturnTypeSourceRange();
3890 return true;
3891 }
3892 else
3893 NewQType = ResQT;
3894 }
3895
3896 QualType OldReturnType = OldType->getReturnType();
3897 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3898 if (OldReturnType != NewReturnType) {
3899 // If this function has a deduced return type and has already been
3900 // defined, copy the deduced value from the old declaration.
3901 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3902 if (OldAT && OldAT->isDeduced()) {
3903 QualType DT = OldAT->getDeducedType();
3904 if (DT.isNull()) {
3906 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3907 } else {
3908 New->setType(SubstAutoType(New->getType(), DT));
3909 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3910 }
3911 }
3912 }
3913
3914 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3915 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3916 if (OldMethod && NewMethod) {
3917 // Preserve triviality.
3918 NewMethod->setTrivial(OldMethod->isTrivial());
3919
3920 // MSVC allows explicit template specialization at class scope:
3921 // 2 CXXMethodDecls referring to the same function will be injected.
3922 // We don't want a redeclaration error.
3923 bool IsClassScopeExplicitSpecialization =
3924 OldMethod->isFunctionTemplateSpecialization() &&
3926 bool isFriend = NewMethod->getFriendObjectKind();
3927
3928 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3929 !IsClassScopeExplicitSpecialization) {
3930 // -- Member function declarations with the same name and the
3931 // same parameter types cannot be overloaded if any of them
3932 // is a static member function declaration.
3933 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3934 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3935 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3936 return true;
3937 }
3938
3939 // C++ [class.mem]p1:
3940 // [...] A member shall not be declared twice in the
3941 // member-specification, except that a nested class or member
3942 // class template can be declared and then later defined.
3943 if (!inTemplateInstantiation()) {
3944 unsigned NewDiag;
3945 if (isa<CXXConstructorDecl>(OldMethod))
3946 NewDiag = diag::err_constructor_redeclared;
3947 else if (isa<CXXDestructorDecl>(NewMethod))
3948 NewDiag = diag::err_destructor_redeclared;
3949 else if (isa<CXXConversionDecl>(NewMethod))
3950 NewDiag = diag::err_conv_function_redeclared;
3951 else
3952 NewDiag = diag::err_member_redeclared;
3953
3954 Diag(New->getLocation(), NewDiag);
3955 } else {
3956 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3957 << New << New->getType();
3958 }
3959 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3960 return true;
3961
3962 // Complain if this is an explicit declaration of a special
3963 // member that was initially declared implicitly.
3964 //
3965 // As an exception, it's okay to befriend such methods in order
3966 // to permit the implicit constructor/destructor/operator calls.
3967 } else if (OldMethod->isImplicit()) {
3968 if (isFriend) {
3969 NewMethod->setImplicit();
3970 } else {
3971 Diag(NewMethod->getLocation(),
3972 diag::err_definition_of_implicitly_declared_member)
3973 << New << llvm::to_underlying(getSpecialMember(OldMethod));
3974 return true;
3975 }
3976 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3977 Diag(NewMethod->getLocation(),
3978 diag::err_definition_of_explicitly_defaulted_member)
3979 << llvm::to_underlying(getSpecialMember(OldMethod));
3980 return true;
3981 }
3982 }
3983
3984 // C++1z [over.load]p2
3985 // Certain function declarations cannot be overloaded:
3986 // -- Function declarations that differ only in the return type,
3987 // the exception specification, or both cannot be overloaded.
3988
3989 // Check the exception specifications match. This may recompute the type of
3990 // both Old and New if it resolved exception specifications, so grab the
3991 // types again after this. Because this updates the type, we do this before
3992 // any of the other checks below, which may update the "de facto" NewQType
3993 // but do not necessarily update the type of New.
3994 if (CheckEquivalentExceptionSpec(Old, New))
3995 return true;
3996
3997 // C++11 [dcl.attr.noreturn]p1:
3998 // The first declaration of a function shall specify the noreturn
3999 // attribute if any declaration of that function specifies the noreturn
4000 // attribute.
4001 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4002 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4003 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4004 << NRA;
4005 Diag(Old->getLocation(), diag::note_previous_declaration);
4006 }
4007
4008 // C++11 [dcl.attr.depend]p2:
4009 // The first declaration of a function shall specify the
4010 // carries_dependency attribute for its declarator-id if any declaration
4011 // of the function specifies the carries_dependency attribute.
4012 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4013 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4014 Diag(CDA->getLocation(),
4015 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4016 Diag(Old->getFirstDecl()->getLocation(),
4017 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4018 }
4019
4020 // (C++98 8.3.5p3):
4021 // All declarations for a function shall agree exactly in both the
4022 // return type and the parameter-type-list.
4023 // We also want to respect all the extended bits except noreturn.
4024
4025 // noreturn should now match unless the old type info didn't have it.
4026 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4027 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4028 const FunctionType *OldTypeForComparison
4029 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4030 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4031 assert(OldQTypeForComparison.isCanonical());
4032 }
4033
4034 if (haveIncompatibleLanguageLinkages(Old, New)) {
4035 // As a special case, retain the language linkage from previous
4036 // declarations of a friend function as an extension.
4037 //
4038 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4039 // and is useful because there's otherwise no way to specify language
4040 // linkage within class scope.
4041 //
4042 // Check cautiously as the friend object kind isn't yet complete.
4043 if (New->getFriendObjectKind() != Decl::FOK_None) {
4044 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4045 Diag(OldLocation, PrevDiag);
4046 } else {
4047 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4048 Diag(OldLocation, PrevDiag);
4049 return true;
4050 }
4051 }
4052
4053 // If the function types are compatible, merge the declarations. Ignore the
4054 // exception specifier because it was already checked above in
4055 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4056 // about incompatible types under -fms-compatibility.
4057 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4058 NewQType))
4059 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4060
4061 // If the types are imprecise (due to dependent constructs in friends or
4062 // local extern declarations), it's OK if they differ. We'll check again
4063 // during instantiation.
4064 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4065 return false;
4066
4067 // Fall through for conflicting redeclarations and redefinitions.
4068 }
4069
4070 // C: Function types need to be compatible, not identical. This handles
4071 // duplicate function decls like "void f(int); void f(enum X);" properly.
4072 if (!getLangOpts().CPlusPlus) {
4073 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4074 // type is specified by a function definition that contains a (possibly
4075 // empty) identifier list, both shall agree in the number of parameters
4076 // and the type of each parameter shall be compatible with the type that
4077 // results from the application of default argument promotions to the
4078 // type of the corresponding identifier. ...
4079 // This cannot be handled by ASTContext::typesAreCompatible() because that
4080 // doesn't know whether the function type is for a definition or not when
4081 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4082 // we need to cover here is that the number of arguments agree as the
4083 // default argument promotion rules were already checked by
4084 // ASTContext::typesAreCompatible().
4085 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4086 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4087 if (Old->hasInheritedPrototype())
4088 Old = Old->getCanonicalDecl();
4089 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4090 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4091 return true;
4092 }
4093
4094 // If we are merging two functions where only one of them has a prototype,
4095 // we may have enough information to decide to issue a diagnostic that the
4096 // function without a prototype will change behavior in C23. This handles
4097 // cases like:
4098 // void i(); void i(int j);
4099 // void i(int j); void i();
4100 // void i(); void i(int j) {}
4101 // See ActOnFinishFunctionBody() for other cases of the behavior change
4102 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4103 // type without a prototype.
4104 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4105 !New->isImplicit() && !Old->isImplicit()) {
4106 const FunctionDecl *WithProto, *WithoutProto;
4107 if (New->hasWrittenPrototype()) {
4108 WithProto = New;
4109 WithoutProto = Old;
4110 } else {
4111 WithProto = Old;
4112 WithoutProto = New;
4113 }
4114
4115 if (WithProto->getNumParams() != 0) {
4116 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4117 // The one without the prototype will be changing behavior in C23, so
4118 // warn about that one so long as it's a user-visible declaration.
4119 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4120 if (WithoutProto == New)
4121 IsWithoutProtoADef = NewDeclIsDefn;
4122 else
4123 IsWithProtoADef = NewDeclIsDefn;
4124 Diag(WithoutProto->getLocation(),
4125 diag::warn_non_prototype_changes_behavior)
4126 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4127 << (WithoutProto == Old) << IsWithProtoADef;
4128
4129 // The reason the one without the prototype will be changing behavior
4130 // is because of the one with the prototype, so note that so long as
4131 // it's a user-visible declaration. There is one exception to this:
4132 // when the new declaration is a definition without a prototype, the
4133 // old declaration with a prototype is not the cause of the issue,
4134 // and that does not need to be noted because the one with a
4135 // prototype will not change behavior in C23.
4136 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4137 !IsWithoutProtoADef)
4138 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4139 }
4140 }
4141 }
4142
4143 if (Context.typesAreCompatible(OldQType, NewQType)) {
4144 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4145 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4146 const FunctionProtoType *OldProto = nullptr;
4147 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4148 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4149 // The old declaration provided a function prototype, but the
4150 // new declaration does not. Merge in the prototype.
4151 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4152 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4153 OldProto->getParamTypes(),
4154 OldProto->getExtProtoInfo());
4155 New->setType(NewQType);
4157
4158 // Synthesize parameters with the same types.
4160 for (const auto &ParamType : OldProto->param_types()) {
4162 Context, New, SourceLocation(), SourceLocation(), nullptr,
4163 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4164 Param->setScopeInfo(0, Params.size());
4165 Param->setImplicit();
4166 Params.push_back(Param);
4167 }
4168
4169 New->setParams(Params);
4170 }
4171
4172 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4173 }
4174 }
4175
4176 // Check if the function types are compatible when pointer size address
4177 // spaces are ignored.
4178 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4179 return false;
4180
4181 // GNU C permits a K&R definition to follow a prototype declaration
4182 // if the declared types of the parameters in the K&R definition
4183 // match the types in the prototype declaration, even when the
4184 // promoted types of the parameters from the K&R definition differ
4185 // from the types in the prototype. GCC then keeps the types from
4186 // the prototype.
4187 //
4188 // If a variadic prototype is followed by a non-variadic K&R definition,
4189 // the K&R definition becomes variadic. This is sort of an edge case, but
4190 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4191 // C99 6.9.1p8.
4192 if (!getLangOpts().CPlusPlus &&
4193 Old->hasPrototype() && !New->hasPrototype() &&
4194 New->getType()->getAs<FunctionProtoType>() &&
4195 Old->getNumParams() == New->getNumParams()) {
4198 const FunctionProtoType *OldProto
4199 = Old->getType()->getAs<FunctionProtoType>();
4200 const FunctionProtoType *NewProto
4201 = New->getType()->getAs<FunctionProtoType>();
4202
4203 // Determine whether this is the GNU C extension.
4204 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4205 NewProto->getReturnType());
4206 bool LooseCompatible = !MergedReturn.isNull();
4207 for (unsigned Idx = 0, End = Old->getNumParams();
4208 LooseCompatible && Idx != End; ++Idx) {
4209 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4210 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4211 if (Context.typesAreCompatible(OldParm->getType(),
4212 NewProto->getParamType(Idx))) {
4213 ArgTypes.push_back(NewParm->getType());
4214 } else if (Context.typesAreCompatible(OldParm->getType(),
4215 NewParm->getType(),
4216 /*CompareUnqualified=*/true)) {
4217 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4218 NewProto->getParamType(Idx) };
4219 Warnings.push_back(Warn);
4220 ArgTypes.push_back(NewParm->getType());
4221 } else
4222 LooseCompatible = false;
4223 }
4224
4225 if (LooseCompatible) {
4226 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4227 Diag(Warnings[Warn].NewParm->getLocation(),
4228 diag::ext_param_promoted_not_compatible_with_prototype)
4229 << Warnings[Warn].PromotedType
4230 << Warnings[Warn].OldParm->getType();
4231 if (Warnings[Warn].OldParm->getLocation().isValid())
4232 Diag(Warnings[Warn].OldParm->getLocation(),
4233 diag::note_previous_declaration);
4234 }
4235
4236 if (MergeTypeWithOld)
4237 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4238 OldProto->getExtProtoInfo()));
4239 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4240 }
4241
4242 // Fall through to diagnose conflicting types.
4243 }
4244
4245 // A function that has already been declared has been redeclared or
4246 // defined with a different type; show an appropriate diagnostic.
4247
4248 // If the previous declaration was an implicitly-generated builtin
4249 // declaration, then at the very least we should use a specialized note.
4250 unsigned BuiltinID;
4251 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4252 // If it's actually a library-defined builtin function like 'malloc'
4253 // or 'printf', just warn about the incompatible redeclaration.
4255 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4256 Diag(OldLocation, diag::note_previous_builtin_declaration)
4257 << Old << Old->getType();
4258 return false;
4259 }
4260
4261 PrevDiag = diag::note_previous_builtin_declaration;
4262 }
4263
4264 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4265 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4266 return true;
4267}
4268
4270 Scope *S, bool MergeTypeWithOld) {
4271 // Merge the attributes
4272 mergeDeclAttributes(New, Old);
4273
4274 // Merge "pure" flag.
4275 if (Old->isPureVirtual())
4276 New->setIsPureVirtual();
4277
4278 // Merge "used" flag.
4279 if (Old->getMostRecentDecl()->isUsed(false))
4280 New->setIsUsed();
4281
4282 // Merge attributes from the parameters. These can mismatch with K&R
4283 // declarations.
4284 if (New->getNumParams() == Old->getNumParams())
4285 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4286 ParmVarDecl *NewParam = New->getParamDecl(i);
4287 ParmVarDecl *OldParam = Old->getParamDecl(i);
4288 mergeParamDeclAttributes(NewParam, OldParam, *this);
4289 mergeParamDeclTypes(NewParam, OldParam, *this);
4290 }
4291
4292 if (getLangOpts().CPlusPlus)
4293 return MergeCXXFunctionDecl(New, Old, S);
4294
4295 // Merge the function types so the we get the composite types for the return
4296 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4297 // was visible.
4298 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4299 if (!Merged.isNull() && MergeTypeWithOld)
4300 New->setType(Merged);
4301
4302 return false;
4303}
4304
4306 ObjCMethodDecl *oldMethod) {
4307 // Merge the attributes, including deprecated/unavailable
4308 AvailabilityMergeKind MergeKind =
4309 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4312 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4313 : AMK_Override;
4314
4315 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4316
4317 // Merge attributes from the parameters.
4319 oe = oldMethod->param_end();
4321 ni = newMethod->param_begin(), ne = newMethod->param_end();
4322 ni != ne && oi != oe; ++ni, ++oi)
4323 mergeParamDeclAttributes(*ni, *oi, *this);
4324
4325 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4326}
4327
4329 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4330
4332 ? diag::err_redefinition_different_type
4333 : diag::err_redeclaration_different_type)
4334 << New->getDeclName() << New->getType() << Old->getType();
4335
4336 diag::kind PrevDiag;
4337 SourceLocation OldLocation;
4338 std::tie(PrevDiag, OldLocation)
4340 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4341 New->setInvalidDecl();
4342}
4343
4345 bool MergeTypeWithOld) {
4346 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4347 return;
4348
4349 QualType MergedT;
4350 if (getLangOpts().CPlusPlus) {
4351 if (New->getType()->isUndeducedType()) {
4352 // We don't know what the new type is until the initializer is attached.
4353 return;
4354 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4355 // These could still be something that needs exception specs checked.
4356 return MergeVarDeclExceptionSpecs(New, Old);
4357 }
4358 // C++ [basic.link]p10:
4359 // [...] the types specified by all declarations referring to a given
4360 // object or function shall be identical, except that declarations for an
4361 // array object can specify array types that differ by the presence or
4362 // absence of a major array bound (8.3.4).
4363 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4364 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4365 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4366
4367 // We are merging a variable declaration New into Old. If it has an array
4368 // bound, and that bound differs from Old's bound, we should diagnose the
4369 // mismatch.
4370 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4371 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4372 PrevVD = PrevVD->getPreviousDecl()) {
4373 QualType PrevVDTy = PrevVD->getType();
4374 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4375 continue;
4376
4377 if (!Context.hasSameType(New->getType(), PrevVDTy))
4378 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4379 }
4380 }
4381
4382 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4383 if (Context.hasSameType(OldArray->getElementType(),
4384 NewArray->getElementType()))
4385 MergedT = New->getType();
4386 }
4387 // FIXME: Check visibility. New is hidden but has a complete type. If New
4388 // has no array bound, it should not inherit one from Old, if Old is not
4389 // visible.
4390 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4391 if (Context.hasSameType(OldArray->getElementType(),
4392 NewArray->getElementType()))
4393 MergedT = Old->getType();
4394 }
4395 }
4396 else if (New->getType()->isObjCObjectPointerType() &&
4397 Old->getType()->isObjCObjectPointerType()) {
4398 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4399 Old->getType());
4400 }
4401 } else {
4402 // C 6.2.7p2:
4403 // All declarations that refer to the same object or function shall have
4404 // compatible type.
4405 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4406 }
4407 if (MergedT.isNull()) {
4408 // It's OK if we couldn't merge types if either type is dependent, for a
4409 // block-scope variable. In other cases (static data members of class
4410 // templates, variable templates, ...), we require the types to be
4411 // equivalent.
4412 // FIXME: The C++ standard doesn't say anything about this.
4413 if ((New->getType()->isDependentType() ||
4414 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4415 // If the old type was dependent, we can't merge with it, so the new type
4416 // becomes dependent for now. We'll reproduce the original type when we
4417 // instantiate the TypeSourceInfo for the variable.
4418 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4420 return;
4421 }
4422 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4423 }
4424
4425 // Don't actually update the type on the new declaration if the old
4426 // declaration was an extern declaration in a different scope.
4427 if (MergeTypeWithOld)
4428 New->setType(MergedT);
4429}
4430
4431static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4433 // C11 6.2.7p4:
4434 // For an identifier with internal or external linkage declared
4435 // in a scope in which a prior declaration of that identifier is
4436 // visible, if the prior declaration specifies internal or
4437 // external linkage, the type of the identifier at the later
4438 // declaration becomes the composite type.
4439 //
4440 // If the variable isn't visible, we do not merge with its type.
4441 if (Previous.isShadowed())
4442 return false;
4443
4444 if (S.getLangOpts().CPlusPlus) {
4445 // C++11 [dcl.array]p3:
4446 // If there is a preceding declaration of the entity in the same
4447 // scope in which the bound was specified, an omitted array bound
4448 // is taken to be the same as in that earlier declaration.
4449 return NewVD->isPreviousDeclInSameBlockScope() ||
4452 } else {
4453 // If the old declaration was function-local, don't merge with its
4454 // type unless we're in the same function.
4455 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4456 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4457 }
4458}
4459
4461 // If the new decl is already invalid, don't do any other checking.
4462 if (New->isInvalidDecl())
4463 return;
4464
4465 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4466 return;
4467
4468 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4469
4470 // Verify the old decl was also a variable or variable template.
4471 VarDecl *Old = nullptr;
4472 VarTemplateDecl *OldTemplate = nullptr;
4473 if (Previous.isSingleResult()) {
4474 if (NewTemplate) {
4475 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4476 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4477
4478 if (auto *Shadow =
4479 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4480 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4481 return New->setInvalidDecl();
4482 } else {
4483 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4484
4485 if (auto *Shadow =
4486 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4487 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4488 return New->setInvalidDecl();
4489 }
4490 }
4491 if (!Old) {
4492 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4493 << New->getDeclName();
4494 notePreviousDefinition(Previous.getRepresentativeDecl(),
4495 New->getLocation());
4496 return New->setInvalidDecl();
4497 }
4498
4499 // If the old declaration was found in an inline namespace and the new
4500 // declaration was qualified, update the DeclContext to match.
4502
4503 // Ensure the template parameters are compatible.
4504 if (NewTemplate &&
4506 OldTemplate->getTemplateParameters(),
4507 /*Complain=*/true, TPL_TemplateMatch))
4508 return New->setInvalidDecl();
4509
4510 // C++ [class.mem]p1:
4511 // A member shall not be declared twice in the member-specification [...]
4512 //
4513 // Here, we need only consider static data members.
4514 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4515 Diag(New->getLocation(), diag::err_duplicate_member)
4516 << New->getIdentifier();
4517 Diag(Old->getLocation(), diag::note_previous_declaration);
4518 New->setInvalidDecl();
4519 }
4520
4521 mergeDeclAttributes(New, Old);
4522 // Warn if an already-defined variable is made a weak_import in a subsequent
4523 // declaration
4524 if (New->hasAttr<WeakImportAttr>())
4525 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4526 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4527 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4528 Diag(D->getLocation(), diag::note_previous_definition);
4529 // Remove weak_import attribute on new declaration.
4530 New->dropAttr<WeakImportAttr>();
4531 break;
4532 }
4533 }
4534
4535 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4536 if (!Old->hasAttr<InternalLinkageAttr>()) {
4537 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4538 << ILA;
4539 Diag(Old->getLocation(), diag::note_previous_declaration);
4540 New->dropAttr<InternalLinkageAttr>();
4541 }
4542
4543 // Merge the types.
4544 VarDecl *MostRecent = Old->getMostRecentDecl();
4545 if (MostRecent != Old) {
4546 MergeVarDeclTypes(New, MostRecent,
4547 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4548 if (New->isInvalidDecl())
4549 return;
4550 }
4551
4552 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4553 if (New->isInvalidDecl())
4554 return;
4555
4556 diag::kind PrevDiag;
4557 SourceLocation OldLocation;
4558 std::tie(PrevDiag, OldLocation) =
4560
4561 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4562 if (New->getStorageClass() == SC_Static &&
4563 !New->isStaticDataMember() &&
4564 Old->hasExternalFormalLinkage()) {
4565 if (getLangOpts().MicrosoftExt) {
4566 Diag(New->getLocation(), diag::ext_static_non_static)
4567 << New->getDeclName();
4568 Diag(OldLocation, PrevDiag);
4569 } else {
4570 Diag(New->getLocation(), diag::err_static_non_static)
4571 << New->getDeclName();
4572 Diag(OldLocation, PrevDiag);
4573 return New->setInvalidDecl();
4574 }
4575 }
4576 // C99 6.2.2p4:
4577 // For an identifier declared with the storage-class specifier
4578 // extern in a scope in which a prior declaration of that
4579 // identifier is visible,23) if the prior declaration specifies
4580 // internal or external linkage, the linkage of the identifier at
4581 // the later declaration is the same as the linkage specified at
4582 // the prior declaration. If no prior declaration is visible, or
4583 // if the prior declaration specifies no linkage, then the
4584 // identifier has external linkage.
4585 if (New->hasExternalStorage() && Old->hasLinkage())
4586 /* Okay */;
4587 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4588 !New->isStaticDataMember() &&
4590 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4591 Diag(OldLocation, PrevDiag);
4592 return New->setInvalidDecl();
4593 }
4594
4595 // Check if extern is followed by non-extern and vice-versa.
4596 if (New->hasExternalStorage() &&
4597 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4598 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4599 Diag(OldLocation, PrevDiag);
4600 return New->setInvalidDecl();
4601 }
4602 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4603 !New->hasExternalStorage()) {
4604 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4605 Diag(OldLocation, PrevDiag);
4606 return New->setInvalidDecl();
4607 }
4608
4609 if (CheckRedeclarationInModule(New, Old))
4610 return;
4611
4612 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4613
4614 // FIXME: The test for external storage here seems wrong? We still
4615 // need to check for mismatches.
4616 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4617 // Don't complain about out-of-line definitions of static members.
4618 !(Old->getLexicalDeclContext()->isRecord() &&
4619 !New->getLexicalDeclContext()->isRecord())) {
4620 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4621 Diag(OldLocation, PrevDiag);
4622 return New->setInvalidDecl();
4623 }
4624
4625 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4626 if (VarDecl *Def = Old->getDefinition()) {
4627 // C++1z [dcl.fcn.spec]p4:
4628 // If the definition of a variable appears in a translation unit before
4629 // its first declaration as inline, the program is ill-formed.
4630 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4631 Diag(Def->getLocation(), diag::note_previous_definition);
4632 }
4633 }
4634
4635 // If this redeclaration makes the variable inline, we may need to add it to
4636 // UndefinedButUsed.
4637 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4639 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4640 SourceLocation()));
4641
4642 if (New->getTLSKind() != Old->getTLSKind()) {
4643 if (!Old->getTLSKind()) {
4644 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4645 Diag(OldLocation, PrevDiag);
4646 } else if (!New->getTLSKind()) {
4647 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4648 Diag(OldLocation, PrevDiag);
4649 } else {
4650 // Do not allow redeclaration to change the variable between requiring
4651 // static and dynamic initialization.
4652 // FIXME: GCC allows this, but uses the TLS keyword on the first
4653 // declaration to determine the kind. Do we need to be compatible here?
4654 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4655 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4656 Diag(OldLocation, PrevDiag);
4657 }
4658 }
4659
4660 // C++ doesn't have tentative definitions, so go right ahead and check here.
4661 if (getLangOpts().CPlusPlus) {
4662 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4663 Old->getCanonicalDecl()->isConstexpr()) {
4664 // This definition won't be a definition any more once it's been merged.
4665 Diag(New->getLocation(),
4666 diag::warn_deprecated_redundant_constexpr_static_def);
4668 VarDecl *Def = Old->getDefinition();
4669 if (Def && checkVarDeclRedefinition(Def, New))
4670 return;
4671 }
4672 }
4673
4674 if (haveIncompatibleLanguageLinkages(Old, New)) {
4675 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4676 Diag(OldLocation, PrevDiag);
4677 New->setInvalidDecl();
4678 return;
4679 }
4680
4681 // Merge "used" flag.
4682 if (Old->getMostRecentDecl()->isUsed(false))
4683 New->setIsUsed();
4684
4685 // Keep a chain of previous declarations.
4686 New->setPreviousDecl(Old);
4687 if (NewTemplate)
4688 NewTemplate->setPreviousDecl(OldTemplate);
4689
4690 // Inherit access appropriately.
4691 New->setAccess(Old->getAccess());
4692 if (NewTemplate)
4693 NewTemplate->setAccess(New->getAccess());
4694
4695 if (Old->isInline())
4696 New->setImplicitlyInline();
4697}
4698
4700 SourceManager &SrcMgr = getSourceManager();
4701 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4702 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4703 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4704 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4705 auto &HSI = PP.getHeaderSearchInfo();
4706 StringRef HdrFilename =
4707 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4708
4709 auto noteFromModuleOrInclude = [&](Module *Mod,
4710 SourceLocation IncLoc) -> bool {
4711 // Redefinition errors with modules are common with non modular mapped
4712 // headers, example: a non-modular header H in module A that also gets
4713 // included directly in a TU. Pointing twice to the same header/definition
4714 // is confusing, try to get better diagnostics when modules is on.
4715 if (IncLoc.isValid()) {
4716 if (Mod) {
4717 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4718 << HdrFilename.str() << Mod->getFullModuleName();
4719 if (!Mod->DefinitionLoc.isInvalid())
4720 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4721 << Mod->getFullModuleName();
4722 } else {
4723 Diag(IncLoc, diag::note_redefinition_include_same_file)
4724 << HdrFilename.str();
4725 }
4726 return true;
4727 }
4728
4729 return false;
4730 };
4731
4732 // Is it the same file and same offset? Provide more information on why
4733 // this leads to a redefinition error.
4734 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4735 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4736 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4737 bool EmittedDiag =
4738 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4739 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4740
4741 // If the header has no guards, emit a note suggesting one.
4742 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4743 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4744
4745 if (EmittedDiag)
4746 return;
4747 }
4748
4749 // Redefinition coming from different files or couldn't do better above.
4750 if (Old->getLocation().isValid())
4751 Diag(Old->getLocation(), diag::note_previous_definition);
4752}
4753
4755 if (!hasVisibleDefinition(Old) &&
4756 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4757 isa<VarTemplateSpecializationDecl>(New) ||
4760 // The previous definition is hidden, and multiple definitions are
4761 // permitted (in separate TUs). Demote this to a declaration.
4763
4764 // Make the canonical definition visible.
4765 if (auto *OldTD = Old->getDescribedVarTemplate())
4768 return false;
4769 } else {
4770 Diag(New->getLocation(), diag::err_redefinition) << New;
4772 New->setInvalidDecl();
4773 return true;
4774 }
4775}
4776
4778 DeclSpec &DS,
4779 const ParsedAttributesView &DeclAttrs,
4780 RecordDecl *&AnonRecord) {
4782 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4783}
4784
4785// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4786// disambiguate entities defined in different scopes.
4787// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4788// compatibility.
4789// We will pick our mangling number depending on which version of MSVC is being
4790// targeted.
4791static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4793 ? S->getMSCurManglingNumber()
4794 : S->getMSLastManglingNumber();
4795}
4796
4797void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4798 if (!Context.getLangOpts().CPlusPlus)
4799 return;
4800
4801 if (isa<CXXRecordDecl>(Tag->getParent())) {
4802 // If this tag is the direct child of a class, number it if
4803 // it is anonymous.
4804 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4805 return;
4807 Context.getManglingNumberContext(Tag->getParent());
4809 Tag, MCtx.getManglingNumber(
4810 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4811 return;
4812 }
4813
4814 // If this tag isn't a direct child of a class, number it if it is local.
4816 Decl *ManglingContextDecl;
4817 std::tie(MCtx, ManglingContextDecl) =
4818 getCurrentMangleNumberContext(Tag->getDeclContext());
4819 if (MCtx) {
4821 Tag, MCtx->getManglingNumber(
4822 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4823 }
4824}
4825
4826namespace {
4827struct NonCLikeKind {
4828 enum {
4829 None,
4830 BaseClass,
4831 DefaultMemberInit,
4832 Lambda,
4833 Friend,
4834 OtherMember,
4835 Invalid,
4836 } Kind = None;
4838
4839 explicit operator bool() { return Kind != None; }
4840};
4841}
4842
4843/// Determine whether a class is C-like, according to the rules of C++
4844/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4845static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4846 if (RD->isInvalidDecl())
4847 return {NonCLikeKind::Invalid, {}};
4848
4849 // C++ [dcl.typedef]p9: [P1766R1]
4850 // An unnamed class with a typedef name for linkage purposes shall not
4851 //
4852 // -- have any base classes
4853 if (RD->getNumBases())
4854 return {NonCLikeKind::BaseClass,
4856 RD->bases_end()[-1].getEndLoc())};
4857 bool Invalid = false;
4858 for (Decl *D : RD->decls()) {
4859 // Don't complain about things we already diagnosed.
4860 if (D->isInvalidDecl()) {
4861 Invalid = true;
4862 continue;
4863 }
4864
4865 // -- have any [...] default member initializers
4866 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4867 if (FD->hasInClassInitializer()) {
4868 auto *Init = FD->getInClassInitializer();
4869 return {NonCLikeKind::DefaultMemberInit,
4870 Init ? Init->getSourceRange() : D->getSourceRange()};
4871 }
4872 continue;
4873 }
4874
4875 // FIXME: We don't allow friend declarations. This violates the wording of
4876 // P1766, but not the intent.
4877 if (isa<FriendDecl>(D))
4878 return {NonCLikeKind::Friend, D->getSourceRange()};
4879
4880 // -- declare any members other than non-static data members, member
4881 // enumerations, or member classes,
4882 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4883 isa<EnumDecl>(D))
4884 continue;
4885 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4886 if (!MemberRD) {
4887 if (D->isImplicit())
4888 continue;
4889 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4890 }
4891
4892 // -- contain a lambda-expression,
4893 if (MemberRD->isLambda())
4894 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4895
4896 // and all member classes shall also satisfy these requirements
4897 // (recursively).
4898 if (MemberRD->isThisDeclarationADefinition()) {
4899 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4900 return Kind;
4901 }
4902 }
4903
4904 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4905}
4906
4908 TypedefNameDecl *NewTD) {
4909 if (TagFromDeclSpec->isInvalidDecl())
4910 return;
4911
4912 // Do nothing if the tag already has a name for linkage purposes.
4913 if (TagFromDeclSpec->hasNameForLinkage())
4914 return;
4915
4916 // A well-formed anonymous tag must always be a TagUseKind::Definition.
4917 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4918
4919 // The type must match the tag exactly; no qualifiers allowed.
4921 Context.getTagDeclType(TagFromDeclSpec))) {
4922 if (getLangOpts().CPlusPlus)
4923 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4924 return;
4925 }
4926
4927 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4928 // An unnamed class with a typedef name for linkage purposes shall [be
4929 // C-like].
4930 //
4931 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4932 // shouldn't happen, but there are constructs that the language rule doesn't
4933 // disallow for which we can't reasonably avoid computing linkage early.
4934 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4935 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4936 : NonCLikeKind();
4937 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4938 if (NonCLike || ChangesLinkage) {
4939 if (NonCLike.Kind == NonCLikeKind::Invalid)
4940 return;
4941
4942 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4943 if (ChangesLinkage) {
4944 // If the linkage changes, we can't accept this as an extension.
4945 if (NonCLike.Kind == NonCLikeKind::None)
4946 DiagID = diag::err_typedef_changes_linkage;
4947 else
4948 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4949 }
4950
4951 SourceLocation FixitLoc =
4952 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4953 llvm::SmallString<40> TextToInsert;
4954 TextToInsert += ' ';
4955 TextToInsert += NewTD->getIdentifier()->getName();
4956
4957 Diag(FixitLoc, DiagID)
4958 << isa<TypeAliasDecl>(NewTD)
4959 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4960 if (NonCLike.Kind != NonCLikeKind::None) {
4961 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4962 << NonCLike.Kind - 1 << NonCLike.Range;
4963 }
4964 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4965 << NewTD << isa<TypeAliasDecl>(NewTD);
4966
4967 if (ChangesLinkage)
4968 return;
4969 }
4970
4971 // Otherwise, set this as the anon-decl typedef for the tag.
4972 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4973}
4974
4975static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
4977 switch (T) {
4979 return 0;
4981 return 1;
4983 return 2;
4985 return 3;
4986 case DeclSpec::TST_enum:
4987 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
4988 if (ED->isScopedUsingClassTag())
4989 return 5;
4990 if (ED->isScoped())
4991 return 6;
4992 }
4993 return 4;
4994 default:
4995 llvm_unreachable("unexpected type specifier");
4996 }
4997}
4998
5000 DeclSpec &DS,
5001 const ParsedAttributesView &DeclAttrs,
5002 MultiTemplateParamsArg TemplateParams,
5003 bool IsExplicitInstantiation,
5004 RecordDecl *&AnonRecord,
5005 SourceLocation EllipsisLoc) {
5006 Decl *TagD = nullptr;
5007 TagDecl *Tag = nullptr;
5013 TagD = DS.getRepAsDecl();
5014
5015 if (!TagD) // We probably had an error
5016 return nullptr;
5017
5018 // Note that the above type specs guarantee that the
5019 // type rep is a Decl, whereas in many of the others
5020 // it's a Type.
5021 if (isa<TagDecl>(TagD))
5022 Tag = cast<TagDecl>(TagD);
5023 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5024 Tag = CTD->getTemplatedDecl();
5025 }
5026
5027 if (Tag) {
5028 handleTagNumbering(Tag, S);
5029 Tag->setFreeStanding();
5030 if (Tag->isInvalidDecl())
5031 return Tag;
5032 }
5033
5034 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5035 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5036 // or incomplete types shall not be restrict-qualified."
5037 if (TypeQuals & DeclSpec::TQ_restrict)
5039 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5040 << DS.getSourceRange();
5041 }
5042
5043 if (DS.isInlineSpecified())
5044 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5045 << getLangOpts().CPlusPlus17;
5046
5047 if (DS.hasConstexprSpecifier()) {
5048 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5049 // and definitions of functions and variables.
5050 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5051 // the declaration of a function or function template
5052 if (Tag)
5053 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5055 << static_cast<int>(DS.getConstexprSpecifier());
5056 else if (getLangOpts().C23)
5057 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5058 else
5059 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5060 << static_cast<int>(DS.getConstexprSpecifier());
5061 // Don't emit warnings after this error.
5062 return TagD;
5063 }
5064
5066
5067 if (DS.isFriendSpecified()) {
5068 // If we're dealing with a decl but not a TagDecl, assume that
5069 // whatever routines created it handled the friendship aspect.
5070 if (TagD && !Tag)
5071 return nullptr;
5072 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5073 }
5074
5075 assert(EllipsisLoc.isInvalid() &&
5076 "Friend ellipsis but not friend-specified?");
5077
5078 // Track whether this decl-specifier declares anything.
5079 bool DeclaresAnything = true;
5080
5081 // Handle anonymous struct definitions.
5082 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5083 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5085 if (getLangOpts().CPlusPlus ||
5086 Record->getDeclContext()->isRecord()) {
5087 // If CurContext is a DeclContext that can contain statements,
5088 // RecursiveASTVisitor won't visit the decls that
5089 // BuildAnonymousStructOrUnion() will put into CurContext.
5090 // Also store them here so that they can be part of the
5091 // DeclStmt that gets created in this case.
5092 // FIXME: Also return the IndirectFieldDecls created by
5093 // BuildAnonymousStructOr union, for the same reason?
5095 AnonRecord = Record;
5096 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5098 }
5099
5100 DeclaresAnything = false;
5101 }
5102 }
5103
5104 // C11 6.7.2.1p2:
5105 // A struct-declaration that does not declare an anonymous structure or
5106 // anonymous union shall contain a struct-declarator-list.
5107 //
5108 // This rule also existed in C89 and C99; the grammar for struct-declaration
5109 // did not permit a struct-declaration without a struct-declarator-list.
5112 // Check for Microsoft C extension: anonymous struct/union member.
5113 // Handle 2 kinds of anonymous struct/union:
5114 // struct STRUCT;
5115 // union UNION;
5116 // and
5117 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5118 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5119 if ((Tag && Tag->getDeclName()) ||
5121 RecordDecl *Record = nullptr;
5122 if (Tag)
5123 Record = dyn_cast<RecordDecl>(Tag);
5124 else if (const RecordType *RT =
5126 Record = RT->getDecl();
5127 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5128 Record = UT->getDecl();
5129
5130 if (Record && getLangOpts().MicrosoftExt) {
5131 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5132 << Record->isUnion() << DS.getSourceRange();
5134 }
5135
5136 DeclaresAnything = false;
5137 }
5138 }
5139
5140 // Skip all the checks below if we have a type error.
5142 (TagD && TagD->isInvalidDecl()))
5143 return TagD;
5144
5145 if (getLangOpts().CPlusPlus &&
5147 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5148 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5149 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5150 DeclaresAnything = false;
5151
5152 if (!DS.isMissingDeclaratorOk()) {
5153 // Customize diagnostic for a typedef missing a name.
5155 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5156 << DS.getSourceRange();
5157 else
5158 DeclaresAnything = false;
5159 }
5160
5161 if (DS.isModulePrivateSpecified() &&
5162 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5163 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5164 << llvm::to_underlying(Tag->getTagKind())
5166
5168
5169 // C 6.7/2:
5170 // A declaration [...] shall declare at least a declarator [...], a tag,
5171 // or the members of an enumeration.
5172 // C++ [dcl.dcl]p3:
5173 // [If there are no declarators], and except for the declaration of an
5174 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5175 // names into the program, or shall redeclare a name introduced by a
5176 // previous declaration.
5177 if (!DeclaresAnything) {
5178 // In C, we allow this as a (popular) extension / bug. Don't bother
5179 // producing further diagnostics for redundant qualifiers after this.
5180 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5181 ? diag::err_no_declarators
5182 : diag::ext_no_declarators)
5183 << DS.getSourceRange();
5184 return TagD;
5185 }
5186
5187 // C++ [dcl.stc]p1:
5188 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5189 // init-declarator-list of the declaration shall not be empty.
5190 // C++ [dcl.fct.spec]p1:
5191 // If a cv-qualifier appears in a decl-specifier-seq, the
5192 // init-declarator-list of the declaration shall not be empty.
5193 //
5194 // Spurious qualifiers here appear to be valid in C.
5195 unsigned DiagID = diag::warn_standalone_specifier;
5196 if (getLangOpts().CPlusPlus)
5197 DiagID = diag::ext_standalone_specifier;
5198
5199 // Note that a linkage-specification sets a storage class, but
5200 // 'extern "C" struct foo;' is actually valid and not theoretically
5201 // useless.
5202 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5203 if (SCS == DeclSpec::SCS_mutable)
5204 // Since mutable is not a viable storage class specifier in C, there is
5205 // no reason to treat it as an extension. Instead, diagnose as an error.
5206 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5207 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5208 Diag(DS.getStorageClassSpecLoc(), DiagID)
5210 }
5211
5215 if (DS.getTypeQualifiers()) {
5217 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5219 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5220 // Restrict is covered above.
5222 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5224 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5225 }
5226
5227 // Warn about ignored type attributes, for example:
5228 // __attribute__((aligned)) struct A;
5229 // Attributes should be placed after tag to apply to type declaration.
5230 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5231 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5232 if (TypeSpecType == DeclSpec::TST_class ||
5233 TypeSpecType == DeclSpec::TST_struct ||
5234 TypeSpecType == DeclSpec::TST_interface ||
5235 TypeSpecType == DeclSpec::TST_union ||
5236 TypeSpecType == DeclSpec::TST_enum) {
5237
5238 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5239 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5240 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5241 DiagnosticId = diag::warn_attribute_ignored;
5242 else if (AL.isRegularKeywordAttribute())
5243 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5244 else
5245 DiagnosticId = diag::warn_declspec_attribute_ignored;
5246 Diag(AL.getLoc(), DiagnosticId)
5247 << AL << GetDiagnosticTypeSpecifierID(DS);
5248 };
5249
5250 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5251 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5252 }
5253 }
5254
5255 return TagD;
5256}
5257
5258/// We are trying to inject an anonymous member into the given scope;
5259/// check if there's an existing declaration that can't be overloaded.
5260///
5261/// \return true if this is a forbidden redeclaration
5262static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5263 DeclContext *Owner,
5264 DeclarationName Name,
5265 SourceLocation NameLoc, bool IsUnion,
5266 StorageClass SC) {
5267 LookupResult R(SemaRef, Name, NameLoc,
5270 RedeclarationKind::ForVisibleRedeclaration);
5271 if (!SemaRef.LookupName(R, S)) return false;
5272
5273 // Pick a representative declaration.
5275 assert(PrevDecl && "Expected a non-null Decl");
5276
5277 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5278 return false;
5279
5280 if (SC == StorageClass::SC_None &&
5281 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5282 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5283 if (!Owner->isRecord())
5284 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5285 return false;
5286 }
5287
5288 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5289 << IsUnion << Name;
5290 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5291
5292 return true;
5293}
5294
5296 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5298}
5299
5301 if (!getLangOpts().CPlusPlus)
5302 return;
5303
5304 // This function can be parsed before we have validated the
5305 // structure as an anonymous struct
5306 if (Record->isAnonymousStructOrUnion())
5307 return;
5308
5309 const NamedDecl *First = 0;
5310 for (const Decl *D : Record->decls()) {
5311 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5312 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5313 continue;
5314 if (!First)
5315 First = ND;
5316 else
5318 }
5319}
5320
5321/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5322/// anonymous struct or union AnonRecord into the owning context Owner
5323/// and scope S. This routine will be invoked just after we realize
5324/// that an unnamed union or struct is actually an anonymous union or
5325/// struct, e.g.,
5326///
5327/// @code
5328/// union {
5329/// int i;
5330/// float f;
5331/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5332/// // f into the surrounding scope.x
5333/// @endcode
5334///
5335/// This routine is recursive, injecting the names of nested anonymous
5336/// structs/unions into the owning context and scope as well.
5337static bool
5339 RecordDecl *AnonRecord, AccessSpecifier AS,
5340 StorageClass SC,
5341 SmallVectorImpl<NamedDecl *> &Chaining) {
5342 bool Invalid = false;
5343
5344 // Look every FieldDecl and IndirectFieldDecl with a name.
5345 for (auto *D : AnonRecord->decls()) {
5346 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5347 cast<NamedDecl>(D)->getDeclName()) {
5348 ValueDecl *VD = cast<ValueDecl>(D);
5349 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5350 VD->getLocation(), AnonRecord->isUnion(),
5351 SC)) {
5352 // C++ [class.union]p2:
5353 // The names of the members of an anonymous union shall be
5354 // distinct from the names of any other entity in the
5355 // scope in which the anonymous union is declared.
5356 Invalid = true;
5357 } else {
5358 // C++ [class.union]p2:
5359 // For the purpose of name lookup, after the anonymous union
5360 // definition, the members of the anonymous union are
5361 // considered to have been defined in the scope in which the
5362 // anonymous union is declared.
5363 unsigned OldChainingSize = Chaining.size();
5364 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5365 Chaining.append(IF->chain_begin(), IF->chain_end());
5366 else
5367 Chaining.push_back(VD);
5368
5369 assert(Chaining.size() >= 2);
5370 NamedDecl **NamedChain =
5371 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5372 for (unsigned i = 0; i < Chaining.size(); i++)
5373 NamedChain[i] = Chaining[i];
5374
5376 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5377 VD->getType(), {NamedChain, Chaining.size()});
5378
5379 for (const auto *Attr : VD->attrs())
5380 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5381
5382 IndirectField->setAccess(AS);
5383 IndirectField->setImplicit();
5384 SemaRef.PushOnScopeChains(IndirectField, S);
5385
5386 // That includes picking up the appropriate access specifier.
5387 if (AS != AS_none) IndirectField->setAccess(AS);
5388
5389 Chaining.resize(OldChainingSize);
5390 }
5391 }
5392 }
5393
5394 return Invalid;
5395}
5396
5397/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5398/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5399/// illegal input values are mapped to SC_None.
5400static StorageClass
5402 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5403 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5404 "Parser allowed 'typedef' as storage class VarDecl.");
5405 switch (StorageClassSpec) {
5408 if (DS.isExternInLinkageSpec())
5409 return SC_None;
5410 return SC_Extern;
5411 case DeclSpec::SCS_static: return SC_Static;
5412 case DeclSpec::SCS_auto: return SC_Auto;
5415 // Illegal SCSs map to None: error reporting is up to the caller.
5416 case DeclSpec::SCS_mutable: // Fall through.
5417 case DeclSpec::SCS_typedef: return SC_None;
5418 }
5419 llvm_unreachable("unknown storage class specifier");
5420}
5421
5423 assert(Record->hasInClassInitializer());
5424
5425 for (const auto *I : Record->decls()) {
5426 const auto *FD = dyn_cast<FieldDecl>(I);
5427 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5428 FD = IFD->getAnonField();
5429 if (FD && FD->hasInClassInitializer())
5430 return FD->getLocation();
5431 }
5432
5433 llvm_unreachable("couldn't find in-class initializer");
5434}
5435
5437 SourceLocation DefaultInitLoc) {
5438 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5439 return;
5440
5441 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5442 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5443}
5444
5446 CXXRecordDecl *AnonUnion) {
5447 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5448 return;
5449
5451}
5452
5454 AccessSpecifier AS,
5456 const PrintingPolicy &Policy) {
5457 DeclContext *Owner = Record->getDeclContext();
5458
5459 // Diagnose whether this anonymous struct/union is an extension.
5460 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5461 Diag(Record->getLocation(), diag::ext_anonymous_union);
5462 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5463 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5464 else if (!Record->isUnion() && !getLangOpts().C11)
5465 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5466
5467 // C and C++ require different kinds of checks for anonymous
5468 // structs/unions.
5469 bool Invalid = false;
5470 if (getLangOpts().CPlusPlus) {
5471 const char *PrevSpec = nullptr;
5472 if (Record->isUnion()) {
5473 // C++ [class.union]p6:
5474 // C++17 [class.union.anon]p2:
5475 // Anonymous unions declared in a named namespace or in the
5476 // global namespace shall be declared static.
5477 unsigned DiagID;
5478 DeclContext *OwnerScope = Owner->getRedeclContext();
5480 (OwnerScope->isTranslationUnit() ||
5481 (OwnerScope->isNamespace() &&
5482 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5483 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5484 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5485
5486 // Recover by adding 'static'.
5488 PrevSpec, DiagID, Policy);
5489 }
5490 // C++ [class.union]p6:
5491 // A storage class is not allowed in a declaration of an
5492 // anonymous union in a class scope.
5494 isa<RecordDecl>(Owner)) {
5496 diag::err_anonymous_union_with_storage_spec)
5498
5499 // Recover by removing the storage specifier.
5502 PrevSpec, DiagID, Context.getPrintingPolicy());
5503 }
5504 }
5505
5506 // Ignore const/volatile/restrict qualifiers.
5507 if (DS.getTypeQualifiers()) {
5509 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5510 << Record->isUnion() << "const"
5514 diag::ext_anonymous_struct_union_qualified)
5515 << Record->isUnion() << "volatile"
5519 diag::ext_anonymous_struct_union_qualified)
5520 << Record->isUnion() << "restrict"
5524 diag::ext_anonymous_struct_union_qualified)
5525 << Record->isUnion() << "_Atomic"
5529 diag::ext_anonymous_struct_union_qualified)
5530 << Record->isUnion() << "__unaligned"
5532
5534 }
5535
5536 // C++ [class.union]p2:
5537 // The member-specification of an anonymous union shall only
5538 // define non-static data members. [Note: nested types and
5539 // functions cannot be declared within an anonymous union. ]
5540 for (auto *Mem : Record->decls()) {
5541 // Ignore invalid declarations; we already diagnosed them.
5542 if (Mem->isInvalidDecl())
5543 continue;
5544
5545 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5546 // C++ [class.union]p3:
5547 // An anonymous union shall not have private or protected
5548 // members (clause 11).
5549 assert(FD->getAccess() != AS_none);
5550 if (FD->getAccess() != AS_public) {
5551 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5552 << Record->isUnion() << (FD->getAccess() == AS_protected);
5553 Invalid = true;
5554 }
5555
5556 // C++ [class.union]p1
5557 // An object of a class with a non-trivial constructor, a non-trivial
5558 // copy constructor, a non-trivial destructor, or a non-trivial copy
5559 // assignment operator cannot be a member of a union, nor can an
5560 // array of such objects.
5561 if (CheckNontrivialField(FD))
5562 Invalid = true;
5563 } else if (Mem->isImplicit()) {
5564 // Any implicit members are fine.
5565 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5566 // This is a type that showed up in an
5567 // elaborated-type-specifier inside the anonymous struct or
5568 // union, but which actually declares a type outside of the
5569 // anonymous struct or union. It's okay.
5570 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5571 if (!MemRecord->isAnonymousStructOrUnion() &&
5572 MemRecord->getDeclName()) {
5573 // Visual C++ allows type definition in anonymous struct or union.
5574 if (getLangOpts().MicrosoftExt)
5575 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5576 << Record->isUnion();
5577 else {
5578 // This is a nested type declaration.
5579 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5580 << Record->isUnion();
5581 Invalid = true;
5582 }
5583 } else {
5584 // This is an anonymous type definition within another anonymous type.
5585 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5586 // not part of standard C++.
5587 Diag(MemRecord->getLocation(),
5588 diag::ext_anonymous_record_with_anonymous_type)
5589 << Record->isUnion();
5590 }
5591 } else if (isa<AccessSpecDecl>(Mem)) {
5592 // Any access specifier is fine.
5593 } else if (isa<StaticAssertDecl>(Mem)) {
5594 // In C++1z, static_assert declarations are also fine.
5595 } else {
5596 // We have something that isn't a non-static data
5597 // member. Complain about it.
5598 unsigned DK = diag::err_anonymous_record_bad_member;
5599 if (isa<TypeDecl>(Mem))
5600 DK = diag::err_anonymous_record_with_type;
5601 else if (isa<FunctionDecl>(Mem))
5602 DK = diag::err_anonymous_record_with_function;
5603 else if (isa<VarDecl>(Mem))
5604 DK = diag::err_anonymous_record_with_static;
5605
5606 // Visual C++ allows type definition in anonymous struct or union.
5607 if (getLangOpts().MicrosoftExt &&
5608 DK == diag::err_anonymous_record_with_type)
5609 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5610 << Record->isUnion();
5611 else {
5612 Diag(Mem->getLocation(), DK) << Record->isUnion();
5613 Invalid = true;
5614 }
5615 }
5616 }
5617
5618 // C++11 [class.union]p8 (DR1460):
5619 // At most one variant member of a union may have a
5620 // brace-or-equal-initializer.
5621 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5622 Owner->isRecord())
5623 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5624 cast<CXXRecordDecl>(Record));
5625 }
5626
5627 if (!Record->isUnion() && !Owner->isRecord()) {
5628 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5629 << getLangOpts().CPlusPlus;
5630 Invalid = true;
5631 }
5632
5633 // C++ [dcl.dcl]p3:
5634 // [If there are no declarators], and except for the declaration of an
5635 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5636 // names into the program
5637 // C++ [class.mem]p2:
5638 // each such member-declaration shall either declare at least one member
5639 // name of the class or declare at least one unnamed bit-field
5640 //
5641 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5642 if (getLangOpts().CPlusPlus && Record->field_empty())
5643 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5644
5645 // Mock up a declarator.
5649 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5650
5651 // Create a declaration for this anonymous struct/union.
5652 NamedDecl *Anon = nullptr;
5653 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5654 Anon = FieldDecl::Create(
5655 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5656 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5657 /*BitWidth=*/nullptr, /*Mutable=*/false,
5658 /*InitStyle=*/ICIS_NoInit);
5659 Anon->setAccess(AS);
5660 ProcessDeclAttributes(S, Anon, Dc);
5661
5662 if (getLangOpts().CPlusPlus)
5663 FieldCollector->Add(cast<FieldDecl>(Anon));
5664 } else {
5665 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5666 if (SCSpec == DeclSpec::SCS_mutable) {
5667 // mutable can only appear on non-static class members, so it's always
5668 // an error here
5669 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5670 Invalid = true;
5671 SC = SC_None;
5672 }
5673
5674 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5675 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5676 Context.getTypeDeclType(Record), TInfo, SC);
5677 if (Invalid)
5678 Anon->setInvalidDecl();
5679
5680 ProcessDeclAttributes(S, Anon, Dc);
5681
5682 // Default-initialize the implicit variable. This initialization will be
5683 // trivial in almost all cases, except if a union member has an in-class
5684 // initializer:
5685 // union { int n = 0; };
5687 }
5688 Anon->setImplicit();
5689
5690 // Mark this as an anonymous struct/union type.
5691 Record->setAnonymousStructOrUnion(true);
5692
5693 // Add the anonymous struct/union object to the current
5694 // context. We'll be referencing this object when we refer to one of
5695 // its members.
5696 Owner->addDecl(Anon);
5697
5698 // Inject the members of the anonymous struct/union into the owning
5699 // context and into the identifier resolver chain for name lookup
5700 // purposes.
5702 Chain.push_back(Anon);
5703
5704 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5705 Chain))
5706 Invalid = true;
5707
5708 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5709 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5711 Decl *ManglingContextDecl;
5712 std::tie(MCtx, ManglingContextDecl) =
5713 getCurrentMangleNumberContext(NewVD->getDeclContext());
5714 if (MCtx) {
5716 NewVD, MCtx->getManglingNumber(
5717 NewVD, getMSManglingNumber(getLangOpts(), S)));
5719 }
5720 }
5721 }
5722
5723 if (Invalid)
5724 Anon->setInvalidDecl();
5725
5726 return Anon;
5727}
5728
5730 RecordDecl *Record) {
5731 assert(Record && "expected a record!");
5732
5733 // Mock up a declarator.
5736 assert(TInfo && "couldn't build declarator info for anonymous struct");
5737
5738 auto *ParentDecl = cast<RecordDecl>(CurContext);
5740
5741 // Create a declaration for this anonymous struct.
5742 NamedDecl *Anon =
5743 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5744 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5745 /*BitWidth=*/nullptr, /*Mutable=*/false,
5746 /*InitStyle=*/ICIS_NoInit);
5747 Anon->setImplicit();
5748
5749 // Add the anonymous struct object to the current context.
5750 CurContext->addDecl(Anon);
5751
5752 // Inject the members of the anonymous struct into the current
5753 // context and into the identifier resolver chain for name lookup
5754 // purposes.
5756 Chain.push_back(Anon);
5757
5758 RecordDecl *RecordDef = Record->getDefinition();
5759 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5760 diag::err_field_incomplete_or_sizeless) ||
5762 *this, S, CurContext, RecordDef, AS_none,
5764 Anon->setInvalidDecl();
5765 ParentDecl->setInvalidDecl();
5766 }
5767
5768 return Anon;
5769}
5770
5772 return GetNameFromUnqualifiedId(D.getName());
5773}
5774
5777 DeclarationNameInfo NameInfo;
5778 NameInfo.setLoc(Name.StartLocation);
5779
5780 switch (Name.getKind()) {
5781
5784 NameInfo.setName(Name.Identifier);
5785 return NameInfo;
5786
5788 // C++ [temp.deduct.guide]p3:
5789 // The simple-template-id shall name a class template specialization.
5790 // The template-name shall be the same identifier as the template-name
5791 // of the simple-template-id.
5792 // These together intend to imply that the template-name shall name a
5793 // class template.
5794 // FIXME: template<typename T> struct X {};
5795 // template<typename T> using Y = X<T>;
5796 // Y(int) -> Y<int>;
5797 // satisfies these rules but does not name a class template.
5798 TemplateName TN = Name.TemplateName.get().get();
5799 auto *Template = TN.getAsTemplateDecl();
5800 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5801 Diag(Name.StartLocation,
5802 diag::err_deduction_guide_name_not_class_template)
5804 if (Template)
5805 NoteTemplateLocation(*Template);
5806 return DeclarationNameInfo();
5807 }
5808
5809 NameInfo.setName(
5811 return NameInfo;
5812 }
5813
5816 Name.OperatorFunctionId.Operator));
5818 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5819 return NameInfo;
5820
5823 Name.Identifier));
5824 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5825 return NameInfo;
5826
5828 TypeSourceInfo *TInfo;
5829 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5830 if (Ty.isNull())
5831 return DeclarationNameInfo();
5834 NameInfo.setNamedTypeInfo(TInfo);
5835 return NameInfo;
5836 }
5837
5839 TypeSourceInfo *TInfo;
5840 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5841 if (Ty.isNull())
5842 return DeclarationNameInfo();
5845 NameInfo.setNamedTypeInfo(TInfo);
5846 return NameInfo;
5847 }
5848
5850 // In well-formed code, we can only have a constructor
5851 // template-id that refers to the current context, so go there
5852 // to find the actual type being constructed.
5853 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5854 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5855 return DeclarationNameInfo();
5856
5857 // Determine the type of the class being constructed.
5858 QualType CurClassType = Context.getTypeDeclType(CurClass);
5859
5860 // FIXME: Check two things: that the template-id names the same type as
5861 // CurClassType, and that the template-id does not occur when the name
5862 // was qualified.
5863
5865 Context.getCanonicalType(CurClassType)));
5866 // FIXME: should we retrieve TypeSourceInfo?
5867 NameInfo.setNamedTypeInfo(nullptr);
5868 return NameInfo;
5869 }
5870
5872 TypeSourceInfo *TInfo;
5873 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5874 if (Ty.isNull())
5875 return DeclarationNameInfo();
5878 NameInfo.setNamedTypeInfo(TInfo);
5879 return NameInfo;
5880 }
5881
5883 TemplateName TName = Name.TemplateId->Template.get();
5884 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5885 return Context.getNameForTemplate(TName, TNameLoc);
5886 }
5887
5888 } // switch (Name.getKind())
5889
5890 llvm_unreachable("Unknown name kind");
5891}
5892
5894 do {
5895 if (Ty->isPointerOrReferenceType())
5896 Ty = Ty->getPointeeType();
5897 else if (Ty->isArrayType())
5899 else
5900 return Ty.withoutLocalFastQualifiers();
5901 } while (true);
5902}
5903
5904/// hasSimilarParameters - Determine whether the C++ functions Declaration
5905/// and Definition have "nearly" matching parameters. This heuristic is
5906/// used to improve diagnostics in the case where an out-of-line function
5907/// definition doesn't match any declaration within the class or namespace.
5908/// Also sets Params to the list of indices to the parameters that differ
5909/// between the declaration and the definition. If hasSimilarParameters
5910/// returns true and Params is empty, then all of the parameters match.
5914 SmallVectorImpl<unsigned> &Params) {
5915 Params.clear();
5916 if (Declaration->param_size() != Definition->param_size())
5917 return false;
5918 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5919 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5920 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5921
5922 // The parameter types are identical
5923 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5924 continue;
5925
5926 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5927 QualType DefParamBaseTy = getCoreType(DefParamTy);
5928 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5929 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5930
5931 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5932 (DeclTyName && DeclTyName == DefTyName))
5933 Params.push_back(Idx);
5934 else // The two parameters aren't even close
5935 return false;
5936 }
5937
5938 return true;
5939}
5940
5941/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5942/// declarator needs to be rebuilt in the current instantiation.
5943/// Any bits of declarator which appear before the name are valid for
5944/// consideration here. That's specifically the type in the decl spec
5945/// and the base type in any member-pointer chunks.
5947 DeclarationName Name) {
5948 // The types we specifically need to rebuild are:
5949 // - typenames, typeofs, and decltypes
5950 // - types which will become injected class names
5951 // Of course, we also need to rebuild any type referencing such a
5952 // type. It's safest to just say "dependent", but we call out a
5953 // few cases here.
5954
5955 DeclSpec &DS = D.getMutableDeclSpec();
5956 switch (DS.getTypeSpecType()) {
5960#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
5961#include "clang/Basic/TransformTypeTraits.def"
5962 case DeclSpec::TST_atomic: {
5963 // Grab the type from the parser.
5964 TypeSourceInfo *TSI = nullptr;
5965 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5966 if (T.isNull() || !T->isInstantiationDependentType()) break;
5967
5968 // Make sure there's a type source info. This isn't really much
5969 // of a waste; most dependent types should have type source info
5970 // attached already.
5971 if (!TSI)
5973
5974 // Rebuild the type in the current instantiation.
5975 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5976 if (!TSI) return true;
5977
5978 // Store the new type back in the decl spec.
5979 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5980 DS.UpdateTypeRep(LocType);
5981 break;
5982 }
5983
5987 Expr *E = DS.getRepAsExpr();
5989 if (Result.isInvalid()) return true;
5990 DS.UpdateExprRep(Result.get());
5991 break;
5992 }
5993
5994 default:
5995 // Nothing to do for these decl specs.
5996 break;
5997 }
5998
5999 // It doesn't matter what order we do this in.
6000 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6001 DeclaratorChunk &Chunk = D.getTypeObject(I);
6002
6003 // The only type information in the declarator which can come
6004 // before the declaration name is the base type of a member
6005 // pointer.
6007 continue;
6008
6009 // Rebuild the scope specifier in-place.
6010 CXXScopeSpec &SS = Chunk.Mem.Scope();
6012 return true;
6013 }
6014
6015 return false;
6016}
6017
6018/// Returns true if the declaration is declared in a system header or from a
6019/// system macro.
6021 return SM.isInSystemHeader(D->getLocation()) ||
6022 SM.isInSystemMacro(D->getLocation());
6023}
6024
6026 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6027 // of system decl.
6028 if (D->getPreviousDecl() || D->isImplicit())
6029 return;
6030 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6033 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6034 << D << static_cast<int>(Status);
6035 }
6036}
6037
6039 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6040
6041 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6042 // declaration only if the `bind_to_declaration` extension is set.
6044 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6045 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6046 llvm::omp::TraitProperty::
6047 implementation_extension_bind_to_declaration))
6049 S, D, MultiTemplateParamsArg(), Bases);
6050
6052
6054 Dcl && Dcl->getDeclContext()->isFileContext())
6056
6057 if (!Bases.empty())
6059 Bases);
6060
6061 return Dcl;
6062}
6063
6065 DeclarationNameInfo NameInfo) {
6066 DeclarationName Name = NameInfo.getName();
6067
6068 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6069 while (Record && Record->isAnonymousStructOrUnion())
6070 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6071 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6072 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6073 return true;
6074 }
6075
6076 return false;
6077}
6078
6080 DeclarationName Name,
6082 TemplateIdAnnotation *TemplateId,
6083 bool IsMemberSpecialization) {
6084 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6085 "without nested-name-specifier");
6086 DeclContext *Cur = CurContext;
6087 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6088 Cur = Cur->getParent();
6089
6090 // If the user provided a superfluous scope specifier that refers back to the
6091 // class in which the entity is already declared, diagnose and ignore it.
6092 //
6093 // class X {
6094 // void X::f();
6095 // };
6096 //
6097 // Note, it was once ill-formed to give redundant qualification in all
6098 // contexts, but that rule was removed by DR482.
6099 if (Cur->Equals(DC)) {
6100 if (Cur->isRecord()) {
6101 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6102 : diag::err_member_extra_qualification)
6103 << Name << FixItHint::CreateRemoval(SS.getRange());
6104 SS.clear();
6105 } else {
6106 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6107 }
6108 return false;
6109 }
6110
6111 // Check whether the qualifying scope encloses the scope of the original
6112 // declaration. For a template-id, we perform the checks in
6113 // CheckTemplateSpecializationScope.
6114 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6115 if (Cur->isRecord())
6116 Diag(Loc, diag::err_member_qualification)
6117 << Name << SS.getRange();
6118 else if (isa<TranslationUnitDecl>(DC))
6119 Diag(Loc, diag::err_invalid_declarator_global_scope)
6120 << Name << SS.getRange();
6121 else if (isa<FunctionDecl>(Cur))
6122 Diag(Loc, diag::err_invalid_declarator_in_function)
6123 << Name << SS.getRange();
6124 else if (isa<BlockDecl>(Cur))
6125 Diag(Loc, diag::err_invalid_declarator_in_block)
6126 << Name << SS.getRange();
6127 else if (isa<ExportDecl>(Cur)) {
6128 if (!isa<NamespaceDecl>(DC))
6129 Diag(Loc, diag::err_export_non_namespace_scope_name)
6130 << Name << SS.getRange();
6131 else
6132 // The cases that DC is not NamespaceDecl should be handled in
6133 // CheckRedeclarationExported.
6134 return false;
6135 } else
6136 Diag(Loc, diag::err_invalid_declarator_scope)
6137 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6138
6139 return true;
6140 }
6141
6142 if (Cur->isRecord()) {
6143 // Cannot qualify members within a class.
6144 Diag(Loc, diag::err_member_qualification)
6145 << Name << SS.getRange();
6146 SS.clear();
6147
6148 // C++ constructors and destructors with incorrect scopes can break
6149 // our AST invariants by having the wrong underlying types. If
6150 // that's the case, then drop this declaration entirely.
6151 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6152 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6153 !Context.hasSameType(Name.getCXXNameType(),
6154 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6155 return true;
6156
6157 return false;
6158 }
6159
6160 // C++23 [temp.names]p5:
6161 // The keyword template shall not appear immediately after a declarative
6162 // nested-name-specifier.
6163 //
6164 // First check the template-id (if any), and then check each component of the
6165 // nested-name-specifier in reverse order.
6166 //
6167 // FIXME: nested-name-specifiers in friend declarations are declarative,
6168 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6169 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6170 Diag(Loc, diag::ext_template_after_declarative_nns)
6172
6174 do {
6175 if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6177 Diag(Loc, diag::ext_template_after_declarative_nns)
6179 SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6180
6181 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6182 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6183 // C++23 [expr.prim.id.qual]p3:
6184 // [...] If a nested-name-specifier N is declarative and has a
6185 // simple-template-id with a template argument list A that involves a
6186 // template parameter, let T be the template nominated by N without A.
6187 // T shall be a class template.
6188 if (TST->isDependentType() && TST->isTypeAlias())
6189 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6190 << SpecLoc.getLocalSourceRange();
6191 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6192 // C++23 [expr.prim.id.qual]p2:
6193 // [...] A declarative nested-name-specifier shall not have a
6194 // computed-type-specifier.
6195 //
6196 // CWG2858 changed this from 'decltype-specifier' to
6197 // 'computed-type-specifier'.
6198 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6199 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6200 }
6201 }
6202 } while ((SpecLoc = SpecLoc.getPrefix()));
6203
6204 return false;
6205}
6206
6208 MultiTemplateParamsArg TemplateParamLists) {
6209 // TODO: consider using NameInfo for diagnostic.
6211 DeclarationName Name = NameInfo.getName();
6212
6213 // All of these full declarators require an identifier. If it doesn't have
6214 // one, the ParsedFreeStandingDeclSpec action should be used.
6215 if (D.isDecompositionDeclarator()) {
6216 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6217 } else if (!Name) {
6218 if (!D.isInvalidType()) // Reject this if we think it is valid.
6219 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6220 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6221 return nullptr;
6223 return nullptr;
6224
6225 DeclContext *DC = CurContext;
6226 if (D.getCXXScopeSpec().isInvalid())
6227 D.setInvalidType();
6228 else if (D.getCXXScopeSpec().isSet()) {
6229 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6231 return nullptr;
6232
6233 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6234 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6235 if (!DC || isa<EnumDecl>(DC)) {
6236 // If we could not compute the declaration context, it's because the
6237 // declaration context is dependent but does not refer to a class,
6238 // class template, or class template partial specialization. Complain
6239 // and return early, to avoid the coming semantic disaster.
6240 Diag(D.getIdentifierLoc(),
6241 diag::err_template_qualified_declarator_no_match)
6242 << D.getCXXScopeSpec().getScopeRep()
6243 << D.getCXXScopeSpec().getRange();
6244 return nullptr;
6245 }
6246 bool IsDependentContext = DC->isDependentContext();
6247
6248 if (!IsDependentContext &&
6249 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6250 return nullptr;
6251
6252 // If a class is incomplete, do not parse entities inside it.
6253 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6254 Diag(D.getIdentifierLoc(),
6255 diag::err_member_def_undefined_record)
6256 << Name << DC << D.getCXXScopeSpec().getRange();
6257 return nullptr;
6258 }
6259 if (!D.getDeclSpec().isFriendSpecified()) {
6260 TemplateIdAnnotation *TemplateId =
6262 ? D.getName().TemplateId
6263 : nullptr;
6264 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name,
6265 D.getIdentifierLoc(), TemplateId,
6266 /*IsMemberSpecialization=*/false)) {
6267 if (DC->isRecord())
6268 return nullptr;
6269
6270 D.setInvalidType();
6271 }
6272 }
6273
6274 // Check whether we need to rebuild the type of the given
6275 // declaration in the current instantiation.
6276 if (EnteringContext && IsDependentContext &&
6277 TemplateParamLists.size() != 0) {
6278 ContextRAII SavedContext(*this, DC);
6280 D.setInvalidType();
6281 }
6282 }
6283
6285 QualType R = TInfo->getType();
6286
6287 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6289 D.setInvalidType();
6290
6291 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6293
6294 // See if this is a redefinition of a variable in the same scope.
6295 if (!D.getCXXScopeSpec().isSet()) {
6296 bool IsLinkageLookup = false;
6297 bool CreateBuiltins = false;
6298
6299 // If the declaration we're planning to build will be a function
6300 // or object with linkage, then look for another declaration with
6301 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6302 //
6303 // If the declaration we're planning to build will be declared with
6304 // external linkage in the translation unit, create any builtin with
6305 // the same name.
6306 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6307 /* Do nothing*/;
6308 else if (CurContext->isFunctionOrMethod() &&
6309 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6310 R->isFunctionType())) {
6311 IsLinkageLookup = true;
6312 CreateBuiltins =
6315 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6316 CreateBuiltins = true;
6317
6318 if (IsLinkageLookup) {
6320 Previous.setRedeclarationKind(
6321 RedeclarationKind::ForExternalRedeclaration);
6322 }
6323
6324 LookupName(Previous, S, CreateBuiltins);
6325 } else { // Something like "int foo::x;"
6327
6328 // C++ [dcl.meaning]p1:
6329 // When the declarator-id is qualified, the declaration shall refer to a
6330 // previously declared member of the class or namespace to which the
6331 // qualifier refers (or, in the case of a namespace, of an element of the
6332 // inline namespace set of that namespace (7.3.1)) or to a specialization
6333 // thereof; [...]
6334 //
6335 // Note that we already checked the context above, and that we do not have
6336 // enough information to make sure that Previous contains the declaration
6337 // we want to match. For example, given:
6338 //
6339 // class X {
6340 // void f();
6341 // void f(float);
6342 // };
6343 //
6344 // void X::f(int) { } // ill-formed
6345 //
6346 // In this case, Previous will point to the overload set
6347 // containing the two f's declared in X, but neither of them
6348 // matches.
6349
6351 }
6352
6353 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6354 TPD && TPD->isTemplateParameter()) {
6355 // Older versions of clang allowed the names of function/variable templates
6356 // to shadow the names of their template parameters. For the compatibility
6357 // purposes we detect such cases and issue a default-to-error warning that
6358 // can be disabled with -Wno-strict-primary-template-shadow.
6359 if (!D.isInvalidType()) {
6360 bool AllowForCompatibility = false;
6361 if (Scope *DeclParent = S->getDeclParent();
6362 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6363 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6364 TemplateParamParent->isDeclScope(TPD);
6365 }
6366 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
6367 AllowForCompatibility);
6368 }
6369
6370 // Just pretend that we didn't see the previous declaration.
6371 Previous.clear();
6372 }
6373
6374 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6375 // Forget that the previous declaration is the injected-class-name.
6376 Previous.clear();
6377
6378 // In C++, the previous declaration we find might be a tag type
6379 // (class or enum). In this case, the new declaration will hide the
6380 // tag type. Note that this applies to functions, function templates, and
6381 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6382 if (Previous.isSingleTagDecl() &&
6383 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6384 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6385 Previous.clear();
6386
6387 // Check that there are no default arguments other than in the parameters
6388 // of a function declaration (C++ only).
6389 if (getLangOpts().CPlusPlus)
6391
6392 /// Get the innermost enclosing declaration scope.
6393 S = S->getDeclParent();
6394
6395 NamedDecl *New;
6396
6397 bool AddToScope = true;
6398 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6399 if (TemplateParamLists.size()) {
6400 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6401 return nullptr;
6402 }
6403
6404 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6405 } else if (R->isFunctionType()) {
6406 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6407 TemplateParamLists,
6408 AddToScope);
6409 } else {
6410 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6411 AddToScope);
6412 }
6413
6414 if (!New)
6415 return nullptr;
6416
6417 // If this has an identifier and is not a function template specialization,
6418 // add it to the scope stack.
6419 if (New->getDeclName() && AddToScope)
6420 PushOnScopeChains(New, S);
6421
6422 if (OpenMP().isInOpenMPDeclareTargetContext())
6424
6425 return New;
6426}
6427
6428/// Helper method to turn variable array types into constant array
6429/// types in certain situations which would otherwise be errors (for
6430/// GCC compatibility).
6432 ASTContext &Context,
6433 bool &SizeIsNegative,
6434 llvm::APSInt &Oversized) {
6435 // This method tries to turn a variable array into a constant
6436 // array even when the size isn't an ICE. This is necessary
6437 // for compatibility with code that depends on gcc's buggy
6438 // constant expression folding, like struct {char x[(int)(char*)2];}
6439 SizeIsNegative = false;
6440 Oversized = 0;
6441
6442 if (T->isDependentType())
6443 return QualType();
6444
6446 const Type *Ty = Qs.strip(T);
6447
6448 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6449 QualType Pointee = PTy->getPointeeType();
6450 QualType FixedType =
6451 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6452 Oversized);
6453 if (FixedType.isNull()) return FixedType;
6454 FixedType = Context.getPointerType(FixedType);
6455 return Qs.apply(Context, FixedType);
6456 }
6457 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6458 QualType Inner = PTy->getInnerType();
6459 QualType FixedType =
6460 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6461 Oversized);
6462 if (FixedType.isNull()) return FixedType;
6463 FixedType = Context.getParenType(FixedType);
6464 return Qs.apply(Context, FixedType);
6465 }
6466
6467 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6468 if (!VLATy)
6469 return QualType();
6470
6471 QualType ElemTy = VLATy->getElementType();
6472 if (ElemTy->isVariablyModifiedType()) {
6473 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6474 SizeIsNegative, Oversized);
6475 if (ElemTy.isNull())
6476 return QualType();
6477 }
6478
6480 if (!VLATy->getSizeExpr() ||
6481 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6482 return QualType();
6483
6484 llvm::APSInt Res = Result.Val.getInt();
6485
6486 // Check whether the array size is negative.
6487 if (Res.isSigned() && Res.isNegative()) {
6488 SizeIsNegative = true;
6489 return QualType();
6490 }
6491
6492 // Check whether the array is too large to be addressed.
6493 unsigned ActiveSizeBits =
6494 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6495 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6496 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6497 : Res.getActiveBits();
6498 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6499 Oversized = Res;
6500 return QualType();
6501 }
6502
6503 QualType FoldedArrayType = Context.getConstantArrayType(
6504 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6505 return Qs.apply(Context, FoldedArrayType);
6506}
6507
6508static void
6510 SrcTL = SrcTL.getUnqualifiedLoc();
6511 DstTL = DstTL.getUnqualifiedLoc();
6512 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6513 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6514 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6515 DstPTL.getPointeeLoc());
6516 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6517 return;
6518 }
6519 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6520 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6521 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6522 DstPTL.getInnerLoc());
6523 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6524 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6525 return;
6526 }
6527 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6528 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6529 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6530 TypeLoc DstElemTL = DstATL.getElementLoc();
6531 if (VariableArrayTypeLoc SrcElemATL =
6532 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6533 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6534 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6535 } else {
6536 DstElemTL.initializeFullCopy(SrcElemTL);
6537 }
6538 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6539 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6540 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6541}
6542
6543/// Helper method to turn variable array types into constant array
6544/// types in certain situations which would otherwise be errors (for
6545/// GCC compatibility).
6546static TypeSourceInfo*
6548 ASTContext &Context,
6549 bool &SizeIsNegative,
6550 llvm::APSInt &Oversized) {
6551 QualType FixedTy
6552 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6553 SizeIsNegative, Oversized);
6554 if (FixedTy.isNull())
6555 return nullptr;
6556 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6558 FixedTInfo->getTypeLoc());
6559 return FixedTInfo;
6560}
6561
6564 unsigned FailedFoldDiagID) {
6565 bool SizeIsNegative;
6566 llvm::APSInt Oversized;
6568 TInfo, Context, SizeIsNegative, Oversized);
6569 if (FixedTInfo) {
6570 Diag(Loc, diag::ext_vla_folded_to_constant);
6571 TInfo = FixedTInfo;
6572 T = FixedTInfo->getType();
6573 return true;
6574 }
6575
6576 if (SizeIsNegative)
6577 Diag(Loc, diag::err_typecheck_negative_array_size);
6578 else if (Oversized.getBoolValue())
6579 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6580 else if (FailedFoldDiagID)
6581 Diag(Loc, FailedFoldDiagID);
6582 return false;
6583}
6584
6585void
6587 if (!getLangOpts().CPlusPlus &&
6589 // Don't need to track declarations in the TU in C.
6590 return;
6591
6592 // Note that we have a locally-scoped external with this name.
6594}
6595
6597 // FIXME: We can have multiple results via __attribute__((overloadable)).
6599 return Result.empty() ? nullptr : *Result.begin();
6600}
6601
6603 // FIXME: We should probably indicate the identifier in question to avoid
6604 // confusion for constructs like "virtual int a(), b;"
6605 if (DS.isVirtualSpecified())
6607 diag::err_virtual_non_function);
6608
6609 if (DS.hasExplicitSpecifier())
6611 diag::err_explicit_non_function);
6612
6613 if (DS.isNoreturnSpecified())
6615 diag::err_noreturn_non_function);
6616}
6617
6618NamedDecl*
6621 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6622 if (D.getCXXScopeSpec().isSet()) {
6623 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6624 << D.getCXXScopeSpec().getRange();
6625 D.setInvalidType();
6626 // Pretend we didn't see the scope specifier.
6627 DC = CurContext;
6628 Previous.clear();
6629 }
6630
6631 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6632
6633 if (D.getDeclSpec().isInlineSpecified())
6634 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6635 << getLangOpts().CPlusPlus17;
6636 if (D.getDeclSpec().hasConstexprSpecifier())
6637 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6638 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6639
6640 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6642 Diag(D.getName().StartLocation,
6643 diag::err_deduction_guide_invalid_specifier)
6644 << "typedef";
6645 else
6646 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6647 << D.getName().getSourceRange();
6648 return nullptr;
6649 }
6650
6651 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6652 if (!NewTD) return nullptr;
6653
6654 // Handle attributes prior to checking for duplicates in MergeVarDecl
6655 ProcessDeclAttributes(S, NewTD, D);
6656
6658
6659 bool Redeclaration = D.isRedeclaration();
6660 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6661 D.setRedeclaration(Redeclaration);
6662 return ND;
6663}
6664
6665void
6667 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6668 // then it shall have block scope.
6669 // Note that variably modified types must be fixed before merging the decl so
6670 // that redeclarations will match.
6671 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6672 QualType T = TInfo->getType();
6673 if (T->isVariablyModifiedType()) {
6675
6676 if (S->getFnParent() == nullptr) {
6677 bool SizeIsNegative;
6678 llvm::APSInt Oversized;
6679 TypeSourceInfo *FixedTInfo =
6681 SizeIsNegative,
6682 Oversized);
6683 if (FixedTInfo) {
6684 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6685 NewTD->setTypeSourceInfo(FixedTInfo);
6686 } else {
6687 if (SizeIsNegative)
6688 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6689 else if (T->isVariableArrayType())
6690 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6691 else if (Oversized.getBoolValue())
6692 Diag(NewTD->getLocation(), diag::err_array_too_large)
6693 << toString(Oversized, 10);
6694 else
6695 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6696 NewTD->setInvalidDecl();
6697 }
6698 }
6699 }
6700}
6701
6702NamedDecl*
6704 LookupResult &Previous, bool &Redeclaration) {
6705
6706 // Find the shadowed declaration before filtering for scope.
6707 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6708
6709 // Merge the decl with the existing one if appropriate. If the decl is
6710 // in an outer scope, it isn't the same thing.
6711 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6712 /*AllowInlineNamespace*/false);
6714 if (!Previous.empty()) {
6715 Redeclaration = true;
6716 MergeTypedefNameDecl(S, NewTD, Previous);
6717 } else {
6719 }
6720
6721 if (ShadowedDecl && !Redeclaration)
6722 CheckShadow(NewTD, ShadowedDecl, Previous);
6723
6724 // If this is the C FILE type, notify the AST context.
6725 if (IdentifierInfo *II = NewTD->getIdentifier())
6726 if (!NewTD->isInvalidDecl() &&
6728 switch (II->getNotableIdentifierID()) {
6729 case tok::NotableIdentifierKind::FILE:
6730 Context.setFILEDecl(NewTD);
6731 break;
6732 case tok::NotableIdentifierKind::jmp_buf:
6733 Context.setjmp_bufDecl(NewTD);
6734 break;
6735 case tok::NotableIdentifierKind::sigjmp_buf:
6737 break;
6738 case tok::NotableIdentifierKind::ucontext_t:
6740 break;
6741 case tok::NotableIdentifierKind::float_t:
6742 case tok::NotableIdentifierKind::double_t:
6743 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6744 break;
6745 default:
6746 break;
6747 }
6748 }
6749
6750 return NewTD;
6751}
6752
6753/// Determines whether the given declaration is an out-of-scope
6754/// previous declaration.
6755///
6756/// This routine should be invoked when name lookup has found a
6757/// previous declaration (PrevDecl) that is not in the scope where a
6758/// new declaration by the same name is being introduced. If the new
6759/// declaration occurs in a local scope, previous declarations with
6760/// linkage may still be considered previous declarations (C99
6761/// 6.2.2p4-5, C++ [basic.link]p6).
6762///
6763/// \param PrevDecl the previous declaration found by name
6764/// lookup
6765///
6766/// \param DC the context in which the new declaration is being
6767/// declared.
6768///
6769/// \returns true if PrevDecl is an out-of-scope previous declaration
6770/// for a new delcaration with the same name.
6771static bool
6773 ASTContext &Context) {
6774 if (!PrevDecl)
6775 return false;
6776
6777 if (!PrevDecl->hasLinkage())
6778 return false;
6779
6780 if (Context.getLangOpts().CPlusPlus) {
6781 // C++ [basic.link]p6:
6782 // If there is a visible declaration of an entity with linkage
6783 // having the same name and type, ignoring entities declared
6784 // outside the innermost enclosing namespace scope, the block
6785 // scope declaration declares that same entity and receives the
6786 // linkage of the previous declaration.
6787 DeclContext *OuterContext = DC->getRedeclContext();
6788 if (!OuterContext->isFunctionOrMethod())
6789 // This rule only applies to block-scope declarations.
6790 return false;
6791
6792 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6793 if (PrevOuterContext->isRecord())
6794 // We found a member function: ignore it.
6795 return false;
6796
6797 // Find the innermost enclosing namespace for the new and
6798 // previous declarations.
6799 OuterContext = OuterContext->getEnclosingNamespaceContext();
6800 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6801
6802 // The previous declaration is in a different namespace, so it
6803 // isn't the same function.
6804 if (!OuterContext->Equals(PrevOuterContext))
6805 return false;
6806 }
6807
6808 return true;
6809}
6810
6812 CXXScopeSpec &SS = D.getCXXScopeSpec();
6813 if (!SS.isSet()) return;
6815}
6816
6818 if (Decl->getType().hasAddressSpace())
6819 return;
6820 if (Decl->getType()->isDependentType())
6821 return;
6822 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6823 QualType Type = Var->getType();
6824 if (Type->isSamplerT() || Type->isVoidType())
6825 return;
6827 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6828 // __opencl_c_program_scope_global_variables feature, the address space
6829 // for a variable at program scope or a static or extern variable inside
6830 // a function are inferred to be __global.
6831 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6832 Var->hasGlobalStorage())
6833 ImplAS = LangAS::opencl_global;
6834 // If the original type from a decayed type is an array type and that array
6835 // type has no address space yet, deduce it now.
6836 if (auto DT = dyn_cast<DecayedType>(Type)) {
6837 auto OrigTy = DT->getOriginalType();
6838 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6839 // Add the address space to the original array type and then propagate
6840 // that to the element type through `getAsArrayType`.
6841 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6842 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6843 // Re-generate the decayed type.
6844 Type = Context.getDecayedType(OrigTy);
6845 }
6846 }
6848 // Apply any qualifiers (including address space) from the array type to
6849 // the element type. This implements C99 6.7.3p8: "If the specification of
6850 // an array type includes any type qualifiers, the element type is so
6851 // qualified, not the array type."
6852 if (Type->isArrayType())
6854 Decl->setType(Type);
6855 }
6856}
6857
6859 // Ensure that an auto decl is deduced otherwise the checks below might cache
6860 // the wrong linkage.
6861 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6862
6863 // 'weak' only applies to declarations with external linkage.
6864 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6865 if (!ND.isExternallyVisible()) {
6866 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6867 ND.dropAttr<WeakAttr>();
6868 }
6869 }
6870 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6871 if (ND.isExternallyVisible()) {
6872 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6873 ND.dropAttrs<WeakRefAttr, AliasAttr>();
6874 }
6875 }
6876
6877 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6878 if (VD->hasInit()) {
6879 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6880 assert(VD->isThisDeclarationADefinition() &&
6881 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6882 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6883 VD->dropAttr<AliasAttr>();
6884 }
6885 }
6886 }
6887
6888 // 'selectany' only applies to externally visible variable declarations.
6889 // It does not apply to functions.
6890 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6891 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6892 S.Diag(Attr->getLocation(),
6893 diag::err_attribute_selectany_non_extern_data);
6894 ND.dropAttr<SelectAnyAttr>();
6895 }
6896 }
6897
6898 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
6899 if (!ND.isExternallyVisible())
6900 S.Diag(Attr->getLocation(),
6901 diag::warn_attribute_hybrid_patchable_non_extern);
6902 }
6903 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6904 auto *VD = dyn_cast<VarDecl>(&ND);
6905 bool IsAnonymousNS = false;
6906 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6907 if (VD) {
6908 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6909 while (NS && !IsAnonymousNS) {
6910 IsAnonymousNS = NS->isAnonymousNamespace();
6911 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6912 }
6913 }
6914 // dll attributes require external linkage. Static locals may have external
6915 // linkage but still cannot be explicitly imported or exported.
6916 // In Microsoft mode, a variable defined in anonymous namespace must have
6917 // external linkage in order to be exported.
6918 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6919 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6920 (!AnonNSInMicrosoftMode &&
6921 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6922 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6923 << &ND << Attr;
6924 ND.setInvalidDecl();
6925 }
6926 }
6927
6928 // Check the attributes on the function type, if any.
6929 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6930 // Don't declare this variable in the second operand of the for-statement;
6931 // GCC miscompiles that by ending its lifetime before evaluating the
6932 // third operand. See gcc.gnu.org/PR86769.
6934 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6935 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6936 TL = ATL.getModifiedLoc()) {
6937 // The [[lifetimebound]] attribute can be applied to the implicit object
6938 // parameter of a non-static member function (other than a ctor or dtor)
6939 // by applying it to the function type.
6940 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6941 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6942 int NoImplicitObjectError = -1;
6943 if (!MD)
6944 NoImplicitObjectError = 0;
6945 else if (MD->isStatic())
6946 NoImplicitObjectError = 1;
6947 else if (MD->isExplicitObjectMemberFunction())
6948 NoImplicitObjectError = 2;
6949 if (NoImplicitObjectError != -1) {
6950 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6951 << NoImplicitObjectError << A->getRange();
6952 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6953 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6954 << isa<CXXDestructorDecl>(MD) << A->getRange();
6955 }
6956 }
6957 }
6958 }
6959}
6960
6962 NamedDecl *NewDecl,
6963 bool IsSpecialization,
6964 bool IsDefinition) {
6965 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6966 return;
6967
6968 bool IsTemplate = false;
6969 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6970 OldDecl = OldTD->getTemplatedDecl();
6971 IsTemplate = true;
6972 if (!IsSpecialization)
6973 IsDefinition = false;
6974 }
6975 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6976 NewDecl = NewTD->getTemplatedDecl();
6977 IsTemplate = true;
6978 }
6979
6980 if (!OldDecl || !NewDecl)
6981 return;
6982
6983 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6984 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6985 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6986 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6987
6988 // dllimport and dllexport are inheritable attributes so we have to exclude
6989 // inherited attribute instances.
6990 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6991 (NewExportAttr && !NewExportAttr->isInherited());
6992
6993 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6994 // the only exception being explicit specializations.
6995 // Implicitly generated declarations are also excluded for now because there
6996 // is no other way to switch these to use dllimport or dllexport.
6997 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6998
6999 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7000 // Allow with a warning for free functions and global variables.
7001 bool JustWarn = false;
7002 if (!OldDecl->isCXXClassMember()) {
7003 auto *VD = dyn_cast<VarDecl>(OldDecl);
7004 if (VD && !VD->getDescribedVarTemplate())
7005 JustWarn = true;
7006 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7007 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7008 JustWarn = true;
7009 }
7010
7011 // We cannot change a declaration that's been used because IR has already
7012 // been emitted. Dllimported functions will still work though (modulo
7013 // address equality) as they can use the thunk.
7014 if (OldDecl->isUsed())
7015 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7016 JustWarn = false;
7017
7018 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7019 : diag::err_attribute_dll_redeclaration;
7020 S.Diag(NewDecl->getLocation(), DiagID)
7021 << NewDecl
7022 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7023 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7024 if (!JustWarn) {
7025 NewDecl->setInvalidDecl();
7026 return;
7027 }
7028 }
7029
7030 // A redeclaration is not allowed to drop a dllimport attribute, the only
7031 // exceptions being inline function definitions (except for function
7032 // templates), local extern declarations, qualified friend declarations or
7033 // special MSVC extension: in the last case, the declaration is treated as if
7034 // it were marked dllexport.
7035 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7036 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7037 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7038 // Ignore static data because out-of-line definitions are diagnosed
7039 // separately.
7040 IsStaticDataMember = VD->isStaticDataMember();
7041 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7043 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7044 IsInline = FD->isInlined();
7045 IsQualifiedFriend = FD->getQualifier() &&
7046 FD->getFriendObjectKind() == Decl::FOK_Declared;
7047 }
7048
7049 if (OldImportAttr && !HasNewAttr &&
7050 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7051 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7052 if (IsMicrosoftABI && IsDefinition) {
7053 if (IsSpecialization) {
7054 S.Diag(
7055 NewDecl->getLocation(),
7056 diag::err_attribute_dllimport_function_specialization_definition);
7057 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7058 NewDecl->dropAttr<DLLImportAttr>();
7059 } else {
7060 S.Diag(NewDecl->getLocation(),
7061 diag::warn_redeclaration_without_import_attribute)
7062 << NewDecl;
7063 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7064 NewDecl->dropAttr<DLLImportAttr>();
7065 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7066 S.Context, NewImportAttr->getRange()));
7067 }
7068 } else if (IsMicrosoftABI && IsSpecialization) {
7069 assert(!IsDefinition);
7070 // MSVC allows this. Keep the inherited attribute.
7071 } else {
7072 S.Diag(NewDecl->getLocation(),
7073 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7074 << NewDecl << OldImportAttr;
7075 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7076 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7077 OldDecl->dropAttr<DLLImportAttr>();
7078 NewDecl->dropAttr<DLLImportAttr>();
7079 }
7080 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7081 // In MinGW, seeing a function declared inline drops the dllimport
7082 // attribute.
7083 OldDecl->dropAttr<DLLImportAttr>();
7084 NewDecl->dropAttr<DLLImportAttr>();
7085 S.Diag(NewDecl->getLocation(),
7086 diag::warn_dllimport_dropped_from_inline_function)
7087 << NewDecl << OldImportAttr;
7088 }
7089
7090 // A specialization of a class template member function is processed here
7091 // since it's a redeclaration. If the parent class is dllexport, the
7092 // specialization inherits that attribute. This doesn't happen automatically
7093 // since the parent class isn't instantiated until later.
7094 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7095 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7096 !NewImportAttr && !NewExportAttr) {
7097 if (const DLLExportAttr *ParentExportAttr =
7098 MD->getParent()->getAttr<DLLExportAttr>()) {
7099 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7100 NewAttr->setInherited(true);
7101 NewDecl->addAttr(NewAttr);
7102 }
7103 }
7104 }
7105}
7106
7107/// Given that we are within the definition of the given function,
7108/// will that definition behave like C99's 'inline', where the
7109/// definition is discarded except for optimization purposes?
7111 // Try to avoid calling GetGVALinkageForFunction.
7112
7113 // All cases of this require the 'inline' keyword.
7114 if (!FD->isInlined()) return false;
7115
7116 // This is only possible in C++ with the gnu_inline attribute.
7117 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7118 return false;
7119
7120 // Okay, go ahead and call the relatively-more-expensive function.
7122}
7123
7124/// Determine whether a variable is extern "C" prior to attaching
7125/// an initializer. We can't just call isExternC() here, because that
7126/// will also compute and cache whether the declaration is externally
7127/// visible, which might change when we attach the initializer.
7128///
7129/// This can only be used if the declaration is known to not be a
7130/// redeclaration of an internal linkage declaration.
7131///
7132/// For instance:
7133///
7134/// auto x = []{};
7135///
7136/// Attaching the initializer here makes this declaration not externally
7137/// visible, because its type has internal linkage.
7138///
7139/// FIXME: This is a hack.
7140template<typename T>
7141static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7142 if (S.getLangOpts().CPlusPlus) {
7143 // In C++, the overloadable attribute negates the effects of extern "C".
7144 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7145 return false;
7146
7147 // So do CUDA's host/device attributes.
7148 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7149 D->template hasAttr<CUDAHostAttr>()))
7150 return false;
7151 }
7152 return D->isExternC();
7153}
7154
7155static bool shouldConsiderLinkage(const VarDecl *VD) {
7156 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7157 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7158 isa<OMPDeclareMapperDecl>(DC))
7159 return VD->hasExternalStorage();
7160 if (DC->isFileContext())
7161 return true;
7162 if (DC->isRecord())
7163 return false;
7164 if (DC->getDeclKind() == Decl::HLSLBuffer)
7165 return false;
7166
7167 if (isa<RequiresExprBodyDecl>(DC))
7168 return false;
7169 llvm_unreachable("Unexpected context");
7170}
7171
7172static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7173 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7174 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7175 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7176 return true;
7177 if (DC->isRecord())
7178 return false;
7179 llvm_unreachable("Unexpected context");
7180}
7181
7182static bool hasParsedAttr(Scope *S, const Declarator &PD,
7183 ParsedAttr::Kind Kind) {
7184 // Check decl attributes on the DeclSpec.
7185 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7186 return true;
7187
7188 // Walk the declarator structure, checking decl attributes that were in a type
7189 // position to the decl itself.
7190 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7191 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7192 return true;
7193 }
7194
7195 // Finally, check attributes on the decl itself.
7196 return PD.getAttributes().hasAttribute(Kind) ||
7198}
7199
7201 if (!DC->isFunctionOrMethod())
7202 return false;
7203
7204 // If this is a local extern function or variable declared within a function
7205 // template, don't add it into the enclosing namespace scope until it is
7206 // instantiated; it might have a dependent type right now.
7207 if (DC->isDependentContext())
7208 return true;
7209
7210 // C++11 [basic.link]p7:
7211 // When a block scope declaration of an entity with linkage is not found to
7212 // refer to some other declaration, then that entity is a member of the
7213 // innermost enclosing namespace.
7214 //
7215 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7216 // semantically-enclosing namespace, not a lexically-enclosing one.
7217 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7218 DC = DC->getParent();
7219 return true;
7220}
7221
7222/// Returns true if given declaration has external C language linkage.
7223static bool isDeclExternC(const Decl *D) {
7224 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7225 return FD->isExternC();
7226 if (const auto *VD = dyn_cast<VarDecl>(D))
7227 return VD->isExternC();
7228
7229 llvm_unreachable("Unknown type of decl!");
7230}
7231
7232/// Returns true if there hasn't been any invalid type diagnosed.
7233static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7234 DeclContext *DC = NewVD->getDeclContext();
7235 QualType R = NewVD->getType();
7236
7237 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7238 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7239 // argument.
7240 if (R->isImageType() || R->isPipeType()) {
7241 Se.Diag(NewVD->getLocation(),
7242 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7243 << R;
7244 NewVD->setInvalidDecl();
7245 return false;
7246 }
7247
7248 // OpenCL v1.2 s6.9.r:
7249 // The event type cannot be used to declare a program scope variable.
7250 // OpenCL v2.0 s6.9.q:
7251 // The clk_event_t and reserve_id_t types cannot be declared in program
7252 // scope.
7253 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7254 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7255 Se.Diag(NewVD->getLocation(),
7256 diag::err_invalid_type_for_program_scope_var)
7257 << R;
7258 NewVD->setInvalidDecl();
7259 return false;
7260 }
7261 }
7262
7263 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7264 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7265 Se.getLangOpts())) {
7266 QualType NR = R.getCanonicalType();
7267 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7268 NR->isReferenceType()) {
7271 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7272 << NR->isReferenceType();
7273 NewVD->setInvalidDecl();
7274 return false;
7275 }
7276 NR = NR->getPointeeType();
7277 }
7278 }
7279
7280 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7281 Se.getLangOpts())) {
7282 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7283 // half array type (unless the cl_khr_fp16 extension is enabled).
7284 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7285 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7286 NewVD->setInvalidDecl();
7287 return false;
7288 }
7289 }
7290
7291 // OpenCL v1.2 s6.9.r:
7292 // The event type cannot be used with the __local, __constant and __global
7293 // address space qualifiers.
7294 if (R->isEventT()) {
7296 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7297 NewVD->setInvalidDecl();
7298 return false;
7299 }
7300 }
7301
7302 if (R->isSamplerT()) {
7303 // OpenCL v1.2 s6.9.b p4:
7304 // The sampler type cannot be used with the __local and __global address
7305 // space qualifiers.
7308 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7309 NewVD->setInvalidDecl();
7310 }
7311
7312 // OpenCL v1.2 s6.12.14.1:
7313 // A global sampler must be declared with either the constant address
7314 // space qualifier or with the const qualifier.
7315 if (DC->isTranslationUnit() &&
7317 R.isConstQualified())) {
7318 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7319 NewVD->setInvalidDecl();
7320 }
7321 if (NewVD->isInvalidDecl())
7322 return false;
7323 }
7324
7325 return true;
7326}
7327
7328template <typename AttrTy>
7329static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7330 const TypedefNameDecl *TND = TT->getDecl();
7331 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7332 AttrTy *Clone = Attribute->clone(S.Context);
7333 Clone->setInherited(true);
7334 D->addAttr(Clone);
7335 }
7336}
7337
7338// This function emits warning and a corresponding note based on the
7339// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7340// declarations of an annotated type must be const qualified.
7342 QualType VarType = VD->getType().getCanonicalType();
7343
7344 // Ignore local declarations (for now) and those with const qualification.
7345 // TODO: Local variables should not be allowed if their type declaration has
7346 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7347 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7348 return;
7349
7350 if (VarType->isArrayType()) {
7351 // Retrieve element type for array declarations.
7352 VarType = S.getASTContext().getBaseElementType(VarType);
7353 }
7354
7355 const RecordDecl *RD = VarType->getAsRecordDecl();
7356
7357 // Check if the record declaration is present and if it has any attributes.
7358 if (RD == nullptr)
7359 return;
7360
7361 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7362 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7363 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7364 return;
7365 }
7366}
7367
7368// Checks if VD is declared at global scope or with C language linkage.
7369static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7370 return Name.getAsIdentifierInfo() &&
7371 Name.getAsIdentifierInfo()->isStr("main") &&
7372 !VD->getDescribedVarTemplate() &&
7374 VD->isExternC());
7375}
7376
7378 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7379 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7380 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7381 QualType R = TInfo->getType();
7383
7384 IdentifierInfo *II = Name.getAsIdentifierInfo();
7385 bool IsPlaceholderVariable = false;
7386
7387 if (D.isDecompositionDeclarator()) {
7388 // Take the name of the first declarator as our name for diagnostic
7389 // purposes.
7390 auto &Decomp = D.getDecompositionDeclarator();
7391 if (!Decomp.bindings().empty()) {
7392 II = Decomp.bindings()[0].Name;
7393 Name = II;
7394 }
7395 } else if (!II) {
7396 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7397 return nullptr;
7398 }
7399
7400
7401 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7403
7404 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7405 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7406 IsPlaceholderVariable = true;
7407 if (!Previous.empty()) {
7408 NamedDecl *PrevDecl = *Previous.begin();
7409 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7410 DC->getRedeclContext());
7411 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7412 DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7413 }
7414 }
7415
7416 // dllimport globals without explicit storage class are treated as extern. We
7417 // have to change the storage class this early to get the right DeclContext.
7418 if (SC == SC_None && !DC->isRecord() &&
7419 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7420 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7421 SC = SC_Extern;
7422
7423 DeclContext *OriginalDC = DC;
7424 bool IsLocalExternDecl = SC == SC_Extern &&
7426
7427 if (SCSpec == DeclSpec::SCS_mutable) {
7428 // mutable can only appear on non-static class members, so it's always
7429 // an error here
7430 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7431 D.setInvalidType();
7432 SC = SC_None;
7433 }
7434
7435 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7436 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7437 D.getDeclSpec().getStorageClassSpecLoc())) {
7438 // In C++11, the 'register' storage class specifier is deprecated.
7439 // Suppress the warning in system macros, it's used in macros in some
7440 // popular C system headers, such as in glibc's htonl() macro.
7441 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7442 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7443 : diag::warn_deprecated_register)
7444 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7445 }
7446
7447 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7448
7449 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7450 // C99 6.9p2: The storage-class specifiers auto and register shall not
7451 // appear in the declaration specifiers in an external declaration.
7452 // Global Register+Asm is a GNU extension we support.
7453 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7454 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7455 D.setInvalidType();
7456 }
7457 }
7458
7459 // If this variable has a VLA type and an initializer, try to
7460 // fold to a constant-sized type. This is otherwise invalid.
7461 if (D.hasInitializer() && R->isVariableArrayType())
7462 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7463 /*DiagID=*/0);
7464
7465 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7466 const AutoType *AT = TL.getTypePtr();
7467 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7468 }
7469
7470 bool IsMemberSpecialization = false;
7471 bool IsVariableTemplateSpecialization = false;
7472 bool IsPartialSpecialization = false;
7473 bool IsVariableTemplate = false;
7474 VarDecl *NewVD = nullptr;
7475 VarTemplateDecl *NewTemplate = nullptr;
7476 TemplateParameterList *TemplateParams = nullptr;
7477 if (!getLangOpts().CPlusPlus) {
7478 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7479 II, R, TInfo, SC);
7480
7481 if (R->getContainedDeducedType())
7482 ParsingInitForAutoVars.insert(NewVD);
7483
7484 if (D.isInvalidType())
7485 NewVD->setInvalidDecl();
7486
7488 NewVD->hasLocalStorage())
7489 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7491 } else {
7492 bool Invalid = false;
7493 // Match up the template parameter lists with the scope specifier, then
7494 // determine whether we have a template or a template specialization.
7496 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7497 D.getCXXScopeSpec(),
7499 ? D.getName().TemplateId
7500 : nullptr,
7501 TemplateParamLists,
7502 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7503
7504 if (TemplateParams) {
7505 if (!TemplateParams->size() &&
7507 // There is an extraneous 'template<>' for this variable. Complain
7508 // about it, but allow the declaration of the variable.
7509 Diag(TemplateParams->getTemplateLoc(),
7510 diag::err_template_variable_noparams)
7511 << II
7512 << SourceRange(TemplateParams->getTemplateLoc(),
7513 TemplateParams->getRAngleLoc());
7514 TemplateParams = nullptr;
7515 } else {
7516 // Check that we can declare a template here.
7517 if (CheckTemplateDeclScope(S, TemplateParams))
7518 return nullptr;
7519
7520 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7521 // This is an explicit specialization or a partial specialization.
7522 IsVariableTemplateSpecialization = true;
7523 IsPartialSpecialization = TemplateParams->size() > 0;
7524 } else { // if (TemplateParams->size() > 0)
7525 // This is a template declaration.
7526 IsVariableTemplate = true;
7527
7528 // Only C++1y supports variable templates (N3651).
7529 Diag(D.getIdentifierLoc(),
7531 ? diag::warn_cxx11_compat_variable_template
7532 : diag::ext_variable_template);
7533 }
7534 }
7535 } else {
7536 // Check that we can declare a member specialization here.
7537 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7538 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7539 return nullptr;
7540 assert((Invalid ||
7541 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7542 "should have a 'template<>' for this decl");
7543 }
7544
7545 bool IsExplicitSpecialization =
7546 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7547
7548 // C++ [temp.expl.spec]p2:
7549 // The declaration in an explicit-specialization shall not be an
7550 // export-declaration. An explicit specialization shall not use a
7551 // storage-class-specifier other than thread_local.
7552 //
7553 // We use the storage-class-specifier from DeclSpec because we may have
7554 // added implicit 'extern' for declarations with __declspec(dllimport)!
7555 if (SCSpec != DeclSpec::SCS_unspecified &&
7556 (IsExplicitSpecialization || IsMemberSpecialization)) {
7557 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7558 diag::ext_explicit_specialization_storage_class)
7559 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7560 }
7561
7562 if (CurContext->isRecord()) {
7563 if (SC == SC_Static) {
7564 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7565 // Walk up the enclosing DeclContexts to check for any that are
7566 // incompatible with static data members.
7567 const DeclContext *FunctionOrMethod = nullptr;
7568 const CXXRecordDecl *AnonStruct = nullptr;
7569 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7570 if (Ctxt->isFunctionOrMethod()) {
7571 FunctionOrMethod = Ctxt;
7572 break;
7573 }
7574 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7575 if (ParentDecl && !ParentDecl->getDeclName()) {
7576 AnonStruct = ParentDecl;
7577 break;
7578 }
7579 }
7580 if (FunctionOrMethod) {
7581 // C++ [class.static.data]p5: A local class shall not have static
7582 // data members.
7583 Diag(D.getIdentifierLoc(),
7584 diag::err_static_data_member_not_allowed_in_local_class)
7585 << Name << RD->getDeclName()
7586 << llvm::to_underlying(RD->getTagKind());
7587 } else if (AnonStruct) {
7588 // C++ [class.static.data]p4: Unnamed classes and classes contained
7589 // directly or indirectly within unnamed classes shall not contain
7590 // static data members.
7591 Diag(D.getIdentifierLoc(),
7592 diag::err_static_data_member_not_allowed_in_anon_struct)
7593 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7594 Invalid = true;
7595 } else if (RD->isUnion()) {
7596 // C++98 [class.union]p1: If a union contains a static data member,
7597 // the program is ill-formed. C++11 drops this restriction.
7598 Diag(D.getIdentifierLoc(),
7600 ? diag::warn_cxx98_compat_static_data_member_in_union
7601 : diag::ext_static_data_member_in_union)
7602 << Name;
7603 }
7604 }
7605 } else if (IsVariableTemplate || IsPartialSpecialization) {
7606 // There is no such thing as a member field template.
7607 Diag(D.getIdentifierLoc(), diag::err_template_member)
7608 << II << TemplateParams->getSourceRange();
7609 // Recover by pretending this is a static data member template.
7610 SC = SC_Static;
7611 }
7612 } else if (DC->isRecord()) {
7613 // This is an out-of-line definition of a static data member.
7614 switch (SC) {
7615 case SC_None:
7616 break;
7617 case SC_Static:
7618 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7619 diag::err_static_out_of_line)
7621 D.getDeclSpec().getStorageClassSpecLoc());
7622 break;
7623 case SC_Auto:
7624 case SC_Register:
7625 case SC_Extern:
7626 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7627 // to names of variables declared in a block or to function parameters.
7628 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7629 // of class members
7630
7631 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7632 diag::err_storage_class_for_static_member)
7634 D.getDeclSpec().getStorageClassSpecLoc());
7635 break;
7636 case SC_PrivateExtern:
7637 llvm_unreachable("C storage class in c++!");
7638 }
7639 }
7640
7641 if (IsVariableTemplateSpecialization) {
7642 SourceLocation TemplateKWLoc =
7643 TemplateParamLists.size() > 0
7644 ? TemplateParamLists[0]->getTemplateLoc()
7645 : SourceLocation();
7647 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7649 if (Res.isInvalid())
7650 return nullptr;
7651 NewVD = cast<VarDecl>(Res.get());
7652 AddToScope = false;
7653 } else if (D.isDecompositionDeclarator()) {
7655 D.getIdentifierLoc(), R, TInfo, SC,
7656 Bindings);
7657 } else
7658 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7659 D.getIdentifierLoc(), II, R, TInfo, SC);
7660
7661 // If this is supposed to be a variable template, create it as such.
7662 if (IsVariableTemplate) {
7663 NewTemplate =
7664 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7665 TemplateParams, NewVD);
7666 NewVD->setDescribedVarTemplate(NewTemplate);
7667 }
7668
7669 // If this decl has an auto type in need of deduction, make a note of the
7670 // Decl so we can diagnose uses of it in its own initializer.
7671 if (R->getContainedDeducedType())
7672 ParsingInitForAutoVars.insert(NewVD);
7673
7674 if (D.isInvalidType() || Invalid) {
7675 NewVD->setInvalidDecl();
7676 if (NewTemplate)
7677 NewTemplate->setInvalidDecl();
7678 }
7679
7680 SetNestedNameSpecifier(*this, NewVD, D);
7681
7682 // If we have any template parameter lists that don't directly belong to
7683 // the variable (matching the scope specifier), store them.
7684 // An explicit variable template specialization does not own any template
7685 // parameter lists.
7686 unsigned VDTemplateParamLists =
7687 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7688 if (TemplateParamLists.size() > VDTemplateParamLists)
7690 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7691 }
7692
7693 if (D.getDeclSpec().isInlineSpecified()) {
7694 if (!getLangOpts().CPlusPlus) {
7695 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7696 << 0;
7697 } else if (CurContext->isFunctionOrMethod()) {
7698 // 'inline' is not allowed on block scope variable declaration.
7699 Diag(D.getDeclSpec().getInlineSpecLoc(),
7700 diag::err_inline_declaration_block_scope) << Name
7701 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7702 } else {
7703 Diag(D.getDeclSpec().getInlineSpecLoc(),
7704 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7705 : diag::ext_inline_variable);
7706 NewVD->setInlineSpecified();
7707 }
7708 }
7709
7710 // Set the lexical context. If the declarator has a C++ scope specifier, the
7711 // lexical context will be different from the semantic context.
7713 if (NewTemplate)
7714 NewTemplate->setLexicalDeclContext(CurContext);
7715
7716 if (IsLocalExternDecl) {
7717 if (D.isDecompositionDeclarator())
7718 for (auto *B : Bindings)
7719 B->setLocalExternDecl();
7720 else
7721 NewVD->setLocalExternDecl();
7722 }
7723
7724 bool EmitTLSUnsupportedError = false;
7725 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7726 // C++11 [dcl.stc]p4:
7727 // When thread_local is applied to a variable of block scope the
7728 // storage-class-specifier static is implied if it does not appear
7729 // explicitly.
7730 // Core issue: 'static' is not implied if the variable is declared
7731 // 'extern'.
7732 if (NewVD->hasLocalStorage() &&
7733 (SCSpec != DeclSpec::SCS_unspecified ||
7735 !DC->isFunctionOrMethod()))
7736 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7737 diag::err_thread_non_global)
7739 else if (!Context.getTargetInfo().isTLSSupported()) {
7740 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7741 getLangOpts().SYCLIsDevice) {
7742 // Postpone error emission until we've collected attributes required to
7743 // figure out whether it's a host or device variable and whether the
7744 // error should be ignored.
7745 EmitTLSUnsupportedError = true;
7746 // We still need to mark the variable as TLS so it shows up in AST with
7747 // proper storage class for other tools to use even if we're not going
7748 // to emit any code for it.
7749 NewVD->setTSCSpec(TSCS);
7750 } else
7751 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7752 diag::err_thread_unsupported);
7753 } else
7754 NewVD->setTSCSpec(TSCS);
7755 }
7756
7757 switch (D.getDeclSpec().getConstexprSpecifier()) {
7759 break;
7760
7762 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7763 diag::err_constexpr_wrong_decl_kind)
7764 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7765 [[fallthrough]];
7766
7768 NewVD->setConstexpr(true);
7769 // C++1z [dcl.spec.constexpr]p1:
7770 // A static data member declared with the constexpr specifier is
7771 // implicitly an inline variable.
7772 if (NewVD->isStaticDataMember() &&
7773 (getLangOpts().CPlusPlus17 ||
7775 NewVD->setImplicitlyInline();
7776 break;
7777
7779 if (!NewVD->hasGlobalStorage())
7780 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7781 diag::err_constinit_local_variable);
7782 else
7783 NewVD->addAttr(
7784 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7785 ConstInitAttr::Keyword_constinit));
7786 break;
7787 }
7788
7789 // C99 6.7.4p3
7790 // An inline definition of a function with external linkage shall
7791 // not contain a definition of a modifiable object with static or
7792 // thread storage duration...
7793 // We only apply this when the function is required to be defined
7794 // elsewhere, i.e. when the function is not 'extern inline'. Note
7795 // that a local variable with thread storage duration still has to
7796 // be marked 'static'. Also note that it's possible to get these
7797 // semantics in C++ using __attribute__((gnu_inline)).
7798 if (SC == SC_Static && S->getFnParent() != nullptr &&
7799 !NewVD->getType().isConstQualified()) {
7801 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7802 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7803 diag::warn_static_local_in_extern_inline);
7805 }
7806 }
7807
7808 if (D.getDeclSpec().isModulePrivateSpecified()) {
7809 if (IsVariableTemplateSpecialization)
7810 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7811 << (IsPartialSpecialization ? 1 : 0)
7813 D.getDeclSpec().getModulePrivateSpecLoc());
7814 else if (IsMemberSpecialization)
7815 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7816 << 2
7817 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7818 else if (NewVD->hasLocalStorage())
7819 Diag(NewVD->getLocation(), diag::err_module_private_local)
7820 << 0 << NewVD
7821 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7823 D.getDeclSpec().getModulePrivateSpecLoc());
7824 else {
7825 NewVD->setModulePrivate();
7826 if (NewTemplate)
7827 NewTemplate->setModulePrivate();
7828 for (auto *B : Bindings)
7829 B->setModulePrivate();
7830 }
7831 }
7832
7833 if (getLangOpts().OpenCL) {
7835
7836 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7837 if (TSC != TSCS_unspecified) {
7838 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7839 diag::err_opencl_unknown_type_specifier)
7841 << DeclSpec::getSpecifierName(TSC) << 1;
7842 NewVD->setInvalidDecl();
7843 }
7844 }
7845
7846 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7847 // address space if the table has local storage (semantic checks elsewhere
7848 // will produce an error anyway).
7849 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7850 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7851 !NewVD->hasLocalStorage()) {
7854 NewVD->setType(Type);
7855 }
7856 }
7857
7858 // Handle attributes prior to checking for duplicates in MergeVarDecl
7859 ProcessDeclAttributes(S, NewVD, D);
7860
7861 // FIXME: This is probably the wrong location to be doing this and we should
7862 // probably be doing this for more attributes (especially for function
7863 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7864 // the code to copy attributes would be generated by TableGen.
7865 if (R->isFunctionPointerType())
7866 if (const auto *TT = R->getAs<TypedefType>())
7867 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7868
7869 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7870 getLangOpts().SYCLIsDevice) {
7871 if (EmitTLSUnsupportedError &&
7873 (getLangOpts().OpenMPIsTargetDevice &&
7874 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7875 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7876 diag::err_thread_unsupported);
7877
7878 if (EmitTLSUnsupportedError &&
7879 (LangOpts.SYCLIsDevice ||
7880 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7881 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7882 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7883 // storage [duration]."
7884 if (SC == SC_None && S->getFnParent() != nullptr &&
7885 (NewVD->hasAttr<CUDASharedAttr>() ||
7886 NewVD->hasAttr<CUDAConstantAttr>())) {
7887 NewVD->setStorageClass(SC_Static);
7888 }
7889 }
7890
7891 // Ensure that dllimport globals without explicit storage class are treated as
7892 // extern. The storage class is set above using parsed attributes. Now we can
7893 // check the VarDecl itself.
7894 assert(!NewVD->hasAttr<DLLImportAttr>() ||
7895 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7896 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7897
7898 // In auto-retain/release, infer strong retension for variables of
7899 // retainable type.
7900 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
7901 NewVD->setInvalidDecl();
7902
7903 // Handle GNU asm-label extension (encoded as an attribute).
7904 if (Expr *E = (Expr*)D.getAsmLabel()) {
7905 // The parser guarantees this is a string.
7906 StringLiteral *SE = cast<StringLiteral>(E);
7907 StringRef Label = SE->getString();
7908 if (S->getFnParent() != nullptr) {
7909 switch (SC) {
7910 case SC_None:
7911 case SC_Auto:
7912 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7913 break;
7914 case SC_Register:
7915 // Local Named register
7918 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7919 break;
7920 case SC_Static:
7921 case SC_Extern:
7922 case SC_PrivateExtern:
7923 break;
7924 }
7925 } else if (SC == SC_Register) {
7926 // Global Named register
7927 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7928 const auto &TI = Context.getTargetInfo();
7929 bool HasSizeMismatch;
7930
7931 if (!TI.isValidGCCRegisterName(Label))
7932 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7933 else if (!TI.validateGlobalRegisterVariable(Label,
7935 HasSizeMismatch))
7936 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7937 else if (HasSizeMismatch)
7938 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7939 }
7940
7941 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7942 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7943 NewVD->setInvalidDecl(true);
7944 }
7945 }
7946
7947 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7948 /*IsLiteralLabel=*/true,
7949 SE->getStrTokenLoc(0)));
7950 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7951 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7953 if (I != ExtnameUndeclaredIdentifiers.end()) {
7954 if (isDeclExternC(NewVD)) {
7955 NewVD->addAttr(I->second);
7957 } else
7958 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7959 << /*Variable*/1 << NewVD;
7960 }
7961 }
7962
7963 // Find the shadowed declaration before filtering for scope.
7964 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7966 : nullptr;
7967
7968 // Don't consider existing declarations that are in a different
7969 // scope and are out-of-semantic-context declarations (if the new
7970 // declaration has linkage).
7972 D.getCXXScopeSpec().isNotEmpty() ||
7973 IsMemberSpecialization ||
7974 IsVariableTemplateSpecialization);
7975
7976 // Check whether the previous declaration is in the same block scope. This
7977 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7978 if (getLangOpts().CPlusPlus &&
7979 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7981 Previous.isSingleResult() && !Previous.isShadowed() &&
7982 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7983
7984 if (!getLangOpts().CPlusPlus) {
7985 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7986 } else {
7987 // If this is an explicit specialization of a static data member, check it.
7988 if (IsMemberSpecialization && !IsVariableTemplate &&
7989 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
7991 NewVD->setInvalidDecl();
7992
7993 // Merge the decl with the existing one if appropriate.
7994 if (!Previous.empty()) {
7995 if (Previous.isSingleResult() &&
7996 isa<FieldDecl>(Previous.getFoundDecl()) &&
7997 D.getCXXScopeSpec().isSet()) {
7998 // The user tried to define a non-static data member
7999 // out-of-line (C++ [dcl.meaning]p1).
8000 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8001 << D.getCXXScopeSpec().getRange();
8002 Previous.clear();
8003 NewVD->setInvalidDecl();
8004 }
8005 } else if (D.getCXXScopeSpec().isSet() &&
8006 !IsVariableTemplateSpecialization) {
8007 // No previous declaration in the qualifying scope.
8008 Diag(D.getIdentifierLoc(), diag::err_no_member)
8009 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8010 << D.getCXXScopeSpec().getRange();
8011 NewVD->setInvalidDecl();
8012 }
8013
8014 if (!IsPlaceholderVariable)
8015 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8016
8017 // CheckVariableDeclaration will set NewVD as invalid if something is in
8018 // error like WebAssembly tables being declared as arrays with a non-zero
8019 // size, but then parsing continues and emits further errors on that line.
8020 // To avoid that we check here if it happened and return nullptr.
8021 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8022 return nullptr;
8023
8024 if (NewTemplate) {
8025 VarTemplateDecl *PrevVarTemplate =
8026 NewVD->getPreviousDecl()
8028 : nullptr;
8029
8030 // Check the template parameter list of this declaration, possibly
8031 // merging in the template parameter list from the previous variable
8032 // template declaration.
8034 TemplateParams,
8035 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8036 : nullptr,
8037 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8038 DC->isDependentContext())
8040 : TPC_VarTemplate))
8041 NewVD->setInvalidDecl();
8042
8043 // If we are providing an explicit specialization of a static variable
8044 // template, make a note of that.
8045 if (PrevVarTemplate &&
8046 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8047 PrevVarTemplate->setMemberSpecialization();
8048 }
8049 }
8050
8051 // Diagnose shadowed variables iff this isn't a redeclaration.
8052 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8053 CheckShadow(NewVD, ShadowedDecl, Previous);
8054
8055 ProcessPragmaWeak(S, NewVD);
8056
8057 // If this is the first declaration of an extern C variable, update
8058 // the map of such variables.
8059 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8060 isIncompleteDeclExternC(*this, NewVD))
8062
8063 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8065 Decl *ManglingContextDecl;
8066 std::tie(MCtx, ManglingContextDecl) =
8068 if (MCtx) {
8070 NewVD, MCtx->getManglingNumber(
8071 NewVD, getMSManglingNumber(getLangOpts(), S)));
8073 }
8074 }
8075
8076 // Special handling of variable named 'main'.
8077 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8078 // C++ [basic.start.main]p3:
8079 // A program that declares
8080 // - a variable main at global scope, or
8081 // - an entity named main with C language linkage (in any namespace)
8082 // is ill-formed
8083 if (getLangOpts().CPlusPlus)
8084 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8085 << NewVD->isExternC();
8086
8087 // In C, and external-linkage variable named main results in undefined
8088 // behavior.
8089 else if (NewVD->hasExternalFormalLinkage())
8090 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8091 }
8092
8093 if (D.isRedeclaration() && !Previous.empty()) {
8094 NamedDecl *Prev = Previous.getRepresentativeDecl();
8095 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8096 D.isFunctionDefinition());
8097 }
8098
8099 if (NewTemplate) {
8100 if (NewVD->isInvalidDecl())
8101 NewTemplate->setInvalidDecl();
8102 ActOnDocumentableDecl(NewTemplate);
8103 return NewTemplate;
8104 }
8105
8106 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8108
8110
8111 return NewVD;
8112}
8113
8114/// Enum describing the %select options in diag::warn_decl_shadow.
8124
8125/// Determine what kind of declaration we're shadowing.
8127 const DeclContext *OldDC) {
8128 if (isa<TypeAliasDecl>(ShadowedDecl))
8129 return SDK_Using;
8130 else if (isa<TypedefDecl>(ShadowedDecl))
8131 return SDK_Typedef;
8132 else if (isa<BindingDecl>(ShadowedDecl))
8133 return SDK_StructuredBinding;
8134 else if (isa<RecordDecl>(OldDC))
8135 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8136
8137 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8138}
8139
8140/// Return the location of the capture if the given lambda captures the given
8141/// variable \p VD, or an invalid source location otherwise.
8143 const VarDecl *VD) {
8144 for (const Capture &Capture : LSI->Captures) {
8146 return Capture.getLocation();
8147 }
8148 return SourceLocation();
8149}
8150
8152 const LookupResult &R) {
8153 // Only diagnose if we're shadowing an unambiguous field or variable.
8155 return false;
8156
8157 // Return false if warning is ignored.
8158 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8159}
8160
8162 const LookupResult &R) {
8164 return nullptr;
8165
8166 // Don't diagnose declarations at file scope.
8167 if (D->hasGlobalStorage() && !D->isStaticLocal())
8168 return nullptr;
8169
8170 NamedDecl *ShadowedDecl = R.getFoundDecl();
8171 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8172 : nullptr;
8173}
8174
8176 const LookupResult &R) {
8177 // Don't warn if typedef declaration is part of a class
8178 if (D->getDeclContext()->isRecord())
8179 return nullptr;
8180
8182 return nullptr;
8183
8184 NamedDecl *ShadowedDecl = R.getFoundDecl();
8185 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8186}
8187
8189 const LookupResult &R) {
8191 return nullptr;
8192
8193 NamedDecl *ShadowedDecl = R.getFoundDecl();
8194 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8195 : nullptr;
8196}
8197
8199 const LookupResult &R) {
8200 DeclContext *NewDC = D->getDeclContext();
8201
8202 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8203 // Fields are not shadowed by variables in C++ static methods.
8204 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8205 if (MD->isStatic())
8206 return;
8207
8208 // Fields shadowed by constructor parameters are a special case. Usually
8209 // the constructor initializes the field with the parameter.
8210 if (isa<CXXConstructorDecl>(NewDC))
8211 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8212 // Remember that this was shadowed so we can either warn about its
8213 // modification or its existence depending on warning settings.
8214 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8215 return;
8216 }
8217 }
8218
8219 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8220 if (shadowedVar->isExternC()) {
8221 // For shadowing external vars, make sure that we point to the global
8222 // declaration, not a locally scoped extern declaration.
8223 for (auto *I : shadowedVar->redecls())
8224 if (I->isFileVarDecl()) {
8225 ShadowedDecl = I;
8226 break;
8227 }
8228 }
8229
8230 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8231
8232 unsigned WarningDiag = diag::warn_decl_shadow;
8233 SourceLocation CaptureLoc;
8234 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8235 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8236 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8237 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8238 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8239 if (RD->getLambdaCaptureDefault() == LCD_None) {
8240 // Try to avoid warnings for lambdas with an explicit capture
8241 // list. Warn only when the lambda captures the shadowed decl
8242 // explicitly.
8243 CaptureLoc = getCaptureLocation(LSI, VD);
8244 if (CaptureLoc.isInvalid())
8245 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8246 } else {
8247 // Remember that this was shadowed so we can avoid the warning if
8248 // the shadowed decl isn't captured and the warning settings allow
8249 // it.
8250 cast<LambdaScopeInfo>(getCurFunction())
8251 ->ShadowingDecls.push_back({D, VD});
8252 return;
8253 }
8254 }
8255 if (isa<FieldDecl>(ShadowedDecl)) {
8256 // If lambda can capture this, then emit default shadowing warning,
8257 // Otherwise it is not really a shadowing case since field is not
8258 // available in lambda's body.
8259 // At this point we don't know that lambda can capture this, so
8260 // remember that this was shadowed and delay until we know.
8261 cast<LambdaScopeInfo>(getCurFunction())
8262 ->ShadowingDecls.push_back({D, ShadowedDecl});
8263 return;
8264 }
8265 }
8266 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8267 VD && VD->hasLocalStorage()) {
8268 // A variable can't shadow a local variable in an enclosing scope, if
8269 // they are separated by a non-capturing declaration context.
8270 for (DeclContext *ParentDC = NewDC;
8271 ParentDC && !ParentDC->Equals(OldDC);
8272 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8273 // Only block literals, captured statements, and lambda expressions
8274 // can capture; other scopes don't.
8275 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8276 !isLambdaCallOperator(ParentDC)) {
8277 return;
8278 }
8279 }
8280 }
8281 }
8282 }
8283
8284 // Never warn about shadowing a placeholder variable.
8285 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8286 return;
8287
8288 // Only warn about certain kinds of shadowing for class members.
8289 if (NewDC && NewDC->isRecord()) {
8290 // In particular, don't warn about shadowing non-class members.
8291 if (!OldDC->isRecord())
8292 return;
8293
8294 // TODO: should we warn about static data members shadowing
8295 // static data members from base classes?
8296
8297 // TODO: don't diagnose for inaccessible shadowed members.
8298 // This is hard to do perfectly because we might friend the
8299 // shadowing context, but that's just a false negative.
8300 }
8301
8302
8303 DeclarationName Name = R.getLookupName();
8304
8305 // Emit warning and note.
8306 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8307 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8308 if (!CaptureLoc.isInvalid())
8309 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8310 << Name << /*explicitly*/ 1;
8311 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8312}
8313
8315 for (const auto &Shadow : LSI->ShadowingDecls) {
8316 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8317 // Try to avoid the warning when the shadowed decl isn't captured.
8318 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8319 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8320 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8321 Diag(Shadow.VD->getLocation(),
8322 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8323 : diag::warn_decl_shadow)
8324 << Shadow.VD->getDeclName()
8325 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8326 if (CaptureLoc.isValid())
8327 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8328 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8329 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8330 } else if (isa<FieldDecl>(ShadowedDecl)) {
8331 Diag(Shadow.VD->getLocation(),
8332 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8333 : diag::warn_decl_shadow_uncaptured_local)
8334 << Shadow.VD->getDeclName()
8335 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8336 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8337 }
8338 }
8339}
8340
8342 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8343 return;
8344
8345 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8347 RedeclarationKind::ForVisibleRedeclaration);
8348 LookupName(R, S);
8349 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8350 CheckShadow(D, ShadowedDecl, R);
8351}
8352
8353/// Check if 'E', which is an expression that is about to be modified, refers
8354/// to a constructor parameter that shadows a field.
8356 // Quickly ignore expressions that can't be shadowing ctor parameters.
8357 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8358 return;
8359 E = E->IgnoreParenImpCasts();
8360 auto *DRE = dyn_cast<DeclRefExpr>(E);
8361 if (!DRE)
8362 return;
8363 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8364 auto I = ShadowingDecls.find(D);
8365 if (I == ShadowingDecls.end())
8366 return;
8367 const NamedDecl *ShadowedDecl = I->second;
8368 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8369 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8370 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8371 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8372
8373 // Avoid issuing multiple warnings about the same decl.
8374 ShadowingDecls.erase(I);
8375}
8376
8377/// Check for conflict between this global or extern "C" declaration and
8378/// previous global or extern "C" declarations. This is only used in C++.
8379template<typename T>
8381 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8382 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8383 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8384
8385 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8386 // The common case: this global doesn't conflict with any extern "C"
8387 // declaration.
8388 return false;
8389 }
8390
8391 if (Prev) {
8392 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8393 // Both the old and new declarations have C language linkage. This is a
8394 // redeclaration.
8395 Previous.clear();
8396 Previous.addDecl(Prev);
8397 return true;
8398 }
8399
8400 // This is a global, non-extern "C" declaration, and there is a previous
8401 // non-global extern "C" declaration. Diagnose if this is a variable
8402 // declaration.
8403 if (!isa<VarDecl>(ND))
8404 return false;
8405 } else {
8406 // The declaration is extern "C". Check for any declaration in the
8407 // translation unit which might conflict.
8408 if (IsGlobal) {
8409 // We have already performed the lookup into the translation unit.
8410 IsGlobal = false;
8411 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8412 I != E; ++I) {
8413 if (isa<VarDecl>(*I)) {
8414 Prev = *I;
8415 break;
8416 }
8417 }
8418 } else {
8420 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8421 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8422 I != E; ++I) {
8423 if (isa<VarDecl>(*I)) {
8424 Prev = *I;
8425 break;
8426 }
8427 // FIXME: If we have any other entity with this name in global scope,
8428 // the declaration is ill-formed, but that is a defect: it breaks the
8429 // 'stat' hack, for instance. Only variables can have mangled name
8430 // clashes with extern "C" declarations, so only they deserve a
8431 // diagnostic.
8432 }
8433 }
8434
8435 if (!Prev)
8436 return false;
8437 }
8438
8439 // Use the first declaration's location to ensure we point at something which
8440 // is lexically inside an extern "C" linkage-spec.
8441 assert(Prev && "should have found a previous declaration to diagnose");
8442 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8443 Prev = FD->getFirstDecl();
8444 else
8445 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8446
8447 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8448 << IsGlobal << ND;
8449 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8450 << IsGlobal;
8451 return false;
8452}
8453
8454/// Apply special rules for handling extern "C" declarations. Returns \c true
8455/// if we have found that this is a redeclaration of some prior entity.
8456///
8457/// Per C++ [dcl.link]p6:
8458/// Two declarations [for a function or variable] with C language linkage
8459/// with the same name that appear in different scopes refer to the same
8460/// [entity]. An entity with C language linkage shall not be declared with
8461/// the same name as an entity in global scope.
8462template<typename T>
8465 if (!S.getLangOpts().CPlusPlus) {
8466 // In C, when declaring a global variable, look for a corresponding 'extern'
8467 // variable declared in function scope. We don't need this in C++, because
8468 // we find local extern decls in the surrounding file-scope DeclContext.
8469 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8470 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8471 Previous.clear();
8472 Previous.addDecl(Prev);
8473 return true;
8474 }
8475 }
8476 return false;
8477 }
8478
8479 // A declaration in the translation unit can conflict with an extern "C"
8480 // declaration.
8481 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8482 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8483
8484 // An extern "C" declaration can conflict with a declaration in the
8485 // translation unit or can be a redeclaration of an extern "C" declaration
8486 // in another scope.
8487 if (isIncompleteDeclExternC(S,ND))
8488 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8489
8490 // Neither global nor extern "C": nothing to do.
8491 return false;
8492}
8493
8494static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8495 QualType T) {
8496 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8497 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8498 // any of its members, even recursively, shall not have an atomic type, or a
8499 // variably modified type, or a type that is volatile or restrict qualified.
8500 if (CanonT->isVariablyModifiedType()) {
8501 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8502 return true;
8503 }
8504
8505 // Arrays are qualified by their element type, so get the base type (this
8506 // works on non-arrays as well).
8507 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8508
8509 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8510 CanonT.isRestrictQualified()) {
8511 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8512 return true;
8513 }
8514
8515 if (CanonT->isRecordType()) {
8516 const RecordDecl *RD = CanonT->getAsRecordDecl();
8517 if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8518 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8519 }))
8520 return true;
8521 }
8522
8523 return false;
8524}
8525
8527 // If the decl is already known invalid, don't check it.
8528 if (NewVD->isInvalidDecl())
8529 return;
8530
8531 QualType T = NewVD->getType();
8532
8533 // Defer checking an 'auto' type until its initializer is attached.
8534 if (T->isUndeducedType())
8535 return;
8536
8537 if (NewVD->hasAttrs())
8539
8540 if (T->isObjCObjectType()) {
8541 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8542 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8544 NewVD->setType(T);
8545 }
8546
8547 // Emit an error if an address space was applied to decl with local storage.
8548 // This includes arrays of objects with address space qualifiers, but not
8549 // automatic variables that point to other address spaces.
8550 // ISO/IEC TR 18037 S5.1.2
8551 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8552 T.getAddressSpace() != LangAS::Default) {
8553 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8554 NewVD->setInvalidDecl();
8555 return;
8556 }
8557
8558 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8559 // scope.
8560 if (getLangOpts().OpenCLVersion == 120 &&
8561 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8562 getLangOpts()) &&
8563 NewVD->isStaticLocal()) {
8564 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8565 NewVD->setInvalidDecl();
8566 return;
8567 }
8568
8569 if (getLangOpts().OpenCL) {
8570 if (!diagnoseOpenCLTypes(*this, NewVD))
8571 return;
8572
8573 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8574 if (NewVD->hasAttr<BlocksAttr>()) {
8575 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8576 return;
8577 }
8578
8579 if (T->isBlockPointerType()) {
8580 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8581 // can't use 'extern' storage class.
8582 if (!T.isConstQualified()) {
8583 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8584 << 0 /*const*/;
8585 NewVD->setInvalidDecl();
8586 return;
8587 }
8588 if (NewVD->hasExternalStorage()) {
8589 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8590 NewVD->setInvalidDecl();
8591 return;
8592 }
8593 }
8594
8595 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8596 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8597 NewVD->hasExternalStorage()) {
8598 if (!T->isSamplerT() && !T->isDependentType() &&
8599 !(T.getAddressSpace() == LangAS::opencl_constant ||
8600 (T.getAddressSpace() == LangAS::opencl_global &&
8601 getOpenCLOptions().areProgramScopeVariablesSupported(
8602 getLangOpts())))) {
8603 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8604 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8605 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8606 << Scope << "global or constant";
8607 else
8608 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8609 << Scope << "constant";
8610 NewVD->setInvalidDecl();
8611 return;
8612 }
8613 } else {
8614 if (T.getAddressSpace() == LangAS::opencl_global) {
8615 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8616 << 1 /*is any function*/ << "global";
8617 NewVD->setInvalidDecl();
8618 return;
8619 }
8620 if (T.getAddressSpace() == LangAS::opencl_constant ||
8621 T.getAddressSpace() == LangAS::opencl_local) {
8623 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8624 // in functions.
8625 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8626 if (T.getAddressSpace() == LangAS::opencl_constant)
8627 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8628 << 0 /*non-kernel only*/ << "constant";
8629 else
8630 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8631 << 0 /*non-kernel only*/ << "local";
8632 NewVD->setInvalidDecl();
8633 return;
8634 }
8635 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8636 // in the outermost scope of a kernel function.
8637 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8638 if (!getCurScope()->isFunctionScope()) {
8639 if (T.getAddressSpace() == LangAS::opencl_constant)
8640 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8641 << "constant";
8642 else
8643 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8644 << "local";
8645 NewVD->setInvalidDecl();
8646 return;
8647 }
8648 }
8649 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8650 // If we are parsing a template we didn't deduce an addr
8651 // space yet.
8652 T.getAddressSpace() != LangAS::Default) {
8653 // Do not allow other address spaces on automatic variable.
8654 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8655 NewVD->setInvalidDecl();
8656 return;
8657 }
8658 }
8659 }
8660
8661 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8662 && !NewVD->hasAttr<BlocksAttr>()) {
8663 if (getLangOpts().getGC() != LangOptions::NonGC)
8664 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8665 else {
8666 assert(!getLangOpts().ObjCAutoRefCount);
8667 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8668 }
8669 }
8670
8671 // WebAssembly tables must be static with a zero length and can't be
8672 // declared within functions.
8673 if (T->isWebAssemblyTableType()) {
8674 if (getCurScope()->getParent()) { // Parent is null at top-level
8675 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8676 NewVD->setInvalidDecl();
8677 return;
8678 }
8679 if (NewVD->getStorageClass() != SC_Static) {
8680 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8681 NewVD->setInvalidDecl();
8682 return;
8683 }
8684 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8685 if (!ATy || ATy->getZExtSize() != 0) {
8686 Diag(NewVD->getLocation(),
8687 diag::err_typecheck_wasm_table_must_have_zero_length);
8688 NewVD->setInvalidDecl();
8689 return;
8690 }
8691 }
8692
8693 bool isVM = T->isVariablyModifiedType();
8694 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8695 NewVD->hasAttr<BlocksAttr>())
8697
8698 if ((isVM && NewVD->hasLinkage()) ||
8699 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8700 bool SizeIsNegative;
8701 llvm::APSInt Oversized;
8703 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8704 QualType FixedT;
8705 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8706 FixedT = FixedTInfo->getType();
8707 else if (FixedTInfo) {
8708 // Type and type-as-written are canonically different. We need to fix up
8709 // both types separately.
8710 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8711 Oversized);
8712 }
8713 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8715 // FIXME: This won't give the correct result for
8716 // int a[10][n];
8717 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8718
8719 if (NewVD->isFileVarDecl())
8720 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8721 << SizeRange;
8722 else if (NewVD->isStaticLocal())
8723 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8724 << SizeRange;
8725 else
8726 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8727 << SizeRange;
8728 NewVD->setInvalidDecl();
8729 return;
8730 }
8731
8732 if (!FixedTInfo) {
8733 if (NewVD->isFileVarDecl())
8734 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8735 else
8736 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8737 NewVD->setInvalidDecl();
8738 return;
8739 }
8740
8741 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8742 NewVD->setType(FixedT);
8743 NewVD->setTypeSourceInfo(FixedTInfo);
8744 }
8745
8746 if (T->isVoidType()) {
8747 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8748 // of objects and functions.
8750 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8751 << T;
8752 NewVD->setInvalidDecl();
8753 return;
8754 }
8755 }
8756
8757 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8758 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8759 NewVD->setInvalidDecl();
8760 return;
8761 }
8762
8763 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8764 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
8765 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8766 NewVD->setInvalidDecl();
8767 return;
8768 }
8769
8770 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8771 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8772 NewVD->setInvalidDecl();
8773 return;
8774 }
8775
8776 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8777 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8778 NewVD->setInvalidDecl();
8779 return;
8780 }
8781
8782 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
8783 !T->isDependentType() &&
8785 diag::err_constexpr_var_non_literal)) {
8786 NewVD->setInvalidDecl();
8787 return;
8788 }
8789
8790 // PPC MMA non-pointer types are not allowed as non-local variable types.
8791 if (Context.getTargetInfo().getTriple().isPPC64() &&
8792 !NewVD->isLocalVarDecl() &&
8793 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
8794 NewVD->setInvalidDecl();
8795 return;
8796 }
8797
8798 // Check that SVE types are only used in functions with SVE available.
8799 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8800 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8801 llvm::StringMap<bool> CallerFeatureMap;
8802 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8803
8804 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
8805 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
8806 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8807 NewVD->setInvalidDecl();
8808 return;
8809 } else if (!IsArmStreamingFunction(FD,
8810 /*IncludeLocallyStreaming=*/true)) {
8811 Diag(NewVD->getLocation(),
8812 diag::err_sve_vector_in_non_streaming_function)
8813 << T;
8814 NewVD->setInvalidDecl();
8815 return;
8816 }
8817 }
8818 }
8819
8820 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8821 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8822 llvm::StringMap<bool> CallerFeatureMap;
8823 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8824 RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
8825 CallerFeatureMap);
8826 }
8827}
8828
8831
8832 // If the decl is already known invalid, don't check it.
8833 if (NewVD->isInvalidDecl())
8834 return false;
8835
8836 // If we did not find anything by this name, look for a non-visible
8837 // extern "C" declaration with the same name.
8838 if (Previous.empty() &&
8840 Previous.setShadowed();
8841
8842 if (!Previous.empty()) {
8843 MergeVarDecl(NewVD, Previous);
8844 return true;
8845 }
8846 return false;
8847}
8848
8851
8852 // Look for methods in base classes that this method might override.
8853 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8854 /*DetectVirtual=*/false);
8855 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8856 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8857 DeclarationName Name = MD->getDeclName();
8858
8859 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8860 // We really want to find the base class destructor here.
8861 QualType T = Context.getTypeDeclType(BaseRecord);
8864 }
8865
8866 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8867 CXXMethodDecl *BaseMD =
8868 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8869 if (!BaseMD || !BaseMD->isVirtual() ||
8870 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8871 /*ConsiderCudaAttrs=*/true))
8872 continue;
8873 if (!CheckExplicitObjectOverride(MD, BaseMD))
8874 continue;
8875 if (Overridden.insert(BaseMD).second) {
8876 MD->addOverriddenMethod(BaseMD);
8881 }
8882
8883 // A method can only override one function from each base class. We
8884 // don't track indirectly overridden methods from bases of bases.
8885 return true;
8886 }
8887
8888 return false;
8889 };
8890
8891 DC->lookupInBases(VisitBase, Paths);
8892 return !Overridden.empty();
8893}
8894
8895namespace {
8896 // Struct for holding all of the extra arguments needed by
8897 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8898 struct ActOnFDArgs {
8899 Scope *S;
8900 Declarator &D;
8901 MultiTemplateParamsArg TemplateParamLists;
8902 bool AddToScope;
8903 };
8904} // end anonymous namespace
8905
8906namespace {
8907
8908// Callback to only accept typo corrections that have a non-zero edit distance.
8909// Also only accept corrections that have the same parent decl.
8910class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8911 public:
8912 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8914 : Context(Context), OriginalFD(TypoFD),
8915 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8916
8917 bool ValidateCandidate(const TypoCorrection &candidate) override {
8918 if (candidate.getEditDistance() == 0)
8919 return false;
8920
8921 SmallVector<unsigned, 1> MismatchedParams;
8922 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8923 CDeclEnd = candidate.end();
8924 CDecl != CDeclEnd; ++CDecl) {
8925 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8926
8927 if (FD && !FD->hasBody() &&
8928 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8929 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8930 CXXRecordDecl *Parent = MD->getParent();
8931 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8932 return true;
8933 } else if (!ExpectedParent) {
8934 return true;
8935 }
8936 }
8937 }
8938
8939 return false;
8940 }
8941
8942 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8943 return std::make_unique<DifferentNameValidatorCCC>(*this);
8944 }
8945
8946 private:
8947 ASTContext &Context;
8948 FunctionDecl *OriginalFD;
8949 CXXRecordDecl *ExpectedParent;
8950};
8951
8952} // end anonymous namespace
8953
8956}
8957
8958/// Generate diagnostics for an invalid function redeclaration.
8959///
8960/// This routine handles generating the diagnostic messages for an invalid
8961/// function redeclaration, including finding possible similar declarations
8962/// or performing typo correction if there are no previous declarations with
8963/// the same name.
8964///
8965/// Returns a NamedDecl iff typo correction was performed and substituting in
8966/// the new declaration name does not cause new errors.
8968 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8969 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8970 DeclarationName Name = NewFD->getDeclName();
8971 DeclContext *NewDC = NewFD->getDeclContext();
8972 SmallVector<unsigned, 1> MismatchedParams;
8974 TypoCorrection Correction;
8975 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8976 unsigned DiagMsg =
8977 IsLocalFriend ? diag::err_no_matching_local_friend :
8978 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8979 diag::err_member_decl_does_not_match;
8980 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8981 IsLocalFriend ? Sema::LookupLocalFriendName
8983 RedeclarationKind::ForVisibleRedeclaration);
8984
8985 NewFD->setInvalidDecl();
8986 if (IsLocalFriend)
8987 SemaRef.LookupName(Prev, S);
8988 else
8989 SemaRef.LookupQualifiedName(Prev, NewDC);
8990 assert(!Prev.isAmbiguous() &&
8991 "Cannot have an ambiguity in previous-declaration lookup");
8992 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8993 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8994 MD ? MD->getParent() : nullptr);
8995 if (!Prev.empty()) {
8996 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8997 Func != FuncEnd; ++Func) {
8998 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8999 if (FD &&
9000 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9001 // Add 1 to the index so that 0 can mean the mismatch didn't
9002 // involve a parameter
9003 unsigned ParamNum =
9004 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9005 NearMatches.push_back(std::make_pair(FD, ParamNum));
9006 }
9007 }
9008 // If the qualified name lookup yielded nothing, try typo correction
9009 } else if ((Correction = SemaRef.CorrectTypo(
9010 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9011 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9012 IsLocalFriend ? nullptr : NewDC))) {
9013 // Set up everything for the call to ActOnFunctionDeclarator
9014 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9015 ExtraArgs.D.getIdentifierLoc());
9016 Previous.clear();
9017 Previous.setLookupName(Correction.getCorrection());
9018 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9019 CDeclEnd = Correction.end();
9020 CDecl != CDeclEnd; ++CDecl) {
9021 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9022 if (FD && !FD->hasBody() &&
9023 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9024 Previous.addDecl(FD);
9025 }
9026 }
9027 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9028
9030 // Retry building the function declaration with the new previous
9031 // declarations, and with errors suppressed.
9032 {
9033 // Trap errors.
9034 Sema::SFINAETrap Trap(SemaRef);
9035
9036 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9037 // pieces need to verify the typo-corrected C++ declaration and hopefully
9038 // eliminate the need for the parameter pack ExtraArgs.
9040 ExtraArgs.S, ExtraArgs.D,
9041 Correction.getCorrectionDecl()->getDeclContext(),
9042 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9043 ExtraArgs.AddToScope);
9044
9045 if (Trap.hasErrorOccurred())
9046 Result = nullptr;
9047 }
9048
9049 if (Result) {
9050 // Determine which correction we picked.
9051 Decl *Canonical = Result->getCanonicalDecl();
9052 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9053 I != E; ++I)
9054 if ((*I)->getCanonicalDecl() == Canonical)
9055 Correction.setCorrectionDecl(*I);
9056
9057 // Let Sema know about the correction.
9059 SemaRef.diagnoseTypo(
9060 Correction,
9061 SemaRef.PDiag(IsLocalFriend
9062 ? diag::err_no_matching_local_friend_suggest
9063 : diag::err_member_decl_does_not_match_suggest)
9064 << Name << NewDC << IsDefinition);
9065 return Result;
9066 }
9067
9068 // Pretend the typo correction never occurred
9069 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9070 ExtraArgs.D.getIdentifierLoc());
9071 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9072 Previous.clear();
9073 Previous.setLookupName(Name);
9074 }
9075
9076 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9077 << Name << NewDC << IsDefinition << NewFD->getLocation();
9078
9079 bool NewFDisConst = false;
9080 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9081 NewFDisConst = NewMD->isConst();
9082
9083 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9084 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9085 NearMatch != NearMatchEnd; ++NearMatch) {
9086 FunctionDecl *FD = NearMatch->first;
9087 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9088 bool FDisConst = MD && MD->isConst();
9089 bool IsMember = MD || !IsLocalFriend;
9090
9091 // FIXME: These notes are poorly worded for the local friend case.
9092 if (unsigned Idx = NearMatch->second) {
9093 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9095 if (Loc.isInvalid()) Loc = FD->getLocation();
9096 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9097 : diag::note_local_decl_close_param_match)
9098 << Idx << FDParam->getType()
9099 << NewFD->getParamDecl(Idx - 1)->getType();
9100 } else if (FDisConst != NewFDisConst) {
9101 auto DB = SemaRef.Diag(FD->getLocation(),
9102 diag::note_member_def_close_const_match)
9103 << NewFDisConst << FD->getSourceRange().getEnd();
9104 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9105 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9106 " const");
9107 else if (FTI.hasMethodTypeQualifiers() &&
9108 FTI.getConstQualifierLoc().isValid())
9109 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9110 } else {
9111 SemaRef.Diag(FD->getLocation(),
9112 IsMember ? diag::note_member_def_close_match
9113 : diag::note_local_decl_close_match);
9114 }
9115 }
9116 return nullptr;
9117}
9118
9120 switch (D.getDeclSpec().getStorageClassSpec()) {
9121 default: llvm_unreachable("Unknown storage class!");
9122 case DeclSpec::SCS_auto:
9125 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9126 diag::err_typecheck_sclass_func);
9127 D.getMutableDeclSpec().ClearStorageClassSpecs();
9128 D.setInvalidType();
9129 break;
9130 case DeclSpec::SCS_unspecified: break;
9132 if (D.getDeclSpec().isExternInLinkageSpec())
9133 return SC_None;
9134 return SC_Extern;
9135 case DeclSpec::SCS_static: {
9137 // C99 6.7.1p5:
9138 // The declaration of an identifier for a function that has
9139 // block scope shall have no explicit storage-class specifier
9140 // other than extern
9141 // See also (C++ [dcl.stc]p4).
9142 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9143 diag::err_static_block_func);
9144 break;
9145 } else
9146 return SC_Static;
9147 }
9149 }
9150
9151 // No explicit storage class has already been returned
9152 return SC_None;
9153}
9154
9156 DeclContext *DC, QualType &R,
9157 TypeSourceInfo *TInfo,
9158 StorageClass SC,
9159 bool &IsVirtualOkay) {
9160 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9161 DeclarationName Name = NameInfo.getName();
9162
9163 FunctionDecl *NewFD = nullptr;
9164 bool isInline = D.getDeclSpec().isInlineSpecified();
9165
9166 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9167 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9168 (SemaRef.getLangOpts().C23 &&
9169 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9170
9171 if (SemaRef.getLangOpts().C23)
9172 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9173 diag::err_c23_constexpr_not_variable);
9174 else
9175 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9176 diag::err_constexpr_wrong_decl_kind)
9177 << static_cast<int>(ConstexprKind);
9178 ConstexprKind = ConstexprSpecKind::Unspecified;
9179 D.getMutableDeclSpec().ClearConstexprSpec();
9180 }
9181
9182 if (!SemaRef.getLangOpts().CPlusPlus) {
9183 // Determine whether the function was written with a prototype. This is
9184 // true when:
9185 // - there is a prototype in the declarator, or
9186 // - the type R of the function is some kind of typedef or other non-
9187 // attributed reference to a type name (which eventually refers to a
9188 // function type). Note, we can't always look at the adjusted type to
9189 // check this case because attributes may cause a non-function
9190 // declarator to still have a function type. e.g.,
9191 // typedef void func(int a);
9192 // __attribute__((noreturn)) func other_func; // This has a prototype
9193 bool HasPrototype =
9194 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9195 (D.getDeclSpec().isTypeRep() &&
9196 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9197 ->isFunctionProtoType()) ||
9199 assert(
9200 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9201 "Strict prototypes are required");
9202
9203 NewFD = FunctionDecl::Create(
9204 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9205 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9207 /*TrailingRequiresClause=*/nullptr);
9208 if (D.isInvalidType())
9209 NewFD->setInvalidDecl();
9210
9211 return NewFD;
9212 }
9213
9214 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9215 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9216
9217 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9218
9219 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9220 // This is a C++ constructor declaration.
9221 assert(DC->isRecord() &&
9222 "Constructors can only be declared in a member context");
9223
9224 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9226 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9228 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9229 InheritedConstructor(), TrailingRequiresClause);
9230
9231 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9232 // This is a C++ destructor declaration.
9233 if (DC->isRecord()) {
9234 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9235 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9237 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9238 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9239 /*isImplicitlyDeclared=*/false, ConstexprKind,
9240 TrailingRequiresClause);
9241 // User defined destructors start as not selected if the class definition is still
9242 // not done.
9243 if (Record->isBeingDefined())
9244 NewDD->setIneligibleOrNotSelected(true);
9245
9246 // If the destructor needs an implicit exception specification, set it
9247 // now. FIXME: It'd be nice to be able to create the right type to start
9248 // with, but the type needs to reference the destructor declaration.
9249 if (SemaRef.getLangOpts().CPlusPlus11)
9250 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9251
9252 IsVirtualOkay = true;
9253 return NewDD;
9254
9255 } else {
9256 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9257 D.setInvalidType();
9258
9259 // Create a FunctionDecl to satisfy the function definition parsing
9260 // code path.
9261 return FunctionDecl::Create(
9262 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9263 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9264 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9265 }
9266
9267 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9268 if (!DC->isRecord()) {
9269 SemaRef.Diag(D.getIdentifierLoc(),
9270 diag::err_conv_function_not_member);
9271 return nullptr;
9272 }
9273
9274 SemaRef.CheckConversionDeclarator(D, R, SC);
9275 if (D.isInvalidType())
9276 return nullptr;
9277
9278 IsVirtualOkay = true;
9280 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9281 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9282 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9283 TrailingRequiresClause);
9284
9285 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9286 if (TrailingRequiresClause)
9287 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9288 diag::err_trailing_requires_clause_on_deduction_guide)
9289 << TrailingRequiresClause->getSourceRange();
9290 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9291 return nullptr;
9292 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9293 ExplicitSpecifier, NameInfo, R, TInfo,
9294 D.getEndLoc());
9295 } else if (DC->isRecord()) {
9296 // If the name of the function is the same as the name of the record,
9297 // then this must be an invalid constructor that has a return type.
9298 // (The parser checks for a return type and makes the declarator a
9299 // constructor if it has no return type).
9300 if (Name.getAsIdentifierInfo() &&
9301 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9302 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9303 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9304 << SourceRange(D.getIdentifierLoc());
9305 return nullptr;
9306 }
9307
9308 // This is a C++ method declaration.
9310 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9311 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9312 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9313 IsVirtualOkay = !Ret->isStatic();
9314 return Ret;
9315 } else {
9316 bool isFriend =
9317 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9318 if (!isFriend && SemaRef.CurContext->isRecord())
9319 return nullptr;
9320
9321 // Determine whether the function was written with a
9322 // prototype. This true when:
9323 // - we're in C++ (where every function has a prototype),
9324 return FunctionDecl::Create(
9325 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9326 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9327 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9328 }
9329}
9330
9339
9341 // Size dependent types are just typedefs to normal integer types
9342 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9343 // integers other than by their names.
9344 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9345
9346 // Remove typedefs one by one until we reach a typedef
9347 // for a size dependent type.
9348 QualType DesugaredTy = Ty;
9349 do {
9350 ArrayRef<StringRef> Names(SizeTypeNames);
9351 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9352 if (Names.end() != Match)
9353 return true;
9354
9355 Ty = DesugaredTy;
9356 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9357 } while (DesugaredTy != Ty);
9358
9359 return false;
9360}
9361
9363 if (PT->isDependentType())
9364 return InvalidKernelParam;
9365
9366 if (PT->isPointerOrReferenceType()) {
9367 QualType PointeeType = PT->getPointeeType();
9368 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9369 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9370 PointeeType.getAddressSpace() == LangAS::Default)
9372
9373 if (PointeeType->isPointerType()) {
9374 // This is a pointer to pointer parameter.
9375 // Recursively check inner type.
9376 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9377 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9378 ParamKind == InvalidKernelParam)
9379 return ParamKind;
9380
9381 // OpenCL v3.0 s6.11.a:
9382 // A restriction to pass pointers to pointers only applies to OpenCL C
9383 // v1.2 or below.
9385 return ValidKernelParam;
9386
9387 return PtrPtrKernelParam;
9388 }
9389
9390 // C++ for OpenCL v1.0 s2.4:
9391 // Moreover the types used in parameters of the kernel functions must be:
9392 // Standard layout types for pointer parameters. The same applies to
9393 // reference if an implementation supports them in kernel parameters.
9394 if (S.getLangOpts().OpenCLCPlusPlus &&
9396 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9397 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9398 bool IsStandardLayoutType = true;
9399 if (CXXRec) {
9400 // If template type is not ODR-used its definition is only available
9401 // in the template definition not its instantiation.
9402 // FIXME: This logic doesn't work for types that depend on template
9403 // parameter (PR58590).
9404 if (!CXXRec->hasDefinition())
9405 CXXRec = CXXRec->getTemplateInstantiationPattern();
9406 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9407 IsStandardLayoutType = false;
9408 }
9409 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9410 !IsStandardLayoutType)
9411 return InvalidKernelParam;
9412 }
9413
9414 // OpenCL v1.2 s6.9.p:
9415 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9417 return ValidKernelParam;
9418
9419 return PtrKernelParam;
9420 }
9421
9422 // OpenCL v1.2 s6.9.k:
9423 // Arguments to kernel functions in a program cannot be declared with the
9424 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9425 // uintptr_t or a struct and/or union that contain fields declared to be one
9426 // of these built-in scalar types.
9428 return InvalidKernelParam;
9429
9430 if (PT->isImageType())
9431 return PtrKernelParam;
9432
9433 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9434 return InvalidKernelParam;
9435
9436 // OpenCL extension spec v1.2 s9.5:
9437 // This extension adds support for half scalar and vector types as built-in
9438 // types that can be used for arithmetic operations, conversions etc.
9439 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9440 PT->isHalfType())
9441 return InvalidKernelParam;
9442
9443 // Look into an array argument to check if it has a forbidden type.
9444 if (PT->isArrayType()) {
9445 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9446 // Call ourself to check an underlying type of an array. Since the
9447 // getPointeeOrArrayElementType returns an innermost type which is not an
9448 // array, this recursive call only happens once.
9449 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9450 }
9451
9452 // C++ for OpenCL v1.0 s2.4:
9453 // Moreover the types used in parameters of the kernel functions must be:
9454 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9455 // types) for parameters passed by value;
9456 if (S.getLangOpts().OpenCLCPlusPlus &&
9458 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9459 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9460 return InvalidKernelParam;
9461
9462 if (PT->isRecordType())
9463 return RecordKernelParam;
9464
9465 return ValidKernelParam;
9466}
9467
9469 Sema &S,
9470 Declarator &D,
9471 ParmVarDecl *Param,
9472 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9473 QualType PT = Param->getType();
9474
9475 // Cache the valid types we encounter to avoid rechecking structs that are
9476 // used again
9477 if (ValidTypes.count(PT.getTypePtr()))
9478 return;
9479
9480 switch (getOpenCLKernelParameterType(S, PT)) {
9481 case PtrPtrKernelParam:
9482 // OpenCL v3.0 s6.11.a:
9483 // A kernel function argument cannot be declared as a pointer to a pointer
9484 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9485 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9486 D.setInvalidType();
9487 return;
9488
9490 // OpenCL v1.0 s6.5:
9491 // __kernel function arguments declared to be a pointer of a type can point
9492 // to one of the following address spaces only : __global, __local or
9493 // __constant.
9494 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9495 D.setInvalidType();
9496 return;
9497
9498 // OpenCL v1.2 s6.9.k:
9499 // Arguments to kernel functions in a program cannot be declared with the
9500 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9501 // uintptr_t or a struct and/or union that contain fields declared to be
9502 // one of these built-in scalar types.
9503
9504 case InvalidKernelParam:
9505 // OpenCL v1.2 s6.8 n:
9506 // A kernel function argument cannot be declared
9507 // of event_t type.
9508 // Do not diagnose half type since it is diagnosed as invalid argument
9509 // type for any function elsewhere.
9510 if (!PT->isHalfType()) {
9511 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9512
9513 // Explain what typedefs are involved.
9514 const TypedefType *Typedef = nullptr;
9515 while ((Typedef = PT->getAs<TypedefType>())) {
9516 SourceLocation Loc = Typedef->getDecl()->getLocation();
9517 // SourceLocation may be invalid for a built-in type.
9518 if (Loc.isValid())
9519 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9520 PT = Typedef->desugar();
9521 }
9522 }
9523
9524 D.setInvalidType();
9525 return;
9526
9527 case PtrKernelParam:
9528 case ValidKernelParam:
9529 ValidTypes.insert(PT.getTypePtr());
9530 return;
9531
9532 case RecordKernelParam:
9533 break;
9534 }
9535
9536 // Track nested structs we will inspect
9538
9539 // Track where we are in the nested structs. Items will migrate from
9540 // VisitStack to HistoryStack as we do the DFS for bad field.
9542 HistoryStack.push_back(nullptr);
9543
9544 // At this point we already handled everything except of a RecordType or
9545 // an ArrayType of a RecordType.
9546 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9547 const RecordType *RecTy =
9549 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9550
9551 VisitStack.push_back(RecTy->getDecl());
9552 assert(VisitStack.back() && "First decl null?");
9553
9554 do {
9555 const Decl *Next = VisitStack.pop_back_val();
9556 if (!Next) {
9557 assert(!HistoryStack.empty());
9558 // Found a marker, we have gone up a level
9559 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9560 ValidTypes.insert(Hist->getType().getTypePtr());
9561
9562 continue;
9563 }
9564
9565 // Adds everything except the original parameter declaration (which is not a
9566 // field itself) to the history stack.
9567 const RecordDecl *RD;
9568 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9569 HistoryStack.push_back(Field);
9570
9571 QualType FieldTy = Field->getType();
9572 // Other field types (known to be valid or invalid) are handled while we
9573 // walk around RecordDecl::fields().
9574 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9575 "Unexpected type.");
9576 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9577
9578 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9579 } else {
9580 RD = cast<RecordDecl>(Next);
9581 }
9582
9583 // Add a null marker so we know when we've gone back up a level
9584 VisitStack.push_back(nullptr);
9585
9586 for (const auto *FD : RD->fields()) {
9587 QualType QT = FD->getType();
9588
9589 if (ValidTypes.count(QT.getTypePtr()))
9590 continue;
9591
9593 if (ParamType == ValidKernelParam)
9594 continue;
9595
9596 if (ParamType == RecordKernelParam) {
9597 VisitStack.push_back(FD);
9598 continue;
9599 }
9600
9601 // OpenCL v1.2 s6.9.p:
9602 // Arguments to kernel functions that are declared to be a struct or union
9603 // do not allow OpenCL objects to be passed as elements of the struct or
9604 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9605 // of SVM.
9606 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9607 ParamType == InvalidAddrSpacePtrKernelParam) {
9608 S.Diag(Param->getLocation(),
9609 diag::err_record_with_pointers_kernel_param)
9610 << PT->isUnionType()
9611 << PT;
9612 } else {
9613 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9614 }
9615
9616 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9617 << OrigRecDecl->getDeclName();
9618
9619 // We have an error, now let's go back up through history and show where
9620 // the offending field came from
9622 I = HistoryStack.begin() + 1,
9623 E = HistoryStack.end();
9624 I != E; ++I) {
9625 const FieldDecl *OuterField = *I;
9626 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9627 << OuterField->getType();
9628 }
9629
9630 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9631 << QT->isPointerType()
9632 << QT;
9633 D.setInvalidType();
9634 return;
9635 }
9636 } while (!VisitStack.empty());
9637}
9638
9639/// Find the DeclContext in which a tag is implicitly declared if we see an
9640/// elaborated type specifier in the specified context, and lookup finds
9641/// nothing.
9643 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9644 DC = DC->getParent();
9645 return DC;
9646}
9647
9648/// Find the Scope in which a tag is implicitly declared if we see an
9649/// elaborated type specifier in the specified context, and lookup finds
9650/// nothing.
9651static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9652 while (S->isClassScope() ||
9653 (LangOpts.CPlusPlus &&
9654 S->isFunctionPrototypeScope()) ||
9655 ((S->getFlags() & Scope::DeclScope) == 0) ||
9656 (S->getEntity() && S->getEntity()->isTransparentContext()))
9657 S = S->getParent();
9658 return S;
9659}
9660
9661/// Determine whether a declaration matches a known function in namespace std.
9663 unsigned BuiltinID) {
9664 switch (BuiltinID) {
9665 case Builtin::BI__GetExceptionInfo:
9666 // No type checking whatsoever.
9667 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9668
9669 case Builtin::BIaddressof:
9670 case Builtin::BI__addressof:
9671 case Builtin::BIforward:
9672 case Builtin::BIforward_like:
9673 case Builtin::BImove:
9674 case Builtin::BImove_if_noexcept:
9675 case Builtin::BIas_const: {
9676 // Ensure that we don't treat the algorithm
9677 // OutputIt std::move(InputIt, InputIt, OutputIt)
9678 // as the builtin std::move.
9679 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9680 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9681 }
9682
9683 default:
9684 return false;
9685 }
9686}
9687
9688NamedDecl*
9691 MultiTemplateParamsArg TemplateParamListsRef,
9692 bool &AddToScope) {
9693 QualType R = TInfo->getType();
9694
9695 assert(R->isFunctionType());
9697 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9698
9699 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9700 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9701 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9702 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9703 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9704 TemplateParamLists.back() = Invented;
9705 else
9706 TemplateParamLists.push_back(Invented);
9707 }
9708
9709 // TODO: consider using NameInfo for diagnostic.
9711 DeclarationName Name = NameInfo.getName();
9713
9714 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9715 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9716 diag::err_invalid_thread)
9718
9719 if (D.isFirstDeclarationOfMember())
9721 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9722 D.isCtorOrDtor(), D.getIdentifierLoc());
9723
9724 bool isFriend = false;
9726 bool isMemberSpecialization = false;
9727 bool isFunctionTemplateSpecialization = false;
9728
9729 bool HasExplicitTemplateArgs = false;
9730 TemplateArgumentListInfo TemplateArgs;
9731
9732 bool isVirtualOkay = false;
9733
9734 DeclContext *OriginalDC = DC;
9735 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9736
9737 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9738 isVirtualOkay);
9739 if (!NewFD) return nullptr;
9740
9743
9744 // Set the lexical context. If this is a function-scope declaration, or has a
9745 // C++ scope specifier, or is the object of a friend declaration, the lexical
9746 // context will be different from the semantic context.
9748
9749 if (IsLocalExternDecl)
9750 NewFD->setLocalExternDecl();
9751
9752 if (getLangOpts().CPlusPlus) {
9753 // The rules for implicit inlines changed in C++20 for methods and friends
9754 // with an in-class definition (when such a definition is not attached to
9755 // the global module). User-specified 'inline' overrides this (set when
9756 // the function decl is created above).
9757 // FIXME: We need a better way to separate C++ standard and clang modules.
9758 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9759 !NewFD->getOwningModule() ||
9760 NewFD->isFromExplicitGlobalModule() ||
9762 bool isInline = D.getDeclSpec().isInlineSpecified();
9763 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9764 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9765 isFriend = D.getDeclSpec().isFriendSpecified();
9766 if (isFriend && !isInline && D.isFunctionDefinition()) {
9767 // Pre-C++20 [class.friend]p5
9768 // A function can be defined in a friend declaration of a
9769 // class . . . . Such a function is implicitly inline.
9770 // Post C++20 [class.friend]p7
9771 // Such a function is implicitly an inline function if it is attached
9772 // to the global module.
9773 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9774 }
9775
9776 // If this is a method defined in an __interface, and is not a constructor
9777 // or an overloaded operator, then set the pure flag (isVirtual will already
9778 // return true).
9779 if (const CXXRecordDecl *Parent =
9780 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9781 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9782 NewFD->setIsPureVirtual(true);
9783
9784 // C++ [class.union]p2
9785 // A union can have member functions, but not virtual functions.
9786 if (isVirtual && Parent->isUnion()) {
9787 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9788 NewFD->setInvalidDecl();
9789 }
9790 if ((Parent->isClass() || Parent->isStruct()) &&
9791 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9792 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9793 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9794 if (auto *Def = Parent->getDefinition())
9795 Def->setInitMethod(true);
9796 }
9797 }
9798
9799 SetNestedNameSpecifier(*this, NewFD, D);
9800 isMemberSpecialization = false;
9801 isFunctionTemplateSpecialization = false;
9802 if (D.isInvalidType())
9803 NewFD->setInvalidDecl();
9804
9805 // Match up the template parameter lists with the scope specifier, then
9806 // determine whether we have a template or a template specialization.
9807 bool Invalid = false;
9808 TemplateIdAnnotation *TemplateId =
9810 ? D.getName().TemplateId
9811 : nullptr;
9812 TemplateParameterList *TemplateParams =
9814 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9815 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
9816 isMemberSpecialization, Invalid);
9817 if (TemplateParams) {
9818 // Check that we can declare a template here.
9819 if (CheckTemplateDeclScope(S, TemplateParams))
9820 NewFD->setInvalidDecl();
9821
9822 if (TemplateParams->size() > 0) {
9823 // This is a function template
9824
9825 // A destructor cannot be a template.
9826 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9827 Diag(NewFD->getLocation(), diag::err_destructor_template);
9828 NewFD->setInvalidDecl();
9829 // Function template with explicit template arguments.
9830 } else if (TemplateId) {
9831 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9832 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9833 NewFD->setInvalidDecl();
9834 }
9835
9836 // If we're adding a template to a dependent context, we may need to
9837 // rebuilding some of the types used within the template parameter list,
9838 // now that we know what the current instantiation is.
9839 if (DC->isDependentContext()) {
9840 ContextRAII SavedContext(*this, DC);
9842 Invalid = true;
9843 }
9844
9846 NewFD->getLocation(),
9847 Name, TemplateParams,
9848 NewFD);
9849 FunctionTemplate->setLexicalDeclContext(CurContext);
9851
9852 // For source fidelity, store the other template param lists.
9853 if (TemplateParamLists.size() > 1) {
9855 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9856 .drop_back(1));
9857 }
9858 } else {
9859 // This is a function template specialization.
9860 isFunctionTemplateSpecialization = true;
9861 // For source fidelity, store all the template param lists.
9862 if (TemplateParamLists.size() > 0)
9863 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9864
9865 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9866 if (isFriend) {
9867 // We want to remove the "template<>", found here.
9868 SourceRange RemoveRange = TemplateParams->getSourceRange();
9869
9870 // If we remove the template<> and the name is not a
9871 // template-id, we're actually silently creating a problem:
9872 // the friend declaration will refer to an untemplated decl,
9873 // and clearly the user wants a template specialization. So
9874 // we need to insert '<>' after the name.
9875 SourceLocation InsertLoc;
9876 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9877 InsertLoc = D.getName().getSourceRange().getEnd();
9878 InsertLoc = getLocForEndOfToken(InsertLoc);
9879 }
9880
9881 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9882 << Name << RemoveRange
9883 << FixItHint::CreateRemoval(RemoveRange)
9884 << FixItHint::CreateInsertion(InsertLoc, "<>");
9885 Invalid = true;
9886
9887 // Recover by faking up an empty template argument list.
9888 HasExplicitTemplateArgs = true;
9889 TemplateArgs.setLAngleLoc(InsertLoc);
9890 TemplateArgs.setRAngleLoc(InsertLoc);
9891 }
9892 }
9893 } else {
9894 // Check that we can declare a template here.
9895 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9896 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9897 NewFD->setInvalidDecl();
9898
9899 // All template param lists were matched against the scope specifier:
9900 // this is NOT (an explicit specialization of) a template.
9901 if (TemplateParamLists.size() > 0)
9902 // For source fidelity, store all the template param lists.
9903 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9904
9905 // "friend void foo<>(int);" is an implicit specialization decl.
9906 if (isFriend && TemplateId)
9907 isFunctionTemplateSpecialization = true;
9908 }
9909
9910 // If this is a function template specialization and the unqualified-id of
9911 // the declarator-id is a template-id, convert the template argument list
9912 // into our AST format and check for unexpanded packs.
9913 if (isFunctionTemplateSpecialization && TemplateId) {
9914 HasExplicitTemplateArgs = true;
9915
9916 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9917 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9918 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9919 TemplateId->NumArgs);
9920 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
9921
9922 // FIXME: Should we check for unexpanded packs if this was an (invalid)
9923 // declaration of a function template partial specialization? Should we
9924 // consider the unexpanded pack context to be a partial specialization?
9925 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
9927 ArgLoc, isFriend ? UPPC_FriendDeclaration
9929 NewFD->setInvalidDecl();
9930 }
9931 }
9932
9933 if (Invalid) {
9934 NewFD->setInvalidDecl();
9935 if (FunctionTemplate)
9936 FunctionTemplate->setInvalidDecl();
9937 }
9938
9939 // C++ [dcl.fct.spec]p5:
9940 // The virtual specifier shall only be used in declarations of
9941 // nonstatic class member functions that appear within a
9942 // member-specification of a class declaration; see 10.3.
9943 //
9944 if (isVirtual && !NewFD->isInvalidDecl()) {
9945 if (!isVirtualOkay) {
9946 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9947 diag::err_virtual_non_function);
9948 } else if (!CurContext->isRecord()) {
9949 // 'virtual' was specified outside of the class.
9950 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9951 diag::err_virtual_out_of_class)
9952 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9953 } else if (NewFD->getDescribedFunctionTemplate()) {
9954 // C++ [temp.mem]p3:
9955 // A member function template shall not be virtual.
9956 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9957 diag::err_virtual_member_function_template)
9958 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9959 } else {
9960 // Okay: Add virtual to the method.
9961 NewFD->setVirtualAsWritten(true);
9962 }
9963
9964 if (getLangOpts().CPlusPlus14 &&
9965 NewFD->getReturnType()->isUndeducedType())
9966 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9967 }
9968
9969 // C++ [dcl.fct.spec]p3:
9970 // The inline specifier shall not appear on a block scope function
9971 // declaration.
9972 if (isInline && !NewFD->isInvalidDecl()) {
9974 // 'inline' is not allowed on block scope function declaration.
9975 Diag(D.getDeclSpec().getInlineSpecLoc(),
9976 diag::err_inline_declaration_block_scope) << Name
9977 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9978 }
9979 }
9980
9981 // C++ [dcl.fct.spec]p6:
9982 // The explicit specifier shall be used only in the declaration of a
9983 // constructor or conversion function within its class definition;
9984 // see 12.3.1 and 12.3.2.
9985 if (hasExplicit && !NewFD->isInvalidDecl() &&
9986 !isa<CXXDeductionGuideDecl>(NewFD)) {
9987 if (!CurContext->isRecord()) {
9988 // 'explicit' was specified outside of the class.
9989 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9990 diag::err_explicit_out_of_class)
9991 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9992 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9993 !isa<CXXConversionDecl>(NewFD)) {
9994 // 'explicit' was specified on a function that wasn't a constructor
9995 // or conversion function.
9996 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9997 diag::err_explicit_non_ctor_or_conv_function)
9998 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9999 }
10000 }
10001
10002 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10003 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10004 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10005 // are implicitly inline.
10006 NewFD->setImplicitlyInline();
10007
10008 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10009 // be either constructors or to return a literal type. Therefore,
10010 // destructors cannot be declared constexpr.
10011 if (isa<CXXDestructorDecl>(NewFD) &&
10013 ConstexprKind == ConstexprSpecKind::Consteval)) {
10014 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10015 << static_cast<int>(ConstexprKind);
10016 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10019 }
10020 // C++20 [dcl.constexpr]p2: An allocation function, or a
10021 // deallocation function shall not be declared with the consteval
10022 // specifier.
10023 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10024 (NewFD->getOverloadedOperator() == OO_New ||
10025 NewFD->getOverloadedOperator() == OO_Array_New ||
10026 NewFD->getOverloadedOperator() == OO_Delete ||
10027 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10028 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10029 diag::err_invalid_consteval_decl_kind)
10030 << NewFD;
10032 }
10033 }
10034
10035 // If __module_private__ was specified, mark the function accordingly.
10036 if (D.getDeclSpec().isModulePrivateSpecified()) {
10037 if (isFunctionTemplateSpecialization) {
10038 SourceLocation ModulePrivateLoc
10039 = D.getDeclSpec().getModulePrivateSpecLoc();
10040 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10041 << 0
10042 << FixItHint::CreateRemoval(ModulePrivateLoc);
10043 } else {
10044 NewFD->setModulePrivate();
10045 if (FunctionTemplate)
10046 FunctionTemplate->setModulePrivate();
10047 }
10048 }
10049
10050 if (isFriend) {
10051 if (FunctionTemplate) {
10052 FunctionTemplate->setObjectOfFriendDecl();
10053 FunctionTemplate->setAccess(AS_public);
10054 }
10055 NewFD->setObjectOfFriendDecl();
10056 NewFD->setAccess(AS_public);
10057 }
10058
10059 // If a function is defined as defaulted or deleted, mark it as such now.
10060 // We'll do the relevant checks on defaulted / deleted functions later.
10061 switch (D.getFunctionDefinitionKind()) {
10064 break;
10065
10067 NewFD->setDefaulted();
10068 break;
10069
10071 NewFD->setDeletedAsWritten();
10072 break;
10073 }
10074
10075 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10076 D.isFunctionDefinition() && !isInline) {
10077 // Pre C++20 [class.mfct]p2:
10078 // A member function may be defined (8.4) in its class definition, in
10079 // which case it is an inline member function (7.1.2)
10080 // Post C++20 [class.mfct]p1:
10081 // If a member function is attached to the global module and is defined
10082 // in its class definition, it is inline.
10083 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10084 }
10085
10086 if (!isFriend && SC != SC_None) {
10087 // C++ [temp.expl.spec]p2:
10088 // The declaration in an explicit-specialization shall not be an
10089 // export-declaration. An explicit specialization shall not use a
10090 // storage-class-specifier other than thread_local.
10091 //
10092 // We diagnose friend declarations with storage-class-specifiers
10093 // elsewhere.
10094 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10095 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10096 diag::ext_explicit_specialization_storage_class)
10098 D.getDeclSpec().getStorageClassSpecLoc());
10099 }
10100
10101 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10102 assert(isa<CXXMethodDecl>(NewFD) &&
10103 "Out-of-line member function should be a CXXMethodDecl");
10104 // C++ [class.static]p1:
10105 // A data or function member of a class may be declared static
10106 // in a class definition, in which case it is a static member of
10107 // the class.
10108
10109 // Complain about the 'static' specifier if it's on an out-of-line
10110 // member function definition.
10111
10112 // MSVC permits the use of a 'static' storage specifier on an
10113 // out-of-line member function template declaration and class member
10114 // template declaration (MSVC versions before 2015), warn about this.
10115 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10116 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10117 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10118 (getLangOpts().MSVCCompat &&
10120 ? diag::ext_static_out_of_line
10121 : diag::err_static_out_of_line)
10123 D.getDeclSpec().getStorageClassSpecLoc());
10124 }
10125 }
10126
10127 // C++11 [except.spec]p15:
10128 // A deallocation function with no exception-specification is treated
10129 // as if it were specified with noexcept(true).
10130 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10131 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10132 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10133 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10135 FPT->getReturnType(), FPT->getParamTypes(),
10137
10138 // C++20 [dcl.inline]/7
10139 // If an inline function or variable that is attached to a named module
10140 // is declared in a definition domain, it shall be defined in that
10141 // domain.
10142 // So, if the current declaration does not have a definition, we must
10143 // check at the end of the TU (or when the PMF starts) to see that we
10144 // have a definition at that point.
10145 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10146 NewFD->isInNamedModule()) {
10147 PendingInlineFuncDecls.insert(NewFD);
10148 }
10149 }
10150
10151 // Filter out previous declarations that don't match the scope.
10153 D.getCXXScopeSpec().isNotEmpty() ||
10154 isMemberSpecialization ||
10155 isFunctionTemplateSpecialization);
10156
10157 // Handle GNU asm-label extension (encoded as an attribute).
10158 if (Expr *E = (Expr*) D.getAsmLabel()) {
10159 // The parser guarantees this is a string.
10160 StringLiteral *SE = cast<StringLiteral>(E);
10161 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10162 /*IsLiteralLabel=*/true,
10163 SE->getStrTokenLoc(0)));
10164 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10165 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10167 if (I != ExtnameUndeclaredIdentifiers.end()) {
10168 if (isDeclExternC(NewFD)) {
10169 NewFD->addAttr(I->second);
10171 } else
10172 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10173 << /*Variable*/0 << NewFD;
10174 }
10175 }
10176
10177 // Copy the parameter declarations from the declarator D to the function
10178 // declaration NewFD, if they are available. First scavenge them into Params.
10180 unsigned FTIIdx;
10181 if (D.isFunctionDeclarator(FTIIdx)) {
10182 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10183
10184 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10185 // function that takes no arguments, not a function that takes a
10186 // single void argument.
10187 // We let through "const void" here because Sema::GetTypeForDeclarator
10188 // already checks for that case.
10189 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10190 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10191 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10192 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10193 Param->setDeclContext(NewFD);
10194 Params.push_back(Param);
10195
10196 if (Param->isInvalidDecl())
10197 NewFD->setInvalidDecl();
10198 }
10199 }
10200
10201 if (!getLangOpts().CPlusPlus) {
10202 // In C, find all the tag declarations from the prototype and move them
10203 // into the function DeclContext. Remove them from the surrounding tag
10204 // injection context of the function, which is typically but not always
10205 // the TU.
10206 DeclContext *PrototypeTagContext =
10208 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10209 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10210
10211 // We don't want to reparent enumerators. Look at their parent enum
10212 // instead.
10213 if (!TD) {
10214 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10215 TD = cast<EnumDecl>(ECD->getDeclContext());
10216 }
10217 if (!TD)
10218 continue;
10219 DeclContext *TagDC = TD->getLexicalDeclContext();
10220 if (!TagDC->containsDecl(TD))
10221 continue;
10222 TagDC->removeDecl(TD);
10223 TD->setDeclContext(NewFD);
10224 NewFD->addDecl(TD);
10225
10226 // Preserve the lexical DeclContext if it is not the surrounding tag
10227 // injection context of the FD. In this example, the semantic context of
10228 // E will be f and the lexical context will be S, while both the
10229 // semantic and lexical contexts of S will be f:
10230 // void f(struct S { enum E { a } f; } s);
10231 if (TagDC != PrototypeTagContext)
10232 TD->setLexicalDeclContext(TagDC);
10233 }
10234 }
10235 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10236 // When we're declaring a function with a typedef, typeof, etc as in the
10237 // following example, we'll need to synthesize (unnamed)
10238 // parameters for use in the declaration.
10239 //
10240 // @code
10241 // typedef void fn(int);
10242 // fn f;
10243 // @endcode
10244
10245 // Synthesize a parameter for each argument type.
10246 for (const auto &AI : FT->param_types()) {
10247 ParmVarDecl *Param =
10248 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10249 Param->setScopeInfo(0, Params.size());
10250 Params.push_back(Param);
10251 }
10252 } else {
10253 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10254 "Should not need args for typedef of non-prototype fn");
10255 }
10256
10257 // Finally, we know we have the right number of parameters, install them.
10258 NewFD->setParams(Params);
10259
10260 if (D.getDeclSpec().isNoreturnSpecified())
10261 NewFD->addAttr(
10262 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10263
10264 // Functions returning a variably modified type violate C99 6.7.5.2p2
10265 // because all functions have linkage.
10266 if (!NewFD->isInvalidDecl() &&
10268 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10269 NewFD->setInvalidDecl();
10270 }
10271
10272 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10273 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10274 !NewFD->hasAttr<SectionAttr>())
10275 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10278
10279 // Apply an implicit SectionAttr if #pragma code_seg is active.
10280 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10281 !NewFD->hasAttr<SectionAttr>()) {
10282 NewFD->addAttr(SectionAttr::CreateImplicit(
10283 Context, CodeSegStack.CurrentValue->getString(),
10284 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10285 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10288 NewFD))
10289 NewFD->dropAttr<SectionAttr>();
10290 }
10291
10292 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10293 // active.
10294 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10295 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10296 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10298
10299 // Apply an implicit CodeSegAttr from class declspec or
10300 // apply an implicit SectionAttr from #pragma code_seg if active.
10301 if (!NewFD->hasAttr<CodeSegAttr>()) {
10303 D.isFunctionDefinition())) {
10304 NewFD->addAttr(SAttr);
10305 }
10306 }
10307
10308 // Handle attributes.
10309 ProcessDeclAttributes(S, NewFD, D);
10310 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10311 if (NewTVA && !NewTVA->isDefaultVersion() &&
10312 !Context.getTargetInfo().hasFeature("fmv")) {
10313 // Don't add to scope fmv functions declarations if fmv disabled
10314 AddToScope = false;
10315 return NewFD;
10316 }
10317
10318 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10319 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10320 // type.
10321 //
10322 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10323 // type declaration will generate a compilation error.
10324 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10325 if (AddressSpace != LangAS::Default) {
10326 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10327 NewFD->setInvalidDecl();
10328 }
10329 }
10330
10331 if (!getLangOpts().CPlusPlus) {
10332 // Perform semantic checking on the function declaration.
10333 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10334 CheckMain(NewFD, D.getDeclSpec());
10335
10336 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10337 CheckMSVCRTEntryPoint(NewFD);
10338
10339 if (!NewFD->isInvalidDecl())
10340 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10341 isMemberSpecialization,
10342 D.isFunctionDefinition()));
10343 else if (!Previous.empty())
10344 // Recover gracefully from an invalid redeclaration.
10345 D.setRedeclaration(true);
10346 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10347 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10348 "previous declaration set still overloaded");
10349
10350 // Diagnose no-prototype function declarations with calling conventions that
10351 // don't support variadic calls. Only do this in C and do it after merging
10352 // possibly prototyped redeclarations.
10353 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10354 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10355 CallingConv CC = FT->getExtInfo().getCC();
10356 if (!supportsVariadicCall(CC)) {
10357 // Windows system headers sometimes accidentally use stdcall without
10358 // (void) parameters, so we relax this to a warning.
10359 int DiagID =
10360 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10361 Diag(NewFD->getLocation(), DiagID)
10363 }
10364 }
10365
10371 } else {
10372 // C++11 [replacement.functions]p3:
10373 // The program's definitions shall not be specified as inline.
10374 //
10375 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10376 //
10377 // Suppress the diagnostic if the function is __attribute__((used)), since
10378 // that forces an external definition to be emitted.
10379 if (D.getDeclSpec().isInlineSpecified() &&
10381 !NewFD->hasAttr<UsedAttr>())
10382 Diag(D.getDeclSpec().getInlineSpecLoc(),
10383 diag::ext_operator_new_delete_declared_inline)
10384 << NewFD->getDeclName();
10385
10386 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10387 // C++20 [dcl.decl.general]p4:
10388 // The optional requires-clause in an init-declarator or
10389 // member-declarator shall be present only if the declarator declares a
10390 // templated function.
10391 //
10392 // C++20 [temp.pre]p8:
10393 // An entity is templated if it is
10394 // - a template,
10395 // - an entity defined or created in a templated entity,
10396 // - a member of a templated entity,
10397 // - an enumerator for an enumeration that is a templated entity, or
10398 // - the closure type of a lambda-expression appearing in the
10399 // declaration of a templated entity.
10400 //
10401 // [Note 6: A local class, a local or block variable, or a friend
10402 // function defined in a templated entity is a templated entity.
10403 // — end note]
10404 //
10405 // A templated function is a function template or a function that is
10406 // templated. A templated class is a class template or a class that is
10407 // templated. A templated variable is a variable template or a variable
10408 // that is templated.
10409 if (!FunctionTemplate) {
10410 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10411 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10412 // An explicit specialization shall not have a trailing
10413 // requires-clause unless it declares a function template.
10414 //
10415 // Since a friend function template specialization cannot be
10416 // definition, and since a non-template friend declaration with a
10417 // trailing requires-clause must be a definition, we diagnose
10418 // friend function template specializations with trailing
10419 // requires-clauses on the same path as explicit specializations
10420 // even though they aren't necessarily prohibited by the same
10421 // language rule.
10422 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10423 << isFriend;
10424 } else if (isFriend && NewFD->isTemplated() &&
10425 !D.isFunctionDefinition()) {
10426 // C++ [temp.friend]p9:
10427 // A non-template friend declaration with a requires-clause shall be
10428 // a definition.
10429 Diag(NewFD->getBeginLoc(),
10430 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10431 NewFD->setInvalidDecl();
10432 } else if (!NewFD->isTemplated() ||
10433 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10434 Diag(TRC->getBeginLoc(),
10435 diag::err_constrained_non_templated_function);
10436 }
10437 }
10438 }
10439
10440 // We do not add HD attributes to specializations here because
10441 // they may have different constexpr-ness compared to their
10442 // templates and, after maybeAddHostDeviceAttrs() is applied,
10443 // may end up with different effective targets. Instead, a
10444 // specialization inherits its target attributes from its template
10445 // in the CheckFunctionTemplateSpecialization() call below.
10446 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10448
10449 // Handle explicit specializations of function templates
10450 // and friend function declarations with an explicit
10451 // template argument list.
10452 if (isFunctionTemplateSpecialization) {
10453 bool isDependentSpecialization = false;
10454 if (isFriend) {
10455 // For friend function specializations, this is a dependent
10456 // specialization if its semantic context is dependent, its
10457 // type is dependent, or if its template-id is dependent.
10458 isDependentSpecialization =
10459 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10460 (HasExplicitTemplateArgs &&
10463 TemplateArgs.arguments()));
10464 assert((!isDependentSpecialization ||
10465 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10466 "dependent friend function specialization without template "
10467 "args");
10468 } else {
10469 // For class-scope explicit specializations of function templates,
10470 // if the lexical context is dependent, then the specialization
10471 // is dependent.
10472 isDependentSpecialization =
10474 }
10475
10476 TemplateArgumentListInfo *ExplicitTemplateArgs =
10477 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10478 if (isDependentSpecialization) {
10479 // If it's a dependent specialization, it may not be possible
10480 // to determine the primary template (for explicit specializations)
10481 // or befriended declaration (for friends) until the enclosing
10482 // template is instantiated. In such cases, we store the declarations
10483 // found by name lookup and defer resolution until instantiation.
10485 NewFD, ExplicitTemplateArgs, Previous))
10486 NewFD->setInvalidDecl();
10487 } else if (!NewFD->isInvalidDecl()) {
10488 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10489 Previous))
10490 NewFD->setInvalidDecl();
10491 }
10492 } else if (isMemberSpecialization && !FunctionTemplate) {
10494 NewFD->setInvalidDecl();
10495 }
10496
10497 // Perform semantic checking on the function declaration.
10498 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10499 CheckMain(NewFD, D.getDeclSpec());
10500
10501 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10502 CheckMSVCRTEntryPoint(NewFD);
10503
10504 if (!NewFD->isInvalidDecl())
10505 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10506 isMemberSpecialization,
10507 D.isFunctionDefinition()));
10508 else if (!Previous.empty())
10509 // Recover gracefully from an invalid redeclaration.
10510 D.setRedeclaration(true);
10511
10512 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10513 !D.isRedeclaration() ||
10514 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10515 "previous declaration set still overloaded");
10516
10517 NamedDecl *PrincipalDecl = (FunctionTemplate
10518 ? cast<NamedDecl>(FunctionTemplate)
10519 : NewFD);
10520
10521 if (isFriend && NewFD->getPreviousDecl()) {
10522 AccessSpecifier Access = AS_public;
10523 if (!NewFD->isInvalidDecl())
10524 Access = NewFD->getPreviousDecl()->getAccess();
10525
10526 NewFD->setAccess(Access);
10527 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10528 }
10529
10530 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10532 PrincipalDecl->setNonMemberOperator();
10533
10534 // If we have a function template, check the template parameter
10535 // list. This will check and merge default template arguments.
10536 if (FunctionTemplate) {
10537 FunctionTemplateDecl *PrevTemplate =
10538 FunctionTemplate->getPreviousDecl();
10539 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10540 PrevTemplate ? PrevTemplate->getTemplateParameters()
10541 : nullptr,
10542 D.getDeclSpec().isFriendSpecified()
10543 ? (D.isFunctionDefinition()
10546 : (D.getCXXScopeSpec().isSet() &&
10547 DC && DC->isRecord() &&
10548 DC->isDependentContext())
10551 }
10552
10553 if (NewFD->isInvalidDecl()) {
10554 // Ignore all the rest of this.
10555 } else if (!D.isRedeclaration()) {
10556 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10557 AddToScope };
10558 // Fake up an access specifier if it's supposed to be a class member.
10559 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10560 NewFD->setAccess(AS_public);
10561
10562 // Qualified decls generally require a previous declaration.
10563 if (D.getCXXScopeSpec().isSet()) {
10564 // ...with the major exception of templated-scope or
10565 // dependent-scope friend declarations.
10566
10567 // TODO: we currently also suppress this check in dependent
10568 // contexts because (1) the parameter depth will be off when
10569 // matching friend templates and (2) we might actually be
10570 // selecting a friend based on a dependent factor. But there
10571 // are situations where these conditions don't apply and we
10572 // can actually do this check immediately.
10573 //
10574 // Unless the scope is dependent, it's always an error if qualified
10575 // redeclaration lookup found nothing at all. Diagnose that now;
10576 // nothing will diagnose that error later.
10577 if (isFriend &&
10578 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10579 (!Previous.empty() && CurContext->isDependentContext()))) {
10580 // ignore these
10581 } else if (NewFD->isCPUDispatchMultiVersion() ||
10582 NewFD->isCPUSpecificMultiVersion()) {
10583 // ignore this, we allow the redeclaration behavior here to create new
10584 // versions of the function.
10585 } else {
10586 // The user tried to provide an out-of-line definition for a
10587 // function that is a member of a class or namespace, but there
10588 // was no such member function declared (C++ [class.mfct]p2,
10589 // C++ [namespace.memdef]p2). For example:
10590 //
10591 // class X {
10592 // void f() const;
10593 // };
10594 //
10595 // void X::f() { } // ill-formed
10596 //
10597 // Complain about this problem, and attempt to suggest close
10598 // matches (e.g., those that differ only in cv-qualifiers and
10599 // whether the parameter types are references).
10600
10602 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10603 AddToScope = ExtraArgs.AddToScope;
10604 return Result;
10605 }
10606 }
10607
10608 // Unqualified local friend declarations are required to resolve
10609 // to something.
10610 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10612 *this, Previous, NewFD, ExtraArgs, true, S)) {
10613 AddToScope = ExtraArgs.AddToScope;
10614 return Result;
10615 }
10616 }
10617 } else if (!D.isFunctionDefinition() &&
10618 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10619 !isFriend && !isFunctionTemplateSpecialization &&
10620 !isMemberSpecialization) {
10621 // An out-of-line member function declaration must also be a
10622 // definition (C++ [class.mfct]p2).
10623 // Note that this is not the case for explicit specializations of
10624 // function templates or member functions of class templates, per
10625 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10626 // extension for compatibility with old SWIG code which likes to
10627 // generate them.
10628 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10629 << D.getCXXScopeSpec().getRange();
10630 }
10631 }
10632
10633 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10634 // Any top level function could potentially be specified as an entry.
10635 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10636 HLSL().ActOnTopLevelFunction(NewFD);
10637
10638 if (NewFD->hasAttr<HLSLShaderAttr>())
10639 HLSL().CheckEntryPoint(NewFD);
10640 }
10641
10642 // If this is the first declaration of a library builtin function, add
10643 // attributes as appropriate.
10644 if (!D.isRedeclaration()) {
10645 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10646 if (unsigned BuiltinID = II->getBuiltinID()) {
10647 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10648 if (!InStdNamespace &&
10650 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10651 // Validate the type matches unless this builtin is specified as
10652 // matching regardless of its declared type.
10653 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10654 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10655 } else {
10657 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10658 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10659
10660 if (!Error && !BuiltinType.isNull() &&
10662 NewFD->getType(), BuiltinType))
10663 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10664 }
10665 }
10666 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10667 isStdBuiltin(Context, NewFD, BuiltinID)) {
10668 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10669 }
10670 }
10671 }
10672 }
10673
10674 ProcessPragmaWeak(S, NewFD);
10675 checkAttributesAfterMerging(*this, *NewFD);
10676
10678
10679 if (NewFD->hasAttr<OverloadableAttr>() &&
10680 !NewFD->getType()->getAs<FunctionProtoType>()) {
10681 Diag(NewFD->getLocation(),
10682 diag::err_attribute_overloadable_no_prototype)
10683 << NewFD;
10684 NewFD->dropAttr<OverloadableAttr>();
10685 }
10686
10687 // If there's a #pragma GCC visibility in scope, and this isn't a class
10688 // member, set the visibility of this function.
10689 if (!DC->isRecord() && NewFD->isExternallyVisible())
10691
10692 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10693 // marking the function.
10694 ObjC().AddCFAuditedAttribute(NewFD);
10695
10696 // If this is a function definition, check if we have to apply any
10697 // attributes (i.e. optnone and no_builtin) due to a pragma.
10698 if (D.isFunctionDefinition()) {
10699 AddRangeBasedOptnone(NewFD);
10701 AddSectionMSAllocText(NewFD);
10703 }
10704
10705 // If this is the first declaration of an extern C variable, update
10706 // the map of such variables.
10707 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10708 isIncompleteDeclExternC(*this, NewFD))
10710
10711 // Set this FunctionDecl's range up to the right paren.
10712 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10713
10714 if (D.isRedeclaration() && !Previous.empty()) {
10715 NamedDecl *Prev = Previous.getRepresentativeDecl();
10716 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10717 isMemberSpecialization ||
10718 isFunctionTemplateSpecialization,
10719 D.isFunctionDefinition());
10720 }
10721
10722 if (getLangOpts().CUDA) {
10723 IdentifierInfo *II = NewFD->getIdentifier();
10724 if (II && II->isStr(CUDA().getConfigureFuncName()) &&
10725 !NewFD->isInvalidDecl() &&
10728 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10731 }
10732
10733 // Variadic functions, other than a *declaration* of printf, are not allowed
10734 // in device-side CUDA code, unless someone passed
10735 // -fcuda-allow-variadic-functions.
10736 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10737 (NewFD->hasAttr<CUDADeviceAttr>() ||
10738 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10739 !(II && II->isStr("printf") && NewFD->isExternC() &&
10740 !D.isFunctionDefinition())) {
10741 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10742 }
10743 }
10744
10746
10747
10748
10749 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10750 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10751 if (SC == SC_Static) {
10752 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10753 D.setInvalidType();
10754 }
10755
10756 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10757 if (!NewFD->getReturnType()->isVoidType()) {
10758 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10759 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10760 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10761 : FixItHint());
10762 D.setInvalidType();
10763 }
10764
10766 for (auto *Param : NewFD->parameters())
10767 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10768
10769 if (getLangOpts().OpenCLCPlusPlus) {
10770 if (DC->isRecord()) {
10771 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10772 D.setInvalidType();
10773 }
10774 if (FunctionTemplate) {
10775 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10776 D.setInvalidType();
10777 }
10778 }
10779 }
10780
10781 if (getLangOpts().CPlusPlus) {
10782 // Precalculate whether this is a friend function template with a constraint
10783 // that depends on an enclosing template, per [temp.friend]p9.
10784 if (isFriend && FunctionTemplate &&
10787
10788 // C++ [temp.friend]p9:
10789 // A friend function template with a constraint that depends on a
10790 // template parameter from an enclosing template shall be a definition.
10791 if (!D.isFunctionDefinition()) {
10792 Diag(NewFD->getBeginLoc(),
10793 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10794 NewFD->setInvalidDecl();
10795 }
10796 }
10797
10798 if (FunctionTemplate) {
10799 if (NewFD->isInvalidDecl())
10800 FunctionTemplate->setInvalidDecl();
10801 return FunctionTemplate;
10802 }
10803
10804 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10806 }
10807
10808 for (const ParmVarDecl *Param : NewFD->parameters()) {
10809 QualType PT = Param->getType();
10810
10811 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10812 // types.
10813 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10814 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10815 QualType ElemTy = PipeTy->getElementType();
10816 if (ElemTy->isPointerOrReferenceType()) {
10817 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
10818 D.setInvalidType();
10819 }
10820 }
10821 }
10822 // WebAssembly tables can't be used as function parameters.
10823 if (Context.getTargetInfo().getTriple().isWasm()) {
10825 Diag(Param->getTypeSpecStartLoc(),
10826 diag::err_wasm_table_as_function_parameter);
10827 D.setInvalidType();
10828 }
10829 }
10830 }
10831
10832 // Diagnose availability attributes. Availability cannot be used on functions
10833 // that are run during load/unload.
10834 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10835 if (NewFD->hasAttr<ConstructorAttr>()) {
10836 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10837 << 1;
10838 NewFD->dropAttr<AvailabilityAttr>();
10839 }
10840 if (NewFD->hasAttr<DestructorAttr>()) {
10841 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10842 << 2;
10843 NewFD->dropAttr<AvailabilityAttr>();
10844 }
10845 }
10846
10847 // Diagnose no_builtin attribute on function declaration that are not a
10848 // definition.
10849 // FIXME: We should really be doing this in
10850 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10851 // the FunctionDecl and at this point of the code
10852 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10853 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10854 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10855 switch (D.getFunctionDefinitionKind()) {
10858 Diag(NBA->getLocation(),
10859 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10860 << NBA->getSpelling();
10861 break;
10863 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10864 << NBA->getSpelling();
10865 break;
10867 break;
10868 }
10869
10870 // Similar to no_builtin logic above, at this point of the code
10871 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
10872 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10874 !NewFD->isInvalidDecl() &&
10875 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
10876 ExternalDeclarations.push_back(NewFD);
10877
10878 return NewFD;
10879}
10880
10881/// Return a CodeSegAttr from a containing class. The Microsoft docs say
10882/// when __declspec(code_seg) "is applied to a class, all member functions of
10883/// the class and nested classes -- this includes compiler-generated special
10884/// member functions -- are put in the specified segment."
10885/// The actual behavior is a little more complicated. The Microsoft compiler
10886/// won't check outer classes if there is an active value from #pragma code_seg.
10887/// The CodeSeg is always applied from the direct parent but only from outer
10888/// classes when the #pragma code_seg stack is empty. See:
10889/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10890/// available since MS has removed the page.
10892 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10893 if (!Method)
10894 return nullptr;
10895 const CXXRecordDecl *Parent = Method->getParent();
10896 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10897 Attr *NewAttr = SAttr->clone(S.getASTContext());
10898 NewAttr->setImplicit(true);
10899 return NewAttr;
10900 }
10901
10902 // The Microsoft compiler won't check outer classes for the CodeSeg
10903 // when the #pragma code_seg stack is active.
10904 if (S.CodeSegStack.CurrentValue)
10905 return nullptr;
10906
10907 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10908 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10909 Attr *NewAttr = SAttr->clone(S.getASTContext());
10910 NewAttr->setImplicit(true);
10911 return NewAttr;
10912 }
10913 }
10914 return nullptr;
10915}
10916
10918 bool IsDefinition) {
10919 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10920 return A;
10921 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10922 CodeSegStack.CurrentValue)
10923 return SectionAttr::CreateImplicit(
10924 getASTContext(), CodeSegStack.CurrentValue->getString(),
10925 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
10926 return nullptr;
10927}
10928
10930 QualType NewT, QualType OldT) {
10932 return true;
10933
10934 // For dependently-typed local extern declarations and friends, we can't
10935 // perform a correct type check in general until instantiation:
10936 //
10937 // int f();
10938 // template<typename T> void g() { T f(); }
10939 //
10940 // (valid if g() is only instantiated with T = int).
10941 if (NewT->isDependentType() &&
10942 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10943 return false;
10944
10945 // Similarly, if the previous declaration was a dependent local extern
10946 // declaration, we don't really know its type yet.
10947 if (OldT->isDependentType() && OldD->isLocalExternDecl())
10948 return false;
10949
10950 return true;
10951}
10952
10955 return true;
10956
10957 // Don't chain dependent friend function definitions until instantiation, to
10958 // permit cases like
10959 //
10960 // void func();
10961 // template<typename T> class C1 { friend void func() {} };
10962 // template<typename T> class C2 { friend void func() {} };
10963 //
10964 // ... which is valid if only one of C1 and C2 is ever instantiated.
10965 //
10966 // FIXME: This need only apply to function definitions. For now, we proxy
10967 // this by checking for a file-scope function. We do not want this to apply
10968 // to friend declarations nominating member functions, because that gets in
10969 // the way of access checks.
10971 return false;
10972
10973 auto *VD = dyn_cast<ValueDecl>(D);
10974 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10975 return !VD || !PrevVD ||
10976 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10977 PrevVD->getType());
10978}
10979
10980/// Check the target or target_version attribute of the function for
10981/// MultiVersion validity.
10982///
10983/// Returns true if there was an error, false otherwise.
10984static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10985 const auto *TA = FD->getAttr<TargetAttr>();
10986 const auto *TVA = FD->getAttr<TargetVersionAttr>();
10987 assert(
10988 (TA || TVA) &&
10989 "MultiVersion candidate requires a target or target_version attribute");
10991 enum ErrType { Feature = 0, Architecture = 1 };
10992
10993 if (TA) {
10994 ParsedTargetAttr ParseInfo =
10995 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
10996 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
10997 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10998 << Architecture << ParseInfo.CPU;
10999 return true;
11000 }
11001 for (const auto &Feat : ParseInfo.Features) {
11002 auto BareFeat = StringRef{Feat}.substr(1);
11003 if (Feat[0] == '-') {
11004 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11005 << Feature << ("no-" + BareFeat).str();
11006 return true;
11007 }
11008
11009 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11010 !TargetInfo.isValidFeatureName(BareFeat)) {
11011 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11012 << Feature << BareFeat;
11013 return true;
11014 }
11015 }
11016 }
11017
11018 if (TVA) {
11020 TVA->getFeatures(Feats);
11021 for (const auto &Feat : Feats) {
11022 if (!TargetInfo.validateCpuSupports(Feat)) {
11023 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11024 << Feature << Feat;
11025 return true;
11026 }
11027 }
11028 }
11029 return false;
11030}
11031
11032// Provide a white-list of attributes that are allowed to be combined with
11033// multiversion functions.
11035 MultiVersionKind MVKind) {
11036 // Note: this list/diagnosis must match the list in
11037 // checkMultiversionAttributesAllSame.
11038 switch (Kind) {
11039 default:
11040 return false;
11041 case attr::ArmLocallyStreaming:
11042 return MVKind == MultiVersionKind::TargetVersion ||
11044 case attr::Used:
11045 return MVKind == MultiVersionKind::Target;
11046 case attr::NonNull:
11047 case attr::NoThrow:
11048 return true;
11049 }
11050}
11051
11053 const FunctionDecl *FD,
11054 const FunctionDecl *CausedFD,
11055 MultiVersionKind MVKind) {
11056 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11057 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11058 << static_cast<unsigned>(MVKind) << A;
11059 if (CausedFD)
11060 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11061 return true;
11062 };
11063
11064 for (const Attr *A : FD->attrs()) {
11065 switch (A->getKind()) {
11066 case attr::CPUDispatch:
11067 case attr::CPUSpecific:
11068 if (MVKind != MultiVersionKind::CPUDispatch &&
11070 return Diagnose(S, A);
11071 break;
11072 case attr::Target:
11073 if (MVKind != MultiVersionKind::Target)
11074 return Diagnose(S, A);
11075 break;
11076 case attr::TargetVersion:
11077 if (MVKind != MultiVersionKind::TargetVersion &&
11079 return Diagnose(S, A);
11080 break;
11081 case attr::TargetClones:
11082 if (MVKind != MultiVersionKind::TargetClones &&
11084 return Diagnose(S, A);
11085 break;
11086 default:
11087 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11088 return Diagnose(S, A);
11089 break;
11090 }
11091 }
11092 return false;
11093}
11094
11096 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11097 const PartialDiagnostic &NoProtoDiagID,
11098 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11099 const PartialDiagnosticAt &NoSupportDiagIDAt,
11100 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11101 bool ConstexprSupported, bool CLinkageMayDiffer) {
11102 enum DoesntSupport {
11103 FuncTemplates = 0,
11104 VirtFuncs = 1,
11105 DeducedReturn = 2,
11106 Constructors = 3,
11107 Destructors = 4,
11108 DeletedFuncs = 5,
11109 DefaultedFuncs = 6,
11110 ConstexprFuncs = 7,
11111 ConstevalFuncs = 8,
11112 Lambda = 9,
11113 };
11114 enum Different {
11115 CallingConv = 0,
11116 ReturnType = 1,
11117 ConstexprSpec = 2,
11118 InlineSpec = 3,
11119 Linkage = 4,
11120 LanguageLinkage = 5,
11121 };
11122
11123 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11124 !OldFD->getType()->getAs<FunctionProtoType>()) {
11125 Diag(OldFD->getLocation(), NoProtoDiagID);
11126 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11127 return true;
11128 }
11129
11130 if (NoProtoDiagID.getDiagID() != 0 &&
11131 !NewFD->getType()->getAs<FunctionProtoType>())
11132 return Diag(NewFD->getLocation(), NoProtoDiagID);
11133
11134 if (!TemplatesSupported &&
11136 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11137 << FuncTemplates;
11138
11139 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11140 if (NewCXXFD->isVirtual())
11141 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11142 << VirtFuncs;
11143
11144 if (isa<CXXConstructorDecl>(NewCXXFD))
11145 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11146 << Constructors;
11147
11148 if (isa<CXXDestructorDecl>(NewCXXFD))
11149 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11150 << Destructors;
11151 }
11152
11153 if (NewFD->isDeleted())
11154 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11155 << DeletedFuncs;
11156
11157 if (NewFD->isDefaulted())
11158 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11159 << DefaultedFuncs;
11160
11161 if (!ConstexprSupported && NewFD->isConstexpr())
11162 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11163 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11164
11165 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11166 const auto *NewType = cast<FunctionType>(NewQType);
11167 QualType NewReturnType = NewType->getReturnType();
11168
11169 if (NewReturnType->isUndeducedType())
11170 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11171 << DeducedReturn;
11172
11173 // Ensure the return type is identical.
11174 if (OldFD) {
11175 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11176 const auto *OldType = cast<FunctionType>(OldQType);
11177 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11178 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11179
11180 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11181 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11182
11183 bool ArmStreamingCCMismatched = false;
11184 if (OldFPT && NewFPT) {
11185 unsigned Diff =
11187 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11188 // cannot be mixed.
11191 ArmStreamingCCMismatched = true;
11192 }
11193
11194 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11195 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11196
11197 QualType OldReturnType = OldType->getReturnType();
11198
11199 if (OldReturnType != NewReturnType)
11200 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11201
11202 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11203 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11204
11205 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11206 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11207
11208 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11209 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11210
11211 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11212 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11213
11214 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11215 NewFD->getLocation()))
11216 return true;
11217 }
11218 return false;
11219}
11220
11222 const FunctionDecl *NewFD,
11223 bool CausesMV,
11224 MultiVersionKind MVKind) {
11226 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11227 if (OldFD)
11228 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11229 return true;
11230 }
11231
11232 bool IsCPUSpecificCPUDispatchMVKind =
11235
11236 if (CausesMV && OldFD &&
11237 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11238 return true;
11239
11240 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11241 return true;
11242
11243 // Only allow transition to MultiVersion if it hasn't been used.
11244 if (OldFD && CausesMV && OldFD->isUsed(false))
11245 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11246
11248 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11250 S.PDiag(diag::note_multiversioning_caused_here)),
11252 S.PDiag(diag::err_multiversion_doesnt_support)
11253 << static_cast<unsigned>(MVKind)),
11255 S.PDiag(diag::err_multiversion_diff)),
11256 /*TemplatesSupported=*/false,
11257 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11258 /*CLinkageMayDiffer=*/false);
11259}
11260
11261/// Check the validity of a multiversion function declaration that is the
11262/// first of its kind. Also sets the multiversion'ness' of the function itself.
11263///
11264/// This sets NewFD->isInvalidDecl() to true if there was an error.
11265///
11266/// Returns true if there was an error, false otherwise.
11269 assert(MVKind != MultiVersionKind::None &&
11270 "Function lacks multiversion attribute");
11271 const auto *TA = FD->getAttr<TargetAttr>();
11272 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11273 // The target attribute only causes MV if this declaration is the default,
11274 // otherwise it is treated as a normal function.
11275 if (TA && !TA->isDefaultVersion())
11276 return false;
11277 // The target_version attribute only causes Multiversioning if this
11278 // declaration is NOT the default version.
11279 if (TVA && TVA->isDefaultVersion())
11280 return false;
11281
11282 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11283 FD->setInvalidDecl();
11284 return true;
11285 }
11286
11287 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11288 FD->setInvalidDecl();
11289 return true;
11290 }
11291
11292 FD->setIsMultiVersion();
11293 return false;
11294}
11295
11297 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11299 return true;
11300 }
11301
11302 return false;
11303}
11304
11306 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64())
11307 return;
11308
11309 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11310 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11311
11312 if (MVKindTo == MultiVersionKind::None &&
11313 (MVKindFrom == MultiVersionKind::TargetVersion ||
11314 MVKindFrom == MultiVersionKind::TargetClones))
11315 To->addAttr(TargetVersionAttr::CreateImplicit(
11316 To->getASTContext(), "default", To->getSourceRange()));
11317}
11318
11320 FunctionDecl *NewFD,
11321 bool &Redeclaration,
11322 NamedDecl *&OldDecl,
11324 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11325
11326 // The definitions should be allowed in any order. If we have discovered
11327 // a new target version and the preceeding was the default, then add the
11328 // corresponding attribute to it.
11329 patchDefaultTargetVersion(NewFD, OldFD);
11330
11331 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11332 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11333 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11334
11335 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11336 // to change, this is a simple redeclaration.
11337 if (NewTA && !NewTA->isDefaultVersion() &&
11338 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11339 return false;
11340
11341 // The target_version attribute only causes Multiversioning if this
11342 // declaration is NOT the default version.
11343 if (NewTVA && NewTVA->isDefaultVersion())
11344 return false;
11345
11346 // Otherwise, this decl causes MultiVersioning.
11347 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11350 NewFD->setInvalidDecl();
11351 return true;
11352 }
11353
11354 if (CheckMultiVersionValue(S, NewFD)) {
11355 NewFD->setInvalidDecl();
11356 return true;
11357 }
11358
11359 // If this is 'default', permit the forward declaration.
11360 if (NewTA && NewTA->isDefaultVersion() && !OldTA) {
11361 Redeclaration = true;
11362 OldDecl = OldFD;
11363 OldFD->setIsMultiVersion();
11364 NewFD->setIsMultiVersion();
11365 return false;
11366 }
11367
11368 if (CheckMultiVersionValue(S, OldFD)) {
11369 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11370 NewFD->setInvalidDecl();
11371 return true;
11372 }
11373
11374 if (NewTA) {
11375 ParsedTargetAttr OldParsed =
11377 OldTA->getFeaturesStr());
11378 llvm::sort(OldParsed.Features);
11379 ParsedTargetAttr NewParsed =
11381 NewTA->getFeaturesStr());
11382 // Sort order doesn't matter, it just needs to be consistent.
11383 llvm::sort(NewParsed.Features);
11384 if (OldParsed == NewParsed) {
11385 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11386 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11387 NewFD->setInvalidDecl();
11388 return true;
11389 }
11390 }
11391
11392 for (const auto *FD : OldFD->redecls()) {
11393 const auto *CurTA = FD->getAttr<TargetAttr>();
11394 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11395 // We allow forward declarations before ANY multiversioning attributes, but
11396 // nothing after the fact.
11398 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11399 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11400 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11401 << (NewTA ? 0 : 2);
11402 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11403 NewFD->setInvalidDecl();
11404 return true;
11405 }
11406 }
11407
11408 OldFD->setIsMultiVersion();
11409 NewFD->setIsMultiVersion();
11410 Redeclaration = false;
11411 OldDecl = nullptr;
11412 Previous.clear();
11413 return false;
11414}
11415
11417 MultiVersionKind OldKind = Old->getMultiVersionKind();
11418 MultiVersionKind NewKind = New->getMultiVersionKind();
11419
11420 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11421 NewKind == MultiVersionKind::None)
11422 return true;
11423
11424 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11425 switch (OldKind) {
11427 return NewKind == MultiVersionKind::TargetClones;
11429 return NewKind == MultiVersionKind::TargetVersion;
11430 default:
11431 return false;
11432 }
11433 } else {
11434 switch (OldKind) {
11436 return NewKind == MultiVersionKind::CPUSpecific;
11438 return NewKind == MultiVersionKind::CPUDispatch;
11439 default:
11440 return false;
11441 }
11442 }
11443}
11444
11445/// Check the validity of a new function declaration being added to an existing
11446/// multiversioned declaration collection.
11448 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11449 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11450 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11452
11453 // Disallow mixing of multiversioning types.
11454 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11455 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11456 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11457 NewFD->setInvalidDecl();
11458 return true;
11459 }
11460
11461 // Add the default target_version attribute if it's missing.
11462 patchDefaultTargetVersion(OldFD, NewFD);
11463 patchDefaultTargetVersion(NewFD, OldFD);
11464
11465 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11466 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11467 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11468 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11469
11470 ParsedTargetAttr NewParsed;
11471 if (NewTA) {
11473 NewTA->getFeaturesStr());
11474 llvm::sort(NewParsed.Features);
11475 }
11477 if (NewTVA) {
11478 NewTVA->getFeatures(NewFeats);
11479 llvm::sort(NewFeats);
11480 }
11481
11482 bool UseMemberUsingDeclRules =
11483 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11484
11485 bool MayNeedOverloadableChecks =
11487
11488 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11489 // of a previous member of the MultiVersion set.
11490 for (NamedDecl *ND : Previous) {
11491 FunctionDecl *CurFD = ND->getAsFunction();
11492 if (!CurFD || CurFD->isInvalidDecl())
11493 continue;
11494 if (MayNeedOverloadableChecks &&
11495 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11496 continue;
11497
11498 switch (NewMVKind) {
11500 assert(OldMVKind == MultiVersionKind::TargetClones &&
11501 "Only target_clones can be omitted in subsequent declarations");
11502 break;
11504 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11505 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11506 NewFD->setIsMultiVersion();
11507 Redeclaration = true;
11508 OldDecl = ND;
11509 return false;
11510 }
11511
11512 ParsedTargetAttr CurParsed =
11514 CurTA->getFeaturesStr());
11515 llvm::sort(CurParsed.Features);
11516 if (CurParsed == NewParsed) {
11517 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11518 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11519 NewFD->setInvalidDecl();
11520 return true;
11521 }
11522 break;
11523 }
11525 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11526 if (CurTVA->getName() == NewTVA->getName()) {
11527 NewFD->setIsMultiVersion();
11528 Redeclaration = true;
11529 OldDecl = ND;
11530 return false;
11531 }
11533 CurTVA->getFeatures(CurFeats);
11534 llvm::sort(CurFeats);
11535
11536 if (CurFeats == NewFeats) {
11537 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11538 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11539 NewFD->setInvalidDecl();
11540 return true;
11541 }
11542 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11543 // Default
11544 if (NewFeats.empty())
11545 break;
11546
11547 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11549 CurClones->getFeatures(CurFeats, I);
11550 llvm::sort(CurFeats);
11551
11552 if (CurFeats == NewFeats) {
11553 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11554 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11555 NewFD->setInvalidDecl();
11556 return true;
11557 }
11558 }
11559 }
11560 break;
11561 }
11563 assert(NewClones && "MultiVersionKind does not match attribute type");
11564 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11565 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11566 !std::equal(CurClones->featuresStrs_begin(),
11567 CurClones->featuresStrs_end(),
11568 NewClones->featuresStrs_begin())) {
11569 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11570 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11571 NewFD->setInvalidDecl();
11572 return true;
11573 }
11574 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11576 CurTVA->getFeatures(CurFeats);
11577 llvm::sort(CurFeats);
11578
11579 // Default
11580 if (CurFeats.empty())
11581 break;
11582
11583 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11584 NewFeats.clear();
11585 NewClones->getFeatures(NewFeats, I);
11586 llvm::sort(NewFeats);
11587
11588 if (CurFeats == NewFeats) {
11589 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11590 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11591 NewFD->setInvalidDecl();
11592 return true;
11593 }
11594 }
11595 break;
11596 }
11597 Redeclaration = true;
11598 OldDecl = CurFD;
11599 NewFD->setIsMultiVersion();
11600 return false;
11601 }
11604 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11605 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11606 // Handle CPUDispatch/CPUSpecific versions.
11607 // Only 1 CPUDispatch function is allowed, this will make it go through
11608 // the redeclaration errors.
11609 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11610 CurFD->hasAttr<CPUDispatchAttr>()) {
11611 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11612 std::equal(
11613 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11614 NewCPUDisp->cpus_begin(),
11615 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11616 return Cur->getName() == New->getName();
11617 })) {
11618 NewFD->setIsMultiVersion();
11619 Redeclaration = true;
11620 OldDecl = ND;
11621 return false;
11622 }
11623
11624 // If the declarations don't match, this is an error condition.
11625 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11626 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11627 NewFD->setInvalidDecl();
11628 return true;
11629 }
11630 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11631 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11632 std::equal(
11633 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11634 NewCPUSpec->cpus_begin(),
11635 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11636 return Cur->getName() == New->getName();
11637 })) {
11638 NewFD->setIsMultiVersion();
11639 Redeclaration = true;
11640 OldDecl = ND;
11641 return false;
11642 }
11643
11644 // Only 1 version of CPUSpecific is allowed for each CPU.
11645 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11646 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11647 if (CurII == NewII) {
11648 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11649 << NewII;
11650 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11651 NewFD->setInvalidDecl();
11652 return true;
11653 }
11654 }
11655 }
11656 }
11657 break;
11658 }
11659 }
11660 }
11661
11662 // Else, this is simply a non-redecl case. Checking the 'value' is only
11663 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11664 // handled in the attribute adding step.
11665 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11666 NewMVKind == MultiVersionKind::Target) &&
11667 CheckMultiVersionValue(S, NewFD)) {
11668 NewFD->setInvalidDecl();
11669 return true;
11670 }
11671
11672 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11673 !OldFD->isMultiVersion(), NewMVKind)) {
11674 NewFD->setInvalidDecl();
11675 return true;
11676 }
11677
11678 // Permit forward declarations in the case where these two are compatible.
11679 if (!OldFD->isMultiVersion()) {
11680 OldFD->setIsMultiVersion();
11681 NewFD->setIsMultiVersion();
11682 Redeclaration = true;
11683 OldDecl = OldFD;
11684 return false;
11685 }
11686
11687 NewFD->setIsMultiVersion();
11688 Redeclaration = false;
11689 OldDecl = nullptr;
11690 Previous.clear();
11691 return false;
11692}
11693
11694/// Check the validity of a mulitversion function declaration.
11695/// Also sets the multiversion'ness' of the function itself.
11696///
11697/// This sets NewFD->isInvalidDecl() to true if there was an error.
11698///
11699/// Returns true if there was an error, false otherwise.
11701 bool &Redeclaration, NamedDecl *&OldDecl,
11703 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11704 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11705 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11706 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11707 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11708 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11709
11710 // Main isn't allowed to become a multiversion function, however it IS
11711 // permitted to have 'main' be marked with the 'target' optimization hint,
11712 // for 'target_version' only default is allowed.
11713 if (NewFD->isMain()) {
11714 if (MVKind != MultiVersionKind::None &&
11715 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11716 !(MVKind == MultiVersionKind::TargetVersion &&
11717 NewTVA->isDefaultVersion())) {
11718 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11719 NewFD->setInvalidDecl();
11720 return true;
11721 }
11722 return false;
11723 }
11724
11725 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
11726
11727 // Target attribute on AArch64 is not used for multiversioning
11728 if (NewTA && T.isAArch64())
11729 return false;
11730
11731 // Target attribute on RISCV is not used for multiversioning
11732 if (NewTA && T.isRISCV())
11733 return false;
11734
11735 if (!OldDecl || !OldDecl->getAsFunction() ||
11736 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
11737 NewFD->getDeclContext()->getRedeclContext())) {
11738 // If there's no previous declaration, AND this isn't attempting to cause
11739 // multiversioning, this isn't an error condition.
11740 if (MVKind == MultiVersionKind::None)
11741 return false;
11742 return CheckMultiVersionFirstFunction(S, NewFD);
11743 }
11744
11745 FunctionDecl *OldFD = OldDecl->getAsFunction();
11746
11747 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11748 return false;
11749
11750 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11751 // for target_clones and target_version.
11752 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11755 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11757 NewFD->setInvalidDecl();
11758 return true;
11759 }
11760
11761 if (!OldFD->isMultiVersion()) {
11762 switch (MVKind) {
11766 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
11768 if (OldFD->isUsed(false)) {
11769 NewFD->setInvalidDecl();
11770 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11771 }
11772 OldFD->setIsMultiVersion();
11773 break;
11774
11778 break;
11779 }
11780 }
11781
11782 // At this point, we have a multiversion function decl (in OldFD) AND an
11783 // appropriate attribute in the current function decl. Resolve that these are
11784 // still compatible with previous declarations.
11785 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11786 NewCPUSpec, NewClones, Redeclaration,
11787 OldDecl, Previous);
11788}
11789
11791 bool IsPure = NewFD->hasAttr<PureAttr>();
11792 bool IsConst = NewFD->hasAttr<ConstAttr>();
11793
11794 // If there are no pure or const attributes, there's nothing to check.
11795 if (!IsPure && !IsConst)
11796 return;
11797
11798 // If the function is marked both pure and const, we retain the const
11799 // attribute because it makes stronger guarantees than the pure attribute, and
11800 // we drop the pure attribute explicitly to prevent later confusion about
11801 // semantics.
11802 if (IsPure && IsConst) {
11803 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
11804 NewFD->dropAttrs<PureAttr>();
11805 }
11806
11807 // Constructors and destructors are functions which return void, so are
11808 // handled here as well.
11809 if (NewFD->getReturnType()->isVoidType()) {
11810 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
11811 << IsConst;
11812 NewFD->dropAttrs<PureAttr, ConstAttr>();
11813 }
11814}
11815
11818 bool IsMemberSpecialization,
11819 bool DeclIsDefn) {
11820 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11821 "Variably modified return types are not handled here");
11822
11823 // Determine whether the type of this function should be merged with
11824 // a previous visible declaration. This never happens for functions in C++,
11825 // and always happens in C if the previous declaration was visible.
11826 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11827 !Previous.isShadowed();
11828
11829 bool Redeclaration = false;
11830 NamedDecl *OldDecl = nullptr;
11831 bool MayNeedOverloadableChecks = false;
11832
11833 // Merge or overload the declaration with an existing declaration of
11834 // the same name, if appropriate.
11835 if (!Previous.empty()) {
11836 // Determine whether NewFD is an overload of PrevDecl or
11837 // a declaration that requires merging. If it's an overload,
11838 // there's no more work to do here; we'll just add the new
11839 // function to the scope.
11841 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11842 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11843 Redeclaration = true;
11844 OldDecl = Candidate;
11845 }
11846 } else {
11847 MayNeedOverloadableChecks = true;
11848 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11849 /*NewIsUsingDecl*/ false)) {
11850 case Ovl_Match:
11851 Redeclaration = true;
11852 break;
11853
11854 case Ovl_NonFunction:
11855 Redeclaration = true;
11856 break;
11857
11858 case Ovl_Overload:
11859 Redeclaration = false;
11860 break;
11861 }
11862 }
11863 }
11864
11865 // Check for a previous extern "C" declaration with this name.
11866 if (!Redeclaration &&
11868 if (!Previous.empty()) {
11869 // This is an extern "C" declaration with the same name as a previous
11870 // declaration, and thus redeclares that entity...
11871 Redeclaration = true;
11872 OldDecl = Previous.getFoundDecl();
11873 MergeTypeWithPrevious = false;
11874
11875 // ... except in the presence of __attribute__((overloadable)).
11876 if (OldDecl->hasAttr<OverloadableAttr>() ||
11877 NewFD->hasAttr<OverloadableAttr>()) {
11878 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11879 MayNeedOverloadableChecks = true;
11880 Redeclaration = false;
11881 OldDecl = nullptr;
11882 }
11883 }
11884 }
11885 }
11886
11887 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11888 return Redeclaration;
11889
11890 // PPC MMA non-pointer types are not allowed as function return types.
11891 if (Context.getTargetInfo().getTriple().isPPC64() &&
11892 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11893 NewFD->setInvalidDecl();
11894 }
11895
11896 CheckConstPureAttributesUsage(*this, NewFD);
11897
11898 // C++ [dcl.spec.auto.general]p12:
11899 // Return type deduction for a templated function with a placeholder in its
11900 // declared type occurs when the definition is instantiated even if the
11901 // function body contains a return statement with a non-type-dependent
11902 // operand.
11903 //
11904 // C++ [temp.dep.expr]p3:
11905 // An id-expression is type-dependent if it is a template-id that is not a
11906 // concept-id and is dependent; or if its terminal name is:
11907 // - [...]
11908 // - associated by name lookup with one or more declarations of member
11909 // functions of a class that is the current instantiation declared with a
11910 // return type that contains a placeholder type,
11911 // - [...]
11912 //
11913 // If this is a templated function with a placeholder in its return type,
11914 // make the placeholder type dependent since it won't be deduced until the
11915 // definition is instantiated. We do this here because it needs to happen
11916 // for implicitly instantiated member functions/member function templates.
11917 if (getLangOpts().CPlusPlus14 &&
11918 (NewFD->isDependentContext() &&
11919 NewFD->getReturnType()->isUndeducedType())) {
11920 const FunctionProtoType *FPT =
11921 NewFD->getType()->castAs<FunctionProtoType>();
11922 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
11923 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
11924 FPT->getExtProtoInfo()));
11925 }
11926
11927 // C++11 [dcl.constexpr]p8:
11928 // A constexpr specifier for a non-static member function that is not
11929 // a constructor declares that member function to be const.
11930 //
11931 // This needs to be delayed until we know whether this is an out-of-line
11932 // definition of a static member function.
11933 //
11934 // This rule is not present in C++1y, so we produce a backwards
11935 // compatibility warning whenever it happens in C++11.
11936 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11937 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11938 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11939 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11940 CXXMethodDecl *OldMD = nullptr;
11941 if (OldDecl)
11942 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11943 if (!OldMD || !OldMD->isStatic()) {
11944 const FunctionProtoType *FPT =
11947 EPI.TypeQuals.addConst();
11949 FPT->getParamTypes(), EPI));
11950
11951 // Warn that we did this, if we're not performing template instantiation.
11952 // In that case, we'll have warned already when the template was defined.
11953 if (!inTemplateInstantiation()) {
11954 SourceLocation AddConstLoc;
11957 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11958
11959 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11960 << FixItHint::CreateInsertion(AddConstLoc, " const");
11961 }
11962 }
11963 }
11964
11965 if (Redeclaration) {
11966 // NewFD and OldDecl represent declarations that need to be
11967 // merged.
11968 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11969 DeclIsDefn)) {
11970 NewFD->setInvalidDecl();
11971 return Redeclaration;
11972 }
11973
11974 Previous.clear();
11975 Previous.addDecl(OldDecl);
11976
11977 if (FunctionTemplateDecl *OldTemplateDecl =
11978 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11979 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11980 FunctionTemplateDecl *NewTemplateDecl
11982 assert(NewTemplateDecl && "Template/non-template mismatch");
11983
11984 // The call to MergeFunctionDecl above may have created some state in
11985 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11986 // can add it as a redeclaration.
11987 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11988
11989 NewFD->setPreviousDeclaration(OldFD);
11990 if (NewFD->isCXXClassMember()) {
11991 NewFD->setAccess(OldTemplateDecl->getAccess());
11992 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11993 }
11994
11995 // If this is an explicit specialization of a member that is a function
11996 // template, mark it as a member specialization.
11997 if (IsMemberSpecialization &&
11998 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11999 NewTemplateDecl->setMemberSpecialization();
12000 assert(OldTemplateDecl->isMemberSpecialization());
12001 // Explicit specializations of a member template do not inherit deleted
12002 // status from the parent member template that they are specializing.
12003 if (OldFD->isDeleted()) {
12004 // FIXME: This assert will not hold in the presence of modules.
12005 assert(OldFD->getCanonicalDecl() == OldFD);
12006 // FIXME: We need an update record for this AST mutation.
12007 OldFD->setDeletedAsWritten(false);
12008 }
12009 }
12010
12011 } else {
12012 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12013 auto *OldFD = cast<FunctionDecl>(OldDecl);
12014 // This needs to happen first so that 'inline' propagates.
12015 NewFD->setPreviousDeclaration(OldFD);
12016 if (NewFD->isCXXClassMember())
12017 NewFD->setAccess(OldFD->getAccess());
12018 }
12019 }
12020 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12021 !NewFD->getAttr<OverloadableAttr>()) {
12022 assert((Previous.empty() ||
12023 llvm::any_of(Previous,
12024 [](const NamedDecl *ND) {
12025 return ND->hasAttr<OverloadableAttr>();
12026 })) &&
12027 "Non-redecls shouldn't happen without overloadable present");
12028
12029 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12030 const auto *FD = dyn_cast<FunctionDecl>(ND);
12031 return FD && !FD->hasAttr<OverloadableAttr>();
12032 });
12033
12034 if (OtherUnmarkedIter != Previous.end()) {
12035 Diag(NewFD->getLocation(),
12036 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12037 Diag((*OtherUnmarkedIter)->getLocation(),
12038 diag::note_attribute_overloadable_prev_overload)
12039 << false;
12040
12041 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12042 }
12043 }
12044
12045 if (LangOpts.OpenMP)
12047
12048 // Semantic checking for this function declaration (in isolation).
12049
12050 if (getLangOpts().CPlusPlus) {
12051 // C++-specific checks.
12052 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12053 CheckConstructor(Constructor);
12054 } else if (CXXDestructorDecl *Destructor =
12055 dyn_cast<CXXDestructorDecl>(NewFD)) {
12056 // We check here for invalid destructor names.
12057 // If we have a friend destructor declaration that is dependent, we can't
12058 // diagnose right away because cases like this are still valid:
12059 // template <class T> struct A { friend T::X::~Y(); };
12060 // struct B { struct Y { ~Y(); }; using X = Y; };
12061 // template struct A<B>;
12063 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12064 CXXRecordDecl *Record = Destructor->getParent();
12066
12068 Context.getCanonicalType(ClassType));
12069 if (NewFD->getDeclName() != Name) {
12070 Diag(NewFD->getLocation(), diag::err_destructor_name);
12071 NewFD->setInvalidDecl();
12072 return Redeclaration;
12073 }
12074 }
12075 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12076 if (auto *TD = Guide->getDescribedFunctionTemplate())
12078
12079 // A deduction guide is not on the list of entities that can be
12080 // explicitly specialized.
12081 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12082 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12083 << /*explicit specialization*/ 1;
12084 }
12085
12086 // Find any virtual functions that this function overrides.
12087 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12088 if (!Method->isFunctionTemplateSpecialization() &&
12089 !Method->getDescribedFunctionTemplate() &&
12090 Method->isCanonicalDecl()) {
12091 AddOverriddenMethods(Method->getParent(), Method);
12092 }
12093 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12094 // C++2a [class.virtual]p6
12095 // A virtual method shall not have a requires-clause.
12097 diag::err_constrained_virtual_method);
12098
12099 if (Method->isStatic())
12101 }
12102
12103 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12104 ActOnConversionDeclarator(Conversion);
12105
12106 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12107 if (NewFD->isOverloadedOperator() &&
12109 NewFD->setInvalidDecl();
12110 return Redeclaration;
12111 }
12112
12113 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12114 if (NewFD->getLiteralIdentifier() &&
12116 NewFD->setInvalidDecl();
12117 return Redeclaration;
12118 }
12119
12120 // In C++, check default arguments now that we have merged decls. Unless
12121 // the lexical context is the class, because in this case this is done
12122 // during delayed parsing anyway.
12123 if (!CurContext->isRecord())
12125
12126 // If this function is declared as being extern "C", then check to see if
12127 // the function returns a UDT (class, struct, or union type) that is not C
12128 // compatible, and if it does, warn the user.
12129 // But, issue any diagnostic on the first declaration only.
12130 if (Previous.empty() && NewFD->isExternC()) {
12131 QualType R = NewFD->getReturnType();
12132 if (R->isIncompleteType() && !R->isVoidType())
12133 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12134 << NewFD << R;
12135 else if (!R.isPODType(Context) && !R->isVoidType() &&
12137 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12138 }
12139
12140 // C++1z [dcl.fct]p6:
12141 // [...] whether the function has a non-throwing exception-specification
12142 // [is] part of the function type
12143 //
12144 // This results in an ABI break between C++14 and C++17 for functions whose
12145 // declared type includes an exception-specification in a parameter or
12146 // return type. (Exception specifications on the function itself are OK in
12147 // most cases, and exception specifications are not permitted in most other
12148 // contexts where they could make it into a mangling.)
12149 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12150 auto HasNoexcept = [&](QualType T) -> bool {
12151 // Strip off declarator chunks that could be between us and a function
12152 // type. We don't need to look far, exception specifications are very
12153 // restricted prior to C++17.
12154 if (auto *RT = T->getAs<ReferenceType>())
12155 T = RT->getPointeeType();
12156 else if (T->isAnyPointerType())
12157 T = T->getPointeeType();
12158 else if (auto *MPT = T->getAs<MemberPointerType>())
12159 T = MPT->getPointeeType();
12160 if (auto *FPT = T->getAs<FunctionProtoType>())
12161 if (FPT->isNothrow())
12162 return true;
12163 return false;
12164 };
12165
12166 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12167 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12168 for (QualType T : FPT->param_types())
12169 AnyNoexcept |= HasNoexcept(T);
12170 if (AnyNoexcept)
12171 Diag(NewFD->getLocation(),
12172 diag::warn_cxx17_compat_exception_spec_in_signature)
12173 << NewFD;
12174 }
12175
12176 if (!Redeclaration && LangOpts.CUDA)
12178 }
12179
12180 // Check if the function definition uses any AArch64 SME features without
12181 // having the '+sme' feature enabled and warn user if sme locally streaming
12182 // function returns or uses arguments with VL-based types.
12183 if (DeclIsDefn) {
12184 const auto *Attr = NewFD->getAttr<ArmNewAttr>();
12185 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12186 bool UsesZA = Attr && Attr->isNewZA();
12187 bool UsesZT0 = Attr && Attr->isNewZT0();
12188
12189 if (NewFD->hasAttr<ArmLocallyStreamingAttr>()) {
12190 if (NewFD->getReturnType()->isSizelessVectorType())
12191 Diag(NewFD->getLocation(),
12192 diag::warn_sme_locally_streaming_has_vl_args_returns)
12193 << /*IsArg=*/false;
12194 if (llvm::any_of(NewFD->parameters(), [](ParmVarDecl *P) {
12195 return P->getOriginalType()->isSizelessVectorType();
12196 }))
12197 Diag(NewFD->getLocation(),
12198 diag::warn_sme_locally_streaming_has_vl_args_returns)
12199 << /*IsArg=*/true;
12200 }
12201 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12202 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12203 UsesSM |=
12209 }
12210
12211 if (UsesSM || UsesZA) {
12212 llvm::StringMap<bool> FeatureMap;
12213 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12214 if (!FeatureMap.contains("sme")) {
12215 if (UsesSM)
12216 Diag(NewFD->getLocation(),
12217 diag::err_sme_definition_using_sm_in_non_sme_target);
12218 else
12219 Diag(NewFD->getLocation(),
12220 diag::err_sme_definition_using_za_in_non_sme_target);
12221 }
12222 }
12223 if (UsesZT0) {
12224 llvm::StringMap<bool> FeatureMap;
12225 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12226 if (!FeatureMap.contains("sme2")) {
12227 Diag(NewFD->getLocation(),
12228 diag::err_sme_definition_using_zt0_in_non_sme2_target);
12229 }
12230 }
12231 }
12232
12233 return Redeclaration;
12234}
12235
12237 // [basic.start.main]p3
12238 // The main function shall not be declared with a linkage-specification.
12239 if (FD->isExternCContext() ||
12240 (FD->isExternCXXContext() &&
12242 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification)
12243 << FD->getLanguageLinkage();
12244
12245 // C++11 [basic.start.main]p3:
12246 // A program that [...] declares main to be inline, static or
12247 // constexpr is ill-formed.
12248 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12249 // appear in a declaration of main.
12250 // static main is not an error under C99, but we should warn about it.
12251 // We accept _Noreturn main as an extension.
12252 if (FD->getStorageClass() == SC_Static)
12254 ? diag::err_static_main : diag::warn_static_main)
12256 if (FD->isInlineSpecified())
12257 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12259 if (DS.isNoreturnSpecified()) {
12260 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12261 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12262 Diag(NoreturnLoc, diag::ext_noreturn_main);
12263 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12264 << FixItHint::CreateRemoval(NoreturnRange);
12265 }
12266 if (FD->isConstexpr()) {
12267 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12268 << FD->isConsteval()
12271 }
12272
12273 if (getLangOpts().OpenCL) {
12274 Diag(FD->getLocation(), diag::err_opencl_no_main)
12275 << FD->hasAttr<OpenCLKernelAttr>();
12276 FD->setInvalidDecl();
12277 return;
12278 }
12279
12280 // Functions named main in hlsl are default entries, but don't have specific
12281 // signatures they are required to conform to.
12282 if (getLangOpts().HLSL)
12283 return;
12284
12285 QualType T = FD->getType();
12286 assert(T->isFunctionType() && "function decl is not of function type");
12287 const FunctionType* FT = T->castAs<FunctionType>();
12288
12289 // Set default calling convention for main()
12290 if (FT->getCallConv() != CC_C) {
12292 FD->setType(QualType(FT, 0));
12294 }
12295
12296 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12297 // In C with GNU extensions we allow main() to have non-integer return
12298 // type, but we should warn about the extension, and we disable the
12299 // implicit-return-zero rule.
12300
12301 // GCC in C mode accepts qualified 'int'.
12303 FD->setHasImplicitReturnZero(true);
12304 else {
12305 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12306 SourceRange RTRange = FD->getReturnTypeSourceRange();
12307 if (RTRange.isValid())
12308 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12309 << FixItHint::CreateReplacement(RTRange, "int");
12310 }
12311 } else {
12312 // In C and C++, main magically returns 0 if you fall off the end;
12313 // set the flag which tells us that.
12314 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12315
12316 // All the standards say that main() should return 'int'.
12318 FD->setHasImplicitReturnZero(true);
12319 else {
12320 // Otherwise, this is just a flat-out error.
12321 SourceRange RTRange = FD->getReturnTypeSourceRange();
12322 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12323 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12324 : FixItHint());
12325 FD->setInvalidDecl(true);
12326 }
12327 }
12328
12329 // Treat protoless main() as nullary.
12330 if (isa<FunctionNoProtoType>(FT)) return;
12331
12332 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12333 unsigned nparams = FTP->getNumParams();
12334 assert(FD->getNumParams() == nparams);
12335
12336 bool HasExtraParameters = (nparams > 3);
12337
12338 if (FTP->isVariadic()) {
12339 Diag(FD->getLocation(), diag::ext_variadic_main);
12340 // FIXME: if we had information about the location of the ellipsis, we
12341 // could add a FixIt hint to remove it as a parameter.
12342 }
12343
12344 // Darwin passes an undocumented fourth argument of type char**. If
12345 // other platforms start sprouting these, the logic below will start
12346 // getting shifty.
12347 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12348 HasExtraParameters = false;
12349
12350 if (HasExtraParameters) {
12351 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12352 FD->setInvalidDecl(true);
12353 nparams = 3;
12354 }
12355
12356 // FIXME: a lot of the following diagnostics would be improved
12357 // if we had some location information about types.
12358
12359 QualType CharPP =
12361 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12362
12363 for (unsigned i = 0; i < nparams; ++i) {
12364 QualType AT = FTP->getParamType(i);
12365
12366 bool mismatch = true;
12367
12369 mismatch = false;
12370 else if (Expected[i] == CharPP) {
12371 // As an extension, the following forms are okay:
12372 // char const **
12373 // char const * const *
12374 // char * const *
12375
12377 const PointerType* PT;
12378 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12379 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12381 Context.CharTy)) {
12382 qs.removeConst();
12383 mismatch = !qs.empty();
12384 }
12385 }
12386
12387 if (mismatch) {
12388 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12389 // TODO: suggest replacing given type with expected type
12390 FD->setInvalidDecl(true);
12391 }
12392 }
12393
12394 if (nparams == 1 && !FD->isInvalidDecl()) {
12395 Diag(FD->getLocation(), diag::warn_main_one_arg);
12396 }
12397
12398 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12399 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12400 FD->setInvalidDecl();
12401 }
12402}
12403
12404static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12405
12406 // Default calling convention for main and wmain is __cdecl
12407 if (FD->getName() == "main" || FD->getName() == "wmain")
12408 return false;
12409
12410 // Default calling convention for MinGW is __cdecl
12411 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12412 if (T.isWindowsGNUEnvironment())
12413 return false;
12414
12415 // Default calling convention for WinMain, wWinMain and DllMain
12416 // is __stdcall on 32 bit Windows
12417 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12418 return true;
12419
12420 return false;
12421}
12422
12424 QualType T = FD->getType();
12425 assert(T->isFunctionType() && "function decl is not of function type");
12426 const FunctionType *FT = T->castAs<FunctionType>();
12427
12428 // Set an implicit return of 'zero' if the function can return some integral,
12429 // enumeration, pointer or nullptr type.
12433 // DllMain is exempt because a return value of zero means it failed.
12434 if (FD->getName() != "DllMain")
12435 FD->setHasImplicitReturnZero(true);
12436
12437 // Explicitly specified calling conventions are applied to MSVC entry points
12438 if (!hasExplicitCallingConv(T)) {
12439 if (isDefaultStdCall(FD, *this)) {
12440 if (FT->getCallConv() != CC_X86StdCall) {
12443 FD->setType(QualType(FT, 0));
12444 }
12445 } else if (FT->getCallConv() != CC_C) {
12448 FD->setType(QualType(FT, 0));
12449 }
12450 }
12451
12452 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12453 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12454 FD->setInvalidDecl();
12455 }
12456}
12457
12459 // FIXME: Need strict checking. In C89, we need to check for
12460 // any assignment, increment, decrement, function-calls, or
12461 // commas outside of a sizeof. In C99, it's the same list,
12462 // except that the aforementioned are allowed in unevaluated
12463 // expressions. Everything else falls under the
12464 // "may accept other forms of constant expressions" exception.
12465 //
12466 // Regular C++ code will not end up here (exceptions: language extensions,
12467 // OpenCL C++ etc), so the constant expression rules there don't matter.
12468 if (Init->isValueDependent()) {
12469 assert(Init->containsErrors() &&
12470 "Dependent code should only occur in error-recovery path.");
12471 return true;
12472 }
12473 const Expr *Culprit;
12474 if (Init->isConstantInitializer(Context, false, &Culprit))
12475 return false;
12476 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12477 return true;
12478}
12479
12480namespace {
12481 // Visits an initialization expression to see if OrigDecl is evaluated in
12482 // its own initialization and throws a warning if it does.
12483 class SelfReferenceChecker
12484 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12485 Sema &S;
12486 Decl *OrigDecl;
12487 bool isRecordType;
12488 bool isPODType;
12489 bool isReferenceType;
12490
12491 bool isInitList;
12492 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12493
12494 public:
12496
12497 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12498 S(S), OrigDecl(OrigDecl) {
12499 isPODType = false;
12500 isRecordType = false;
12501 isReferenceType = false;
12502 isInitList = false;
12503 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12504 isPODType = VD->getType().isPODType(S.Context);
12505 isRecordType = VD->getType()->isRecordType();
12506 isReferenceType = VD->getType()->isReferenceType();
12507 }
12508 }
12509
12510 // For most expressions, just call the visitor. For initializer lists,
12511 // track the index of the field being initialized since fields are
12512 // initialized in order allowing use of previously initialized fields.
12513 void CheckExpr(Expr *E) {
12514 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12515 if (!InitList) {
12516 Visit(E);
12517 return;
12518 }
12519
12520 // Track and increment the index here.
12521 isInitList = true;
12522 InitFieldIndex.push_back(0);
12523 for (auto *Child : InitList->children()) {
12524 CheckExpr(cast<Expr>(Child));
12525 ++InitFieldIndex.back();
12526 }
12527 InitFieldIndex.pop_back();
12528 }
12529
12530 // Returns true if MemberExpr is checked and no further checking is needed.
12531 // Returns false if additional checking is required.
12532 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12534 Expr *Base = E;
12535 bool ReferenceField = false;
12536
12537 // Get the field members used.
12538 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12539 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12540 if (!FD)
12541 return false;
12542 Fields.push_back(FD);
12543 if (FD->getType()->isReferenceType())
12544 ReferenceField = true;
12545 Base = ME->getBase()->IgnoreParenImpCasts();
12546 }
12547
12548 // Keep checking only if the base Decl is the same.
12549 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12550 if (!DRE || DRE->getDecl() != OrigDecl)
12551 return false;
12552
12553 // A reference field can be bound to an unininitialized field.
12554 if (CheckReference && !ReferenceField)
12555 return true;
12556
12557 // Convert FieldDecls to their index number.
12558 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12559 for (const FieldDecl *I : llvm::reverse(Fields))
12560 UsedFieldIndex.push_back(I->getFieldIndex());
12561
12562 // See if a warning is needed by checking the first difference in index
12563 // numbers. If field being used has index less than the field being
12564 // initialized, then the use is safe.
12565 for (auto UsedIter = UsedFieldIndex.begin(),
12566 UsedEnd = UsedFieldIndex.end(),
12567 OrigIter = InitFieldIndex.begin(),
12568 OrigEnd = InitFieldIndex.end();
12569 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12570 if (*UsedIter < *OrigIter)
12571 return true;
12572 if (*UsedIter > *OrigIter)
12573 break;
12574 }
12575
12576 // TODO: Add a different warning which will print the field names.
12577 HandleDeclRefExpr(DRE);
12578 return true;
12579 }
12580
12581 // For most expressions, the cast is directly above the DeclRefExpr.
12582 // For conditional operators, the cast can be outside the conditional
12583 // operator if both expressions are DeclRefExpr's.
12584 void HandleValue(Expr *E) {
12585 E = E->IgnoreParens();
12586 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12587 HandleDeclRefExpr(DRE);
12588 return;
12589 }
12590
12591 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12592 Visit(CO->getCond());
12593 HandleValue(CO->getTrueExpr());
12594 HandleValue(CO->getFalseExpr());
12595 return;
12596 }
12597
12598 if (BinaryConditionalOperator *BCO =
12599 dyn_cast<BinaryConditionalOperator>(E)) {
12600 Visit(BCO->getCond());
12601 HandleValue(BCO->getFalseExpr());
12602 return;
12603 }
12604
12605 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12606 if (Expr *SE = OVE->getSourceExpr())
12607 HandleValue(SE);
12608 return;
12609 }
12610
12611 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12612 if (BO->getOpcode() == BO_Comma) {
12613 Visit(BO->getLHS());
12614 HandleValue(BO->getRHS());
12615 return;
12616 }
12617 }
12618
12619 if (isa<MemberExpr>(E)) {
12620 if (isInitList) {
12621 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12622 false /*CheckReference*/))
12623 return;
12624 }
12625
12627 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12628 // Check for static member variables and don't warn on them.
12629 if (!isa<FieldDecl>(ME->getMemberDecl()))
12630 return;
12631 Base = ME->getBase()->IgnoreParenImpCasts();
12632 }
12633 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12634 HandleDeclRefExpr(DRE);
12635 return;
12636 }
12637
12638 Visit(E);
12639 }
12640
12641 // Reference types not handled in HandleValue are handled here since all
12642 // uses of references are bad, not just r-value uses.
12643 void VisitDeclRefExpr(DeclRefExpr *E) {
12644 if (isReferenceType)
12645 HandleDeclRefExpr(E);
12646 }
12647
12648 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12649 if (E->getCastKind() == CK_LValueToRValue) {
12650 HandleValue(E->getSubExpr());
12651 return;
12652 }
12653
12654 Inherited::VisitImplicitCastExpr(E);
12655 }
12656
12657 void VisitMemberExpr(MemberExpr *E) {
12658 if (isInitList) {
12659 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12660 return;
12661 }
12662
12663 // Don't warn on arrays since they can be treated as pointers.
12664 if (E->getType()->canDecayToPointerType()) return;
12665
12666 // Warn when a non-static method call is followed by non-static member
12667 // field accesses, which is followed by a DeclRefExpr.
12668 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12669 bool Warn = (MD && !MD->isStatic());
12670 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12671 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12672 if (!isa<FieldDecl>(ME->getMemberDecl()))
12673 Warn = false;
12674 Base = ME->getBase()->IgnoreParenImpCasts();
12675 }
12676
12677 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12678 if (Warn)
12679 HandleDeclRefExpr(DRE);
12680 return;
12681 }
12682
12683 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12684 // Visit that expression.
12685 Visit(Base);
12686 }
12687
12688 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12689 Expr *Callee = E->getCallee();
12690
12691 if (isa<UnresolvedLookupExpr>(Callee))
12692 return Inherited::VisitCXXOperatorCallExpr(E);
12693
12694 Visit(Callee);
12695 for (auto Arg: E->arguments())
12696 HandleValue(Arg->IgnoreParenImpCasts());
12697 }
12698
12699 void VisitUnaryOperator(UnaryOperator *E) {
12700 // For POD record types, addresses of its own members are well-defined.
12701 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12702 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12703 if (!isPODType)
12704 HandleValue(E->getSubExpr());
12705 return;
12706 }
12707
12708 if (E->isIncrementDecrementOp()) {
12709 HandleValue(E->getSubExpr());
12710 return;
12711 }
12712
12713 Inherited::VisitUnaryOperator(E);
12714 }
12715
12716 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12717
12718 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12719 if (E->getConstructor()->isCopyConstructor()) {
12720 Expr *ArgExpr = E->getArg(0);
12721 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12722 if (ILE->getNumInits() == 1)
12723 ArgExpr = ILE->getInit(0);
12724 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12725 if (ICE->getCastKind() == CK_NoOp)
12726 ArgExpr = ICE->getSubExpr();
12727 HandleValue(ArgExpr);
12728 return;
12729 }
12730 Inherited::VisitCXXConstructExpr(E);
12731 }
12732
12733 void VisitCallExpr(CallExpr *E) {
12734 // Treat std::move as a use.
12735 if (E->isCallToStdMove()) {
12736 HandleValue(E->getArg(0));
12737 return;
12738 }
12739
12740 Inherited::VisitCallExpr(E);
12741 }
12742
12743 void VisitBinaryOperator(BinaryOperator *E) {
12744 if (E->isCompoundAssignmentOp()) {
12745 HandleValue(E->getLHS());
12746 Visit(E->getRHS());
12747 return;
12748 }
12749
12750 Inherited::VisitBinaryOperator(E);
12751 }
12752
12753 // A custom visitor for BinaryConditionalOperator is needed because the
12754 // regular visitor would check the condition and true expression separately
12755 // but both point to the same place giving duplicate diagnostics.
12756 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12757 Visit(E->getCond());
12758 Visit(E->getFalseExpr());
12759 }
12760
12761 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12762 Decl* ReferenceDecl = DRE->getDecl();
12763 if (OrigDecl != ReferenceDecl) return;
12764 unsigned diag;
12765 if (isReferenceType) {
12766 diag = diag::warn_uninit_self_reference_in_reference_init;
12767 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12768 diag = diag::warn_static_self_reference_in_init;
12769 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12770 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12771 DRE->getDecl()->getType()->isRecordType()) {
12772 diag = diag::warn_uninit_self_reference_in_init;
12773 } else {
12774 // Local variables will be handled by the CFG analysis.
12775 return;
12776 }
12777
12778 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12779 S.PDiag(diag)
12780 << DRE->getDecl() << OrigDecl->getLocation()
12781 << DRE->getSourceRange());
12782 }
12783 };
12784
12785 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12786 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12787 bool DirectInit) {
12788 // Parameters arguments are occassionially constructed with itself,
12789 // for instance, in recursive functions. Skip them.
12790 if (isa<ParmVarDecl>(OrigDecl))
12791 return;
12792
12793 E = E->IgnoreParens();
12794
12795 // Skip checking T a = a where T is not a record or reference type.
12796 // Doing so is a way to silence uninitialized warnings.
12797 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12798 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12799 if (ICE->getCastKind() == CK_LValueToRValue)
12800 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12801 if (DRE->getDecl() == OrigDecl)
12802 return;
12803
12804 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12805 }
12806} // end anonymous namespace
12807
12808namespace {
12809 // Simple wrapper to add the name of a variable or (if no variable is
12810 // available) a DeclarationName into a diagnostic.
12811 struct VarDeclOrName {
12812 VarDecl *VDecl;
12813 DeclarationName Name;
12814
12815 friend const Sema::SemaDiagnosticBuilder &
12816 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12817 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12818 }
12819 };
12820} // end anonymous namespace
12821
12824 TypeSourceInfo *TSI,
12826 Expr *Init) {
12827 bool IsInitCapture = !VDecl;
12828 assert((!VDecl || !VDecl->isInitCapture()) &&
12829 "init captures are expected to be deduced prior to initialization");
12830
12831 VarDeclOrName VN{VDecl, Name};
12832
12834 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12835
12836 // Diagnose auto array declarations in C23, unless it's a supported extension.
12837 if (getLangOpts().C23 && Type->isArrayType() &&
12838 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
12839 Diag(Range.getBegin(), diag::err_auto_not_allowed)
12840 << (int)Deduced->getContainedAutoType()->getKeyword()
12841 << /*in array decl*/ 23 << Range;
12842 return QualType();
12843 }
12844
12845 // C++11 [dcl.spec.auto]p3
12846 if (!Init) {
12847 assert(VDecl && "no init for init capture deduction?");
12848
12849 // Except for class argument deduction, and then for an initializing
12850 // declaration only, i.e. no static at class scope or extern.
12851 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12852 VDecl->hasExternalStorage() ||
12853 VDecl->isStaticDataMember()) {
12854 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12855 << VDecl->getDeclName() << Type;
12856 return QualType();
12857 }
12858 }
12859
12860 ArrayRef<Expr*> DeduceInits;
12861 if (Init)
12862 DeduceInits = Init;
12863
12864 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12865 if (DirectInit && PL)
12866 DeduceInits = PL->exprs();
12867
12868 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12869 assert(VDecl && "non-auto type for init capture deduction?");
12872 VDecl->getLocation(), DirectInit, Init);
12873 // FIXME: Initialization should not be taking a mutable list of inits.
12874 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
12875 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12876 InitsCopy);
12877 }
12878
12879 if (DirectInit) {
12880 if (auto *IL = dyn_cast<InitListExpr>(Init))
12881 DeduceInits = IL->inits();
12882 }
12883
12884 // Deduction only works if we have exactly one source expression.
12885 if (DeduceInits.empty()) {
12886 // It isn't possible to write this directly, but it is possible to
12887 // end up in this situation with "auto x(some_pack...);"
12888 Diag(Init->getBeginLoc(), IsInitCapture
12889 ? diag::err_init_capture_no_expression
12890 : diag::err_auto_var_init_no_expression)
12891 << VN << Type << Range;
12892 return QualType();
12893 }
12894
12895 if (DeduceInits.size() > 1) {
12896 Diag(DeduceInits[1]->getBeginLoc(),
12897 IsInitCapture ? diag::err_init_capture_multiple_expressions
12898 : diag::err_auto_var_init_multiple_expressions)
12899 << VN << Type << Range;
12900 return QualType();
12901 }
12902
12903 Expr *DeduceInit = DeduceInits[0];
12904 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12905 Diag(Init->getBeginLoc(), IsInitCapture
12906 ? diag::err_init_capture_paren_braces
12907 : diag::err_auto_var_init_paren_braces)
12908 << isa<InitListExpr>(Init) << VN << Type << Range;
12909 return QualType();
12910 }
12911
12912 // Expressions default to 'id' when we're in a debugger.
12913 bool DefaultedAnyToId = false;
12914 if (getLangOpts().DebuggerCastResultToId &&
12915 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12917 if (Result.isInvalid()) {
12918 return QualType();
12919 }
12920 Init = Result.get();
12921 DefaultedAnyToId = true;
12922 }
12923
12924 // C++ [dcl.decomp]p1:
12925 // If the assignment-expression [...] has array type A and no ref-qualifier
12926 // is present, e has type cv A
12927 if (VDecl && isa<DecompositionDecl>(VDecl) &&
12929 DeduceInit->getType()->isConstantArrayType())
12930 return Context.getQualifiedType(DeduceInit->getType(),
12931 Type.getQualifiers());
12932
12934 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12936 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12939 if (!IsInitCapture)
12940 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12941 else if (isa<InitListExpr>(Init))
12943 diag::err_init_capture_deduction_failure_from_init_list)
12944 << VN
12945 << (DeduceInit->getType().isNull() ? TSI->getType()
12946 : DeduceInit->getType())
12947 << DeduceInit->getSourceRange();
12948 else
12949 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12950 << VN << TSI->getType()
12951 << (DeduceInit->getType().isNull() ? TSI->getType()
12952 : DeduceInit->getType())
12953 << DeduceInit->getSourceRange();
12954 }
12955
12956 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12957 // 'id' instead of a specific object type prevents most of our usual
12958 // checks.
12959 // We only want to warn outside of template instantiations, though:
12960 // inside a template, the 'id' could have come from a parameter.
12961 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12962 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12964 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12965 }
12966
12967 return DeducedType;
12968}
12969
12971 Expr *Init) {
12972 assert(!Init || !Init->containsErrors());
12974 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12975 VDecl->getSourceRange(), DirectInit, Init);
12976 if (DeducedType.isNull()) {
12977 VDecl->setInvalidDecl();
12978 return true;
12979 }
12980
12981 VDecl->setType(DeducedType);
12982 assert(VDecl->isLinkageValid());
12983
12984 // In ARC, infer lifetime.
12985 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
12986 VDecl->setInvalidDecl();
12987
12988 if (getLangOpts().OpenCL)
12990
12991 // If this is a redeclaration, check that the type we just deduced matches
12992 // the previously declared type.
12993 if (VarDecl *Old = VDecl->getPreviousDecl()) {
12994 // We never need to merge the type, because we cannot form an incomplete
12995 // array of auto, nor deduce such a type.
12996 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12997 }
12998
12999 // Check the deduced type is valid for a variable declaration.
13001 return VDecl->isInvalidDecl();
13002}
13003
13006 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13007 Init = EWC->getSubExpr();
13008
13009 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13010 Init = CE->getSubExpr();
13011
13012 QualType InitType = Init->getType();
13015 "shouldn't be called if type doesn't have a non-trivial C struct");
13016 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13017 for (auto *I : ILE->inits()) {
13018 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13019 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13020 continue;
13021 SourceLocation SL = I->getExprLoc();
13023 }
13024 return;
13025 }
13026
13027 if (isa<ImplicitValueInitExpr>(Init)) {
13030 NTCUK_Init);
13031 } else {
13032 // Assume all other explicit initializers involving copying some existing
13033 // object.
13034 // TODO: ignore any explicit initializers where we can guarantee
13035 // copy-elision.
13038 }
13039}
13040
13041namespace {
13042
13043bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13044 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13045 // in the source code or implicitly by the compiler if it is in a union
13046 // defined in a system header and has non-trivial ObjC ownership
13047 // qualifications. We don't want those fields to participate in determining
13048 // whether the containing union is non-trivial.
13049 return FD->hasAttr<UnavailableAttr>();
13050}
13051
13052struct DiagNonTrivalCUnionDefaultInitializeVisitor
13053 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13054 void> {
13055 using Super =
13056 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13057 void>;
13058
13059 DiagNonTrivalCUnionDefaultInitializeVisitor(
13060 QualType OrigTy, SourceLocation OrigLoc,
13061 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13062 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13063
13064 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13065 const FieldDecl *FD, bool InNonTrivialUnion) {
13066 if (const auto *AT = S.Context.getAsArrayType(QT))
13067 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13068 InNonTrivialUnion);
13069 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13070 }
13071
13072 void visitARCStrong(QualType QT, const FieldDecl *FD,
13073 bool InNonTrivialUnion) {
13074 if (InNonTrivialUnion)
13075 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13076 << 1 << 0 << QT << FD->getName();
13077 }
13078
13079 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13080 if (InNonTrivialUnion)
13081 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13082 << 1 << 0 << QT << FD->getName();
13083 }
13084
13085 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13086 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13087 if (RD->isUnion()) {
13088 if (OrigLoc.isValid()) {
13089 bool IsUnion = false;
13090 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13091 IsUnion = OrigRD->isUnion();
13092 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13093 << 0 << OrigTy << IsUnion << UseContext;
13094 // Reset OrigLoc so that this diagnostic is emitted only once.
13095 OrigLoc = SourceLocation();
13096 }
13097 InNonTrivialUnion = true;
13098 }
13099
13100 if (InNonTrivialUnion)
13101 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13102 << 0 << 0 << QT.getUnqualifiedType() << "";
13103
13104 for (const FieldDecl *FD : RD->fields())
13105 if (!shouldIgnoreForRecordTriviality(FD))
13106 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13107 }
13108
13109 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13110
13111 // The non-trivial C union type or the struct/union type that contains a
13112 // non-trivial C union.
13113 QualType OrigTy;
13114 SourceLocation OrigLoc;
13116 Sema &S;
13117};
13118
13119struct DiagNonTrivalCUnionDestructedTypeVisitor
13120 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13121 using Super =
13123
13124 DiagNonTrivalCUnionDestructedTypeVisitor(
13125 QualType OrigTy, SourceLocation OrigLoc,
13126 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13127 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13128
13129 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13130 const FieldDecl *FD, bool InNonTrivialUnion) {
13131 if (const auto *AT = S.Context.getAsArrayType(QT))
13132 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13133 InNonTrivialUnion);
13134 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13135 }
13136
13137 void visitARCStrong(QualType QT, const FieldDecl *FD,
13138 bool InNonTrivialUnion) {
13139 if (InNonTrivialUnion)
13140 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13141 << 1 << 1 << QT << FD->getName();
13142 }
13143
13144 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13145 if (InNonTrivialUnion)
13146 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13147 << 1 << 1 << QT << FD->getName();
13148 }
13149
13150 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13151 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13152 if (RD->isUnion()) {
13153 if (OrigLoc.isValid()) {
13154 bool IsUnion = false;
13155 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13156 IsUnion = OrigRD->isUnion();
13157 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13158 << 1 << OrigTy << IsUnion << UseContext;
13159 // Reset OrigLoc so that this diagnostic is emitted only once.
13160 OrigLoc = SourceLocation();
13161 }
13162 InNonTrivialUnion = true;
13163 }
13164
13165 if (InNonTrivialUnion)
13166 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13167 << 0 << 1 << QT.getUnqualifiedType() << "";
13168
13169 for (const FieldDecl *FD : RD->fields())
13170 if (!shouldIgnoreForRecordTriviality(FD))
13171 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13172 }
13173
13174 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13175 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13176 bool InNonTrivialUnion) {}
13177
13178 // The non-trivial C union type or the struct/union type that contains a
13179 // non-trivial C union.
13180 QualType OrigTy;
13181 SourceLocation OrigLoc;
13183 Sema &S;
13184};
13185
13186struct DiagNonTrivalCUnionCopyVisitor
13187 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13189
13190 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13192 Sema &S)
13193 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13194
13195 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13196 const FieldDecl *FD, bool InNonTrivialUnion) {
13197 if (const auto *AT = S.Context.getAsArrayType(QT))
13198 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13199 InNonTrivialUnion);
13200 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13201 }
13202
13203 void visitARCStrong(QualType QT, const FieldDecl *FD,
13204 bool InNonTrivialUnion) {
13205 if (InNonTrivialUnion)
13206 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13207 << 1 << 2 << QT << FD->getName();
13208 }
13209
13210 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13211 if (InNonTrivialUnion)
13212 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13213 << 1 << 2 << QT << FD->getName();
13214 }
13215
13216 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13217 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13218 if (RD->isUnion()) {
13219 if (OrigLoc.isValid()) {
13220 bool IsUnion = false;
13221 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13222 IsUnion = OrigRD->isUnion();
13223 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13224 << 2 << OrigTy << IsUnion << UseContext;
13225 // Reset OrigLoc so that this diagnostic is emitted only once.
13226 OrigLoc = SourceLocation();
13227 }
13228 InNonTrivialUnion = true;
13229 }
13230
13231 if (InNonTrivialUnion)
13232 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13233 << 0 << 2 << QT.getUnqualifiedType() << "";
13234
13235 for (const FieldDecl *FD : RD->fields())
13236 if (!shouldIgnoreForRecordTriviality(FD))
13237 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13238 }
13239
13240 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13241 const FieldDecl *FD, bool InNonTrivialUnion) {}
13242 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13243 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13244 bool InNonTrivialUnion) {}
13245
13246 // The non-trivial C union type or the struct/union type that contains a
13247 // non-trivial C union.
13248 QualType OrigTy;
13249 SourceLocation OrigLoc;
13251 Sema &S;
13252};
13253
13254} // namespace
13255
13257 NonTrivialCUnionContext UseContext,
13258 unsigned NonTrivialKind) {
13262 "shouldn't be called if type doesn't have a non-trivial C union");
13263
13264 if ((NonTrivialKind & NTCUK_Init) &&
13266 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13267 .visit(QT, nullptr, false);
13268 if ((NonTrivialKind & NTCUK_Destruct) &&
13270 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13271 .visit(QT, nullptr, false);
13272 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13273 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13274 .visit(QT, nullptr, false);
13275}
13276
13278 // If there is no declaration, there was an error parsing it. Just ignore
13279 // the initializer.
13280 if (!RealDecl) {
13281 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13282 return;
13283 }
13284
13285 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13286 if (!Method->isInvalidDecl()) {
13287 // Pure-specifiers are handled in ActOnPureSpecifier.
13288 Diag(Method->getLocation(), diag::err_member_function_initialization)
13289 << Method->getDeclName() << Init->getSourceRange();
13290 Method->setInvalidDecl();
13291 }
13292 return;
13293 }
13294
13295 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13296 if (!VDecl) {
13297 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13298 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13299 RealDecl->setInvalidDecl();
13300 return;
13301 }
13302
13303 if (VDecl->isInvalidDecl()) {
13305 SmallVector<Expr *> SubExprs;
13306 if (Res.isUsable())
13307 SubExprs.push_back(Res.get());
13308 ExprResult Recovery =
13309 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), SubExprs);
13310 if (Expr *E = Recovery.get())
13311 VDecl->setInit(E);
13312 return;
13313 }
13314
13315 // WebAssembly tables can't be used to initialise a variable.
13316 if (Init && !Init->getType().isNull() &&
13317 Init->getType()->isWebAssemblyTableType()) {
13318 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13319 VDecl->setInvalidDecl();
13320 return;
13321 }
13322
13323 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13324 if (VDecl->getType()->isUndeducedType()) {
13325 // Attempt typo correction early so that the type of the init expression can
13326 // be deduced based on the chosen correction if the original init contains a
13327 // TypoExpr.
13329 if (!Res.isUsable()) {
13330 // There are unresolved typos in Init, just drop them.
13331 // FIXME: improve the recovery strategy to preserve the Init.
13332 RealDecl->setInvalidDecl();
13333 return;
13334 }
13335 if (Res.get()->containsErrors()) {
13336 // Invalidate the decl as we don't know the type for recovery-expr yet.
13337 RealDecl->setInvalidDecl();
13338 VDecl->setInit(Res.get());
13339 return;
13340 }
13341 Init = Res.get();
13342
13344 return;
13345 }
13346
13347 // dllimport cannot be used on variable definitions.
13348 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13349 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13350 VDecl->setInvalidDecl();
13351 return;
13352 }
13353
13354 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13355 // the identifier has external or internal linkage, the declaration shall
13356 // have no initializer for the identifier.
13357 // C++14 [dcl.init]p5 is the same restriction for C++.
13358 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13359 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13360 VDecl->setInvalidDecl();
13361 return;
13362 }
13363
13364 if (!VDecl->getType()->isDependentType()) {
13365 // A definition must end up with a complete type, which means it must be
13366 // complete with the restriction that an array type might be completed by
13367 // the initializer; note that later code assumes this restriction.
13368 QualType BaseDeclType = VDecl->getType();
13369 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13370 BaseDeclType = Array->getElementType();
13371 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13372 diag::err_typecheck_decl_incomplete_type)) {
13373 RealDecl->setInvalidDecl();
13374 return;
13375 }
13376
13377 // The variable can not have an abstract class type.
13378 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13379 diag::err_abstract_type_in_decl,
13381 VDecl->setInvalidDecl();
13382 }
13383
13384 // C++ [module.import/6] external definitions are not permitted in header
13385 // units.
13386 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13387 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13388 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13389 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13391 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13392 VDecl->setInvalidDecl();
13393 }
13394
13395 // If adding the initializer will turn this declaration into a definition,
13396 // and we already have a definition for this variable, diagnose or otherwise
13397 // handle the situation.
13398 if (VarDecl *Def = VDecl->getDefinition())
13399 if (Def != VDecl &&
13400 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13402 checkVarDeclRedefinition(Def, VDecl))
13403 return;
13404
13405 if (getLangOpts().CPlusPlus) {
13406 // C++ [class.static.data]p4
13407 // If a static data member is of const integral or const
13408 // enumeration type, its declaration in the class definition can
13409 // specify a constant-initializer which shall be an integral
13410 // constant expression (5.19). In that case, the member can appear
13411 // in integral constant expressions. The member shall still be
13412 // defined in a namespace scope if it is used in the program and the
13413 // namespace scope definition shall not contain an initializer.
13414 //
13415 // We already performed a redefinition check above, but for static
13416 // data members we also need to check whether there was an in-class
13417 // declaration with an initializer.
13418 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13419 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13420 << VDecl->getDeclName();
13421 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13422 diag::note_previous_initializer)
13423 << 0;
13424 return;
13425 }
13426
13427 if (VDecl->hasLocalStorage())
13429
13431 VDecl->setInvalidDecl();
13432 return;
13433 }
13434 }
13435
13436 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13437 // a kernel function cannot be initialized."
13438 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13439 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13440 VDecl->setInvalidDecl();
13441 return;
13442 }
13443
13444 // The LoaderUninitialized attribute acts as a definition (of undef).
13445 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13446 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13447 VDecl->setInvalidDecl();
13448 return;
13449 }
13450
13451 // Get the decls type and save a reference for later, since
13452 // CheckInitializerTypes may change it.
13453 QualType DclT = VDecl->getType(), SavT = DclT;
13454
13455 // Expressions default to 'id' when we're in a debugger
13456 // and we are assigning it to a variable of Objective-C pointer type.
13457 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13458 Init->getType() == Context.UnknownAnyTy) {
13460 if (Result.isInvalid()) {
13461 VDecl->setInvalidDecl();
13462 return;
13463 }
13464 Init = Result.get();
13465 }
13466
13467 // Perform the initialization.
13468 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13469 bool IsParenListInit = false;
13470 if (!VDecl->isInvalidDecl()) {
13473 VDecl->getLocation(), DirectInit, Init);
13474
13475 MultiExprArg Args = Init;
13476 if (CXXDirectInit)
13477 Args = MultiExprArg(CXXDirectInit->getExprs(),
13478 CXXDirectInit->getNumExprs());
13479
13480 // Try to correct any TypoExprs in the initialization arguments.
13481 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13483 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13484 [this, Entity, Kind](Expr *E) {
13485 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13486 return Init.Failed() ? ExprError() : E;
13487 });
13488 if (Res.isInvalid()) {
13489 VDecl->setInvalidDecl();
13490 } else if (Res.get() != Args[Idx]) {
13491 Args[Idx] = Res.get();
13492 }
13493 }
13494 if (VDecl->isInvalidDecl())
13495 return;
13496
13497 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13498 /*TopLevelOfInitList=*/false,
13499 /*TreatUnavailableAsInvalid=*/false);
13500 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13501 if (Result.isInvalid()) {
13502 // If the provided initializer fails to initialize the var decl,
13503 // we attach a recovery expr for better recovery.
13504 auto RecoveryExpr =
13505 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13506 if (RecoveryExpr.get())
13507 VDecl->setInit(RecoveryExpr.get());
13508 // In general, for error recovery purposes, the initializer doesn't play
13509 // part in the valid bit of the declaration. There are a few exceptions:
13510 // 1) if the var decl has a deduced auto type, and the type cannot be
13511 // deduced by an invalid initializer;
13512 // 2) if the var decl is a decomposition decl with a non-deduced type,
13513 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13514 // Case 1) was already handled elsewhere.
13515 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13516 VDecl->setInvalidDecl();
13517 return;
13518 }
13519
13520 Init = Result.getAs<Expr>();
13521 IsParenListInit = !InitSeq.steps().empty() &&
13522 InitSeq.step_begin()->Kind ==
13524 QualType VDeclType = VDecl->getType();
13525 if (Init && !Init->getType().isNull() &&
13526 !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13527 Context.getAsIncompleteArrayType(VDeclType) &&
13529 // Bail out if it is not possible to deduce array size from the
13530 // initializer.
13531 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13532 << VDeclType;
13533 VDecl->setInvalidDecl();
13534 return;
13535 }
13536 }
13537
13538 // Check for self-references within variable initializers.
13539 // Variables declared within a function/method body (except for references)
13540 // are handled by a dataflow analysis.
13541 // This is undefined behavior in C++, but valid in C.
13542 if (getLangOpts().CPlusPlus)
13543 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13544 VDecl->getType()->isReferenceType())
13545 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13546
13547 // If the type changed, it means we had an incomplete type that was
13548 // completed by the initializer. For example:
13549 // int ary[] = { 1, 3, 5 };
13550 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13551 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13552 VDecl->setType(DclT);
13553
13554 if (!VDecl->isInvalidDecl()) {
13555 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13556
13557 if (VDecl->hasAttr<BlocksAttr>())
13558 ObjC().checkRetainCycles(VDecl, Init);
13559
13560 // It is safe to assign a weak reference into a strong variable.
13561 // Although this code can still have problems:
13562 // id x = self.weakProp;
13563 // id y = self.weakProp;
13564 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13565 // paths through the function. This should be revisited if
13566 // -Wrepeated-use-of-weak is made flow-sensitive.
13567 if (FunctionScopeInfo *FSI = getCurFunction())
13568 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13570 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13571 Init->getBeginLoc()))
13572 FSI->markSafeWeakUse(Init);
13573 }
13574
13575 // The initialization is usually a full-expression.
13576 //
13577 // FIXME: If this is a braced initialization of an aggregate, it is not
13578 // an expression, and each individual field initializer is a separate
13579 // full-expression. For instance, in:
13580 //
13581 // struct Temp { ~Temp(); };
13582 // struct S { S(Temp); };
13583 // struct T { S a, b; } t = { Temp(), Temp() }
13584 //
13585 // we should destroy the first Temp before constructing the second.
13588 /*DiscardedValue*/ false, VDecl->isConstexpr());
13589 if (Result.isInvalid()) {
13590 VDecl->setInvalidDecl();
13591 return;
13592 }
13593 Init = Result.get();
13594
13595 // Attach the initializer to the decl.
13596 VDecl->setInit(Init);
13597
13598 if (VDecl->isLocalVarDecl()) {
13599 // Don't check the initializer if the declaration is malformed.
13600 if (VDecl->isInvalidDecl()) {
13601 // do nothing
13602
13603 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13604 // This is true even in C++ for OpenCL.
13605 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13607
13608 // Otherwise, C++ does not restrict the initializer.
13609 } else if (getLangOpts().CPlusPlus) {
13610 // do nothing
13611
13612 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13613 // static storage duration shall be constant expressions or string literals.
13614 } else if (VDecl->getStorageClass() == SC_Static) {
13616
13617 // C89 is stricter than C99 for aggregate initializers.
13618 // C89 6.5.7p3: All the expressions [...] in an initializer list
13619 // for an object that has aggregate or union type shall be
13620 // constant expressions.
13621 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13622 isa<InitListExpr>(Init)) {
13623 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13624 }
13625
13626 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13627 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13628 if (VDecl->hasLocalStorage())
13629 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13630 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13631 VDecl->getLexicalDeclContext()->isRecord()) {
13632 // This is an in-class initialization for a static data member, e.g.,
13633 //
13634 // struct S {
13635 // static const int value = 17;
13636 // };
13637
13638 // C++ [class.mem]p4:
13639 // A member-declarator can contain a constant-initializer only
13640 // if it declares a static member (9.4) of const integral or
13641 // const enumeration type, see 9.4.2.
13642 //
13643 // C++11 [class.static.data]p3:
13644 // If a non-volatile non-inline const static data member is of integral
13645 // or enumeration type, its declaration in the class definition can
13646 // specify a brace-or-equal-initializer in which every initializer-clause
13647 // that is an assignment-expression is a constant expression. A static
13648 // data member of literal type can be declared in the class definition
13649 // with the constexpr specifier; if so, its declaration shall specify a
13650 // brace-or-equal-initializer in which every initializer-clause that is
13651 // an assignment-expression is a constant expression.
13652
13653 // Do nothing on dependent types.
13654 if (DclT->isDependentType()) {
13655
13656 // Allow any 'static constexpr' members, whether or not they are of literal
13657 // type. We separately check that every constexpr variable is of literal
13658 // type.
13659 } else if (VDecl->isConstexpr()) {
13660
13661 // Require constness.
13662 } else if (!DclT.isConstQualified()) {
13663 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13664 << Init->getSourceRange();
13665 VDecl->setInvalidDecl();
13666
13667 // We allow integer constant expressions in all cases.
13668 } else if (DclT->isIntegralOrEnumerationType()) {
13669 // Check whether the expression is a constant expression.
13672 // In C++11, a non-constexpr const static data member with an
13673 // in-class initializer cannot be volatile.
13674 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13675 else if (Init->isValueDependent())
13676 ; // Nothing to check.
13677 else if (Init->isIntegerConstantExpr(Context, &Loc))
13678 ; // Ok, it's an ICE!
13679 else if (Init->getType()->isScopedEnumeralType() &&
13680 Init->isCXX11ConstantExpr(Context))
13681 ; // Ok, it is a scoped-enum constant expression.
13682 else if (Init->isEvaluatable(Context)) {
13683 // If we can constant fold the initializer through heroics, accept it,
13684 // but report this as a use of an extension for -pedantic.
13685 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13686 << Init->getSourceRange();
13687 } else {
13688 // Otherwise, this is some crazy unknown case. Report the issue at the
13689 // location provided by the isIntegerConstantExpr failed check.
13690 Diag(Loc, diag::err_in_class_initializer_non_constant)
13691 << Init->getSourceRange();
13692 VDecl->setInvalidDecl();
13693 }
13694
13695 // We allow foldable floating-point constants as an extension.
13696 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13697 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13698 // it anyway and provide a fixit to add the 'constexpr'.
13699 if (getLangOpts().CPlusPlus11) {
13700 Diag(VDecl->getLocation(),
13701 diag::ext_in_class_initializer_float_type_cxx11)
13702 << DclT << Init->getSourceRange();
13703 Diag(VDecl->getBeginLoc(),
13704 diag::note_in_class_initializer_float_type_cxx11)
13705 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13706 } else {
13707 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13708 << DclT << Init->getSourceRange();
13709
13710 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13711 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13712 << Init->getSourceRange();
13713 VDecl->setInvalidDecl();
13714 }
13715 }
13716
13717 // Suggest adding 'constexpr' in C++11 for literal types.
13718 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13719 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13720 << DclT << Init->getSourceRange()
13721 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13722 VDecl->setConstexpr(true);
13723
13724 } else {
13725 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13726 << DclT << Init->getSourceRange();
13727 VDecl->setInvalidDecl();
13728 }
13729 } else if (VDecl->isFileVarDecl()) {
13730 // In C, extern is typically used to avoid tentative definitions when
13731 // declaring variables in headers, but adding an initializer makes it a
13732 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13733 // In C++, extern is often used to give implicitly static const variables
13734 // external linkage, so don't warn in that case. If selectany is present,
13735 // this might be header code intended for C and C++ inclusion, so apply the
13736 // C++ rules.
13737 if (VDecl->getStorageClass() == SC_Extern &&
13738 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13740 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13742 Diag(VDecl->getLocation(), diag::warn_extern_init);
13743
13744 // In Microsoft C++ mode, a const variable defined in namespace scope has
13745 // external linkage by default if the variable is declared with
13746 // __declspec(dllexport).
13749 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13750 VDecl->setStorageClass(SC_Extern);
13751
13752 // C99 6.7.8p4. All file scoped initializers need to be constant.
13753 // Avoid duplicate diagnostics for constexpr variables.
13754 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13755 !VDecl->isConstexpr())
13757 }
13758
13759 QualType InitType = Init->getType();
13760 if (!InitType.isNull() &&
13764
13765 // We will represent direct-initialization similarly to copy-initialization:
13766 // int x(1); -as-> int x = 1;
13767 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13768 //
13769 // Clients that want to distinguish between the two forms, can check for
13770 // direct initializer using VarDecl::getInitStyle().
13771 // A major benefit is that clients that don't particularly care about which
13772 // exactly form was it (like the CodeGen) can handle both cases without
13773 // special case code.
13774
13775 // C++ 8.5p11:
13776 // The form of initialization (using parentheses or '=') is generally
13777 // insignificant, but does matter when the entity being initialized has a
13778 // class type.
13779 if (CXXDirectInit) {
13780 assert(DirectInit && "Call-style initializer must be direct init.");
13781 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13783 } else if (DirectInit) {
13784 // This must be list-initialization. No other way is direct-initialization.
13786 }
13787
13788 if (LangOpts.OpenMP &&
13789 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13790 VDecl->isFileVarDecl())
13791 DeclsToCheckForDeferredDiags.insert(VDecl);
13793}
13794
13796 // Our main concern here is re-establishing invariants like "a
13797 // variable's type is either dependent or complete".
13798 if (!D || D->isInvalidDecl()) return;
13799
13800 VarDecl *VD = dyn_cast<VarDecl>(D);
13801 if (!VD) return;
13802
13803 // Bindings are not usable if we can't make sense of the initializer.
13804 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13805 for (auto *BD : DD->bindings())
13806 BD->setInvalidDecl();
13807
13808 // Auto types are meaningless if we can't make sense of the initializer.
13809 if (VD->getType()->isUndeducedType()) {
13810 D->setInvalidDecl();
13811 return;
13812 }
13813
13814 QualType Ty = VD->getType();
13815 if (Ty->isDependentType()) return;
13816
13817 // Require a complete type.
13820 diag::err_typecheck_decl_incomplete_type)) {
13821 VD->setInvalidDecl();
13822 return;
13823 }
13824
13825 // Require a non-abstract type.
13826 if (RequireNonAbstractType(VD->getLocation(), Ty,
13827 diag::err_abstract_type_in_decl,
13829 VD->setInvalidDecl();
13830 return;
13831 }
13832
13833 // Don't bother complaining about constructors or destructors,
13834 // though.
13835}
13836
13838 // If there is no declaration, there was an error parsing it. Just ignore it.
13839 if (!RealDecl)
13840 return;
13841
13842 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13843 QualType Type = Var->getType();
13844
13845 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13846 if (isa<DecompositionDecl>(RealDecl)) {
13847 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13848 Var->setInvalidDecl();
13849 return;
13850 }
13851
13852 if (Type->isUndeducedType() &&
13853 DeduceVariableDeclarationType(Var, false, nullptr))
13854 return;
13855
13856 // C++11 [class.static.data]p3: A static data member can be declared with
13857 // the constexpr specifier; if so, its declaration shall specify
13858 // a brace-or-equal-initializer.
13859 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13860 // the definition of a variable [...] or the declaration of a static data
13861 // member.
13862 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13863 !Var->isThisDeclarationADemotedDefinition()) {
13864 if (Var->isStaticDataMember()) {
13865 // C++1z removes the relevant rule; the in-class declaration is always
13866 // a definition there.
13867 if (!getLangOpts().CPlusPlus17 &&
13869 Diag(Var->getLocation(),
13870 diag::err_constexpr_static_mem_var_requires_init)
13871 << Var;
13872 Var->setInvalidDecl();
13873 return;
13874 }
13875 } else {
13876 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13877 Var->setInvalidDecl();
13878 return;
13879 }
13880 }
13881
13882 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13883 // be initialized.
13884 if (!Var->isInvalidDecl() &&
13885 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13886 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13887 bool HasConstExprDefaultConstructor = false;
13888 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13889 for (auto *Ctor : RD->ctors()) {
13890 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13891 Ctor->getMethodQualifiers().getAddressSpace() ==
13893 HasConstExprDefaultConstructor = true;
13894 }
13895 }
13896 }
13897 if (!HasConstExprDefaultConstructor) {
13898 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13899 Var->setInvalidDecl();
13900 return;
13901 }
13902 }
13903
13904 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13905 if (Var->getStorageClass() == SC_Extern) {
13906 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13907 << Var;
13908 Var->setInvalidDecl();
13909 return;
13910 }
13911 if (RequireCompleteType(Var->getLocation(), Var->getType(),
13912 diag::err_typecheck_decl_incomplete_type)) {
13913 Var->setInvalidDecl();
13914 return;
13915 }
13916 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13917 if (!RD->hasTrivialDefaultConstructor()) {
13918 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13919 Var->setInvalidDecl();
13920 return;
13921 }
13922 }
13923 // The declaration is uninitialized, no need for further checks.
13924 return;
13925 }
13926
13927 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13928 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13929 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13930 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13932
13933
13934 switch (DefKind) {
13936 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13937 break;
13938
13939 // We have an out-of-line definition of a static data member
13940 // that has an in-class initializer, so we type-check this like
13941 // a declaration.
13942 //
13943 [[fallthrough]];
13944
13946 // It's only a declaration.
13947
13948 // Block scope. C99 6.7p7: If an identifier for an object is
13949 // declared with no linkage (C99 6.2.2p6), the type for the
13950 // object shall be complete.
13951 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13952 !Var->hasLinkage() && !Var->isInvalidDecl() &&
13953 RequireCompleteType(Var->getLocation(), Type,
13954 diag::err_typecheck_decl_incomplete_type))
13955 Var->setInvalidDecl();
13956
13957 // Make sure that the type is not abstract.
13958 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13959 RequireNonAbstractType(Var->getLocation(), Type,
13960 diag::err_abstract_type_in_decl,
13962 Var->setInvalidDecl();
13963 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13964 Var->getStorageClass() == SC_PrivateExtern) {
13965 Diag(Var->getLocation(), diag::warn_private_extern);
13966 Diag(Var->getLocation(), diag::note_private_extern);
13967 }
13968
13970 !Var->isInvalidDecl())
13971 ExternalDeclarations.push_back(Var);
13972
13973 return;
13974
13976 // File scope. C99 6.9.2p2: A declaration of an identifier for an
13977 // object that has file scope without an initializer, and without a
13978 // storage-class specifier or with the storage-class specifier "static",
13979 // constitutes a tentative definition. Note: A tentative definition with
13980 // external linkage is valid (C99 6.2.2p5).
13981 if (!Var->isInvalidDecl()) {
13982 if (const IncompleteArrayType *ArrayT
13985 Var->getLocation(), ArrayT->getElementType(),
13986 diag::err_array_incomplete_or_sizeless_type))
13987 Var->setInvalidDecl();
13988 } else if (Var->getStorageClass() == SC_Static) {
13989 // C99 6.9.2p3: If the declaration of an identifier for an object is
13990 // a tentative definition and has internal linkage (C99 6.2.2p3), the
13991 // declared type shall not be an incomplete type.
13992 // NOTE: code such as the following
13993 // static struct s;
13994 // struct s { int a; };
13995 // is accepted by gcc. Hence here we issue a warning instead of
13996 // an error and we do not invalidate the static declaration.
13997 // NOTE: to avoid multiple warnings, only check the first declaration.
13998 if (Var->isFirstDecl())
13999 RequireCompleteType(Var->getLocation(), Type,
14000 diag::ext_typecheck_decl_incomplete_type);
14001 }
14002 }
14003
14004 // Record the tentative definition; we're done.
14005 if (!Var->isInvalidDecl())
14007 return;
14008 }
14009
14010 // Provide a specific diagnostic for uninitialized variable
14011 // definitions with incomplete array type.
14012 if (Type->isIncompleteArrayType()) {
14013 if (Var->isConstexpr())
14014 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14015 << Var;
14016 else
14017 Diag(Var->getLocation(),
14018 diag::err_typecheck_incomplete_array_needs_initializer);
14019 Var->setInvalidDecl();
14020 return;
14021 }
14022
14023 // Provide a specific diagnostic for uninitialized variable
14024 // definitions with reference type.
14025 if (Type->isReferenceType()) {
14026 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14027 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14028 return;
14029 }
14030
14031 // Do not attempt to type-check the default initializer for a
14032 // variable with dependent type.
14033 if (Type->isDependentType())
14034 return;
14035
14036 if (Var->isInvalidDecl())
14037 return;
14038
14039 if (!Var->hasAttr<AliasAttr>()) {
14040 if (RequireCompleteType(Var->getLocation(),
14042 diag::err_typecheck_decl_incomplete_type)) {
14043 Var->setInvalidDecl();
14044 return;
14045 }
14046 } else {
14047 return;
14048 }
14049
14050 // The variable can not have an abstract class type.
14051 if (RequireNonAbstractType(Var->getLocation(), Type,
14052 diag::err_abstract_type_in_decl,
14054 Var->setInvalidDecl();
14055 return;
14056 }
14057
14058 // Check for jumps past the implicit initializer. C++0x
14059 // clarifies that this applies to a "variable with automatic
14060 // storage duration", not a "local variable".
14061 // C++11 [stmt.dcl]p3
14062 // A program that jumps from a point where a variable with automatic
14063 // storage duration is not in scope to a point where it is in scope is
14064 // ill-formed unless the variable has scalar type, class type with a
14065 // trivial default constructor and a trivial destructor, a cv-qualified
14066 // version of one of these types, or an array of one of the preceding
14067 // types and is declared without an initializer.
14068 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14069 if (const RecordType *Record
14071 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14072 // Mark the function (if we're in one) for further checking even if the
14073 // looser rules of C++11 do not require such checks, so that we can
14074 // diagnose incompatibilities with C++98.
14075 if (!CXXRecord->isPOD())
14077 }
14078 }
14079 // In OpenCL, we can't initialize objects in the __local address space,
14080 // even implicitly, so don't synthesize an implicit initializer.
14081 if (getLangOpts().OpenCL &&
14082 Var->getType().getAddressSpace() == LangAS::opencl_local)
14083 return;
14084 // C++03 [dcl.init]p9:
14085 // If no initializer is specified for an object, and the
14086 // object is of (possibly cv-qualified) non-POD class type (or
14087 // array thereof), the object shall be default-initialized; if
14088 // the object is of const-qualified type, the underlying class
14089 // type shall have a user-declared default
14090 // constructor. Otherwise, if no initializer is specified for
14091 // a non- static object, the object and its subobjects, if
14092 // any, have an indeterminate initial value); if the object
14093 // or any of its subobjects are of const-qualified type, the
14094 // program is ill-formed.
14095 // C++0x [dcl.init]p11:
14096 // If no initializer is specified for an object, the object is
14097 // default-initialized; [...].
14100 = InitializationKind::CreateDefault(Var->getLocation());
14101
14102 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14103 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
14104
14105 if (Init.get()) {
14106 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14107 // This is important for template substitution.
14108 Var->setInitStyle(VarDecl::CallInit);
14109 } else if (Init.isInvalid()) {
14110 // If default-init fails, attach a recovery-expr initializer to track
14111 // that initialization was attempted and failed.
14112 auto RecoveryExpr =
14113 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14114 if (RecoveryExpr.get())
14115 Var->setInit(RecoveryExpr.get());
14116 }
14117
14119 }
14120}
14121
14123 // If there is no declaration, there was an error parsing it. Ignore it.
14124 if (!D)
14125 return;
14126
14127 VarDecl *VD = dyn_cast<VarDecl>(D);
14128 if (!VD) {
14129 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14130 D->setInvalidDecl();
14131 return;
14132 }
14133
14134 VD->setCXXForRangeDecl(true);
14135
14136 // for-range-declaration cannot be given a storage class specifier.
14137 int Error = -1;
14138 switch (VD->getStorageClass()) {
14139 case SC_None:
14140 break;
14141 case SC_Extern:
14142 Error = 0;
14143 break;
14144 case SC_Static:
14145 Error = 1;
14146 break;
14147 case SC_PrivateExtern:
14148 Error = 2;
14149 break;
14150 case SC_Auto:
14151 Error = 3;
14152 break;
14153 case SC_Register:
14154 Error = 4;
14155 break;
14156 }
14157
14158 // for-range-declaration cannot be given a storage class specifier con't.
14159 switch (VD->getTSCSpec()) {
14160 case TSCS_thread_local:
14161 Error = 6;
14162 break;
14163 case TSCS___thread:
14164 case TSCS__Thread_local:
14165 case TSCS_unspecified:
14166 break;
14167 }
14168
14169 if (Error != -1) {
14170 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14171 << VD << Error;
14172 D->setInvalidDecl();
14173 }
14174}
14175
14177 IdentifierInfo *Ident,
14178 ParsedAttributes &Attrs) {
14179 // C++1y [stmt.iter]p1:
14180 // A range-based for statement of the form
14181 // for ( for-range-identifier : for-range-initializer ) statement
14182 // is equivalent to
14183 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14184 DeclSpec DS(Attrs.getPool().getFactory());
14185
14186 const char *PrevSpec;
14187 unsigned DiagID;
14188 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14190
14192 D.SetIdentifier(Ident, IdentLoc);
14193 D.takeAttributes(Attrs);
14194
14195 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14196 IdentLoc);
14197 Decl *Var = ActOnDeclarator(S, D);
14198 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14200 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14201 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14202 : IdentLoc);
14203}
14204
14206 if (var->isInvalidDecl()) return;
14207
14209
14210 if (getLangOpts().OpenCL) {
14211 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14212 // initialiser
14213 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14214 !var->hasInit()) {
14215 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14216 << 1 /*Init*/;
14217 var->setInvalidDecl();
14218 return;
14219 }
14220 }
14221
14222 // In Objective-C, don't allow jumps past the implicit initialization of a
14223 // local retaining variable.
14224 if (getLangOpts().ObjC &&
14225 var->hasLocalStorage()) {
14226 switch (var->getType().getObjCLifetime()) {
14230 break;
14231
14235 break;
14236 }
14237 }
14238
14239 if (var->hasLocalStorage() &&
14240 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14242
14243 // Warn about externally-visible variables being defined without a
14244 // prior declaration. We only want to do this for global
14245 // declarations, but we also specifically need to avoid doing it for
14246 // class members because the linkage of an anonymous class can
14247 // change if it's later given a typedef name.
14248 if (var->isThisDeclarationADefinition() &&
14249 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14250 var->isExternallyVisible() && var->hasLinkage() &&
14251 !var->isInline() && !var->getDescribedVarTemplate() &&
14252 var->getStorageClass() != SC_Register &&
14253 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14254 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14255 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14256 var->getLocation())) {
14257 // Find a previous declaration that's not a definition.
14258 VarDecl *prev = var->getPreviousDecl();
14259 while (prev && prev->isThisDeclarationADefinition())
14260 prev = prev->getPreviousDecl();
14261
14262 if (!prev) {
14263 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14264 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14265 << /* variable */ 0;
14266 }
14267 }
14268
14269 // Cache the result of checking for constant initialization.
14270 std::optional<bool> CacheHasConstInit;
14271 const Expr *CacheCulprit = nullptr;
14272 auto checkConstInit = [&]() mutable {
14273 if (!CacheHasConstInit)
14274 CacheHasConstInit = var->getInit()->isConstantInitializer(
14275 Context, var->getType()->isReferenceType(), &CacheCulprit);
14276 return *CacheHasConstInit;
14277 };
14278
14279 if (var->getTLSKind() == VarDecl::TLS_Static) {
14280 if (var->getType().isDestructedType()) {
14281 // GNU C++98 edits for __thread, [basic.start.term]p3:
14282 // The type of an object with thread storage duration shall not
14283 // have a non-trivial destructor.
14284 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14286 Diag(var->getLocation(), diag::note_use_thread_local);
14287 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14288 if (!checkConstInit()) {
14289 // GNU C++98 edits for __thread, [basic.start.init]p4:
14290 // An object of thread storage duration shall not require dynamic
14291 // initialization.
14292 // FIXME: Need strict checking here.
14293 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14294 << CacheCulprit->getSourceRange();
14296 Diag(var->getLocation(), diag::note_use_thread_local);
14297 }
14298 }
14299 }
14300
14301
14302 if (!var->getType()->isStructureType() && var->hasInit() &&
14303 isa<InitListExpr>(var->getInit())) {
14304 const auto *ILE = cast<InitListExpr>(var->getInit());
14305 unsigned NumInits = ILE->getNumInits();
14306 if (NumInits > 2)
14307 for (unsigned I = 0; I < NumInits; ++I) {
14308 const auto *Init = ILE->getInit(I);
14309 if (!Init)
14310 break;
14311 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14312 if (!SL)
14313 break;
14314
14315 unsigned NumConcat = SL->getNumConcatenated();
14316 // Diagnose missing comma in string array initialization.
14317 // Do not warn when all the elements in the initializer are concatenated
14318 // together. Do not warn for macros too.
14319 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14320 bool OnlyOneMissingComma = true;
14321 for (unsigned J = I + 1; J < NumInits; ++J) {
14322 const auto *Init = ILE->getInit(J);
14323 if (!Init)
14324 break;
14325 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14326 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14327 OnlyOneMissingComma = false;
14328 break;
14329 }
14330 }
14331
14332 if (OnlyOneMissingComma) {
14334 for (unsigned i = 0; i < NumConcat - 1; ++i)
14335 Hints.push_back(FixItHint::CreateInsertion(
14336 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14337
14338 Diag(SL->getStrTokenLoc(1),
14339 diag::warn_concatenated_literal_array_init)
14340 << Hints;
14341 Diag(SL->getBeginLoc(),
14342 diag::note_concatenated_string_literal_silence);
14343 }
14344 // In any case, stop now.
14345 break;
14346 }
14347 }
14348 }
14349
14350
14351 QualType type = var->getType();
14352
14353 if (var->hasAttr<BlocksAttr>())
14355
14356 Expr *Init = var->getInit();
14357 bool GlobalStorage = var->hasGlobalStorage();
14358 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14360 bool HasConstInit = true;
14361
14362 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14363 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14364 << var;
14365
14366 // Check whether the initializer is sufficiently constant.
14367 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14368 !type->isDependentType() && Init && !Init->isValueDependent() &&
14369 (GlobalStorage || var->isConstexpr() ||
14370 var->mightBeUsableInConstantExpressions(Context))) {
14371 // If this variable might have a constant initializer or might be usable in
14372 // constant expressions, check whether or not it actually is now. We can't
14373 // do this lazily, because the result might depend on things that change
14374 // later, such as which constexpr functions happen to be defined.
14376 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14377 // Prior to C++11, in contexts where a constant initializer is required,
14378 // the set of valid constant initializers is described by syntactic rules
14379 // in [expr.const]p2-6.
14380 // FIXME: Stricter checking for these rules would be useful for constinit /
14381 // -Wglobal-constructors.
14382 HasConstInit = checkConstInit();
14383
14384 // Compute and cache the constant value, and remember that we have a
14385 // constant initializer.
14386 if (HasConstInit) {
14387 (void)var->checkForConstantInitialization(Notes);
14388 Notes.clear();
14389 } else if (CacheCulprit) {
14390 Notes.emplace_back(CacheCulprit->getExprLoc(),
14391 PDiag(diag::note_invalid_subexpr_in_const_expr));
14392 Notes.back().second << CacheCulprit->getSourceRange();
14393 }
14394 } else {
14395 // Evaluate the initializer to see if it's a constant initializer.
14396 HasConstInit = var->checkForConstantInitialization(Notes);
14397 }
14398
14399 if (HasConstInit) {
14400 // FIXME: Consider replacing the initializer with a ConstantExpr.
14401 } else if (var->isConstexpr()) {
14402 SourceLocation DiagLoc = var->getLocation();
14403 // If the note doesn't add any useful information other than a source
14404 // location, fold it into the primary diagnostic.
14405 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14406 diag::note_invalid_subexpr_in_const_expr) {
14407 DiagLoc = Notes[0].first;
14408 Notes.clear();
14409 }
14410 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14411 << var << Init->getSourceRange();
14412 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14413 Diag(Notes[I].first, Notes[I].second);
14414 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14415 auto *Attr = var->getAttr<ConstInitAttr>();
14416 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14417 << Init->getSourceRange();
14418 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14419 << Attr->getRange() << Attr->isConstinit();
14420 for (auto &it : Notes)
14421 Diag(it.first, it.second);
14422 } else if (IsGlobal &&
14423 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14424 var->getLocation())) {
14425 // Warn about globals which don't have a constant initializer. Don't
14426 // warn about globals with a non-trivial destructor because we already
14427 // warned about them.
14428 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14429 if (!(RD && !RD->hasTrivialDestructor())) {
14430 // checkConstInit() here permits trivial default initialization even in
14431 // C++11 onwards, where such an initializer is not a constant initializer
14432 // but nonetheless doesn't require a global constructor.
14433 if (!checkConstInit())
14434 Diag(var->getLocation(), diag::warn_global_constructor)
14435 << Init->getSourceRange();
14436 }
14437 }
14438 }
14439
14440 // Apply section attributes and pragmas to global variables.
14441 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14443 PragmaStack<StringLiteral *> *Stack = nullptr;
14444 int SectionFlags = ASTContext::PSF_Read;
14445 bool MSVCEnv =
14446 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14447 std::optional<QualType::NonConstantStorageReason> Reason;
14448 if (HasConstInit &&
14449 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14450 Stack = &ConstSegStack;
14451 } else {
14452 SectionFlags |= ASTContext::PSF_Write;
14453 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14454 }
14455 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14456 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14457 SectionFlags |= ASTContext::PSF_Implicit;
14458 UnifySection(SA->getName(), SectionFlags, var);
14459 } else if (Stack->CurrentValue) {
14460 if (Stack != &ConstSegStack && MSVCEnv &&
14461 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14462 var->getType().isConstQualified()) {
14463 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14464 NonConstNonReferenceType) &&
14465 "This case should've already been handled elsewhere");
14466 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14467 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14469 : *Reason);
14470 }
14471 SectionFlags |= ASTContext::PSF_Implicit;
14472 auto SectionName = Stack->CurrentValue->getString();
14473 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14474 Stack->CurrentPragmaLocation,
14475 SectionAttr::Declspec_allocate));
14476 if (UnifySection(SectionName, SectionFlags, var))
14477 var->dropAttr<SectionAttr>();
14478 }
14479
14480 // Apply the init_seg attribute if this has an initializer. If the
14481 // initializer turns out to not be dynamic, we'll end up ignoring this
14482 // attribute.
14483 if (CurInitSeg && var->getInit())
14484 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14485 CurInitSegLoc));
14486 }
14487
14488 // All the following checks are C++ only.
14489 if (!getLangOpts().CPlusPlus) {
14490 // If this variable must be emitted, add it as an initializer for the
14491 // current module.
14492 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14493 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14494 return;
14495 }
14496
14497 // Require the destructor.
14498 if (!type->isDependentType())
14499 if (const RecordType *recordType = baseType->getAs<RecordType>())
14501
14502 // If this variable must be emitted, add it as an initializer for the current
14503 // module.
14504 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14505 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14506
14507 // Build the bindings if this is a structured binding declaration.
14508 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14510}
14511
14513 assert(VD->isStaticLocal());
14514
14515 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14516
14517 // Find outermost function when VD is in lambda function.
14518 while (FD && !getDLLAttr(FD) &&
14519 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14520 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14521 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14522 }
14523
14524 if (!FD)
14525 return;
14526
14527 // Static locals inherit dll attributes from their function.
14528 if (Attr *A = getDLLAttr(FD)) {
14529 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14530 NewAttr->setInherited(true);
14531 VD->addAttr(NewAttr);
14532 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14533 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14534 NewAttr->setInherited(true);
14535 VD->addAttr(NewAttr);
14536
14537 // Export this function to enforce exporting this static variable even
14538 // if it is not used in this compilation unit.
14539 if (!FD->hasAttr<DLLExportAttr>())
14540 FD->addAttr(NewAttr);
14541
14542 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14543 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14544 NewAttr->setInherited(true);
14545 VD->addAttr(NewAttr);
14546 }
14547}
14548
14550 assert(VD->getTLSKind());
14551
14552 // Perform TLS alignment check here after attributes attached to the variable
14553 // which may affect the alignment have been processed. Only perform the check
14554 // if the target has a maximum TLS alignment (zero means no constraints).
14555 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14556 // Protect the check so that it's not performed on dependent types and
14557 // dependent alignments (we can't determine the alignment in that case).
14558 if (!VD->hasDependentAlignment()) {
14559 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14560 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14561 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14563 << (unsigned)MaxAlignChars.getQuantity();
14564 }
14565 }
14566 }
14567}
14568
14570 // Note that we are no longer parsing the initializer for this declaration.
14571 ParsingInitForAutoVars.erase(ThisDecl);
14572
14573 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14574 if (!VD)
14575 return;
14576
14577 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14579 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14581 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14585 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14589 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14593 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14596 }
14597
14598 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14599 for (auto *BD : DD->bindings()) {
14601 }
14602 }
14603
14604 checkAttributesAfterMerging(*this, *VD);
14605
14606 if (VD->isStaticLocal())
14608
14609 if (VD->getTLSKind())
14611
14612 // Perform check for initializers of device-side global variables.
14613 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14614 // 7.5). We must also apply the same checks to all __shared__
14615 // variables whether they are local or not. CUDA also allows
14616 // constant initializers for __constant__ and __device__ variables.
14617 if (getLangOpts().CUDA)
14619
14620 // Grab the dllimport or dllexport attribute off of the VarDecl.
14621 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14622
14623 // Imported static data members cannot be defined out-of-line.
14624 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14625 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14627 // We allow definitions of dllimport class template static data members
14628 // with a warning.
14630 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14631 bool IsClassTemplateMember =
14632 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14633 Context->getDescribedClassTemplate();
14634
14635 Diag(VD->getLocation(),
14636 IsClassTemplateMember
14637 ? diag::warn_attribute_dllimport_static_field_definition
14638 : diag::err_attribute_dllimport_static_field_definition);
14639 Diag(IA->getLocation(), diag::note_attribute);
14640 if (!IsClassTemplateMember)
14641 VD->setInvalidDecl();
14642 }
14643 }
14644
14645 // dllimport/dllexport variables cannot be thread local, their TLS index
14646 // isn't exported with the variable.
14647 if (DLLAttr && VD->getTLSKind()) {
14648 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14649 if (F && getDLLAttr(F)) {
14650 assert(VD->isStaticLocal());
14651 // But if this is a static local in a dlimport/dllexport function, the
14652 // function will never be inlined, which means the var would never be
14653 // imported, so having it marked import/export is safe.
14654 } else {
14655 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14656 << DLLAttr;
14657 VD->setInvalidDecl();
14658 }
14659 }
14660
14661 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14662 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14663 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14664 << Attr;
14665 VD->dropAttr<UsedAttr>();
14666 }
14667 }
14668 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14669 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14670 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14671 << Attr;
14672 VD->dropAttr<RetainAttr>();
14673 }
14674 }
14675
14676 const DeclContext *DC = VD->getDeclContext();
14677 // If there's a #pragma GCC visibility in scope, and this isn't a class
14678 // member, set the visibility of this variable.
14681
14682 // FIXME: Warn on unused var template partial specializations.
14683 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14685
14686 // Now we have parsed the initializer and can update the table of magic
14687 // tag values.
14688 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14690 return;
14691
14692 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14693 const Expr *MagicValueExpr = VD->getInit();
14694 if (!MagicValueExpr) {
14695 continue;
14696 }
14697 std::optional<llvm::APSInt> MagicValueInt;
14698 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14699 Diag(I->getRange().getBegin(),
14700 diag::err_type_tag_for_datatype_not_ice)
14701 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14702 continue;
14703 }
14704 if (MagicValueInt->getActiveBits() > 64) {
14705 Diag(I->getRange().getBegin(),
14706 diag::err_type_tag_for_datatype_too_large)
14707 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14708 continue;
14709 }
14710 uint64_t MagicValue = MagicValueInt->getZExtValue();
14711 RegisterTypeTagForDatatype(I->getArgumentKind(),
14712 MagicValue,
14713 I->getMatchingCType(),
14714 I->getLayoutCompatible(),
14715 I->getMustBeNull());
14716 }
14717}
14718
14720 auto *VD = dyn_cast<VarDecl>(DD);
14721 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14722}
14723
14725 ArrayRef<Decl *> Group) {
14727
14728 if (DS.isTypeSpecOwned())
14729 Decls.push_back(DS.getRepAsDecl());
14730
14731 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14732 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14733 bool DiagnosedMultipleDecomps = false;
14734 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14735 bool DiagnosedNonDeducedAuto = false;
14736
14737 for (Decl *D : Group) {
14738 if (!D)
14739 continue;
14740 // Check if the Decl has been declared in '#pragma omp declare target'
14741 // directive and has static storage duration.
14742 if (auto *VD = dyn_cast<VarDecl>(D);
14743 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14744 VD->hasGlobalStorage())
14746 // For declarators, there are some additional syntactic-ish checks we need
14747 // to perform.
14748 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14749 if (!FirstDeclaratorInGroup)
14750 FirstDeclaratorInGroup = DD;
14751 if (!FirstDecompDeclaratorInGroup)
14752 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14753 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14754 !hasDeducedAuto(DD))
14755 FirstNonDeducedAutoInGroup = DD;
14756
14757 if (FirstDeclaratorInGroup != DD) {
14758 // A decomposition declaration cannot be combined with any other
14759 // declaration in the same group.
14760 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14761 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14762 diag::err_decomp_decl_not_alone)
14763 << FirstDeclaratorInGroup->getSourceRange()
14764 << DD->getSourceRange();
14765 DiagnosedMultipleDecomps = true;
14766 }
14767
14768 // A declarator that uses 'auto' in any way other than to declare a
14769 // variable with a deduced type cannot be combined with any other
14770 // declarator in the same group.
14771 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14772 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14773 diag::err_auto_non_deduced_not_alone)
14774 << FirstNonDeducedAutoInGroup->getType()
14776 << FirstDeclaratorInGroup->getSourceRange()
14777 << DD->getSourceRange();
14778 DiagnosedNonDeducedAuto = true;
14779 }
14780 }
14781 }
14782
14783 Decls.push_back(D);
14784 }
14785
14787 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14788 handleTagNumbering(Tag, S);
14789 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14791 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14792 }
14793 }
14794
14795 return BuildDeclaratorGroup(Decls);
14796}
14797
14800 // C++14 [dcl.spec.auto]p7: (DR1347)
14801 // If the type that replaces the placeholder type is not the same in each
14802 // deduction, the program is ill-formed.
14803 if (Group.size() > 1) {
14804 QualType Deduced;
14805 VarDecl *DeducedDecl = nullptr;
14806 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14807 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14808 if (!D || D->isInvalidDecl())
14809 break;
14810 DeducedType *DT = D->getType()->getContainedDeducedType();
14811 if (!DT || DT->getDeducedType().isNull())
14812 continue;
14813 if (Deduced.isNull()) {
14814 Deduced = DT->getDeducedType();
14815 DeducedDecl = D;
14816 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14817 auto *AT = dyn_cast<AutoType>(DT);
14818 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14819 diag::err_auto_different_deductions)
14820 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14821 << DeducedDecl->getDeclName() << DT->getDeducedType()
14822 << D->getDeclName();
14823 if (DeducedDecl->hasInit())
14824 Dia << DeducedDecl->getInit()->getSourceRange();
14825 if (D->getInit())
14826 Dia << D->getInit()->getSourceRange();
14827 D->setInvalidDecl();
14828 break;
14829 }
14830 }
14831 }
14832
14834
14835 return DeclGroupPtrTy::make(
14836 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14837}
14838
14841}
14842
14844 // Don't parse the comment if Doxygen diagnostics are ignored.
14845 if (Group.empty() || !Group[0])
14846 return;
14847
14848 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14849 Group[0]->getLocation()) &&
14850 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14851 Group[0]->getLocation()))
14852 return;
14853
14854 if (Group.size() >= 2) {
14855 // This is a decl group. Normally it will contain only declarations
14856 // produced from declarator list. But in case we have any definitions or
14857 // additional declaration references:
14858 // 'typedef struct S {} S;'
14859 // 'typedef struct S *S;'
14860 // 'struct S *pS;'
14861 // FinalizeDeclaratorGroup adds these as separate declarations.
14862 Decl *MaybeTagDecl = Group[0];
14863 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14864 Group = Group.slice(1);
14865 }
14866 }
14867
14868 // FIMXE: We assume every Decl in the group is in the same file.
14869 // This is false when preprocessor constructs the group from decls in
14870 // different files (e. g. macros or #include).
14872}
14873
14875 // Check that there are no default arguments inside the type of this
14876 // parameter.
14877 if (getLangOpts().CPlusPlus)
14879
14880 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14881 if (D.getCXXScopeSpec().isSet()) {
14882 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14883 << D.getCXXScopeSpec().getRange();
14884 }
14885
14886 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14887 // simple identifier except [...irrelevant cases...].
14888 switch (D.getName().getKind()) {
14890 break;
14891
14899 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14901 break;
14902
14905 // GetNameForDeclarator would not produce a useful name in this case.
14906 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14907 break;
14908 }
14909}
14910
14912 SourceLocation ExplicitThisLoc) {
14913 if (!ExplicitThisLoc.isValid())
14914 return;
14915 assert(S.getLangOpts().CPlusPlus &&
14916 "explicit parameter in non-cplusplus mode");
14917 if (!S.getLangOpts().CPlusPlus23)
14918 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
14919 << P->getSourceRange();
14920
14921 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
14922 // parameter pack.
14923 if (P->isParameterPack()) {
14924 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
14925 << P->getSourceRange();
14926 return;
14927 }
14928 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
14929 if (LambdaScopeInfo *LSI = S.getCurLambda())
14930 LSI->ExplicitObjectParameter = P;
14931}
14932
14934 SourceLocation ExplicitThisLoc) {
14935 const DeclSpec &DS = D.getDeclSpec();
14936
14937 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14938
14939 // C++03 [dcl.stc]p2 also permits 'auto'.
14940 StorageClass SC = SC_None;
14942 SC = SC_Register;
14943 // In C++11, the 'register' storage class specifier is deprecated.
14944 // In C++17, it is not allowed, but we tolerate it as an extension.
14945 if (getLangOpts().CPlusPlus11) {
14947 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14948 : diag::warn_deprecated_register)
14950 }
14951 } else if (getLangOpts().CPlusPlus &&
14953 SC = SC_Auto;
14956 diag::err_invalid_storage_class_in_func_decl);
14957 D.getMutableDeclSpec().ClearStorageClassSpecs();
14958 }
14959
14961 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14963 if (DS.isInlineSpecified())
14964 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14965 << getLangOpts().CPlusPlus17;
14966 if (DS.hasConstexprSpecifier())
14967 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14968 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14969
14971
14973
14975 QualType parmDeclType = TInfo->getType();
14976
14977 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14978 const IdentifierInfo *II = D.getIdentifier();
14979 if (II) {
14980 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14981 RedeclarationKind::ForVisibleRedeclaration);
14982 LookupName(R, S);
14983 if (!R.empty()) {
14984 NamedDecl *PrevDecl = *R.begin();
14985 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
14986 // Maybe we will complain about the shadowed template parameter.
14987 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14988 // Just pretend that we didn't see the previous declaration.
14989 PrevDecl = nullptr;
14990 }
14991 if (PrevDecl && S->isDeclScope(PrevDecl)) {
14992 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14993 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14994 // Recover by removing the name
14995 II = nullptr;
14996 D.SetIdentifier(nullptr, D.getIdentifierLoc());
14997 D.setInvalidType(true);
14998 }
14999 }
15000 }
15001
15002 // Temporarily put parameter variables in the translation unit, not
15003 // the enclosing context. This prevents them from accidentally
15004 // looking like class members in C++.
15005 ParmVarDecl *New =
15007 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15008
15009 if (D.isInvalidType())
15010 New->setInvalidDecl();
15011
15012 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15013
15014 assert(S->isFunctionPrototypeScope());
15015 assert(S->getFunctionPrototypeDepth() >= 1);
15016 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15017 S->getNextFunctionPrototypeIndex());
15018
15019 // Add the parameter declaration into this scope.
15020 S->AddDecl(New);
15021 if (II)
15022 IdResolver.AddDecl(New);
15023
15024 ProcessDeclAttributes(S, New, D);
15025
15026 if (D.getDeclSpec().isModulePrivateSpecified())
15027 Diag(New->getLocation(), diag::err_module_private_local)
15028 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15029 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15030
15031 if (New->hasAttr<BlocksAttr>()) {
15032 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15033 }
15034
15035 if (getLangOpts().OpenCL)
15037
15038 return New;
15039}
15040
15043 QualType T) {
15044 /* FIXME: setting StartLoc == Loc.
15045 Would it be worth to modify callers so as to provide proper source
15046 location for the unnamed parameters, embedding the parameter's type? */
15047 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15049 SC_None, nullptr);
15050 Param->setImplicit();
15051 return Param;
15052}
15053
15055 // Don't diagnose unused-parameter errors in template instantiations; we
15056 // will already have done so in the template itself.
15058 return;
15059
15060 for (const ParmVarDecl *Parameter : Parameters) {
15061 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15062 !Parameter->hasAttr<UnusedAttr>() &&
15063 !Parameter->getIdentifier()->isPlaceholder()) {
15064 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15065 << Parameter->getDeclName();
15066 }
15067 }
15068}
15069
15071 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15072 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15073 return;
15074
15075 // Warn if the return value is pass-by-value and larger than the specified
15076 // threshold.
15077 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15078 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15079 if (Size > LangOpts.NumLargeByValueCopy)
15080 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15081 }
15082
15083 // Warn if any parameter is pass-by-value and larger than the specified
15084 // threshold.
15085 for (const ParmVarDecl *Parameter : Parameters) {
15086 QualType T = Parameter->getType();
15087 if (T->isDependentType() || !T.isPODType(Context))
15088 continue;
15089 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15090 if (Size > LangOpts.NumLargeByValueCopy)
15091 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15092 << Parameter << Size;
15093 }
15094}
15095
15097 SourceLocation NameLoc,
15098 const IdentifierInfo *Name, QualType T,
15099 TypeSourceInfo *TSInfo, StorageClass SC) {
15100 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15101 if (getLangOpts().ObjCAutoRefCount &&
15102 T.getObjCLifetime() == Qualifiers::OCL_None &&
15103 T->isObjCLifetimeType()) {
15104
15105 Qualifiers::ObjCLifetime lifetime;
15106
15107 // Special cases for arrays:
15108 // - if it's const, use __unsafe_unretained
15109 // - otherwise, it's an error
15110 if (T->isArrayType()) {
15111 if (!T.isConstQualified()) {
15115 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15116 else
15117 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15118 << TSInfo->getTypeLoc().getSourceRange();
15119 }
15121 } else {
15122 lifetime = T->getObjCARCImplicitLifetime();
15123 }
15124 T = Context.getLifetimeQualifiedType(T, lifetime);
15125 }
15126
15127 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15129 TSInfo, SC, nullptr);
15130
15131 // Make a note if we created a new pack in the scope of a lambda, so that
15132 // we know that references to that pack must also be expanded within the
15133 // lambda scope.
15134 if (New->isParameterPack())
15135 if (auto *LSI = getEnclosingLambda())
15136 LSI->LocalPacks.push_back(New);
15137
15142
15143 // Parameter declarators cannot be interface types. All ObjC objects are
15144 // passed by reference.
15145 if (T->isObjCObjectType()) {
15146 SourceLocation TypeEndLoc =
15148 Diag(NameLoc,
15149 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15150 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15152 New->setType(T);
15153 }
15154
15155 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15156 // duration shall not be qualified by an address-space qualifier."
15157 // Since all parameters have automatic store duration, they can not have
15158 // an address space.
15159 if (T.getAddressSpace() != LangAS::Default &&
15160 // OpenCL allows function arguments declared to be an array of a type
15161 // to be qualified with an address space.
15162 !(getLangOpts().OpenCL &&
15163 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15164 // WebAssembly allows reference types as parameters. Funcref in particular
15165 // lives in a different address space.
15166 !(T->isFunctionPointerType() &&
15167 T.getAddressSpace() == LangAS::wasm_funcref)) {
15168 Diag(NameLoc, diag::err_arg_with_address_space);
15169 New->setInvalidDecl();
15170 }
15171
15172 // PPC MMA non-pointer types are not allowed as function argument types.
15173 if (Context.getTargetInfo().getTriple().isPPC64() &&
15174 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15175 New->setInvalidDecl();
15176 }
15177
15178 return New;
15179}
15180
15182 SourceLocation LocAfterDecls) {
15183 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15184
15185 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15186 // in the declaration list shall have at least one declarator, those
15187 // declarators shall only declare identifiers from the identifier list, and
15188 // every identifier in the identifier list shall be declared.
15189 //
15190 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15191 // identifiers it names shall be declared in the declaration list."
15192 //
15193 // This is why we only diagnose in C99 and later. Note, the other conditions
15194 // listed are checked elsewhere.
15195 if (!FTI.hasPrototype) {
15196 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15197 --i;
15198 if (FTI.Params[i].Param == nullptr) {
15199 if (getLangOpts().C99) {
15200 SmallString<256> Code;
15201 llvm::raw_svector_ostream(Code)
15202 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15203 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15204 << FTI.Params[i].Ident
15205 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15206 }
15207
15208 // Implicitly declare the argument as type 'int' for lack of a better
15209 // type.
15210 AttributeFactory attrs;
15211 DeclSpec DS(attrs);
15212 const char* PrevSpec; // unused
15213 unsigned DiagID; // unused
15214 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15215 DiagID, Context.getPrintingPolicy());
15216 // Use the identifier location for the type source range.
15217 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15218 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15221 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15222 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15223 }
15224 }
15225 }
15226}
15227
15228Decl *
15230 MultiTemplateParamsArg TemplateParameterLists,
15231 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15232 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15233 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15234 Scope *ParentScope = FnBodyScope->getParent();
15235
15236 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15237 // we define a non-templated function definition, we will create a declaration
15238 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15239 // The base function declaration will have the equivalent of an `omp declare
15240 // variant` annotation which specifies the mangled definition as a
15241 // specialization function under the OpenMP context defined as part of the
15242 // `omp begin declare variant`.
15244 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15246 ParentScope, D, TemplateParameterLists, Bases);
15247
15248 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15249 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15250 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15251
15252 if (!Bases.empty())
15254 Bases);
15255
15256 return Dcl;
15257}
15258
15261}
15262
15264 const FunctionDecl *&PossiblePrototype) {
15265 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15266 Prev = Prev->getPreviousDecl()) {
15267 // Ignore any declarations that occur in function or method
15268 // scope, because they aren't visible from the header.
15269 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15270 continue;
15271
15272 PossiblePrototype = Prev;
15273 return Prev->getType()->isFunctionProtoType();
15274 }
15275 return false;
15276}
15277
15278static bool
15280 const FunctionDecl *&PossiblePrototype) {
15281 // Don't warn about invalid declarations.
15282 if (FD->isInvalidDecl())
15283 return false;
15284
15285 // Or declarations that aren't global.
15286 if (!FD->isGlobal())
15287 return false;
15288
15289 // Don't warn about C++ member functions.
15290 if (isa<CXXMethodDecl>(FD))
15291 return false;
15292
15293 // Don't warn about 'main'.
15294 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15295 if (IdentifierInfo *II = FD->getIdentifier())
15296 if (II->isStr("main") || II->isStr("efi_main"))
15297 return false;
15298
15299 if (FD->isMSVCRTEntryPoint())
15300 return false;
15301
15302 // Don't warn about inline functions.
15303 if (FD->isInlined())
15304 return false;
15305
15306 // Don't warn about function templates.
15308 return false;
15309
15310 // Don't warn about function template specializations.
15312 return false;
15313
15314 // Don't warn for OpenCL kernels.
15315 if (FD->hasAttr<OpenCLKernelAttr>())
15316 return false;
15317
15318 // Don't warn on explicitly deleted functions.
15319 if (FD->isDeleted())
15320 return false;
15321
15322 // Don't warn on implicitly local functions (such as having local-typed
15323 // parameters).
15324 if (!FD->isExternallyVisible())
15325 return false;
15326
15327 // If we were able to find a potential prototype, don't warn.
15328 if (FindPossiblePrototype(FD, PossiblePrototype))
15329 return false;
15330
15331 return true;
15332}
15333
15334void
15336 const FunctionDecl *EffectiveDefinition,
15337 SkipBodyInfo *SkipBody) {
15338 const FunctionDecl *Definition = EffectiveDefinition;
15339 if (!Definition &&
15340 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15341 return;
15342
15343 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15344 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15345 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15346 // A merged copy of the same function, instantiated as a member of
15347 // the same class, is OK.
15348 if (declaresSameEntity(OrigFD, OrigDef) &&
15349 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15350 cast<Decl>(FD->getLexicalDeclContext())))
15351 return;
15352 }
15353 }
15354 }
15355
15357 return;
15358
15359 // Don't emit an error when this is redefinition of a typo-corrected
15360 // definition.
15362 return;
15363
15364 // If we don't have a visible definition of the function, and it's inline or
15365 // a template, skip the new definition.
15366 if (SkipBody && !hasVisibleDefinition(Definition) &&
15367 (Definition->getFormalLinkage() == Linkage::Internal ||
15368 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15369 Definition->getNumTemplateParameterLists())) {
15370 SkipBody->ShouldSkip = true;
15371 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15372 if (auto *TD = Definition->getDescribedFunctionTemplate())
15375 return;
15376 }
15377
15378 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15379 Definition->getStorageClass() == SC_Extern)
15380 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15381 << FD << getLangOpts().CPlusPlus;
15382 else
15383 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15384
15385 Diag(Definition->getLocation(), diag::note_previous_definition);
15386 FD->setInvalidDecl();
15387}
15388
15390 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15391
15393 LSI->CallOperator = CallOperator;
15394 LSI->Lambda = LambdaClass;
15395 LSI->ReturnType = CallOperator->getReturnType();
15396 // This function in calls in situation where the context of the call operator
15397 // is not entered, so we set AfterParameterList to false, so that
15398 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15399 LSI->AfterParameterList = false;
15400 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15401
15402 if (LCD == LCD_None)
15404 else if (LCD == LCD_ByCopy)
15406 else if (LCD == LCD_ByRef)
15408 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15409
15411 LSI->Mutable = !CallOperator->isConst();
15412 if (CallOperator->isExplicitObjectMemberFunction())
15413 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15414
15415 // Add the captures to the LSI so they can be noted as already
15416 // captured within tryCaptureVar.
15417 auto I = LambdaClass->field_begin();
15418 for (const auto &C : LambdaClass->captures()) {
15419 if (C.capturesVariable()) {
15420 ValueDecl *VD = C.getCapturedVar();
15421 if (VD->isInitCapture())
15423 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15424 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15425 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15426 /*EllipsisLoc*/C.isPackExpansion()
15427 ? C.getEllipsisLoc() : SourceLocation(),
15428 I->getType(), /*Invalid*/false);
15429
15430 } else if (C.capturesThis()) {
15431 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15432 C.getCaptureKind() == LCK_StarThis);
15433 } else {
15434 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15435 I->getType());
15436 }
15437 ++I;
15438 }
15439 return LSI;
15440}
15441
15443 SkipBodyInfo *SkipBody,
15444 FnBodyKind BodyKind) {
15445 if (!D) {
15446 // Parsing the function declaration failed in some way. Push on a fake scope
15447 // anyway so we can try to parse the function body.
15450 return D;
15451 }
15452
15453 FunctionDecl *FD = nullptr;
15454
15455 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15456 FD = FunTmpl->getTemplatedDecl();
15457 else
15458 FD = cast<FunctionDecl>(D);
15459
15460 // Do not push if it is a lambda because one is already pushed when building
15461 // the lambda in ActOnStartOfLambdaDefinition().
15462 if (!isLambdaCallOperator(FD))
15463 // [expr.const]/p14.1
15464 // An expression or conversion is in an immediate function context if it is
15465 // potentially evaluated and either: its innermost enclosing non-block scope
15466 // is a function parameter scope of an immediate function.
15469 : ExprEvalContexts.back().Context);
15470
15471 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15472 // context is nested in an immediate function context, so smaller contexts
15473 // that appear inside immediate functions (like variable initializers) are
15474 // considered to be inside an immediate function context even though by
15475 // themselves they are not immediate function contexts. But when a new
15476 // function is entered, we need to reset this tracking, since the entered
15477 // function might be not an immediate function.
15478 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15479 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15480 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15481
15482 // Check for defining attributes before the check for redefinition.
15483 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15484 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15485 FD->dropAttr<AliasAttr>();
15486 FD->setInvalidDecl();
15487 }
15488 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15489 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15490 FD->dropAttr<IFuncAttr>();
15491 FD->setInvalidDecl();
15492 }
15493 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15494 if (!Context.getTargetInfo().hasFeature("fmv") &&
15495 !Attr->isDefaultVersion()) {
15496 // If function multi versioning disabled skip parsing function body
15497 // defined with non-default target_version attribute
15498 if (SkipBody)
15499 SkipBody->ShouldSkip = true;
15500 return nullptr;
15501 }
15502 }
15503
15504 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15505 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15506 Ctor->isDefaultConstructor() &&
15508 // If this is an MS ABI dllexport default constructor, instantiate any
15509 // default arguments.
15511 }
15512 }
15513
15514 // See if this is a redefinition. If 'will have body' (or similar) is already
15515 // set, then these checks were already performed when it was set.
15516 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15518 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15519
15520 // If we're skipping the body, we're done. Don't enter the scope.
15521 if (SkipBody && SkipBody->ShouldSkip)
15522 return D;
15523 }
15524
15525 // Mark this function as "will have a body eventually". This lets users to
15526 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15527 // this function.
15528 FD->setWillHaveBody();
15529
15530 // If we are instantiating a generic lambda call operator, push
15531 // a LambdaScopeInfo onto the function stack. But use the information
15532 // that's already been calculated (ActOnLambdaExpr) to prime the current
15533 // LambdaScopeInfo.
15534 // When the template operator is being specialized, the LambdaScopeInfo,
15535 // has to be properly restored so that tryCaptureVariable doesn't try
15536 // and capture any new variables. In addition when calculating potential
15537 // captures during transformation of nested lambdas, it is necessary to
15538 // have the LSI properly restored.
15540 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15541 // instantiated, explicitly specialized.
15544 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15545 FD->setInvalidDecl();
15547 } else {
15548 assert(inTemplateInstantiation() &&
15549 "There should be an active template instantiation on the stack "
15550 "when instantiating a generic lambda!");
15551 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15552 }
15553 } else {
15554 // Enter a new function scope
15556 }
15557
15558 // Builtin functions cannot be defined.
15559 if (unsigned BuiltinID = FD->getBuiltinID()) {
15562 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15563 FD->setInvalidDecl();
15564 }
15565 }
15566
15567 // The return type of a function definition must be complete (C99 6.9.1p3).
15568 // C++23 [dcl.fct.def.general]/p2
15569 // The type of [...] the return for a function definition
15570 // shall not be a (possibly cv-qualified) class type that is incomplete
15571 // or abstract within the function body unless the function is deleted.
15572 QualType ResultType = FD->getReturnType();
15573 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15574 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15575 (RequireCompleteType(FD->getLocation(), ResultType,
15576 diag::err_func_def_incomplete_result) ||
15578 diag::err_abstract_type_in_decl,
15580 FD->setInvalidDecl();
15581
15582 if (FnBodyScope)
15583 PushDeclContext(FnBodyScope, FD);
15584
15585 // Check the validity of our function parameters
15586 if (BodyKind != FnBodyKind::Delete)
15588 /*CheckParameterNames=*/true);
15589
15590 // Add non-parameter declarations already in the function to the current
15591 // scope.
15592 if (FnBodyScope) {
15593 for (Decl *NPD : FD->decls()) {
15594 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15595 if (!NonParmDecl)
15596 continue;
15597 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15598 "parameters should not be in newly created FD yet");
15599
15600 // If the decl has a name, make it accessible in the current scope.
15601 if (NonParmDecl->getDeclName())
15602 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15603
15604 // Similarly, dive into enums and fish their constants out, making them
15605 // accessible in this scope.
15606 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15607 for (auto *EI : ED->enumerators())
15608 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15609 }
15610 }
15611 }
15612
15613 // Introduce our parameters into the function scope
15614 for (auto *Param : FD->parameters()) {
15615 Param->setOwningFunction(FD);
15616
15617 // If this has an identifier, add it to the scope stack.
15618 if (Param->getIdentifier() && FnBodyScope) {
15619 CheckShadow(FnBodyScope, Param);
15620
15621 PushOnScopeChains(Param, FnBodyScope);
15622 }
15623 }
15624
15625 // C++ [module.import/6] external definitions are not permitted in header
15626 // units. Deleted and Defaulted functions are implicitly inline (but the
15627 // inline state is not set at this point, so check the BodyKind explicitly).
15628 // FIXME: Consider an alternate location for the test where the inlined()
15629 // state is complete.
15630 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15631 !FD->isInvalidDecl() && !FD->isInlined() &&
15632 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15633 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15634 !FD->isTemplateInstantiation()) {
15635 assert(FD->isThisDeclarationADefinition());
15636 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15637 FD->setInvalidDecl();
15638 }
15639
15640 // Ensure that the function's exception specification is instantiated.
15641 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15643
15644 // dllimport cannot be applied to non-inline function definitions.
15645 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15646 !FD->isTemplateInstantiation()) {
15647 assert(!FD->hasAttr<DLLExportAttr>());
15648 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15649 FD->setInvalidDecl();
15650 return D;
15651 }
15652
15653 // Some function attributes (like OptimizeNoneAttr) need actions before
15654 // parsing body started.
15656
15657 // We want to attach documentation to original Decl (which might be
15658 // a function template).
15660 if (getCurLexicalContext()->isObjCContainer() &&
15661 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15662 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15663 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15664
15665 return D;
15666}
15667
15669 if (!FD || FD->isInvalidDecl())
15670 return;
15671 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
15672 FD = TD->getTemplatedDecl();
15673 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
15677 FpPragmaStack.CurrentValue =
15679 }
15680}
15681
15683 ReturnStmt **Returns = Scope->Returns.data();
15684
15685 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15686 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15687 if (!NRVOCandidate->isNRVOVariable())
15688 Returns[I]->setNRVOCandidate(nullptr);
15689 }
15690 }
15691}
15692
15694 // We can't delay parsing the body of a constexpr function template (yet).
15695 if (D.getDeclSpec().hasConstexprSpecifier())
15696 return false;
15697
15698 // We can't delay parsing the body of a function template with a deduced
15699 // return type (yet).
15700 if (D.getDeclSpec().hasAutoTypeSpec()) {
15701 // If the placeholder introduces a non-deduced trailing return type,
15702 // we can still delay parsing it.
15703 if (D.getNumTypeObjects()) {
15704 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15705 if (Outer.Kind == DeclaratorChunk::Function &&
15706 Outer.Fun.hasTrailingReturnType()) {
15707 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15708 return Ty.isNull() || !Ty->isUndeducedType();
15709 }
15710 }
15711 return false;
15712 }
15713
15714 return true;
15715}
15716
15718 // We cannot skip the body of a function (or function template) which is
15719 // constexpr, since we may need to evaluate its body in order to parse the
15720 // rest of the file.
15721 // We cannot skip the body of a function with an undeduced return type,
15722 // because any callers of that function need to know the type.
15723 if (const FunctionDecl *FD = D->getAsFunction()) {
15724 if (FD->isConstexpr())
15725 return false;
15726 // We can't simply call Type::isUndeducedType here, because inside template
15727 // auto can be deduced to a dependent type, which is not considered
15728 // "undeduced".
15729 if (FD->getReturnType()->getContainedDeducedType())
15730 return false;
15731 }
15733}
15734
15736 if (!Decl)
15737 return nullptr;
15738 if (FunctionDecl *FD = Decl->getAsFunction())
15739 FD->setHasSkippedBody();
15740 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15741 MD->setHasSkippedBody();
15742 return Decl;
15743}
15744
15746 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
15747}
15748
15749/// RAII object that pops an ExpressionEvaluationContext when exiting a function
15750/// body.
15752public:
15753 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15755 if (!IsLambda)
15757 }
15758
15759private:
15760 Sema &S;
15761 bool IsLambda = false;
15762};
15763
15765 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15766
15767 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15768 if (EscapeInfo.count(BD))
15769 return EscapeInfo[BD];
15770
15771 bool R = false;
15772 const BlockDecl *CurBD = BD;
15773
15774 do {
15775 R = !CurBD->doesNotEscape();
15776 if (R)
15777 break;
15778 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15779 } while (CurBD);
15780
15781 return EscapeInfo[BD] = R;
15782 };
15783
15784 // If the location where 'self' is implicitly retained is inside a escaping
15785 // block, emit a diagnostic.
15786 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15788 if (IsOrNestedInEscapingBlock(P.second))
15789 S.Diag(P.first, diag::warn_implicitly_retains_self)
15790 << FixItHint::CreateInsertion(P.first, "self->");
15791}
15792
15793static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
15794 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
15795 FD->getDeclName().isIdentifier() && FD->getName() == Name;
15796}
15797
15799 return methodHasName(FD, "get_return_object");
15800}
15801
15803 return FD->isStatic() &&
15804 methodHasName(FD, "get_return_object_on_allocation_failure");
15805}
15806
15809 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15810 return;
15811 // Allow some_promise_type::get_return_object().
15813 return;
15814 if (!FD->hasAttr<CoroWrapperAttr>())
15815 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
15816}
15817
15819 bool IsInstantiation) {
15821 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15822
15823 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15824 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15825
15827 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15828
15829 // If we skip function body, we can't tell if a function is a coroutine.
15830 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
15831 if (FSI->isCoroutine())
15833 else
15835 }
15836
15837 {
15838 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15839 // one is already popped when finishing the lambda in BuildLambdaExpr().
15840 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15841 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15842 if (FD) {
15843 // If this is called by Parser::ParseFunctionDefinition() after marking
15844 // the declaration as deleted, and if the deleted-function-body contains
15845 // a message (C++26), then a DefaultedOrDeletedInfo will have already been
15846 // added to store that message; do not overwrite it in that case.
15847 //
15848 // Since this would always set the body to 'nullptr' in that case anyway,
15849 // which is already done when the function decl is initially created,
15850 // always skipping this irrespective of whether there is a delete message
15851 // should not be a problem.
15852 if (!FD->isDeletedAsWritten())
15853 FD->setBody(Body);
15854 FD->setWillHaveBody(false);
15856
15857 if (getLangOpts().CPlusPlus14) {
15858 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15859 FD->getReturnType()->isUndeducedType()) {
15860 // For a function with a deduced result type to return void,
15861 // the result type as written must be 'auto' or 'decltype(auto)',
15862 // possibly cv-qualified or constrained, but not ref-qualified.
15863 if (!FD->getReturnType()->getAs<AutoType>()) {
15864 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15865 << FD->getReturnType();
15866 FD->setInvalidDecl();
15867 } else {
15868 // Falling off the end of the function is the same as 'return;'.
15869 Expr *Dummy = nullptr;
15871 FD, dcl->getLocation(), Dummy,
15872 FD->getReturnType()->getAs<AutoType>()))
15873 FD->setInvalidDecl();
15874 }
15875 }
15876 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
15877 // In C++11, we don't use 'auto' deduction rules for lambda call
15878 // operators because we don't support return type deduction.
15879 auto *LSI = getCurLambda();
15880 if (LSI->HasImplicitReturnType) {
15882
15883 // C++11 [expr.prim.lambda]p4:
15884 // [...] if there are no return statements in the compound-statement
15885 // [the deduced type is] the type void
15886 QualType RetType =
15887 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15888
15889 // Update the return type to the deduced type.
15890 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15891 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15892 Proto->getExtProtoInfo()));
15893 }
15894 }
15895
15896 // If the function implicitly returns zero (like 'main') or is naked,
15897 // don't complain about missing return statements.
15898 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15900
15901 // MSVC permits the use of pure specifier (=0) on function definition,
15902 // defined at class scope, warn about this non-standard construct.
15903 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
15904 !FD->isOutOfLine())
15905 Diag(FD->getLocation(), diag::ext_pure_function_definition);
15906
15907 if (!FD->isInvalidDecl()) {
15908 // Don't diagnose unused parameters of defaulted, deleted or naked
15909 // functions.
15910 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15911 !FD->hasAttr<NakedAttr>())
15914 FD->getReturnType(), FD);
15915
15916 // If this is a structor, we need a vtable.
15917 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15918 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15919 else if (CXXDestructorDecl *Destructor =
15920 dyn_cast<CXXDestructorDecl>(FD))
15921 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15922
15923 // Try to apply the named return value optimization. We have to check
15924 // if we can do this here because lambdas keep return statements around
15925 // to deduce an implicit return type.
15926 if (FD->getReturnType()->isRecordType() &&
15928 computeNRVO(Body, FSI);
15929 }
15930
15931 // GNU warning -Wmissing-prototypes:
15932 // Warn if a global function is defined without a previous
15933 // prototype declaration. This warning is issued even if the
15934 // definition itself provides a prototype. The aim is to detect
15935 // global functions that fail to be declared in header files.
15936 const FunctionDecl *PossiblePrototype = nullptr;
15937 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15938 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15939
15940 if (PossiblePrototype) {
15941 // We found a declaration that is not a prototype,
15942 // but that could be a zero-parameter prototype
15943 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15944 TypeLoc TL = TI->getTypeLoc();
15946 Diag(PossiblePrototype->getLocation(),
15947 diag::note_declaration_not_a_prototype)
15948 << (FD->getNumParams() != 0)
15950 FTL.getRParenLoc(), "void")
15951 : FixItHint{});
15952 }
15953 } else {
15954 // Returns true if the token beginning at this Loc is `const`.
15955 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15956 const LangOptions &LangOpts) {
15957 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15958 if (LocInfo.first.isInvalid())
15959 return false;
15960
15961 bool Invalid = false;
15962 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15963 if (Invalid)
15964 return false;
15965
15966 if (LocInfo.second > Buffer.size())
15967 return false;
15968
15969 const char *LexStart = Buffer.data() + LocInfo.second;
15970 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15971
15972 return StartTok.consume_front("const") &&
15973 (StartTok.empty() || isWhitespace(StartTok[0]) ||
15974 StartTok.starts_with("/*") || StartTok.starts_with("//"));
15975 };
15976
15977 auto findBeginLoc = [&]() {
15978 // If the return type has `const` qualifier, we want to insert
15979 // `static` before `const` (and not before the typename).
15980 if ((FD->getReturnType()->isAnyPointerType() &&
15983 // But only do this if we can determine where the `const` is.
15984
15985 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15986 getLangOpts()))
15987
15988 return FD->getBeginLoc();
15989 }
15990 return FD->getTypeSpecStartLoc();
15991 };
15993 diag::note_static_for_internal_linkage)
15994 << /* function */ 1
15995 << (FD->getStorageClass() == SC_None
15996 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15997 : FixItHint{});
15998 }
15999 }
16000
16001 // We might not have found a prototype because we didn't wish to warn on
16002 // the lack of a missing prototype. Try again without the checks for
16003 // whether we want to warn on the missing prototype.
16004 if (!PossiblePrototype)
16005 (void)FindPossiblePrototype(FD, PossiblePrototype);
16006
16007 // If the function being defined does not have a prototype, then we may
16008 // need to diagnose it as changing behavior in C23 because we now know
16009 // whether the function accepts arguments or not. This only handles the
16010 // case where the definition has no prototype but does have parameters
16011 // and either there is no previous potential prototype, or the previous
16012 // potential prototype also has no actual prototype. This handles cases
16013 // like:
16014 // void f(); void f(a) int a; {}
16015 // void g(a) int a; {}
16016 // See MergeFunctionDecl() for other cases of the behavior change
16017 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16018 // type without a prototype.
16019 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16020 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16021 !PossiblePrototype->isImplicit()))) {
16022 // The function definition has parameters, so this will change behavior
16023 // in C23. If there is a possible prototype, it comes before the
16024 // function definition.
16025 // FIXME: The declaration may have already been diagnosed as being
16026 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16027 // there's no way to test for the "changes behavior" condition in
16028 // SemaType.cpp when forming the declaration's function type. So, we do
16029 // this awkward dance instead.
16030 //
16031 // If we have a possible prototype and it declares a function with a
16032 // prototype, we don't want to diagnose it; if we have a possible
16033 // prototype and it has no prototype, it may have already been
16034 // diagnosed in SemaType.cpp as deprecated depending on whether
16035 // -Wstrict-prototypes is enabled. If we already warned about it being
16036 // deprecated, add a note that it also changes behavior. If we didn't
16037 // warn about it being deprecated (because the diagnostic is not
16038 // enabled), warn now that it is deprecated and changes behavior.
16039
16040 // This K&R C function definition definitely changes behavior in C23,
16041 // so diagnose it.
16042 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16043 << /*definition*/ 1 << /* not supported in C23 */ 0;
16044
16045 // If we have a possible prototype for the function which is a user-
16046 // visible declaration, we already tested that it has no prototype.
16047 // This will change behavior in C23. This gets a warning rather than a
16048 // note because it's the same behavior-changing problem as with the
16049 // definition.
16050 if (PossiblePrototype)
16051 Diag(PossiblePrototype->getLocation(),
16052 diag::warn_non_prototype_changes_behavior)
16053 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16054 << /*definition*/ 1;
16055 }
16056
16057 // Warn on CPUDispatch with an actual body.
16058 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16059 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16060 if (!CmpndBody->body_empty())
16061 Diag(CmpndBody->body_front()->getBeginLoc(),
16062 diag::warn_dispatch_body_ignored);
16063
16064 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16065 const CXXMethodDecl *KeyFunction;
16066 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16067 MD->isVirtual() &&
16068 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16069 MD == KeyFunction->getCanonicalDecl()) {
16070 // Update the key-function state if necessary for this ABI.
16071 if (FD->isInlined() &&
16074
16075 // If the newly-chosen key function is already defined, then we
16076 // need to mark the vtable as used retroactively.
16077 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16078 const FunctionDecl *Definition;
16079 if (KeyFunction && KeyFunction->isDefined(Definition))
16080 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16081 } else {
16082 // We just defined they key function; mark the vtable as used.
16083 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16084 }
16085 }
16086 }
16087
16088 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16089 "Function parsing confused");
16090 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16091 assert(MD == getCurMethodDecl() && "Method parsing confused");
16092 MD->setBody(Body);
16093 if (!MD->isInvalidDecl()) {
16095 MD->getReturnType(), MD);
16096
16097 if (Body)
16098 computeNRVO(Body, FSI);
16099 }
16100 if (FSI->ObjCShouldCallSuper) {
16101 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16102 << MD->getSelector().getAsString();
16103 FSI->ObjCShouldCallSuper = false;
16104 }
16106 const ObjCMethodDecl *InitMethod = nullptr;
16107 bool isDesignated =
16108 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16109 assert(isDesignated && InitMethod);
16110 (void)isDesignated;
16111
16112 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16113 auto IFace = MD->getClassInterface();
16114 if (!IFace)
16115 return false;
16116 auto SuperD = IFace->getSuperClass();
16117 if (!SuperD)
16118 return false;
16119 return SuperD->getIdentifier() ==
16120 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16121 };
16122 // Don't issue this warning for unavailable inits or direct subclasses
16123 // of NSObject.
16124 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16125 Diag(MD->getLocation(),
16126 diag::warn_objc_designated_init_missing_super_call);
16127 Diag(InitMethod->getLocation(),
16128 diag::note_objc_designated_init_marked_here);
16129 }
16131 }
16132 if (FSI->ObjCWarnForNoInitDelegation) {
16133 // Don't issue this warning for unavailable inits.
16134 if (!MD->isUnavailable())
16135 Diag(MD->getLocation(),
16136 diag::warn_objc_secondary_init_missing_init_call);
16137 FSI->ObjCWarnForNoInitDelegation = false;
16138 }
16139
16141 } else {
16142 // Parsing the function declaration failed in some way. Pop the fake scope
16143 // we pushed on.
16144 PopFunctionScopeInfo(ActivePolicy, dcl);
16145 return nullptr;
16146 }
16147
16148 if (Body && FSI->HasPotentialAvailabilityViolations)
16150
16151 assert(!FSI->ObjCShouldCallSuper &&
16152 "This should only be set for ObjC methods, which should have been "
16153 "handled in the block above.");
16154
16155 // Verify and clean out per-function state.
16156 if (Body && (!FD || !FD->isDefaulted())) {
16157 // C++ constructors that have function-try-blocks can't have return
16158 // statements in the handlers of that block. (C++ [except.handle]p14)
16159 // Verify this.
16160 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16161 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16162
16163 // Verify that gotos and switch cases don't jump into scopes illegally.
16166
16167 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16168 if (!Destructor->getParent()->isDependentType())
16170
16172 Destructor->getParent());
16173 }
16174
16175 // If any errors have occurred, clear out any temporaries that may have
16176 // been leftover. This ensures that these temporaries won't be picked up
16177 // for deletion in some later function.
16180 getDiagnostics().getSuppressAllDiagnostics()) {
16182 }
16183 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16184 // Since the body is valid, issue any analysis-based warnings that are
16185 // enabled.
16186 ActivePolicy = &WP;
16187 }
16188
16189 if (!IsInstantiation && FD &&
16190 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16191 !FD->isInvalidDecl() &&
16193 FD->setInvalidDecl();
16194
16195 if (FD && FD->hasAttr<NakedAttr>()) {
16196 for (const Stmt *S : Body->children()) {
16197 // Allow local register variables without initializer as they don't
16198 // require prologue.
16199 bool RegisterVariables = false;
16200 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16201 for (const auto *Decl : DS->decls()) {
16202 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16203 RegisterVariables =
16204 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16205 if (!RegisterVariables)
16206 break;
16207 }
16208 }
16209 }
16210 if (RegisterVariables)
16211 continue;
16212 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16213 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16214 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16215 FD->setInvalidDecl();
16216 break;
16217 }
16218 }
16219 }
16220
16221 assert(ExprCleanupObjects.size() ==
16222 ExprEvalContexts.back().NumCleanupObjects &&
16223 "Leftover temporaries in function");
16224 assert(!Cleanup.exprNeedsCleanups() &&
16225 "Unaccounted cleanups in function");
16226 assert(MaybeODRUseExprs.empty() &&
16227 "Leftover expressions for odr-use checking");
16228 }
16229 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16230 // the declaration context below. Otherwise, we're unable to transform
16231 // 'this' expressions when transforming immediate context functions.
16232
16233 if (!IsInstantiation)
16235
16236 PopFunctionScopeInfo(ActivePolicy, dcl);
16237 // If any errors have occurred, clear out any temporaries that may have
16238 // been leftover. This ensures that these temporaries won't be picked up for
16239 // deletion in some later function.
16242 }
16243
16244 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16245 !LangOpts.OMPTargetTriples.empty())) ||
16246 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16247 auto ES = getEmissionStatus(FD);
16250 DeclsToCheckForDeferredDiags.insert(FD);
16251 }
16252
16253 if (FD && !FD->isDeleted())
16254 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16255
16256 return dcl;
16257}
16258
16259/// When we finish delayed parsing of an attribute, we must attach it to the
16260/// relevant Decl.
16262 ParsedAttributes &Attrs) {
16263 // Always attach attributes to the underlying decl.
16264 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16265 D = TD->getTemplatedDecl();
16266 ProcessDeclAttributeList(S, D, Attrs);
16268
16269 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16270 if (Method->isStatic())
16272}
16273
16275 IdentifierInfo &II, Scope *S) {
16276 // It is not valid to implicitly define a function in C23.
16278 "Implicit function declarations aren't allowed in this language mode");
16279
16280 // Find the scope in which the identifier is injected and the corresponding
16281 // DeclContext.
16282 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16283 // In that case, we inject the declaration into the translation unit scope
16284 // instead.
16285 Scope *BlockScope = S;
16286 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16287 BlockScope = BlockScope->getParent();
16288
16289 // Loop until we find a DeclContext that is either a function/method or the
16290 // translation unit, which are the only two valid places to implicitly define
16291 // a function. This avoids accidentally defining the function within a tag
16292 // declaration, for example.
16293 Scope *ContextScope = BlockScope;
16294 while (!ContextScope->getEntity() ||
16295 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16296 !ContextScope->getEntity()->isTranslationUnit()))
16297 ContextScope = ContextScope->getParent();
16298 ContextRAII SavedContext(*this, ContextScope->getEntity());
16299
16300 // Before we produce a declaration for an implicitly defined
16301 // function, see whether there was a locally-scoped declaration of
16302 // this name as a function or variable. If so, use that
16303 // (non-visible) declaration, and complain about it.
16304 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16305 if (ExternCPrev) {
16306 // We still need to inject the function into the enclosing block scope so
16307 // that later (non-call) uses can see it.
16308 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16309
16310 // C89 footnote 38:
16311 // If in fact it is not defined as having type "function returning int",
16312 // the behavior is undefined.
16313 if (!isa<FunctionDecl>(ExternCPrev) ||
16315 cast<FunctionDecl>(ExternCPrev)->getType(),
16317 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16318 << ExternCPrev << !getLangOpts().C99;
16319 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16320 return ExternCPrev;
16321 }
16322 }
16323
16324 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16325 unsigned diag_id;
16326 if (II.getName().starts_with("__builtin_"))
16327 diag_id = diag::warn_builtin_unknown;
16328 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16329 else if (getLangOpts().C99)
16330 diag_id = diag::ext_implicit_function_decl_c99;
16331 else
16332 diag_id = diag::warn_implicit_function_decl;
16333
16334 TypoCorrection Corrected;
16335 // Because typo correction is expensive, only do it if the implicit
16336 // function declaration is going to be treated as an error.
16337 //
16338 // Perform the correction before issuing the main diagnostic, as some
16339 // consumers use typo-correction callbacks to enhance the main diagnostic.
16340 if (S && !ExternCPrev &&
16344 S, nullptr, CCC, CTK_NonError);
16345 }
16346
16347 Diag(Loc, diag_id) << &II;
16348 if (Corrected) {
16349 // If the correction is going to suggest an implicitly defined function,
16350 // skip the correction as not being a particularly good idea.
16351 bool Diagnose = true;
16352 if (const auto *D = Corrected.getCorrectionDecl())
16353 Diagnose = !D->isImplicit();
16354 if (Diagnose)
16355 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16356 /*ErrorRecovery*/ false);
16357 }
16358
16359 // If we found a prior declaration of this function, don't bother building
16360 // another one. We've already pushed that one into scope, so there's nothing
16361 // more to do.
16362 if (ExternCPrev)
16363 return ExternCPrev;
16364
16365 // Set a Declarator for the implicit definition: int foo();
16366 const char *Dummy;
16367 AttributeFactory attrFactory;
16368 DeclSpec DS(attrFactory);
16369 unsigned DiagID;
16370 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16372 (void)Error; // Silence warning.
16373 assert(!Error && "Error setting up implicit decl!");
16374 SourceLocation NoLoc;
16376 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16377 /*IsAmbiguous=*/false,
16378 /*LParenLoc=*/NoLoc,
16379 /*Params=*/nullptr,
16380 /*NumParams=*/0,
16381 /*EllipsisLoc=*/NoLoc,
16382 /*RParenLoc=*/NoLoc,
16383 /*RefQualifierIsLvalueRef=*/true,
16384 /*RefQualifierLoc=*/NoLoc,
16385 /*MutableLoc=*/NoLoc, EST_None,
16386 /*ESpecRange=*/SourceRange(),
16387 /*Exceptions=*/nullptr,
16388 /*ExceptionRanges=*/nullptr,
16389 /*NumExceptions=*/0,
16390 /*NoexceptExpr=*/nullptr,
16391 /*ExceptionSpecTokens=*/nullptr,
16392 /*DeclsInPrototype=*/std::nullopt,
16393 Loc, Loc, D),
16394 std::move(DS.getAttributes()), SourceLocation());
16395 D.SetIdentifier(&II, Loc);
16396
16397 // Insert this function into the enclosing block scope.
16398 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16399 FD->setImplicit();
16400
16402
16403 return FD;
16404}
16405
16407 FunctionDecl *FD) {
16408 if (FD->isInvalidDecl())
16409 return;
16410
16411 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16412 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16413 return;
16414
16415 std::optional<unsigned> AlignmentParam;
16416 bool IsNothrow = false;
16417 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16418 return;
16419
16420 // C++2a [basic.stc.dynamic.allocation]p4:
16421 // An allocation function that has a non-throwing exception specification
16422 // indicates failure by returning a null pointer value. Any other allocation
16423 // function never returns a null pointer value and indicates failure only by
16424 // throwing an exception [...]
16425 //
16426 // However, -fcheck-new invalidates this possible assumption, so don't add
16427 // NonNull when that is enabled.
16428 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16429 !getLangOpts().CheckNew)
16430 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16431
16432 // C++2a [basic.stc.dynamic.allocation]p2:
16433 // An allocation function attempts to allocate the requested amount of
16434 // storage. [...] If the request succeeds, the value returned by a
16435 // replaceable allocation function is a [...] pointer value p0 different
16436 // from any previously returned value p1 [...]
16437 //
16438 // However, this particular information is being added in codegen,
16439 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16440
16441 // C++2a [basic.stc.dynamic.allocation]p2:
16442 // An allocation function attempts to allocate the requested amount of
16443 // storage. If it is successful, it returns the address of the start of a
16444 // block of storage whose length in bytes is at least as large as the
16445 // requested size.
16446 if (!FD->hasAttr<AllocSizeAttr>()) {
16447 FD->addAttr(AllocSizeAttr::CreateImplicit(
16448 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16449 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16450 }
16451
16452 // C++2a [basic.stc.dynamic.allocation]p3:
16453 // For an allocation function [...], the pointer returned on a successful
16454 // call shall represent the address of storage that is aligned as follows:
16455 // (3.1) If the allocation function takes an argument of type
16456 // std​::​align_­val_­t, the storage will have the alignment
16457 // specified by the value of this argument.
16458 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16459 FD->addAttr(AllocAlignAttr::CreateImplicit(
16460 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16461 }
16462
16463 // FIXME:
16464 // C++2a [basic.stc.dynamic.allocation]p3:
16465 // For an allocation function [...], the pointer returned on a successful
16466 // call shall represent the address of storage that is aligned as follows:
16467 // (3.2) Otherwise, if the allocation function is named operator new[],
16468 // the storage is aligned for any object that does not have
16469 // new-extended alignment ([basic.align]) and is no larger than the
16470 // requested size.
16471 // (3.3) Otherwise, the storage is aligned for any object that does not
16472 // have new-extended alignment and is of the requested size.
16473}
16474
16476 if (FD->isInvalidDecl())
16477 return;
16478
16479 // If this is a built-in function, map its builtin attributes to
16480 // actual attributes.
16481 if (unsigned BuiltinID = FD->getBuiltinID()) {
16482 // Handle printf-formatting attributes.
16483 unsigned FormatIdx;
16484 bool HasVAListArg;
16485 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16486 if (!FD->hasAttr<FormatAttr>()) {
16487 const char *fmt = "printf";
16488 unsigned int NumParams = FD->getNumParams();
16489 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16490 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16491 fmt = "NSString";
16492 FD->addAttr(FormatAttr::CreateImplicit(Context,
16493 &Context.Idents.get(fmt),
16494 FormatIdx+1,
16495 HasVAListArg ? 0 : FormatIdx+2,
16496 FD->getLocation()));
16497 }
16498 }
16499 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16500 HasVAListArg)) {
16501 if (!FD->hasAttr<FormatAttr>())
16502 FD->addAttr(FormatAttr::CreateImplicit(Context,
16503 &Context.Idents.get("scanf"),
16504 FormatIdx+1,
16505 HasVAListArg ? 0 : FormatIdx+2,
16506 FD->getLocation()));
16507 }
16508
16509 // Handle automatically recognized callbacks.
16510 SmallVector<int, 4> Encoding;
16511 if (!FD->hasAttr<CallbackAttr>() &&
16512 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16513 FD->addAttr(CallbackAttr::CreateImplicit(
16514 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16515
16516 // Mark const if we don't care about errno and/or floating point exceptions
16517 // that are the only thing preventing the function from being const. This
16518 // allows IRgen to use LLVM intrinsics for such functions.
16519 bool NoExceptions =
16521 bool ConstWithoutErrnoAndExceptions =
16523 bool ConstWithoutExceptions =
16525 if (!FD->hasAttr<ConstAttr>() &&
16526 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16527 (!ConstWithoutErrnoAndExceptions ||
16528 (!getLangOpts().MathErrno && NoExceptions)) &&
16529 (!ConstWithoutExceptions || NoExceptions))
16530 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16531
16532 // We make "fma" on GNU or Windows const because we know it does not set
16533 // errno in those environments even though it could set errno based on the
16534 // C standard.
16535 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16536 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16537 !FD->hasAttr<ConstAttr>()) {
16538 switch (BuiltinID) {
16539 case Builtin::BI__builtin_fma:
16540 case Builtin::BI__builtin_fmaf:
16541 case Builtin::BI__builtin_fmal:
16542 case Builtin::BIfma:
16543 case Builtin::BIfmaf:
16544 case Builtin::BIfmal:
16545 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16546 break;
16547 default:
16548 break;
16549 }
16550 }
16551
16552 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16553 !FD->hasAttr<ReturnsTwiceAttr>())
16554 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16555 FD->getLocation()));
16556 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16557 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16558 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16559 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16560 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16561 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16562 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16563 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16564 // Add the appropriate attribute, depending on the CUDA compilation mode
16565 // and which target the builtin belongs to. For example, during host
16566 // compilation, aux builtins are __device__, while the rest are __host__.
16567 if (getLangOpts().CUDAIsDevice !=
16569 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16570 else
16571 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16572 }
16573
16574 // Add known guaranteed alignment for allocation functions.
16575 switch (BuiltinID) {
16576 case Builtin::BImemalign:
16577 case Builtin::BIaligned_alloc:
16578 if (!FD->hasAttr<AllocAlignAttr>())
16579 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16580 FD->getLocation()));
16581 break;
16582 default:
16583 break;
16584 }
16585
16586 // Add allocsize attribute for allocation functions.
16587 switch (BuiltinID) {
16588 case Builtin::BIcalloc:
16589 FD->addAttr(AllocSizeAttr::CreateImplicit(
16590 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16591 break;
16592 case Builtin::BImemalign:
16593 case Builtin::BIaligned_alloc:
16594 case Builtin::BIrealloc:
16595 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16596 ParamIdx(), FD->getLocation()));
16597 break;
16598 case Builtin::BImalloc:
16599 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16600 ParamIdx(), FD->getLocation()));
16601 break;
16602 default:
16603 break;
16604 }
16605
16606 // Add lifetime attribute to std::move, std::fowrard et al.
16607 switch (BuiltinID) {
16608 case Builtin::BIaddressof:
16609 case Builtin::BI__addressof:
16610 case Builtin::BI__builtin_addressof:
16611 case Builtin::BIas_const:
16612 case Builtin::BIforward:
16613 case Builtin::BIforward_like:
16614 case Builtin::BImove:
16615 case Builtin::BImove_if_noexcept:
16616 if (ParmVarDecl *P = FD->getParamDecl(0u);
16617 !P->hasAttr<LifetimeBoundAttr>())
16618 P->addAttr(
16619 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16620 break;
16621 default:
16622 break;
16623 }
16624 }
16625
16627
16628 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16629 // throw, add an implicit nothrow attribute to any extern "C" function we come
16630 // across.
16631 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16632 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16633 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16634 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16635 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16636 }
16637
16638 IdentifierInfo *Name = FD->getIdentifier();
16639 if (!Name)
16640 return;
16642 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16643 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16645 // Okay: this could be a libc/libm/Objective-C function we know
16646 // about.
16647 } else
16648 return;
16649
16650 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16651 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16652 // target-specific builtins, perhaps?
16653 if (!FD->hasAttr<FormatAttr>())
16654 FD->addAttr(FormatAttr::CreateImplicit(Context,
16655 &Context.Idents.get("printf"), 2,
16656 Name->isStr("vasprintf") ? 0 : 3,
16657 FD->getLocation()));
16658 }
16659
16660 if (Name->isStr("__CFStringMakeConstantString")) {
16661 // We already have a __builtin___CFStringMakeConstantString,
16662 // but builds that use -fno-constant-cfstrings don't go through that.
16663 if (!FD->hasAttr<FormatArgAttr>())
16664 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16665 FD->getLocation()));
16666 }
16667}
16668
16670 TypeSourceInfo *TInfo) {
16671 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16672 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16673
16674 if (!TInfo) {
16675 assert(D.isInvalidType() && "no declarator info for valid type");
16677 }
16678
16679 // Scope manipulation handled by caller.
16680 TypedefDecl *NewTD =
16682 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16683
16684 // Bail out immediately if we have an invalid declaration.
16685 if (D.isInvalidType()) {
16686 NewTD->setInvalidDecl();
16687 return NewTD;
16688 }
16689
16690 if (D.getDeclSpec().isModulePrivateSpecified()) {
16692 Diag(NewTD->getLocation(), diag::err_module_private_local)
16693 << 2 << NewTD
16694 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16696 D.getDeclSpec().getModulePrivateSpecLoc());
16697 else
16698 NewTD->setModulePrivate();
16699 }
16700
16701 // C++ [dcl.typedef]p8:
16702 // If the typedef declaration defines an unnamed class (or
16703 // enum), the first typedef-name declared by the declaration
16704 // to be that class type (or enum type) is used to denote the
16705 // class type (or enum type) for linkage purposes only.
16706 // We need to check whether the type was declared in the declaration.
16707 switch (D.getDeclSpec().getTypeSpecType()) {
16708 case TST_enum:
16709 case TST_struct:
16710 case TST_interface:
16711 case TST_union:
16712 case TST_class: {
16713 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16714 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16715 break;
16716 }
16717
16718 default:
16719 break;
16720 }
16721
16722 return NewTD;
16723}
16724
16726 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16727 QualType T = TI->getType();
16728
16729 if (T->isDependentType())
16730 return false;
16731
16732 // This doesn't use 'isIntegralType' despite the error message mentioning
16733 // integral type because isIntegralType would also allow enum types in C.
16734 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16735 if (BT->isInteger())
16736 return false;
16737
16738 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16739 << T << T->isBitIntType();
16740}
16741
16743 QualType EnumUnderlyingTy, bool IsFixed,
16744 const EnumDecl *Prev) {
16745 if (IsScoped != Prev->isScoped()) {
16746 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16747 << Prev->isScoped();
16748 Diag(Prev->getLocation(), diag::note_previous_declaration);
16749 return true;
16750 }
16751
16752 if (IsFixed && Prev->isFixed()) {
16753 if (!EnumUnderlyingTy->isDependentType() &&
16754 !Prev->getIntegerType()->isDependentType() &&
16755 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16756 Prev->getIntegerType())) {
16757 // TODO: Highlight the underlying type of the redeclaration.
16758 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16759 << EnumUnderlyingTy << Prev->getIntegerType();
16760 Diag(Prev->getLocation(), diag::note_previous_declaration)
16761 << Prev->getIntegerTypeRange();
16762 return true;
16763 }
16764 } else if (IsFixed != Prev->isFixed()) {
16765 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16766 << Prev->isFixed();
16767 Diag(Prev->getLocation(), diag::note_previous_declaration);
16768 return true;
16769 }
16770
16771 return false;
16772}
16773
16774/// Get diagnostic %select index for tag kind for
16775/// redeclaration diagnostic message.
16776/// WARNING: Indexes apply to particular diagnostics only!
16777///
16778/// \returns diagnostic %select index.
16780 switch (Tag) {
16782 return 0;
16784 return 1;
16785 case TagTypeKind::Class:
16786 return 2;
16787 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16788 }
16789}
16790
16791/// Determine if tag kind is a class-key compatible with
16792/// class for redeclaration (class, struct, or __interface).
16793///
16794/// \returns true iff the tag kind is compatible.
16796{
16797 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
16799}
16800
16802 TagTypeKind TTK) {
16803 if (isa<TypedefDecl>(PrevDecl))
16804 return NTK_Typedef;
16805 else if (isa<TypeAliasDecl>(PrevDecl))
16806 return NTK_TypeAlias;
16807 else if (isa<ClassTemplateDecl>(PrevDecl))
16808 return NTK_Template;
16809 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16810 return NTK_TypeAliasTemplate;
16811 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16813 switch (TTK) {
16816 case TagTypeKind::Class:
16817 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16818 case TagTypeKind::Union:
16819 return NTK_NonUnion;
16820 case TagTypeKind::Enum:
16821 return NTK_NonEnum;
16822 }
16823 llvm_unreachable("invalid TTK");
16824}
16825
16827 TagTypeKind NewTag, bool isDefinition,
16828 SourceLocation NewTagLoc,
16829 const IdentifierInfo *Name) {
16830 // C++ [dcl.type.elab]p3:
16831 // The class-key or enum keyword present in the
16832 // elaborated-type-specifier shall agree in kind with the
16833 // declaration to which the name in the elaborated-type-specifier
16834 // refers. This rule also applies to the form of
16835 // elaborated-type-specifier that declares a class-name or
16836 // friend class since it can be construed as referring to the
16837 // definition of the class. Thus, in any
16838 // elaborated-type-specifier, the enum keyword shall be used to
16839 // refer to an enumeration (7.2), the union class-key shall be
16840 // used to refer to a union (clause 9), and either the class or
16841 // struct class-key shall be used to refer to a class (clause 9)
16842 // declared using the class or struct class-key.
16843 TagTypeKind OldTag = Previous->getTagKind();
16844 if (OldTag != NewTag &&
16845 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16846 return false;
16847
16848 // Tags are compatible, but we might still want to warn on mismatched tags.
16849 // Non-class tags can't be mismatched at this point.
16850 if (!isClassCompatTagKind(NewTag))
16851 return true;
16852
16853 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16854 // by our warning analysis. We don't want to warn about mismatches with (eg)
16855 // declarations in system headers that are designed to be specialized, but if
16856 // a user asks us to warn, we should warn if their code contains mismatched
16857 // declarations.
16858 auto IsIgnoredLoc = [&](SourceLocation Loc) {
16859 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16860 Loc);
16861 };
16862 if (IsIgnoredLoc(NewTagLoc))
16863 return true;
16864
16865 auto IsIgnored = [&](const TagDecl *Tag) {
16866 return IsIgnoredLoc(Tag->getLocation());
16867 };
16868 while (IsIgnored(Previous)) {
16869 Previous = Previous->getPreviousDecl();
16870 if (!Previous)
16871 return true;
16872 OldTag = Previous->getTagKind();
16873 }
16874
16875 bool isTemplate = false;
16876 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16877 isTemplate = Record->getDescribedClassTemplate();
16878
16880 if (OldTag != NewTag) {
16881 // In a template instantiation, do not offer fix-its for tag mismatches
16882 // since they usually mess up the template instead of fixing the problem.
16883 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16884 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16885 << getRedeclDiagFromTagKind(OldTag);
16886 // FIXME: Note previous location?
16887 }
16888 return true;
16889 }
16890
16891 if (isDefinition) {
16892 // On definitions, check all previous tags and issue a fix-it for each
16893 // one that doesn't match the current tag.
16894 if (Previous->getDefinition()) {
16895 // Don't suggest fix-its for redefinitions.
16896 return true;
16897 }
16898
16899 bool previousMismatch = false;
16900 for (const TagDecl *I : Previous->redecls()) {
16901 if (I->getTagKind() != NewTag) {
16902 // Ignore previous declarations for which the warning was disabled.
16903 if (IsIgnored(I))
16904 continue;
16905
16906 if (!previousMismatch) {
16907 previousMismatch = true;
16908 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16909 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16910 << getRedeclDiagFromTagKind(I->getTagKind());
16911 }
16912 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16913 << getRedeclDiagFromTagKind(NewTag)
16914 << FixItHint::CreateReplacement(I->getInnerLocStart(),
16916 }
16917 }
16918 return true;
16919 }
16920
16921 // Identify the prevailing tag kind: this is the kind of the definition (if
16922 // there is a non-ignored definition), or otherwise the kind of the prior
16923 // (non-ignored) declaration.
16924 const TagDecl *PrevDef = Previous->getDefinition();
16925 if (PrevDef && IsIgnored(PrevDef))
16926 PrevDef = nullptr;
16927 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16928 if (Redecl->getTagKind() != NewTag) {
16929 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16930 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16931 << getRedeclDiagFromTagKind(OldTag);
16932 Diag(Redecl->getLocation(), diag::note_previous_use);
16933
16934 // If there is a previous definition, suggest a fix-it.
16935 if (PrevDef) {
16936 Diag(NewTagLoc, diag::note_struct_class_suggestion)
16940 }
16941 }
16942
16943 return true;
16944}
16945
16946/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16947/// from an outer enclosing namespace or file scope inside a friend declaration.
16948/// This should provide the commented out code in the following snippet:
16949/// namespace N {
16950/// struct X;
16951/// namespace M {
16952/// struct Y { friend struct /*N::*/ X; };
16953/// }
16954/// }
16956 SourceLocation NameLoc) {
16957 // While the decl is in a namespace, do repeated lookup of that name and see
16958 // if we get the same namespace back. If we do not, continue until
16959 // translation unit scope, at which point we have a fully qualified NNS.
16962 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16963 // This tag should be declared in a namespace, which can only be enclosed by
16964 // other namespaces. Bail if there's an anonymous namespace in the chain.
16965 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16966 if (!Namespace || Namespace->isAnonymousNamespace())
16967 return FixItHint();
16968 IdentifierInfo *II = Namespace->getIdentifier();
16969 Namespaces.push_back(II);
16970 NamedDecl *Lookup = SemaRef.LookupSingleName(
16971 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16972 if (Lookup == Namespace)
16973 break;
16974 }
16975
16976 // Once we have all the namespaces, reverse them to go outermost first, and
16977 // build an NNS.
16978 SmallString<64> Insertion;
16979 llvm::raw_svector_ostream OS(Insertion);
16980 if (DC->isTranslationUnit())
16981 OS << "::";
16982 std::reverse(Namespaces.begin(), Namespaces.end());
16983 for (auto *II : Namespaces)
16984 OS << II->getName() << "::";
16985 return FixItHint::CreateInsertion(NameLoc, Insertion);
16986}
16987
16988/// Determine whether a tag originally declared in context \p OldDC can
16989/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16990/// found a declaration in \p OldDC as a previous decl, perhaps through a
16991/// using-declaration).
16993 DeclContext *NewDC) {
16994 OldDC = OldDC->getRedeclContext();
16995 NewDC = NewDC->getRedeclContext();
16996
16997 if (OldDC->Equals(NewDC))
16998 return true;
16999
17000 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17001 // encloses the other).
17002 if (S.getLangOpts().MSVCCompat &&
17003 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17004 return true;
17005
17006 return false;
17007}
17008
17010Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17011 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17012 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17013 SourceLocation ModulePrivateLoc,
17014 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17015 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17016 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17017 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17018 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17019 // If this is not a definition, it must have a name.
17020 IdentifierInfo *OrigName = Name;
17021 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17022 "Nameless record must be a definition!");
17023 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17024
17025 OwnedDecl = false;
17027 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17028
17029 // FIXME: Check member specializations more carefully.
17030 bool isMemberSpecialization = false;
17031 bool Invalid = false;
17032
17033 // We only need to do this matching if we have template parameters
17034 // or a scope specifier, which also conveniently avoids this work
17035 // for non-C++ cases.
17036 if (TemplateParameterLists.size() > 0 ||
17037 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17038 TemplateParameterList *TemplateParams =
17040 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17041 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17042
17043 // C++23 [dcl.type.elab] p2:
17044 // If an elaborated-type-specifier is the sole constituent of a
17045 // declaration, the declaration is ill-formed unless it is an explicit
17046 // specialization, an explicit instantiation or it has one of the
17047 // following forms: [...]
17048 // C++23 [dcl.enum] p1:
17049 // If the enum-head-name of an opaque-enum-declaration contains a
17050 // nested-name-specifier, the declaration shall be an explicit
17051 // specialization.
17052 //
17053 // FIXME: Class template partial specializations can be forward declared
17054 // per CWG2213, but the resolution failed to allow qualified forward
17055 // declarations. This is almost certainly unintentional, so we allow them.
17056 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17057 !isMemberSpecialization)
17058 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17060
17061 if (TemplateParams) {
17062 if (Kind == TagTypeKind::Enum) {
17063 Diag(KWLoc, diag::err_enum_template);
17064 return true;
17065 }
17066
17067 if (TemplateParams->size() > 0) {
17068 // This is a declaration or definition of a class template (which may
17069 // be a member of another template).
17070
17071 if (Invalid)
17072 return true;
17073
17074 OwnedDecl = false;
17076 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17077 AS, ModulePrivateLoc,
17078 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17079 TemplateParameterLists.data(), SkipBody);
17080 return Result.get();
17081 } else {
17082 // The "template<>" header is extraneous.
17083 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17084 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17085 isMemberSpecialization = true;
17086 }
17087 }
17088
17089 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17090 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17091 return true;
17092 }
17093
17094 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17095 // C++23 [dcl.type.elab]p4:
17096 // If an elaborated-type-specifier appears with the friend specifier as
17097 // an entire member-declaration, the member-declaration shall have one
17098 // of the following forms:
17099 // friend class-key nested-name-specifier(opt) identifier ;
17100 // friend class-key simple-template-id ;
17101 // friend class-key nested-name-specifier template(opt)
17102 // simple-template-id ;
17103 //
17104 // Since enum is not a class-key, so declarations like "friend enum E;"
17105 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17106 // invalid, most implementations accept so we issue a pedantic warning.
17107 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17108 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17109 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17110 Diag(KWLoc, diag::note_enum_friend)
17111 << (ScopedEnum + ScopedEnumUsesClassTag);
17112 }
17113
17114 // Figure out the underlying type if this a enum declaration. We need to do
17115 // this early, because it's needed to detect if this is an incompatible
17116 // redeclaration.
17117 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17118 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17119
17120 if (Kind == TagTypeKind::Enum) {
17121 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17122 // No underlying type explicitly specified, or we failed to parse the
17123 // type, default to int.
17124 EnumUnderlying = Context.IntTy.getTypePtr();
17125 } else if (UnderlyingType.get()) {
17126 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17127 // integral type; any cv-qualification is ignored.
17128 TypeSourceInfo *TI = nullptr;
17129 GetTypeFromParser(UnderlyingType.get(), &TI);
17130 EnumUnderlying = TI;
17131
17133 // Recover by falling back to int.
17134 EnumUnderlying = Context.IntTy.getTypePtr();
17135
17138 EnumUnderlying = Context.IntTy.getTypePtr();
17139
17140 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17141 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17142 // of 'int'. However, if this is an unfixed forward declaration, don't set
17143 // the underlying type unless the user enables -fms-compatibility. This
17144 // makes unfixed forward declared enums incomplete and is more conforming.
17145 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17146 EnumUnderlying = Context.IntTy.getTypePtr();
17147 }
17148 }
17149
17150 DeclContext *SearchDC = CurContext;
17151 DeclContext *DC = CurContext;
17152 bool isStdBadAlloc = false;
17153 bool isStdAlignValT = false;
17154
17156 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17157 Redecl = RedeclarationKind::NotForRedeclaration;
17158
17159 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17160 /// implemented asks for structural equivalence checking, the returned decl
17161 /// here is passed back to the parser, allowing the tag body to be parsed.
17162 auto createTagFromNewDecl = [&]() -> TagDecl * {
17163 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17164 // If there is an identifier, use the location of the identifier as the
17165 // location of the decl, otherwise use the location of the struct/union
17166 // keyword.
17167 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17168 TagDecl *New = nullptr;
17169
17170 if (Kind == TagTypeKind::Enum) {
17171 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17172 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17173 // If this is an undefined enum, bail.
17174 if (TUK != TagUseKind::Definition && !Invalid)
17175 return nullptr;
17176 if (EnumUnderlying) {
17177 EnumDecl *ED = cast<EnumDecl>(New);
17178 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17180 else
17181 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17182 QualType EnumTy = ED->getIntegerType();
17185 : EnumTy);
17186 }
17187 } else { // struct/union
17188 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17189 nullptr);
17190 }
17191
17192 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17193 // Add alignment attributes if necessary; these attributes are checked
17194 // when the ASTContext lays out the structure.
17195 //
17196 // It is important for implementing the correct semantics that this
17197 // happen here (in ActOnTag). The #pragma pack stack is
17198 // maintained as a result of parser callbacks which can occur at
17199 // many points during the parsing of a struct declaration (because
17200 // the #pragma tokens are effectively skipped over during the
17201 // parsing of the struct).
17202 if (TUK == TagUseKind::Definition &&
17203 (!SkipBody || !SkipBody->ShouldSkip)) {
17206 }
17207 }
17209 return New;
17210 };
17211
17212 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17213 if (Name && SS.isNotEmpty()) {
17214 // We have a nested-name tag ('struct foo::bar').
17215
17216 // Check for invalid 'foo::'.
17217 if (SS.isInvalid()) {
17218 Name = nullptr;
17219 goto CreateNewDecl;
17220 }
17221
17222 // If this is a friend or a reference to a class in a dependent
17223 // context, don't try to make a decl for it.
17224 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17225 DC = computeDeclContext(SS, false);
17226 if (!DC) {
17227 IsDependent = true;
17228 return true;
17229 }
17230 } else {
17231 DC = computeDeclContext(SS, true);
17232 if (!DC) {
17233 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17234 << SS.getRange();
17235 return true;
17236 }
17237 }
17238
17239 if (RequireCompleteDeclContext(SS, DC))
17240 return true;
17241
17242 SearchDC = DC;
17243 // Look-up name inside 'foo::'.
17245
17246 if (Previous.isAmbiguous())
17247 return true;
17248
17249 if (Previous.empty()) {
17250 // Name lookup did not find anything. However, if the
17251 // nested-name-specifier refers to the current instantiation,
17252 // and that current instantiation has any dependent base
17253 // classes, we might find something at instantiation time: treat
17254 // this as a dependent elaborated-type-specifier.
17255 // But this only makes any sense for reference-like lookups.
17256 if (Previous.wasNotFoundInCurrentInstantiation() &&
17257 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17258 IsDependent = true;
17259 return true;
17260 }
17261
17262 // A tag 'foo::bar' must already exist.
17263 Diag(NameLoc, diag::err_not_tag_in_scope)
17264 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17265 Name = nullptr;
17266 Invalid = true;
17267 goto CreateNewDecl;
17268 }
17269 } else if (Name) {
17270 // C++14 [class.mem]p14:
17271 // If T is the name of a class, then each of the following shall have a
17272 // name different from T:
17273 // -- every member of class T that is itself a type
17274 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17275 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17276 return true;
17277
17278 // If this is a named struct, check to see if there was a previous forward
17279 // declaration or definition.
17280 // FIXME: We're looking into outer scopes here, even when we
17281 // shouldn't be. Doing so can result in ambiguities that we
17282 // shouldn't be diagnosing.
17283 LookupName(Previous, S);
17284
17285 // When declaring or defining a tag, ignore ambiguities introduced
17286 // by types using'ed into this scope.
17287 if (Previous.isAmbiguous() &&
17289 LookupResult::Filter F = Previous.makeFilter();
17290 while (F.hasNext()) {
17291 NamedDecl *ND = F.next();
17292 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17293 SearchDC->getRedeclContext()))
17294 F.erase();
17295 }
17296 F.done();
17297 }
17298
17299 // C++11 [namespace.memdef]p3:
17300 // If the name in a friend declaration is neither qualified nor
17301 // a template-id and the declaration is a function or an
17302 // elaborated-type-specifier, the lookup to determine whether
17303 // the entity has been previously declared shall not consider
17304 // any scopes outside the innermost enclosing namespace.
17305 //
17306 // MSVC doesn't implement the above rule for types, so a friend tag
17307 // declaration may be a redeclaration of a type declared in an enclosing
17308 // scope. They do implement this rule for friend functions.
17309 //
17310 // Does it matter that this should be by scope instead of by
17311 // semantic context?
17312 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17313 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17314 LookupResult::Filter F = Previous.makeFilter();
17315 bool FriendSawTagOutsideEnclosingNamespace = false;
17316 while (F.hasNext()) {
17317 NamedDecl *ND = F.next();
17319 if (DC->isFileContext() &&
17320 !EnclosingNS->Encloses(ND->getDeclContext())) {
17321 if (getLangOpts().MSVCCompat)
17322 FriendSawTagOutsideEnclosingNamespace = true;
17323 else
17324 F.erase();
17325 }
17326 }
17327 F.done();
17328
17329 // Diagnose this MSVC extension in the easy case where lookup would have
17330 // unambiguously found something outside the enclosing namespace.
17331 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17332 NamedDecl *ND = Previous.getFoundDecl();
17333 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17334 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17335 }
17336 }
17337
17338 // Note: there used to be some attempt at recovery here.
17339 if (Previous.isAmbiguous())
17340 return true;
17341
17342 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17343 // FIXME: This makes sure that we ignore the contexts associated
17344 // with C structs, unions, and enums when looking for a matching
17345 // tag declaration or definition. See the similar lookup tweak
17346 // in Sema::LookupName; is there a better way to deal with this?
17347 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17348 SearchDC = SearchDC->getParent();
17349 } else if (getLangOpts().CPlusPlus) {
17350 // Inside ObjCContainer want to keep it as a lexical decl context but go
17351 // past it (most often to TranslationUnit) to find the semantic decl
17352 // context.
17353 while (isa<ObjCContainerDecl>(SearchDC))
17354 SearchDC = SearchDC->getParent();
17355 }
17356 } else if (getLangOpts().CPlusPlus) {
17357 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17358 // TagDecl the same way as we skip it for named TagDecl.
17359 while (isa<ObjCContainerDecl>(SearchDC))
17360 SearchDC = SearchDC->getParent();
17361 }
17362
17363 if (Previous.isSingleResult() &&
17364 Previous.getFoundDecl()->isTemplateParameter()) {
17365 // Maybe we will complain about the shadowed template parameter.
17366 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17367 // Just pretend that we didn't see the previous declaration.
17368 Previous.clear();
17369 }
17370
17371 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17372 DC->Equals(getStdNamespace())) {
17373 if (Name->isStr("bad_alloc")) {
17374 // This is a declaration of or a reference to "std::bad_alloc".
17375 isStdBadAlloc = true;
17376
17377 // If std::bad_alloc has been implicitly declared (but made invisible to
17378 // name lookup), fill in this implicit declaration as the previous
17379 // declaration, so that the declarations get chained appropriately.
17380 if (Previous.empty() && StdBadAlloc)
17381 Previous.addDecl(getStdBadAlloc());
17382 } else if (Name->isStr("align_val_t")) {
17383 isStdAlignValT = true;
17384 if (Previous.empty() && StdAlignValT)
17385 Previous.addDecl(getStdAlignValT());
17386 }
17387 }
17388
17389 // If we didn't find a previous declaration, and this is a reference
17390 // (or friend reference), move to the correct scope. In C++, we
17391 // also need to do a redeclaration lookup there, just in case
17392 // there's a shadow friend decl.
17393 if (Name && Previous.empty() &&
17394 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17395 IsTemplateParamOrArg)) {
17396 if (Invalid) goto CreateNewDecl;
17397 assert(SS.isEmpty());
17398
17399 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17400 // C++ [basic.scope.pdecl]p5:
17401 // -- for an elaborated-type-specifier of the form
17402 //
17403 // class-key identifier
17404 //
17405 // if the elaborated-type-specifier is used in the
17406 // decl-specifier-seq or parameter-declaration-clause of a
17407 // function defined in namespace scope, the identifier is
17408 // declared as a class-name in the namespace that contains
17409 // the declaration; otherwise, except as a friend
17410 // declaration, the identifier is declared in the smallest
17411 // non-class, non-function-prototype scope that contains the
17412 // declaration.
17413 //
17414 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17415 // C structs and unions.
17416 //
17417 // It is an error in C++ to declare (rather than define) an enum
17418 // type, including via an elaborated type specifier. We'll
17419 // diagnose that later; for now, declare the enum in the same
17420 // scope as we would have picked for any other tag type.
17421 //
17422 // GNU C also supports this behavior as part of its incomplete
17423 // enum types extension, while GNU C++ does not.
17424 //
17425 // Find the context where we'll be declaring the tag.
17426 // FIXME: We would like to maintain the current DeclContext as the
17427 // lexical context,
17428 SearchDC = getTagInjectionContext(SearchDC);
17429
17430 // Find the scope where we'll be declaring the tag.
17432 } else {
17433 assert(TUK == TagUseKind::Friend);
17434 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17435
17436 // C++ [namespace.memdef]p3:
17437 // If a friend declaration in a non-local class first declares a
17438 // class or function, the friend class or function is a member of
17439 // the innermost enclosing namespace.
17440 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17441 : SearchDC->getEnclosingNamespaceContext();
17442 }
17443
17444 // In C++, we need to do a redeclaration lookup to properly
17445 // diagnose some problems.
17446 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17447 // hidden declaration so that we don't get ambiguity errors when using a
17448 // type declared by an elaborated-type-specifier. In C that is not correct
17449 // and we should instead merge compatible types found by lookup.
17450 if (getLangOpts().CPlusPlus) {
17451 // FIXME: This can perform qualified lookups into function contexts,
17452 // which are meaningless.
17453 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17454 LookupQualifiedName(Previous, SearchDC);
17455 } else {
17456 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17457 LookupName(Previous, S);
17458 }
17459 }
17460
17461 // If we have a known previous declaration to use, then use it.
17462 if (Previous.empty() && SkipBody && SkipBody->Previous)
17463 Previous.addDecl(SkipBody->Previous);
17464
17465 if (!Previous.empty()) {
17466 NamedDecl *PrevDecl = Previous.getFoundDecl();
17467 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17468
17469 // It's okay to have a tag decl in the same scope as a typedef
17470 // which hides a tag decl in the same scope. Finding this
17471 // with a redeclaration lookup can only actually happen in C++.
17472 //
17473 // This is also okay for elaborated-type-specifiers, which is
17474 // technically forbidden by the current standard but which is
17475 // okay according to the likely resolution of an open issue;
17476 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17477 if (getLangOpts().CPlusPlus) {
17478 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17479 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17480 TagDecl *Tag = TT->getDecl();
17481 if (Tag->getDeclName() == Name &&
17482 Tag->getDeclContext()->getRedeclContext()
17483 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17484 PrevDecl = Tag;
17485 Previous.clear();
17486 Previous.addDecl(Tag);
17487 Previous.resolveKind();
17488 }
17489 }
17490 }
17491 }
17492
17493 // If this is a redeclaration of a using shadow declaration, it must
17494 // declare a tag in the same context. In MSVC mode, we allow a
17495 // redefinition if either context is within the other.
17496 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17497 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17498 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
17499 TUK != TagUseKind::Friend &&
17500 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17501 !(OldTag && isAcceptableTagRedeclContext(
17502 *this, OldTag->getDeclContext(), SearchDC))) {
17503 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17504 Diag(Shadow->getTargetDecl()->getLocation(),
17505 diag::note_using_decl_target);
17506 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17507 << 0;
17508 // Recover by ignoring the old declaration.
17509 Previous.clear();
17510 goto CreateNewDecl;
17511 }
17512 }
17513
17514 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17515 // If this is a use of a previous tag, or if the tag is already declared
17516 // in the same scope (so that the definition/declaration completes or
17517 // rementions the tag), reuse the decl.
17518 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17519 isDeclInScope(DirectPrevDecl, SearchDC, S,
17520 SS.isNotEmpty() || isMemberSpecialization)) {
17521 // Make sure that this wasn't declared as an enum and now used as a
17522 // struct or something similar.
17523 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17524 TUK == TagUseKind::Definition, KWLoc,
17525 Name)) {
17526 bool SafeToContinue =
17527 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17528 Kind != TagTypeKind::Enum);
17529 if (SafeToContinue)
17530 Diag(KWLoc, diag::err_use_with_wrong_tag)
17531 << Name
17533 PrevTagDecl->getKindName());
17534 else
17535 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17536 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17537
17538 if (SafeToContinue)
17539 Kind = PrevTagDecl->getTagKind();
17540 else {
17541 // Recover by making this an anonymous redefinition.
17542 Name = nullptr;
17543 Previous.clear();
17544 Invalid = true;
17545 }
17546 }
17547
17548 if (Kind == TagTypeKind::Enum &&
17549 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17550 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17551 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
17552 return PrevTagDecl;
17553
17554 QualType EnumUnderlyingTy;
17555 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17556 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17557 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17558 EnumUnderlyingTy = QualType(T, 0);
17559
17560 // All conflicts with previous declarations are recovered by
17561 // returning the previous declaration, unless this is a definition,
17562 // in which case we want the caller to bail out.
17563 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17564 ScopedEnum, EnumUnderlyingTy,
17565 IsFixed, PrevEnum))
17566 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
17567 }
17568
17569 // C++11 [class.mem]p1:
17570 // A member shall not be declared twice in the member-specification,
17571 // except that a nested class or member class template can be declared
17572 // and then later defined.
17573 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
17574 S->isDeclScope(PrevDecl)) {
17575 Diag(NameLoc, diag::ext_member_redeclared);
17576 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17577 }
17578
17579 if (!Invalid) {
17580 // If this is a use, just return the declaration we found, unless
17581 // we have attributes.
17582 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17583 if (!Attrs.empty()) {
17584 // FIXME: Diagnose these attributes. For now, we create a new
17585 // declaration to hold them.
17586 } else if (TUK == TagUseKind::Reference &&
17587 (PrevTagDecl->getFriendObjectKind() ==
17589 PrevDecl->getOwningModule() != getCurrentModule()) &&
17590 SS.isEmpty()) {
17591 // This declaration is a reference to an existing entity, but
17592 // has different visibility from that entity: it either makes
17593 // a friend visible or it makes a type visible in a new module.
17594 // In either case, create a new declaration. We only do this if
17595 // the declaration would have meant the same thing if no prior
17596 // declaration were found, that is, if it was found in the same
17597 // scope where we would have injected a declaration.
17598 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17599 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17600 return PrevTagDecl;
17601 // This is in the injected scope, create a new declaration in
17602 // that scope.
17604 } else {
17605 return PrevTagDecl;
17606 }
17607 }
17608
17609 // Diagnose attempts to redefine a tag.
17610 if (TUK == TagUseKind::Definition) {
17611 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17612 // If we're defining a specialization and the previous definition
17613 // is from an implicit instantiation, don't emit an error
17614 // here; we'll catch this in the general case below.
17615 bool IsExplicitSpecializationAfterInstantiation = false;
17616 if (isMemberSpecialization) {
17617 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17618 IsExplicitSpecializationAfterInstantiation =
17619 RD->getTemplateSpecializationKind() !=
17621 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17622 IsExplicitSpecializationAfterInstantiation =
17623 ED->getTemplateSpecializationKind() !=
17625 }
17626
17627 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17628 // not keep more that one definition around (merge them). However,
17629 // ensure the decl passes the structural compatibility check in
17630 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17631 NamedDecl *Hidden = nullptr;
17632 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17633 // There is a definition of this tag, but it is not visible. We
17634 // explicitly make use of C++'s one definition rule here, and
17635 // assume that this definition is identical to the hidden one
17636 // we already have. Make the existing definition visible and
17637 // use it in place of this one.
17638 if (!getLangOpts().CPlusPlus) {
17639 // Postpone making the old definition visible until after we
17640 // complete parsing the new one and do the structural
17641 // comparison.
17642 SkipBody->CheckSameAsPrevious = true;
17643 SkipBody->New = createTagFromNewDecl();
17644 SkipBody->Previous = Def;
17645 return Def;
17646 } else {
17647 SkipBody->ShouldSkip = true;
17648 SkipBody->Previous = Def;
17650 // Carry on and handle it like a normal definition. We'll
17651 // skip starting the definition later.
17652 }
17653 } else if (!IsExplicitSpecializationAfterInstantiation) {
17654 // A redeclaration in function prototype scope in C isn't
17655 // visible elsewhere, so merely issue a warning.
17656 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17657 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17658 else
17659 Diag(NameLoc, diag::err_redefinition) << Name;
17661 NameLoc.isValid() ? NameLoc : KWLoc);
17662 // If this is a redefinition, recover by making this
17663 // struct be anonymous, which will make any later
17664 // references get the previous definition.
17665 Name = nullptr;
17666 Previous.clear();
17667 Invalid = true;
17668 }
17669 } else {
17670 // If the type is currently being defined, complain
17671 // about a nested redefinition.
17672 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17673 if (TD->isBeingDefined()) {
17674 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17675 Diag(PrevTagDecl->getLocation(),
17676 diag::note_previous_definition);
17677 Name = nullptr;
17678 Previous.clear();
17679 Invalid = true;
17680 }
17681 }
17682
17683 // Okay, this is definition of a previously declared or referenced
17684 // tag. We're going to create a new Decl for it.
17685 }
17686
17687 // Okay, we're going to make a redeclaration. If this is some kind
17688 // of reference, make sure we build the redeclaration in the same DC
17689 // as the original, and ignore the current access specifier.
17690 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17691 SearchDC = PrevTagDecl->getDeclContext();
17692 AS = AS_none;
17693 }
17694 }
17695 // If we get here we have (another) forward declaration or we
17696 // have a definition. Just create a new decl.
17697
17698 } else {
17699 // If we get here, this is a definition of a new tag type in a nested
17700 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17701 // new decl/type. We set PrevDecl to NULL so that the entities
17702 // have distinct types.
17703 Previous.clear();
17704 }
17705 // If we get here, we're going to create a new Decl. If PrevDecl
17706 // is non-NULL, it's a definition of the tag declared by
17707 // PrevDecl. If it's NULL, we have a new definition.
17708
17709 // Otherwise, PrevDecl is not a tag, but was found with tag
17710 // lookup. This is only actually possible in C++, where a few
17711 // things like templates still live in the tag namespace.
17712 } else {
17713 // Use a better diagnostic if an elaborated-type-specifier
17714 // found the wrong kind of type on the first
17715 // (non-redeclaration) lookup.
17716 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
17717 !Previous.isForRedeclaration()) {
17718 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17719 Diag(NameLoc, diag::err_tag_reference_non_tag)
17720 << PrevDecl << NTK << llvm::to_underlying(Kind);
17721 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17722 Invalid = true;
17723
17724 // Otherwise, only diagnose if the declaration is in scope.
17725 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17726 SS.isNotEmpty() || isMemberSpecialization)) {
17727 // do nothing
17728
17729 // Diagnose implicit declarations introduced by elaborated types.
17730 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17731 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17732 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17733 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17734 Invalid = true;
17735
17736 // Otherwise it's a declaration. Call out a particularly common
17737 // case here.
17738 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17739 unsigned Kind = 0;
17740 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17741 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17742 << Name << Kind << TND->getUnderlyingType();
17743 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17744 Invalid = true;
17745
17746 // Otherwise, diagnose.
17747 } else {
17748 // The tag name clashes with something else in the target scope,
17749 // issue an error and recover by making this tag be anonymous.
17750 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17751 notePreviousDefinition(PrevDecl, NameLoc);
17752 Name = nullptr;
17753 Invalid = true;
17754 }
17755
17756 // The existing declaration isn't relevant to us; we're in a
17757 // new scope, so clear out the previous declaration.
17758 Previous.clear();
17759 }
17760 }
17761
17762CreateNewDecl:
17763
17764 TagDecl *PrevDecl = nullptr;
17765 if (Previous.isSingleResult())
17766 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17767
17768 // If there is an identifier, use the location of the identifier as the
17769 // location of the decl, otherwise use the location of the struct/union
17770 // keyword.
17771 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17772
17773 // Otherwise, create a new declaration. If there is a previous
17774 // declaration of the same entity, the two will be linked via
17775 // PrevDecl.
17776 TagDecl *New;
17777
17778 if (Kind == TagTypeKind::Enum) {
17779 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17780 // enum X { A, B, C } D; D should chain to X.
17781 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17782 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17783 ScopedEnumUsesClassTag, IsFixed);
17784
17785 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17786 StdAlignValT = cast<EnumDecl>(New);
17787
17788 // If this is an undefined enum, warn.
17789 if (TUK != TagUseKind::Definition && !Invalid) {
17790 TagDecl *Def;
17791 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17792 // C++0x: 7.2p2: opaque-enum-declaration.
17793 // Conflicts are diagnosed above. Do nothing.
17794 }
17795 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17796 Diag(Loc, diag::ext_forward_ref_enum_def)
17797 << New;
17798 Diag(Def->getLocation(), diag::note_previous_definition);
17799 } else {
17800 unsigned DiagID = diag::ext_forward_ref_enum;
17801 if (getLangOpts().MSVCCompat)
17802 DiagID = diag::ext_ms_forward_ref_enum;
17803 else if (getLangOpts().CPlusPlus)
17804 DiagID = diag::err_forward_ref_enum;
17805 Diag(Loc, DiagID);
17806 }
17807 }
17808
17809 if (EnumUnderlying) {
17810 EnumDecl *ED = cast<EnumDecl>(New);
17811 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17813 else
17814 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17815 QualType EnumTy = ED->getIntegerType();
17818 : EnumTy);
17819 assert(ED->isComplete() && "enum with type should be complete");
17820 }
17821 } else {
17822 // struct/union/class
17823
17824 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17825 // struct X { int A; } D; D should chain to X.
17826 if (getLangOpts().CPlusPlus) {
17827 // FIXME: Look for a way to use RecordDecl for simple structs.
17828 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17829 cast_or_null<CXXRecordDecl>(PrevDecl));
17830
17831 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17832 StdBadAlloc = cast<CXXRecordDecl>(New);
17833 } else
17834 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17835 cast_or_null<RecordDecl>(PrevDecl));
17836 }
17837
17838 // Only C23 and later allow defining new types in 'offsetof()'.
17839 if (OOK != OOK_Outside && TUK == TagUseKind::Definition &&
17841 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17842 << (OOK == OOK_Macro) << New->getSourceRange();
17843
17844 // C++11 [dcl.type]p3:
17845 // A type-specifier-seq shall not define a class or enumeration [...].
17846 if (!Invalid && getLangOpts().CPlusPlus &&
17847 (IsTypeSpecifier || IsTemplateParamOrArg) &&
17848 TUK == TagUseKind::Definition) {
17849 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17850 << Context.getTagDeclType(New);
17851 Invalid = true;
17852 }
17853
17855 DC->getDeclKind() == Decl::Enum) {
17856 Diag(New->getLocation(), diag::err_type_defined_in_enum)
17857 << Context.getTagDeclType(New);
17858 Invalid = true;
17859 }
17860
17861 // Maybe add qualifier info.
17862 if (SS.isNotEmpty()) {
17863 if (SS.isSet()) {
17864 // If this is either a declaration or a definition, check the
17865 // nested-name-specifier against the current context.
17866 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
17867 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17868 /*TemplateId=*/nullptr,
17869 isMemberSpecialization))
17870 Invalid = true;
17871
17873 if (TemplateParameterLists.size() > 0) {
17874 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17875 }
17876 }
17877 else
17878 Invalid = true;
17879 }
17880
17881 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17882 // Add alignment attributes if necessary; these attributes are checked when
17883 // the ASTContext lays out the structure.
17884 //
17885 // It is important for implementing the correct semantics that this
17886 // happen here (in ActOnTag). The #pragma pack stack is
17887 // maintained as a result of parser callbacks which can occur at
17888 // many points during the parsing of a struct declaration (because
17889 // the #pragma tokens are effectively skipped over during the
17890 // parsing of the struct).
17891 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17894 }
17895 }
17896
17897 if (ModulePrivateLoc.isValid()) {
17898 if (isMemberSpecialization)
17899 Diag(New->getLocation(), diag::err_module_private_specialization)
17900 << 2
17901 << FixItHint::CreateRemoval(ModulePrivateLoc);
17902 // __module_private__ does not apply to local classes. However, we only
17903 // diagnose this as an error when the declaration specifiers are
17904 // freestanding. Here, we just ignore the __module_private__.
17905 else if (!SearchDC->isFunctionOrMethod())
17906 New->setModulePrivate();
17907 }
17908
17909 // If this is a specialization of a member class (of a class template),
17910 // check the specialization.
17911 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17912 Invalid = true;
17913
17914 // If we're declaring or defining a tag in function prototype scope in C,
17915 // note that this type can only be used within the function and add it to
17916 // the list of decls to inject into the function definition scope.
17917 if ((Name || Kind == TagTypeKind::Enum) &&
17918 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17919 if (getLangOpts().CPlusPlus) {
17920 // C++ [dcl.fct]p6:
17921 // Types shall not be defined in return or parameter types.
17922 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
17923 Diag(Loc, diag::err_type_defined_in_param_type)
17924 << Name;
17925 Invalid = true;
17926 }
17927 } else if (!PrevDecl) {
17928 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17929 }
17930 }
17931
17932 if (Invalid)
17933 New->setInvalidDecl();
17934
17935 // Set the lexical context. If the tag has a C++ scope specifier, the
17936 // lexical context will be different from the semantic context.
17938
17939 // Mark this as a friend decl if applicable.
17940 // In Microsoft mode, a friend declaration also acts as a forward
17941 // declaration so we always pass true to setObjectOfFriendDecl to make
17942 // the tag name visible.
17943 if (TUK == TagUseKind::Friend)
17944 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17945
17946 // Set the access specifier.
17947 if (!Invalid && SearchDC->isRecord())
17948 SetMemberAccessSpecifier(New, PrevDecl, AS);
17949
17950 if (PrevDecl)
17951 CheckRedeclarationInModule(New, PrevDecl);
17952
17953 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
17954 New->startDefinition();
17955
17956 ProcessDeclAttributeList(S, New, Attrs);
17957 AddPragmaAttributes(S, New);
17958
17959 // If this has an identifier, add it to the scope stack.
17960 if (TUK == TagUseKind::Friend) {
17961 // We might be replacing an existing declaration in the lookup tables;
17962 // if so, borrow its access specifier.
17963 if (PrevDecl)
17964 New->setAccess(PrevDecl->getAccess());
17965
17967 DC->makeDeclVisibleInContext(New);
17968 if (Name) // can be null along some error paths
17969 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17970 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17971 } else if (Name) {
17972 S = getNonFieldDeclScope(S);
17973 PushOnScopeChains(New, S, true);
17974 } else {
17975 CurContext->addDecl(New);
17976 }
17977
17978 // If this is the C FILE type, notify the AST context.
17979 if (IdentifierInfo *II = New->getIdentifier())
17980 if (!New->isInvalidDecl() &&
17982 II->isStr("FILE"))
17983 Context.setFILEDecl(New);
17984
17985 if (PrevDecl)
17986 mergeDeclAttributes(New, PrevDecl);
17987
17988 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
17991 }
17992
17993 // If there's a #pragma GCC visibility in scope, set the visibility of this
17994 // record.
17996
17997 if (isMemberSpecialization && !New->isInvalidDecl())
17999
18000 OwnedDecl = true;
18001 // In C++, don't return an invalid declaration. We can't recover well from
18002 // the cases where we make the type anonymous.
18003 if (Invalid && getLangOpts().CPlusPlus) {
18004 if (New->isBeingDefined())
18005 if (auto RD = dyn_cast<RecordDecl>(New))
18006 RD->completeDefinition();
18007 return true;
18008 } else if (SkipBody && SkipBody->ShouldSkip) {
18009 return SkipBody->Previous;
18010 } else {
18011 return New;
18012 }
18013}
18014
18017 TagDecl *Tag = cast<TagDecl>(TagD);
18018
18019 // Enter the tag context.
18020 PushDeclContext(S, Tag);
18021
18023
18024 // If there's a #pragma GCC visibility in scope, set the visibility of this
18025 // record.
18027}
18028
18030 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18031 return false;
18032
18033 // Make the previous decl visible.
18035 return true;
18036}
18037
18039 SourceLocation FinalLoc,
18040 bool IsFinalSpelledSealed,
18041 bool IsAbstract,
18042 SourceLocation LBraceLoc) {
18044 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18045
18046 FieldCollector->StartClass();
18047
18048 if (!Record->getIdentifier())
18049 return;
18050
18051 if (IsAbstract)
18052 Record->markAbstract();
18053
18054 if (FinalLoc.isValid()) {
18055 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18056 IsFinalSpelledSealed
18057 ? FinalAttr::Keyword_sealed
18058 : FinalAttr::Keyword_final));
18059 }
18060 // C++ [class]p2:
18061 // [...] The class-name is also inserted into the scope of the
18062 // class itself; this is known as the injected-class-name. For
18063 // purposes of access checking, the injected-class-name is treated
18064 // as if it were a public member name.
18065 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18066 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18067 Record->getLocation(), Record->getIdentifier(),
18068 /*PrevDecl=*/nullptr,
18069 /*DelayTypeCreation=*/true);
18070 Context.getTypeDeclType(InjectedClassName, Record);
18071 InjectedClassName->setImplicit();
18072 InjectedClassName->setAccess(AS_public);
18073 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18074 InjectedClassName->setDescribedClassTemplate(Template);
18075 PushOnScopeChains(InjectedClassName, S);
18076 assert(InjectedClassName->isInjectedClassName() &&
18077 "Broken injected-class-name");
18078}
18079
18081 SourceRange BraceRange) {
18083 TagDecl *Tag = cast<TagDecl>(TagD);
18084 Tag->setBraceRange(BraceRange);
18085
18086 // Make sure we "complete" the definition even it is invalid.
18087 if (Tag->isBeingDefined()) {
18088 assert(Tag->isInvalidDecl() && "We should already have completed it");
18089 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18090 RD->completeDefinition();
18091 }
18092
18093 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18094 FieldCollector->FinishClass();
18095 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18096 auto *Def = RD->getDefinition();
18097 assert(Def && "The record is expected to have a completed definition");
18098 unsigned NumInitMethods = 0;
18099 for (auto *Method : Def->methods()) {
18100 if (!Method->getIdentifier())
18101 continue;
18102 if (Method->getName() == "__init")
18103 NumInitMethods++;
18104 }
18105 if (NumInitMethods > 1 || !Def->hasInitMethod())
18106 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18107 }
18108
18109 // If we're defining a dynamic class in a module interface unit, we always
18110 // need to produce the vtable for it, even if the vtable is not used in the
18111 // current TU.
18112 //
18113 // The case where the current class is not dynamic is handled in
18114 // MarkVTableUsed.
18115 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18116 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18117 }
18118
18119 // Exit this scope of this tag's definition.
18121
18122 if (getCurLexicalContext()->isObjCContainer() &&
18123 Tag->getDeclContext()->isFileContext())
18124 Tag->setTopLevelDeclInObjCContainer();
18125
18126 // Notify the consumer that we've defined a tag.
18127 if (!Tag->isInvalidDecl())
18129
18130 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18131 // from XLs and instead matches the XL #pragma pack(1) behavior.
18132 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18133 AlignPackStack.hasValue()) {
18134 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18135 // Only diagnose #pragma align(packed).
18136 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18137 return;
18138 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18139 if (!RD)
18140 return;
18141 // Only warn if there is at least 1 bitfield member.
18142 if (llvm::any_of(RD->fields(),
18143 [](const FieldDecl *FD) { return FD->isBitField(); }))
18144 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18145 }
18146}
18147
18150 TagDecl *Tag = cast<TagDecl>(TagD);
18151 Tag->setInvalidDecl();
18152
18153 // Make sure we "complete" the definition even it is invalid.
18154 if (Tag->isBeingDefined()) {
18155 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18156 RD->completeDefinition();
18157 }
18158
18159 // We're undoing ActOnTagStartDefinition here, not
18160 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18161 // the FieldCollector.
18162
18164}
18165
18166// Note that FieldName may be null for anonymous bitfields.
18168 const IdentifierInfo *FieldName,
18169 QualType FieldTy, bool IsMsStruct,
18170 Expr *BitWidth) {
18171 assert(BitWidth);
18172 if (BitWidth->containsErrors())
18173 return ExprError();
18174
18175 // C99 6.7.2.1p4 - verify the field type.
18176 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18177 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18178 // Handle incomplete and sizeless types with a specific error.
18179 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18180 diag::err_field_incomplete_or_sizeless))
18181 return ExprError();
18182 if (FieldName)
18183 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18184 << FieldName << FieldTy << BitWidth->getSourceRange();
18185 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18186 << FieldTy << BitWidth->getSourceRange();
18187 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18189 return ExprError();
18190
18191 // If the bit-width is type- or value-dependent, don't try to check
18192 // it now.
18193 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18194 return BitWidth;
18195
18196 llvm::APSInt Value;
18198 if (ICE.isInvalid())
18199 return ICE;
18200 BitWidth = ICE.get();
18201
18202 // Zero-width bitfield is ok for anonymous field.
18203 if (Value == 0 && FieldName)
18204 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18205 << FieldName << BitWidth->getSourceRange();
18206
18207 if (Value.isSigned() && Value.isNegative()) {
18208 if (FieldName)
18209 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18210 << FieldName << toString(Value, 10);
18211 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18212 << toString(Value, 10);
18213 }
18214
18215 // The size of the bit-field must not exceed our maximum permitted object
18216 // size.
18217 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18218 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18219 << !FieldName << FieldName << toString(Value, 10);
18220 }
18221
18222 if (!FieldTy->isDependentType()) {
18223 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18224 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18225 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18226
18227 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18228 // ABI.
18229 bool CStdConstraintViolation =
18230 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18231 bool MSBitfieldViolation =
18232 Value.ugt(TypeStorageSize) &&
18233 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18234 if (CStdConstraintViolation || MSBitfieldViolation) {
18235 unsigned DiagWidth =
18236 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18237 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18238 << (bool)FieldName << FieldName << toString(Value, 10)
18239 << !CStdConstraintViolation << DiagWidth;
18240 }
18241
18242 // Warn on types where the user might conceivably expect to get all
18243 // specified bits as value bits: that's all integral types other than
18244 // 'bool'.
18245 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18246 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18247 << FieldName << toString(Value, 10)
18248 << (unsigned)TypeWidth;
18249 }
18250 }
18251
18252 return BitWidth;
18253}
18254
18256 Declarator &D, Expr *BitfieldWidth) {
18257 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18258 D, BitfieldWidth,
18259 /*InitStyle=*/ICIS_NoInit, AS_public);
18260 return Res;
18261}
18262
18264 SourceLocation DeclStart,
18265 Declarator &D, Expr *BitWidth,
18266 InClassInitStyle InitStyle,
18267 AccessSpecifier AS) {
18268 if (D.isDecompositionDeclarator()) {
18269 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18270 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18271 << Decomp.getSourceRange();
18272 return nullptr;
18273 }
18274
18275 const IdentifierInfo *II = D.getIdentifier();
18276 SourceLocation Loc = DeclStart;
18277 if (II) Loc = D.getIdentifierLoc();
18278
18280 QualType T = TInfo->getType();
18281 if (getLangOpts().CPlusPlus) {
18283
18284 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18286 D.setInvalidType();
18287 T = Context.IntTy;
18289 }
18290 }
18291
18292 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18293
18294 if (D.getDeclSpec().isInlineSpecified())
18295 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18296 << getLangOpts().CPlusPlus17;
18297 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18298 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18299 diag::err_invalid_thread)
18301
18302 // Check to see if this name was declared as a member previously
18303 NamedDecl *PrevDecl = nullptr;
18305 RedeclarationKind::ForVisibleRedeclaration);
18306 LookupName(Previous, S);
18307 switch (Previous.getResultKind()) {
18310 PrevDecl = Previous.getAsSingle<NamedDecl>();
18311 break;
18312
18314 PrevDecl = Previous.getRepresentativeDecl();
18315 break;
18316
18320 break;
18321 }
18322 Previous.suppressDiagnostics();
18323
18324 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18325 // Maybe we will complain about the shadowed template parameter.
18326 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18327 // Just pretend that we didn't see the previous declaration.
18328 PrevDecl = nullptr;
18329 }
18330
18331 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18332 PrevDecl = nullptr;
18333
18334 bool Mutable
18335 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18336 SourceLocation TSSL = D.getBeginLoc();
18337 FieldDecl *NewFD
18338 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18339 TSSL, AS, PrevDecl, &D);
18340
18341 if (NewFD->isInvalidDecl())
18342 Record->setInvalidDecl();
18343
18344 if (D.getDeclSpec().isModulePrivateSpecified())
18345 NewFD->setModulePrivate();
18346
18347 if (NewFD->isInvalidDecl() && PrevDecl) {
18348 // Don't introduce NewFD into scope; there's already something
18349 // with the same name in the same scope.
18350 } else if (II) {
18351 PushOnScopeChains(NewFD, S);
18352 } else
18353 Record->addDecl(NewFD);
18354
18355 return NewFD;
18356}
18357
18359 TypeSourceInfo *TInfo,
18361 bool Mutable, Expr *BitWidth,
18362 InClassInitStyle InitStyle,
18363 SourceLocation TSSL,
18364 AccessSpecifier AS, NamedDecl *PrevDecl,
18365 Declarator *D) {
18366 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18367 bool InvalidDecl = false;
18368 if (D) InvalidDecl = D->isInvalidType();
18369
18370 // If we receive a broken type, recover by assuming 'int' and
18371 // marking this declaration as invalid.
18372 if (T.isNull() || T->containsErrors()) {
18373 InvalidDecl = true;
18374 T = Context.IntTy;
18375 }
18376
18378 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18379 bool isIncomplete =
18380 LangOpts.HLSL // HLSL allows sizeless builtin types
18381 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
18383 diag::err_field_incomplete_or_sizeless);
18384 if (isIncomplete) {
18385 // Fields of incomplete type force their record to be invalid.
18386 Record->setInvalidDecl();
18387 InvalidDecl = true;
18388 } else {
18389 NamedDecl *Def;
18390 EltTy->isIncompleteType(&Def);
18391 if (Def && Def->isInvalidDecl()) {
18392 Record->setInvalidDecl();
18393 InvalidDecl = true;
18394 }
18395 }
18396 }
18397
18398 // TR 18037 does not allow fields to be declared with address space
18399 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18401 Diag(Loc, diag::err_field_with_address_space);
18402 Record->setInvalidDecl();
18403 InvalidDecl = true;
18404 }
18405
18406 if (LangOpts.OpenCL) {
18407 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18408 // used as structure or union field: image, sampler, event or block types.
18409 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18410 T->isBlockPointerType()) {
18411 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18412 Record->setInvalidDecl();
18413 InvalidDecl = true;
18414 }
18415 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18416 // is enabled.
18417 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18418 "__cl_clang_bitfields", LangOpts)) {
18419 Diag(Loc, diag::err_opencl_bitfields);
18420 InvalidDecl = true;
18421 }
18422 }
18423
18424 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18425 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18426 T.hasQualifiers()) {
18427 InvalidDecl = true;
18428 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18429 }
18430
18431 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18432 // than a variably modified type.
18433 if (!InvalidDecl && T->isVariablyModifiedType()) {
18435 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18436 InvalidDecl = true;
18437 }
18438
18439 // Fields can not have abstract class types
18440 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18441 diag::err_abstract_type_in_decl,
18443 InvalidDecl = true;
18444
18445 if (InvalidDecl)
18446 BitWidth = nullptr;
18447 // If this is declared as a bit-field, check the bit-field.
18448 if (BitWidth) {
18449 BitWidth =
18450 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18451 if (!BitWidth) {
18452 InvalidDecl = true;
18453 BitWidth = nullptr;
18454 }
18455 }
18456
18457 // Check that 'mutable' is consistent with the type of the declaration.
18458 if (!InvalidDecl && Mutable) {
18459 unsigned DiagID = 0;
18460 if (T->isReferenceType())
18461 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18462 : diag::err_mutable_reference;
18463 else if (T.isConstQualified())
18464 DiagID = diag::err_mutable_const;
18465
18466 if (DiagID) {
18467 SourceLocation ErrLoc = Loc;
18468 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18469 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18470 Diag(ErrLoc, DiagID);
18471 if (DiagID != diag::ext_mutable_reference) {
18472 Mutable = false;
18473 InvalidDecl = true;
18474 }
18475 }
18476 }
18477
18478 // C++11 [class.union]p8 (DR1460):
18479 // At most one variant member of a union may have a
18480 // brace-or-equal-initializer.
18481 if (InitStyle != ICIS_NoInit)
18482 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18483
18484 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18485 BitWidth, Mutable, InitStyle);
18486 if (InvalidDecl)
18487 NewFD->setInvalidDecl();
18488
18489 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18490 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18491 Diag(Loc, diag::err_duplicate_member) << II;
18492 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18493 NewFD->setInvalidDecl();
18494 }
18495
18496 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18497 if (Record->isUnion()) {
18498 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18499 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18500 if (RDecl->getDefinition()) {
18501 // C++ [class.union]p1: An object of a class with a non-trivial
18502 // constructor, a non-trivial copy constructor, a non-trivial
18503 // destructor, or a non-trivial copy assignment operator
18504 // cannot be a member of a union, nor can an array of such
18505 // objects.
18506 if (CheckNontrivialField(NewFD))
18507 NewFD->setInvalidDecl();
18508 }
18509 }
18510
18511 // C++ [class.union]p1: If a union contains a member of reference type,
18512 // the program is ill-formed, except when compiling with MSVC extensions
18513 // enabled.
18514 if (EltTy->isReferenceType()) {
18515 const bool HaveMSExt =
18516 getLangOpts().MicrosoftExt &&
18518
18519 Diag(NewFD->getLocation(),
18520 HaveMSExt ? diag::ext_union_member_of_reference_type
18521 : diag::err_union_member_of_reference_type)
18522 << NewFD->getDeclName() << EltTy;
18523 if (!HaveMSExt)
18524 NewFD->setInvalidDecl();
18525 }
18526 }
18527 }
18528
18529 // FIXME: We need to pass in the attributes given an AST
18530 // representation, not a parser representation.
18531 if (D) {
18532 // FIXME: The current scope is almost... but not entirely... correct here.
18534
18535 if (NewFD->hasAttrs())
18537 }
18538
18539 // In auto-retain/release, infer strong retension for fields of
18540 // retainable type.
18541 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
18542 NewFD->setInvalidDecl();
18543
18544 if (T.isObjCGCWeak())
18545 Diag(Loc, diag::warn_attribute_weak_on_field);
18546
18547 // PPC MMA non-pointer types are not allowed as field types.
18548 if (Context.getTargetInfo().getTriple().isPPC64() &&
18549 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
18550 NewFD->setInvalidDecl();
18551
18552 NewFD->setAccess(AS);
18553 return NewFD;
18554}
18555
18557 assert(FD);
18558 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18559
18560 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18561 return false;
18562
18564 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18565 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18566 if (RDecl->getDefinition()) {
18567 // We check for copy constructors before constructors
18568 // because otherwise we'll never get complaints about
18569 // copy constructors.
18570
18572 // We're required to check for any non-trivial constructors. Since the
18573 // implicit default constructor is suppressed if there are any
18574 // user-declared constructors, we just need to check that there is a
18575 // trivial default constructor and a trivial copy constructor. (We don't
18576 // worry about move constructors here, since this is a C++98 check.)
18577 if (RDecl->hasNonTrivialCopyConstructor())
18579 else if (!RDecl->hasTrivialDefaultConstructor())
18581 else if (RDecl->hasNonTrivialCopyAssignment())
18583 else if (RDecl->hasNonTrivialDestructor())
18585
18586 if (member != CXXSpecialMemberKind::Invalid) {
18587 if (!getLangOpts().CPlusPlus11 &&
18588 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18589 // Objective-C++ ARC: it is an error to have a non-trivial field of
18590 // a union. However, system headers in Objective-C programs
18591 // occasionally have Objective-C lifetime objects within unions,
18592 // and rather than cause the program to fail, we make those
18593 // members unavailable.
18595 if (getSourceManager().isInSystemHeader(Loc)) {
18596 if (!FD->hasAttr<UnavailableAttr>())
18597 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18598 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18599 return false;
18600 }
18601 }
18602
18603 Diag(
18604 FD->getLocation(),
18606 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
18607 : diag::err_illegal_union_or_anon_struct_member)
18608 << FD->getParent()->isUnion() << FD->getDeclName()
18609 << llvm::to_underlying(member);
18610 DiagnoseNontrivial(RDecl, member);
18611 return !getLangOpts().CPlusPlus11;
18612 }
18613 }
18614 }
18615
18616 return false;
18617}
18618
18620 SmallVectorImpl<Decl *> &AllIvarDecls) {
18621 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18622 return;
18623
18624 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18625 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18626
18627 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18628 return;
18629 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18630 if (!ID) {
18631 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18632 if (!CD->IsClassExtension())
18633 return;
18634 }
18635 // No need to add this to end of @implementation.
18636 else
18637 return;
18638 }
18639 // All conditions are met. Add a new bitfield to the tail end of ivars.
18640 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18641 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18642
18643 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18644 DeclLoc, DeclLoc, nullptr,
18647 DeclLoc),
18649 true);
18650 AllIvarDecls.push_back(Ivar);
18651}
18652
18653/// [class.dtor]p4:
18654/// At the end of the definition of a class, overload resolution is
18655/// performed among the prospective destructors declared in that class with
18656/// an empty argument list to select the destructor for the class, also
18657/// known as the selected destructor.
18658///
18659/// We do the overload resolution here, then mark the selected constructor in the AST.
18660/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18662 if (!Record->hasUserDeclaredDestructor()) {
18663 return;
18664 }
18665
18666 SourceLocation Loc = Record->getLocation();
18668
18669 for (auto *Decl : Record->decls()) {
18670 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18671 if (DD->isInvalidDecl())
18672 continue;
18673 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18674 OCS);
18675 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18676 }
18677 }
18678
18679 if (OCS.empty()) {
18680 return;
18681 }
18683 unsigned Msg = 0;
18684 OverloadCandidateDisplayKind DisplayKind;
18685
18686 switch (OCS.BestViableFunction(S, Loc, Best)) {
18687 case OR_Success:
18688 case OR_Deleted:
18689 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18690 break;
18691
18692 case OR_Ambiguous:
18693 Msg = diag::err_ambiguous_destructor;
18694 DisplayKind = OCD_AmbiguousCandidates;
18695 break;
18696
18698 Msg = diag::err_no_viable_destructor;
18699 DisplayKind = OCD_AllCandidates;
18700 break;
18701 }
18702
18703 if (Msg) {
18704 // OpenCL have got their own thing going with destructors. It's slightly broken,
18705 // but we allow it.
18706 if (!S.LangOpts.OpenCL) {
18707 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18708 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18709 Record->setInvalidDecl();
18710 }
18711 // It's a bit hacky: At this point we've raised an error but we want the
18712 // rest of the compiler to continue somehow working. However almost
18713 // everything we'll try to do with the class will depend on there being a
18714 // destructor. So let's pretend the first one is selected and hope for the
18715 // best.
18716 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18717 }
18718}
18719
18720/// [class.mem.special]p5
18721/// Two special member functions are of the same kind if:
18722/// - they are both default constructors,
18723/// - they are both copy or move constructors with the same first parameter
18724/// type, or
18725/// - they are both copy or move assignment operators with the same first
18726/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18728 CXXMethodDecl *M1,
18729 CXXMethodDecl *M2,
18731 // We don't want to compare templates to non-templates: See
18732 // https://github.com/llvm/llvm-project/issues/59206
18734 return bool(M1->getDescribedFunctionTemplate()) ==
18736 // FIXME: better resolve CWG
18737 // https://cplusplus.github.io/CWG/issues/2787.html
18738 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18739 M2->getNonObjectParameter(0)->getType()))
18740 return false;
18743 return false;
18744
18745 return true;
18746}
18747
18748/// [class.mem.special]p6:
18749/// An eligible special member function is a special member function for which:
18750/// - the function is not deleted,
18751/// - the associated constraints, if any, are satisfied, and
18752/// - no special member function of the same kind whose associated constraints
18753/// [CWG2595], if any, are satisfied is more constrained.
18757 SmallVector<bool, 4> SatisfactionStatus;
18758
18759 for (CXXMethodDecl *Method : Methods) {
18760 const Expr *Constraints = Method->getTrailingRequiresClause();
18761 if (!Constraints)
18762 SatisfactionStatus.push_back(true);
18763 else {
18764 ConstraintSatisfaction Satisfaction;
18765 if (S.CheckFunctionConstraints(Method, Satisfaction))
18766 SatisfactionStatus.push_back(false);
18767 else
18768 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18769 }
18770 }
18771
18772 for (size_t i = 0; i < Methods.size(); i++) {
18773 if (!SatisfactionStatus[i])
18774 continue;
18775 CXXMethodDecl *Method = Methods[i];
18776 CXXMethodDecl *OrigMethod = Method;
18777 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18778 OrigMethod = cast<CXXMethodDecl>(MF);
18779
18780 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18781 bool AnotherMethodIsMoreConstrained = false;
18782 for (size_t j = 0; j < Methods.size(); j++) {
18783 if (i == j || !SatisfactionStatus[j])
18784 continue;
18785 CXXMethodDecl *OtherMethod = Methods[j];
18786 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18787 OtherMethod = cast<CXXMethodDecl>(MF);
18788
18789 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18790 CSM))
18791 continue;
18792
18793 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18794 if (!OtherConstraints)
18795 continue;
18796 if (!Constraints) {
18797 AnotherMethodIsMoreConstrained = true;
18798 break;
18799 }
18800 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18801 {Constraints},
18802 AnotherMethodIsMoreConstrained)) {
18803 // There was an error with the constraints comparison. Exit the loop
18804 // and don't consider this function eligible.
18805 AnotherMethodIsMoreConstrained = true;
18806 }
18807 if (AnotherMethodIsMoreConstrained)
18808 break;
18809 }
18810 // FIXME: Do not consider deleted methods as eligible after implementing
18811 // DR1734 and DR1496.
18812 if (!AnotherMethodIsMoreConstrained) {
18813 Method->setIneligibleOrNotSelected(false);
18814 Record->addedEligibleSpecialMemberFunction(Method,
18815 1 << llvm::to_underlying(CSM));
18816 }
18817 }
18818}
18819
18822 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18823 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18824 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18825 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18826 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18827
18828 for (auto *Decl : Record->decls()) {
18829 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18830 if (!MD) {
18831 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18832 if (FTD)
18833 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18834 }
18835 if (!MD)
18836 continue;
18837 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18838 if (CD->isInvalidDecl())
18839 continue;
18840 if (CD->isDefaultConstructor())
18841 DefaultConstructors.push_back(MD);
18842 else if (CD->isCopyConstructor())
18843 CopyConstructors.push_back(MD);
18844 else if (CD->isMoveConstructor())
18845 MoveConstructors.push_back(MD);
18846 } else if (MD->isCopyAssignmentOperator()) {
18847 CopyAssignmentOperators.push_back(MD);
18848 } else if (MD->isMoveAssignmentOperator()) {
18849 MoveAssignmentOperators.push_back(MD);
18850 }
18851 }
18852
18853 SetEligibleMethods(S, Record, DefaultConstructors,
18855 SetEligibleMethods(S, Record, CopyConstructors,
18857 SetEligibleMethods(S, Record, MoveConstructors,
18859 SetEligibleMethods(S, Record, CopyAssignmentOperators,
18861 SetEligibleMethods(S, Record, MoveAssignmentOperators,
18863}
18864
18865void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18866 ArrayRef<Decl *> Fields, SourceLocation LBrac,
18867 SourceLocation RBrac,
18868 const ParsedAttributesView &Attrs) {
18869 assert(EnclosingDecl && "missing record or interface decl");
18870
18871 // If this is an Objective-C @implementation or category and we have
18872 // new fields here we should reset the layout of the interface since
18873 // it will now change.
18874 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
18875 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18876 switch (DC->getKind()) {
18877 default: break;
18878 case Decl::ObjCCategory:
18879 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18880 break;
18881 case Decl::ObjCImplementation:
18882 Context.
18883 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18884 break;
18885 }
18886 }
18887
18888 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18889 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18890
18891 // Start counting up the number of named members; make sure to include
18892 // members of anonymous structs and unions in the total.
18893 unsigned NumNamedMembers = 0;
18894 if (Record) {
18895 for (const auto *I : Record->decls()) {
18896 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
18897 if (IFD->getDeclName())
18898 ++NumNamedMembers;
18899 }
18900 }
18901
18902 // Verify that all the fields are okay.
18904
18905 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
18906 i != end; ++i) {
18907 FieldDecl *FD = cast<FieldDecl>(*i);
18908
18909 // Get the type for the field.
18910 const Type *FDTy = FD->getType().getTypePtr();
18911
18912 if (!FD->isAnonymousStructOrUnion()) {
18913 // Remember all fields written by the user.
18914 RecFields.push_back(FD);
18915 }
18916
18917 // If the field is already invalid for some reason, don't emit more
18918 // diagnostics about it.
18919 if (FD->isInvalidDecl()) {
18920 EnclosingDecl->setInvalidDecl();
18921 continue;
18922 }
18923
18924 // C99 6.7.2.1p2:
18925 // A structure or union shall not contain a member with
18926 // incomplete or function type (hence, a structure shall not
18927 // contain an instance of itself, but may contain a pointer to
18928 // an instance of itself), except that the last member of a
18929 // structure with more than one named member may have incomplete
18930 // array type; such a structure (and any union containing,
18931 // possibly recursively, a member that is such a structure)
18932 // shall not be a member of a structure or an element of an
18933 // array.
18934 bool IsLastField = (i + 1 == Fields.end());
18935 if (FDTy->isFunctionType()) {
18936 // Field declared as a function.
18937 Diag(FD->getLocation(), diag::err_field_declared_as_function)
18938 << FD->getDeclName();
18939 FD->setInvalidDecl();
18940 EnclosingDecl->setInvalidDecl();
18941 continue;
18942 } else if (FDTy->isIncompleteArrayType() &&
18943 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
18944 if (Record) {
18945 // Flexible array member.
18946 // Microsoft and g++ is more permissive regarding flexible array.
18947 // It will accept flexible array in union and also
18948 // as the sole element of a struct/class.
18949 unsigned DiagID = 0;
18950 if (!Record->isUnion() && !IsLastField) {
18951 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
18952 << FD->getDeclName() << FD->getType()
18953 << llvm::to_underlying(Record->getTagKind());
18954 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
18955 FD->setInvalidDecl();
18956 EnclosingDecl->setInvalidDecl();
18957 continue;
18958 } else if (Record->isUnion())
18959 DiagID = getLangOpts().MicrosoftExt
18960 ? diag::ext_flexible_array_union_ms
18961 : diag::ext_flexible_array_union_gnu;
18962 else if (NumNamedMembers < 1)
18963 DiagID = getLangOpts().MicrosoftExt
18964 ? diag::ext_flexible_array_empty_aggregate_ms
18965 : diag::ext_flexible_array_empty_aggregate_gnu;
18966
18967 if (DiagID)
18968 Diag(FD->getLocation(), DiagID)
18969 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18970 // While the layout of types that contain virtual bases is not specified
18971 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18972 // virtual bases after the derived members. This would make a flexible
18973 // array member declared at the end of an object not adjacent to the end
18974 // of the type.
18975 if (CXXRecord && CXXRecord->getNumVBases() != 0)
18976 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
18977 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18978 if (!getLangOpts().C99)
18979 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
18980 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18981
18982 // If the element type has a non-trivial destructor, we would not
18983 // implicitly destroy the elements, so disallow it for now.
18984 //
18985 // FIXME: GCC allows this. We should probably either implicitly delete
18986 // the destructor of the containing class, or just allow this.
18987 QualType BaseElem = Context.getBaseElementType(FD->getType());
18988 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18989 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18990 << FD->getDeclName() << FD->getType();
18991 FD->setInvalidDecl();
18992 EnclosingDecl->setInvalidDecl();
18993 continue;
18994 }
18995 // Okay, we have a legal flexible array member at the end of the struct.
18996 Record->setHasFlexibleArrayMember(true);
18997 } else {
18998 // In ObjCContainerDecl ivars with incomplete array type are accepted,
18999 // unless they are followed by another ivar. That check is done
19000 // elsewhere, after synthesized ivars are known.
19001 }
19002 } else if (!FDTy->isDependentType() &&
19003 (LangOpts.HLSL // HLSL allows sizeless builtin types
19005 diag::err_incomplete_type)
19007 FD->getLocation(), FD->getType(),
19008 diag::err_field_incomplete_or_sizeless))) {
19009 // Incomplete type
19010 FD->setInvalidDecl();
19011 EnclosingDecl->setInvalidDecl();
19012 continue;
19013 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19014 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19015 // A type which contains a flexible array member is considered to be a
19016 // flexible array member.
19017 Record->setHasFlexibleArrayMember(true);
19018 if (!Record->isUnion()) {
19019 // If this is a struct/class and this is not the last element, reject
19020 // it. Note that GCC supports variable sized arrays in the middle of
19021 // structures.
19022 if (!IsLastField)
19023 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19024 << FD->getDeclName() << FD->getType();
19025 else {
19026 // We support flexible arrays at the end of structs in
19027 // other structs as an extension.
19028 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19029 << FD->getDeclName();
19030 }
19031 }
19032 }
19033 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19035 diag::err_abstract_type_in_decl,
19037 // Ivars can not have abstract class types
19038 FD->setInvalidDecl();
19039 }
19040 if (Record && FDTTy->getDecl()->hasObjectMember())
19041 Record->setHasObjectMember(true);
19042 if (Record && FDTTy->getDecl()->hasVolatileMember())
19043 Record->setHasVolatileMember(true);
19044 } else if (FDTy->isObjCObjectType()) {
19045 /// A field cannot be an Objective-c object
19046 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19049 FD->setType(T);
19050 } else if (Record && Record->isUnion() &&
19052 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19053 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19056 // For backward compatibility, fields of C unions declared in system
19057 // headers that have non-trivial ObjC ownership qualifications are marked
19058 // as unavailable unless the qualifier is explicit and __strong. This can
19059 // break ABI compatibility between programs compiled with ARC and MRR, but
19060 // is a better option than rejecting programs using those unions under
19061 // ARC.
19062 FD->addAttr(UnavailableAttr::CreateImplicit(
19063 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19064 FD->getLocation()));
19065 } else if (getLangOpts().ObjC &&
19066 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19067 !Record->hasObjectMember()) {
19068 if (FD->getType()->isObjCObjectPointerType() ||
19069 FD->getType().isObjCGCStrong())
19070 Record->setHasObjectMember(true);
19071 else if (Context.getAsArrayType(FD->getType())) {
19072 QualType BaseType = Context.getBaseElementType(FD->getType());
19073 if (BaseType->isRecordType() &&
19074 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19075 Record->setHasObjectMember(true);
19076 else if (BaseType->isObjCObjectPointerType() ||
19077 BaseType.isObjCGCStrong())
19078 Record->setHasObjectMember(true);
19079 }
19080 }
19081
19082 if (Record && !getLangOpts().CPlusPlus &&
19083 !shouldIgnoreForRecordTriviality(FD)) {
19084 QualType FT = FD->getType();
19086 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19088 Record->isUnion())
19089 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19090 }
19093 Record->setNonTrivialToPrimitiveCopy(true);
19094 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19095 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19096 }
19097 if (FT.isDestructedType()) {
19098 Record->setNonTrivialToPrimitiveDestroy(true);
19099 Record->setParamDestroyedInCallee(true);
19100 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19101 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19102 }
19103
19104 if (const auto *RT = FT->getAs<RecordType>()) {
19105 if (RT->getDecl()->getArgPassingRestrictions() ==
19107 Record->setArgPassingRestrictions(
19110 Record->setArgPassingRestrictions(
19112 }
19113
19114 if (Record && FD->getType().isVolatileQualified())
19115 Record->setHasVolatileMember(true);
19116 // Keep track of the number of named members.
19117 if (FD->getIdentifier())
19118 ++NumNamedMembers;
19119 }
19120
19121 // Okay, we successfully defined 'Record'.
19122 if (Record) {
19123 bool Completed = false;
19124 if (S) {
19125 Scope *Parent = S->getParent();
19126 if (Parent && Parent->isTypeAliasScope() &&
19127 Parent->isTemplateParamScope())
19128 Record->setInvalidDecl();
19129 }
19130
19131 if (CXXRecord) {
19132 if (!CXXRecord->isInvalidDecl()) {
19133 // Set access bits correctly on the directly-declared conversions.
19135 I = CXXRecord->conversion_begin(),
19136 E = CXXRecord->conversion_end(); I != E; ++I)
19137 I.setAccess((*I)->getAccess());
19138 }
19139
19140 // Add any implicitly-declared members to this class.
19142
19143 if (!CXXRecord->isDependentType()) {
19144 if (!CXXRecord->isInvalidDecl()) {
19145 // If we have virtual base classes, we may end up finding multiple
19146 // final overriders for a given virtual function. Check for this
19147 // problem now.
19148 if (CXXRecord->getNumVBases()) {
19149 CXXFinalOverriderMap FinalOverriders;
19150 CXXRecord->getFinalOverriders(FinalOverriders);
19151
19152 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19153 MEnd = FinalOverriders.end();
19154 M != MEnd; ++M) {
19155 for (OverridingMethods::iterator SO = M->second.begin(),
19156 SOEnd = M->second.end();
19157 SO != SOEnd; ++SO) {
19158 assert(SO->second.size() > 0 &&
19159 "Virtual function without overriding functions?");
19160 if (SO->second.size() == 1)
19161 continue;
19162
19163 // C++ [class.virtual]p2:
19164 // In a derived class, if a virtual member function of a base
19165 // class subobject has more than one final overrider the
19166 // program is ill-formed.
19167 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19168 << (const NamedDecl *)M->first << Record;
19169 Diag(M->first->getLocation(),
19170 diag::note_overridden_virtual_function);
19172 OM = SO->second.begin(),
19173 OMEnd = SO->second.end();
19174 OM != OMEnd; ++OM)
19175 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19176 << (const NamedDecl *)M->first << OM->Method->getParent();
19177
19178 Record->setInvalidDecl();
19179 }
19180 }
19181 CXXRecord->completeDefinition(&FinalOverriders);
19182 Completed = true;
19183 }
19184 }
19185 ComputeSelectedDestructor(*this, CXXRecord);
19187 }
19188 }
19189
19190 if (!Completed)
19191 Record->completeDefinition();
19192
19193 // Handle attributes before checking the layout.
19195
19196 // Check to see if a FieldDecl is a pointer to a function.
19197 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19198 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19199 if (!FD) {
19200 // Check whether this is a forward declaration that was inserted by
19201 // Clang. This happens when a non-forward declared / defined type is
19202 // used, e.g.:
19203 //
19204 // struct foo {
19205 // struct bar *(*f)();
19206 // struct bar *(*g)();
19207 // };
19208 //
19209 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19210 // incomplete definition.
19211 if (const auto *TD = dyn_cast<TagDecl>(D))
19212 return !TD->isCompleteDefinition();
19213 return false;
19214 }
19215 QualType FieldType = FD->getType().getDesugaredType(Context);
19216 if (isa<PointerType>(FieldType)) {
19217 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19218 return PointeeType.getDesugaredType(Context)->isFunctionType();
19219 }
19220 return false;
19221 };
19222
19223 // Maybe randomize the record's decls. We automatically randomize a record
19224 // of function pointers, unless it has the "no_randomize_layout" attribute.
19225 if (!getLangOpts().CPlusPlus &&
19226 (Record->hasAttr<RandomizeLayoutAttr>() ||
19227 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19228 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19229 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19230 !Record->isRandomized()) {
19231 SmallVector<Decl *, 32> NewDeclOrdering;
19233 NewDeclOrdering))
19234 Record->reorderDecls(NewDeclOrdering);
19235 }
19236
19237 // We may have deferred checking for a deleted destructor. Check now.
19238 if (CXXRecord) {
19239 auto *Dtor = CXXRecord->getDestructor();
19240 if (Dtor && Dtor->isImplicit() &&
19242 CXXRecord->setImplicitDestructorIsDeleted();
19243 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19244 }
19245 }
19246
19247 if (Record->hasAttrs()) {
19249
19250 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19251 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19252 IA->getRange(), IA->getBestCase(),
19253 IA->getInheritanceModel());
19254 }
19255
19256 // Check if the structure/union declaration is a type that can have zero
19257 // size in C. For C this is a language extension, for C++ it may cause
19258 // compatibility problems.
19259 bool CheckForZeroSize;
19260 if (!getLangOpts().CPlusPlus) {
19261 CheckForZeroSize = true;
19262 } else {
19263 // For C++ filter out types that cannot be referenced in C code.
19264 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19265 CheckForZeroSize =
19266 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19267 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19268 CXXRecord->isCLike();
19269 }
19270 if (CheckForZeroSize) {
19271 bool ZeroSize = true;
19272 bool IsEmpty = true;
19273 unsigned NonBitFields = 0;
19274 for (RecordDecl::field_iterator I = Record->field_begin(),
19275 E = Record->field_end();
19276 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19277 IsEmpty = false;
19278 if (I->isUnnamedBitField()) {
19279 if (!I->isZeroLengthBitField(Context))
19280 ZeroSize = false;
19281 } else {
19282 ++NonBitFields;
19283 QualType FieldType = I->getType();
19284 if (FieldType->isIncompleteType() ||
19285 !Context.getTypeSizeInChars(FieldType).isZero())
19286 ZeroSize = false;
19287 }
19288 }
19289
19290 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19291 // allowed in C++, but warn if its declaration is inside
19292 // extern "C" block.
19293 if (ZeroSize) {
19294 Diag(RecLoc, getLangOpts().CPlusPlus ?
19295 diag::warn_zero_size_struct_union_in_extern_c :
19296 diag::warn_zero_size_struct_union_compat)
19297 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19298 }
19299
19300 // Structs without named members are extension in C (C99 6.7.2.1p7),
19301 // but are accepted by GCC.
19302 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19303 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19304 diag::ext_no_named_members_in_struct_union)
19305 << Record->isUnion();
19306 }
19307 }
19308 } else {
19309 ObjCIvarDecl **ClsFields =
19310 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19311 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19312 ID->setEndOfDefinitionLoc(RBrac);
19313 // Add ivar's to class's DeclContext.
19314 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19315 ClsFields[i]->setLexicalDeclContext(ID);
19316 ID->addDecl(ClsFields[i]);
19317 }
19318 // Must enforce the rule that ivars in the base classes may not be
19319 // duplicates.
19320 if (ID->getSuperClass())
19321 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19322 } else if (ObjCImplementationDecl *IMPDecl =
19323 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19324 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19325 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19326 // Ivar declared in @implementation never belongs to the implementation.
19327 // Only it is in implementation's lexical context.
19328 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19329 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
19330 RBrac);
19331 IMPDecl->setIvarLBraceLoc(LBrac);
19332 IMPDecl->setIvarRBraceLoc(RBrac);
19333 } else if (ObjCCategoryDecl *CDecl =
19334 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19335 // case of ivars in class extension; all other cases have been
19336 // reported as errors elsewhere.
19337 // FIXME. Class extension does not have a LocEnd field.
19338 // CDecl->setLocEnd(RBrac);
19339 // Add ivar's to class extension's DeclContext.
19340 // Diagnose redeclaration of private ivars.
19341 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19342 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19343 if (IDecl) {
19344 if (const ObjCIvarDecl *ClsIvar =
19345 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19346 Diag(ClsFields[i]->getLocation(),
19347 diag::err_duplicate_ivar_declaration);
19348 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19349 continue;
19350 }
19351 for (const auto *Ext : IDecl->known_extensions()) {
19352 if (const ObjCIvarDecl *ClsExtIvar
19353 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19354 Diag(ClsFields[i]->getLocation(),
19355 diag::err_duplicate_ivar_declaration);
19356 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19357 continue;
19358 }
19359 }
19360 }
19361 ClsFields[i]->setLexicalDeclContext(CDecl);
19362 CDecl->addDecl(ClsFields[i]);
19363 }
19364 CDecl->setIvarLBraceLoc(LBrac);
19365 CDecl->setIvarRBraceLoc(RBrac);
19366 }
19367 }
19369}
19370
19371/// Determine whether the given integral value is representable within
19372/// the given type T.
19374 llvm::APSInt &Value,
19375 QualType T) {
19376 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19377 "Integral type required!");
19378 unsigned BitWidth = Context.getIntWidth(T);
19379
19380 if (Value.isUnsigned() || Value.isNonNegative()) {
19382 --BitWidth;
19383 return Value.getActiveBits() <= BitWidth;
19384 }
19385 return Value.getSignificantBits() <= BitWidth;
19386}
19387
19388// Given an integral type, return the next larger integral type
19389// (or a NULL type of no such type exists).
19391 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19392 // enum checking below.
19393 assert((T->isIntegralType(Context) ||
19394 T->isEnumeralType()) && "Integral type required!");
19395 const unsigned NumTypes = 4;
19396 QualType SignedIntegralTypes[NumTypes] = {
19397 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19398 };
19399 QualType UnsignedIntegralTypes[NumTypes] = {
19400 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19401 Context.UnsignedLongLongTy
19402 };
19403
19404 unsigned BitWidth = Context.getTypeSize(T);
19405 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19406 : UnsignedIntegralTypes;
19407 for (unsigned I = 0; I != NumTypes; ++I)
19408 if (Context.getTypeSize(Types[I]) > BitWidth)
19409 return Types[I];
19410
19411 return QualType();
19412}
19413
19415 EnumConstantDecl *LastEnumConst,
19416 SourceLocation IdLoc,
19418 Expr *Val) {
19419 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19420 llvm::APSInt EnumVal(IntWidth);
19421 QualType EltTy;
19422
19424 Val = nullptr;
19425
19426 if (Val)
19427 Val = DefaultLvalueConversion(Val).get();
19428
19429 if (Val) {
19430 if (Enum->isDependentType() || Val->isTypeDependent() ||
19431 Val->containsErrors())
19432 EltTy = Context.DependentTy;
19433 else {
19434 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19435 // underlying type, but do allow it in all other contexts.
19436 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19437 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19438 // constant-expression in the enumerator-definition shall be a converted
19439 // constant expression of the underlying type.
19440 EltTy = Enum->getIntegerType();
19441 ExprResult Converted =
19442 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19444 if (Converted.isInvalid())
19445 Val = nullptr;
19446 else
19447 Val = Converted.get();
19448 } else if (!Val->isValueDependent() &&
19449 !(Val =
19451 .get())) {
19452 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19453 } else {
19454 if (Enum->isComplete()) {
19455 EltTy = Enum->getIntegerType();
19456
19457 // In Obj-C and Microsoft mode, require the enumeration value to be
19458 // representable in the underlying type of the enumeration. In C++11,
19459 // we perform a non-narrowing conversion as part of converted constant
19460 // expression checking.
19461 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19463 .getTriple()
19464 .isWindowsMSVCEnvironment()) {
19465 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19466 } else {
19467 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19468 }
19469 }
19470
19471 // Cast to the underlying type.
19472 Val = ImpCastExprToType(Val, EltTy,
19473 EltTy->isBooleanType() ? CK_IntegralToBoolean
19474 : CK_IntegralCast)
19475 .get();
19476 } else if (getLangOpts().CPlusPlus) {
19477 // C++11 [dcl.enum]p5:
19478 // If the underlying type is not fixed, the type of each enumerator
19479 // is the type of its initializing value:
19480 // - If an initializer is specified for an enumerator, the
19481 // initializing value has the same type as the expression.
19482 EltTy = Val->getType();
19483 } else {
19484 // C99 6.7.2.2p2:
19485 // The expression that defines the value of an enumeration constant
19486 // shall be an integer constant expression that has a value
19487 // representable as an int.
19488
19489 // Complain if the value is not representable in an int.
19491 Diag(IdLoc, diag::ext_enum_value_not_int)
19492 << toString(EnumVal, 10) << Val->getSourceRange()
19493 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19494 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19495 // Force the type of the expression to 'int'.
19496 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19497 }
19498 EltTy = Val->getType();
19499 }
19500 }
19501 }
19502 }
19503
19504 if (!Val) {
19505 if (Enum->isDependentType())
19506 EltTy = Context.DependentTy;
19507 else if (!LastEnumConst) {
19508 // C++0x [dcl.enum]p5:
19509 // If the underlying type is not fixed, the type of each enumerator
19510 // is the type of its initializing value:
19511 // - If no initializer is specified for the first enumerator, the
19512 // initializing value has an unspecified integral type.
19513 //
19514 // GCC uses 'int' for its unspecified integral type, as does
19515 // C99 6.7.2.2p3.
19516 if (Enum->isFixed()) {
19517 EltTy = Enum->getIntegerType();
19518 }
19519 else {
19520 EltTy = Context.IntTy;
19521 }
19522 } else {
19523 // Assign the last value + 1.
19524 EnumVal = LastEnumConst->getInitVal();
19525 ++EnumVal;
19526 EltTy = LastEnumConst->getType();
19527
19528 // Check for overflow on increment.
19529 if (EnumVal < LastEnumConst->getInitVal()) {
19530 // C++0x [dcl.enum]p5:
19531 // If the underlying type is not fixed, the type of each enumerator
19532 // is the type of its initializing value:
19533 //
19534 // - Otherwise the type of the initializing value is the same as
19535 // the type of the initializing value of the preceding enumerator
19536 // unless the incremented value is not representable in that type,
19537 // in which case the type is an unspecified integral type
19538 // sufficient to contain the incremented value. If no such type
19539 // exists, the program is ill-formed.
19541 if (T.isNull() || Enum->isFixed()) {
19542 // There is no integral type larger enough to represent this
19543 // value. Complain, then allow the value to wrap around.
19544 EnumVal = LastEnumConst->getInitVal();
19545 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19546 ++EnumVal;
19547 if (Enum->isFixed())
19548 // When the underlying type is fixed, this is ill-formed.
19549 Diag(IdLoc, diag::err_enumerator_wrapped)
19550 << toString(EnumVal, 10)
19551 << EltTy;
19552 else
19553 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19554 << toString(EnumVal, 10);
19555 } else {
19556 EltTy = T;
19557 }
19558
19559 // Retrieve the last enumerator's value, extent that type to the
19560 // type that is supposed to be large enough to represent the incremented
19561 // value, then increment.
19562 EnumVal = LastEnumConst->getInitVal();
19563 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19564 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19565 ++EnumVal;
19566
19567 // If we're not in C++, diagnose the overflow of enumerator values,
19568 // which in C99 means that the enumerator value is not representable in
19569 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19570 // permits enumerator values that are representable in some larger
19571 // integral type.
19572 if (!getLangOpts().CPlusPlus && !T.isNull())
19573 Diag(IdLoc, diag::warn_enum_value_overflow);
19574 } else if (!getLangOpts().CPlusPlus &&
19575 !EltTy->isDependentType() &&
19576 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19577 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19578 Diag(IdLoc, diag::ext_enum_value_not_int)
19579 << toString(EnumVal, 10) << 1;
19580 }
19581 }
19582 }
19583
19584 if (!EltTy->isDependentType()) {
19585 // Make the enumerator value match the signedness and size of the
19586 // enumerator's type.
19587 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19588 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19589 }
19590
19591 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19592 Val, EnumVal);
19593}
19594
19596 SourceLocation IILoc) {
19597 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19599 return SkipBodyInfo();
19600
19601 // We have an anonymous enum definition. Look up the first enumerator to
19602 // determine if we should merge the definition with an existing one and
19603 // skip the body.
19604 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19606 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19607 if (!PrevECD)
19608 return SkipBodyInfo();
19609
19610 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19611 NamedDecl *Hidden;
19612 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19613 SkipBodyInfo Skip;
19614 Skip.Previous = Hidden;
19615 return Skip;
19616 }
19617
19618 return SkipBodyInfo();
19619}
19620
19621Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19623 const ParsedAttributesView &Attrs,
19624 SourceLocation EqualLoc, Expr *Val) {
19625 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19626 EnumConstantDecl *LastEnumConst =
19627 cast_or_null<EnumConstantDecl>(lastEnumConst);
19628
19629 // The scope passed in may not be a decl scope. Zip up the scope tree until
19630 // we find one that is.
19631 S = getNonFieldDeclScope(S);
19632
19633 // Verify that there isn't already something declared with this name in this
19634 // scope.
19635 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
19636 RedeclarationKind::ForVisibleRedeclaration);
19637 LookupName(R, S);
19638 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19639
19640 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19641 // Maybe we will complain about the shadowed template parameter.
19642 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19643 // Just pretend that we didn't see the previous declaration.
19644 PrevDecl = nullptr;
19645 }
19646
19647 // C++ [class.mem]p15:
19648 // If T is the name of a class, then each of the following shall have a name
19649 // different from T:
19650 // - every enumerator of every member of class T that is an unscoped
19651 // enumerated type
19652 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19654 DeclarationNameInfo(Id, IdLoc));
19655
19656 EnumConstantDecl *New =
19657 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19658 if (!New)
19659 return nullptr;
19660
19661 if (PrevDecl) {
19662 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19663 // Check for other kinds of shadowing not already handled.
19664 CheckShadow(New, PrevDecl, R);
19665 }
19666
19667 // When in C++, we may get a TagDecl with the same name; in this case the
19668 // enum constant will 'hide' the tag.
19669 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19670 "Received TagDecl when not in C++!");
19671 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19672 if (isa<EnumConstantDecl>(PrevDecl))
19673 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19674 else
19675 Diag(IdLoc, diag::err_redefinition) << Id;
19676 notePreviousDefinition(PrevDecl, IdLoc);
19677 return nullptr;
19678 }
19679 }
19680
19681 // Process attributes.
19682 ProcessDeclAttributeList(S, New, Attrs);
19683 AddPragmaAttributes(S, New);
19684 ProcessAPINotes(New);
19685
19686 // Register this decl in the current scope stack.
19687 New->setAccess(TheEnumDecl->getAccess());
19688 PushOnScopeChains(New, S);
19689
19691
19692 return New;
19693}
19694
19695// Returns true when the enum initial expression does not trigger the
19696// duplicate enum warning. A few common cases are exempted as follows:
19697// Element2 = Element1
19698// Element2 = Element1 + 1
19699// Element2 = Element1 - 1
19700// Where Element2 and Element1 are from the same enum.
19702 Expr *InitExpr = ECD->getInitExpr();
19703 if (!InitExpr)
19704 return true;
19705 InitExpr = InitExpr->IgnoreImpCasts();
19706
19707 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19708 if (!BO->isAdditiveOp())
19709 return true;
19710 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19711 if (!IL)
19712 return true;
19713 if (IL->getValue() != 1)
19714 return true;
19715
19716 InitExpr = BO->getLHS();
19717 }
19718
19719 // This checks if the elements are from the same enum.
19720 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19721 if (!DRE)
19722 return true;
19723
19724 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19725 if (!EnumConstant)
19726 return true;
19727
19728 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19729 Enum)
19730 return true;
19731
19732 return false;
19733}
19734
19735// Emits a warning when an element is implicitly set a value that
19736// a previous element has already been set to.
19739 // Avoid anonymous enums
19740 if (!Enum->getIdentifier())
19741 return;
19742
19743 // Only check for small enums.
19744 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19745 return;
19746
19747 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19748 return;
19749
19750 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19751 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19752
19753 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19754
19755 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19756 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19757
19758 // Use int64_t as a key to avoid needing special handling for map keys.
19759 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19760 llvm::APSInt Val = D->getInitVal();
19761 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19762 };
19763
19764 DuplicatesVector DupVector;
19765 ValueToVectorMap EnumMap;
19766
19767 // Populate the EnumMap with all values represented by enum constants without
19768 // an initializer.
19769 for (auto *Element : Elements) {
19770 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19771
19772 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19773 // this constant. Skip this enum since it may be ill-formed.
19774 if (!ECD) {
19775 return;
19776 }
19777
19778 // Constants with initializers are handled in the next loop.
19779 if (ECD->getInitExpr())
19780 continue;
19781
19782 // Duplicate values are handled in the next loop.
19783 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19784 }
19785
19786 if (EnumMap.size() == 0)
19787 return;
19788
19789 // Create vectors for any values that has duplicates.
19790 for (auto *Element : Elements) {
19791 // The last loop returned if any constant was null.
19792 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19793 if (!ValidDuplicateEnum(ECD, Enum))
19794 continue;
19795
19796 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19797 if (Iter == EnumMap.end())
19798 continue;
19799
19800 DeclOrVector& Entry = Iter->second;
19801 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19802 // Ensure constants are different.
19803 if (D == ECD)
19804 continue;
19805
19806 // Create new vector and push values onto it.
19807 auto Vec = std::make_unique<ECDVector>();
19808 Vec->push_back(D);
19809 Vec->push_back(ECD);
19810
19811 // Update entry to point to the duplicates vector.
19812 Entry = Vec.get();
19813
19814 // Store the vector somewhere we can consult later for quick emission of
19815 // diagnostics.
19816 DupVector.emplace_back(std::move(Vec));
19817 continue;
19818 }
19819
19820 ECDVector *Vec = Entry.get<ECDVector*>();
19821 // Make sure constants are not added more than once.
19822 if (*Vec->begin() == ECD)
19823 continue;
19824
19825 Vec->push_back(ECD);
19826 }
19827
19828 // Emit diagnostics.
19829 for (const auto &Vec : DupVector) {
19830 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19831
19832 // Emit warning for one enum constant.
19833 auto *FirstECD = Vec->front();
19834 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19835 << FirstECD << toString(FirstECD->getInitVal(), 10)
19836 << FirstECD->getSourceRange();
19837
19838 // Emit one note for each of the remaining enum constants with
19839 // the same value.
19840 for (auto *ECD : llvm::drop_begin(*Vec))
19841 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19842 << ECD << toString(ECD->getInitVal(), 10)
19843 << ECD->getSourceRange();
19844 }
19845}
19846
19847bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19848 bool AllowMask) const {
19849 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19850 assert(ED->isCompleteDefinition() && "expected enum definition");
19851
19852 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19853 llvm::APInt &FlagBits = R.first->second;
19854
19855 if (R.second) {
19856 for (auto *E : ED->enumerators()) {
19857 const auto &EVal = E->getInitVal();
19858 // Only single-bit enumerators introduce new flag values.
19859 if (EVal.isPowerOf2())
19860 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19861 }
19862 }
19863
19864 // A value is in a flag enum if either its bits are a subset of the enum's
19865 // flag bits (the first condition) or we are allowing masks and the same is
19866 // true of its complement (the second condition). When masks are allowed, we
19867 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19868 //
19869 // While it's true that any value could be used as a mask, the assumption is
19870 // that a mask will have all of the insignificant bits set. Anything else is
19871 // likely a logic error.
19872 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19873 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
19874}
19875
19877 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19878 const ParsedAttributesView &Attrs) {
19879 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19881
19882 ProcessDeclAttributeList(S, Enum, Attrs);
19884
19885 if (Enum->isDependentType()) {
19886 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19887 EnumConstantDecl *ECD =
19888 cast_or_null<EnumConstantDecl>(Elements[i]);
19889 if (!ECD) continue;
19890
19891 ECD->setType(EnumType);
19892 }
19893
19894 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
19895 return;
19896 }
19897
19898 // TODO: If the result value doesn't fit in an int, it must be a long or long
19899 // long value. ISO C does not support this, but GCC does as an extension,
19900 // emit a warning.
19901 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19902 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
19903 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
19904
19905 // Verify that all the values are okay, compute the size of the values, and
19906 // reverse the list.
19907 unsigned NumNegativeBits = 0;
19908 unsigned NumPositiveBits = 0;
19909
19910 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19911 EnumConstantDecl *ECD =
19912 cast_or_null<EnumConstantDecl>(Elements[i]);
19913 if (!ECD) continue; // Already issued a diagnostic.
19914
19915 const llvm::APSInt &InitVal = ECD->getInitVal();
19916
19917 // Keep track of the size of positive and negative values.
19918 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
19919 // If the enumerator is zero that should still be counted as a positive
19920 // bit since we need a bit to store the value zero.
19921 unsigned ActiveBits = InitVal.getActiveBits();
19922 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
19923 } else {
19924 NumNegativeBits =
19925 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
19926 }
19927 }
19928
19929 // If we have an empty set of enumerators we still need one bit.
19930 // From [dcl.enum]p8
19931 // If the enumerator-list is empty, the values of the enumeration are as if
19932 // the enumeration had a single enumerator with value 0
19933 if (!NumPositiveBits && !NumNegativeBits)
19934 NumPositiveBits = 1;
19935
19936 // Figure out the type that should be used for this enum.
19937 QualType BestType;
19938 unsigned BestWidth;
19939
19940 // C++0x N3000 [conv.prom]p3:
19941 // An rvalue of an unscoped enumeration type whose underlying
19942 // type is not fixed can be converted to an rvalue of the first
19943 // of the following types that can represent all the values of
19944 // the enumeration: int, unsigned int, long int, unsigned long
19945 // int, long long int, or unsigned long long int.
19946 // C99 6.4.4.3p2:
19947 // An identifier declared as an enumeration constant has type int.
19948 // The C99 rule is modified by a gcc extension
19949 QualType BestPromotionType;
19950
19951 bool Packed = Enum->hasAttr<PackedAttr>();
19952 // -fshort-enums is the equivalent to specifying the packed attribute on all
19953 // enum definitions.
19954 if (LangOpts.ShortEnums)
19955 Packed = true;
19956
19957 // If the enum already has a type because it is fixed or dictated by the
19958 // target, promote that type instead of analyzing the enumerators.
19959 if (Enum->isComplete()) {
19960 BestType = Enum->getIntegerType();
19961 if (Context.isPromotableIntegerType(BestType))
19962 BestPromotionType = Context.getPromotedIntegerType(BestType);
19963 else
19964 BestPromotionType = BestType;
19965
19966 BestWidth = Context.getIntWidth(BestType);
19967 }
19968 else if (NumNegativeBits) {
19969 // If there is a negative value, figure out the smallest integer type (of
19970 // int/long/longlong) that fits.
19971 // If it's packed, check also if it fits a char or a short.
19972 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
19973 BestType = Context.SignedCharTy;
19974 BestWidth = CharWidth;
19975 } else if (Packed && NumNegativeBits <= ShortWidth &&
19976 NumPositiveBits < ShortWidth) {
19977 BestType = Context.ShortTy;
19978 BestWidth = ShortWidth;
19979 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
19980 BestType = Context.IntTy;
19981 BestWidth = IntWidth;
19982 } else {
19983 BestWidth = Context.getTargetInfo().getLongWidth();
19984
19985 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
19986 BestType = Context.LongTy;
19987 } else {
19988 BestWidth = Context.getTargetInfo().getLongLongWidth();
19989
19990 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
19991 Diag(Enum->getLocation(), diag::ext_enum_too_large);
19992 BestType = Context.LongLongTy;
19993 }
19994 }
19995 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
19996 } else {
19997 // If there is no negative value, figure out the smallest type that fits
19998 // all of the enumerator values.
19999 // If it's packed, check also if it fits a char or a short.
20000 if (Packed && NumPositiveBits <= CharWidth) {
20001 BestType = Context.UnsignedCharTy;
20002 BestPromotionType = Context.IntTy;
20003 BestWidth = CharWidth;
20004 } else if (Packed && NumPositiveBits <= ShortWidth) {
20005 BestType = Context.UnsignedShortTy;
20006 BestPromotionType = Context.IntTy;
20007 BestWidth = ShortWidth;
20008 } else if (NumPositiveBits <= IntWidth) {
20009 BestType = Context.UnsignedIntTy;
20010 BestWidth = IntWidth;
20011 BestPromotionType
20012 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20014 } else if (NumPositiveBits <=
20015 (BestWidth = Context.getTargetInfo().getLongWidth())) {
20016 BestType = Context.UnsignedLongTy;
20017 BestPromotionType
20018 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20020 } else {
20021 BestWidth = Context.getTargetInfo().getLongLongWidth();
20022 if (NumPositiveBits > BestWidth) {
20023 // This can happen with bit-precise integer types, but those are not
20024 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
20025 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
20026 // a 128-bit integer, we should consider doing the same.
20027 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20028 }
20029 BestType = Context.UnsignedLongLongTy;
20030 BestPromotionType
20031 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20033 }
20034 }
20035
20036 // Loop over all of the enumerator constants, changing their types to match
20037 // the type of the enum if needed.
20038 for (auto *D : Elements) {
20039 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20040 if (!ECD) continue; // Already issued a diagnostic.
20041
20042 // Standard C says the enumerators have int type, but we allow, as an
20043 // extension, the enumerators to be larger than int size. If each
20044 // enumerator value fits in an int, type it as an int, otherwise type it the
20045 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20046 // that X has type 'int', not 'unsigned'.
20047
20048 // Determine whether the value fits into an int.
20049 llvm::APSInt InitVal = ECD->getInitVal();
20050
20051 // If it fits into an integer type, force it. Otherwise force it to match
20052 // the enum decl type.
20053 QualType NewTy;
20054 unsigned NewWidth;
20055 bool NewSign;
20056 if (!getLangOpts().CPlusPlus &&
20057 !Enum->isFixed() &&
20059 NewTy = Context.IntTy;
20060 NewWidth = IntWidth;
20061 NewSign = true;
20062 } else if (ECD->getType() == BestType) {
20063 // Already the right type!
20064 if (getLangOpts().CPlusPlus)
20065 // C++ [dcl.enum]p4: Following the closing brace of an
20066 // enum-specifier, each enumerator has the type of its
20067 // enumeration.
20068 ECD->setType(EnumType);
20069 continue;
20070 } else {
20071 NewTy = BestType;
20072 NewWidth = BestWidth;
20073 NewSign = BestType->isSignedIntegerOrEnumerationType();
20074 }
20075
20076 // Adjust the APSInt value.
20077 InitVal = InitVal.extOrTrunc(NewWidth);
20078 InitVal.setIsSigned(NewSign);
20079 ECD->setInitVal(Context, InitVal);
20080
20081 // Adjust the Expr initializer and type.
20082 if (ECD->getInitExpr() &&
20083 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20084 ECD->setInitExpr(ImplicitCastExpr::Create(
20085 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20086 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20087 if (getLangOpts().CPlusPlus)
20088 // C++ [dcl.enum]p4: Following the closing brace of an
20089 // enum-specifier, each enumerator has the type of its
20090 // enumeration.
20091 ECD->setType(EnumType);
20092 else
20093 ECD->setType(NewTy);
20094 }
20095
20096 Enum->completeDefinition(BestType, BestPromotionType,
20097 NumPositiveBits, NumNegativeBits);
20098
20099 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20100
20101 if (Enum->isClosedFlag()) {
20102 for (Decl *D : Elements) {
20103 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20104 if (!ECD) continue; // Already issued a diagnostic.
20105
20106 llvm::APSInt InitVal = ECD->getInitVal();
20107 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20108 !IsValueInFlagEnum(Enum, InitVal, true))
20109 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20110 << ECD << Enum;
20111 }
20112 }
20113
20114 // Now that the enum type is defined, ensure it's not been underaligned.
20115 if (Enum->hasAttrs())
20117}
20118
20120 SourceLocation StartLoc,
20121 SourceLocation EndLoc) {
20122 StringLiteral *AsmString = cast<StringLiteral>(expr);
20123
20125 AsmString, StartLoc,
20126 EndLoc);
20127 CurContext->addDecl(New);
20128 return New;
20129}
20130
20132 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20133 CurContext->addDecl(New);
20134 PushDeclContext(S, New);
20136 PushCompoundScope(false);
20137 return New;
20138}
20139
20141 D->setStmt(Statement);
20145}
20146
20148 IdentifierInfo* AliasName,
20149 SourceLocation PragmaLoc,
20150 SourceLocation NameLoc,
20151 SourceLocation AliasNameLoc) {
20152 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20154 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20156 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20157 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20158
20159 // If a declaration that:
20160 // 1) declares a function or a variable
20161 // 2) has external linkage
20162 // already exists, add a label attribute to it.
20163 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20164 if (isDeclExternC(PrevDecl))
20165 PrevDecl->addAttr(Attr);
20166 else
20167 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20168 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20169 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20170 } else
20171 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20172}
20173
20175 SourceLocation PragmaLoc,
20176 SourceLocation NameLoc) {
20177 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20178
20179 if (PrevDecl) {
20180 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20181 } else {
20182 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20183 }
20184}
20185
20187 IdentifierInfo* AliasName,
20188 SourceLocation PragmaLoc,
20189 SourceLocation NameLoc,
20190 SourceLocation AliasNameLoc) {
20191 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20193 WeakInfo W = WeakInfo(Name, NameLoc);
20194
20195 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20196 if (!PrevDecl->hasAttr<AliasAttr>())
20197 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20199 } else {
20200 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20201 }
20202}
20203
20205 bool Final) {
20206 assert(FD && "Expected non-null FunctionDecl");
20207
20208 // SYCL functions can be template, so we check if they have appropriate
20209 // attribute prior to checking if it is a template.
20210 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20212
20213 // Templates are emitted when they're instantiated.
20214 if (FD->isDependentContext())
20216
20217 // Check whether this function is an externally visible definition.
20218 auto IsEmittedForExternalSymbol = [this, FD]() {
20219 // We have to check the GVA linkage of the function's *definition* -- if we
20220 // only have a declaration, we don't know whether or not the function will
20221 // be emitted, because (say) the definition could include "inline".
20222 const FunctionDecl *Def = FD->getDefinition();
20223
20224 // We can't compute linkage when we skip function bodies.
20225 return Def && !Def->hasSkippedBody() &&
20227 getASTContext().GetGVALinkageForFunction(Def));
20228 };
20229
20230 if (LangOpts.OpenMPIsTargetDevice) {
20231 // In OpenMP device mode we will not emit host only functions, or functions
20232 // we don't need due to their linkage.
20233 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20234 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20235 // DevTy may be changed later by
20236 // #pragma omp declare target to(*) device_type(*).
20237 // Therefore DevTy having no value does not imply host. The emission status
20238 // will be checked again at the end of compilation unit with Final = true.
20239 if (DevTy)
20240 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20242 // If we have an explicit value for the device type, or we are in a target
20243 // declare context, we need to emit all extern and used symbols.
20244 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20245 if (IsEmittedForExternalSymbol())
20247 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20248 // we'll omit it.
20249 if (Final)
20251 } else if (LangOpts.OpenMP > 45) {
20252 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20253 // function. In 5.0, no_host was introduced which might cause a function to
20254 // be omitted.
20255 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20256 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20257 if (DevTy)
20258 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20260 }
20261
20262 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20264
20265 if (LangOpts.CUDA) {
20266 // When compiling for device, host functions are never emitted. Similarly,
20267 // when compiling for host, device and global functions are never emitted.
20268 // (Technically, we do emit a host-side stub for global functions, but this
20269 // doesn't count for our purposes here.)
20271 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20273 if (!LangOpts.CUDAIsDevice &&
20276
20277 if (IsEmittedForExternalSymbol())
20279 }
20280
20281 // Otherwise, the function is known-emitted if it's in our set of
20282 // known-emitted functions.
20284}
20285
20287 // Host-side references to a __global__ function refer to the stub, so the
20288 // function itself is never emitted and therefore should not be marked.
20289 // If we have host fn calls kernel fn calls host+device, the HD function
20290 // does not get instantiated on the host. We model this by omitting at the
20291 // call to the kernel from the callgraph. This ensures that, when compiling
20292 // for host, only HD functions actually called from the host get marked as
20293 // known-emitted.
20294 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20296}
20297
20299 const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc,
20300 SourceLocation OldLoc) {
20301 for (const FunctionEffectSet::Conflict &Conflict : Errs) {
20302 Diag(NewLoc, diag::warn_conflicting_func_effects)
20303 << Conflict.Kept.description() << Conflict.Rejected.description();
20304 Diag(OldLoc, diag::note_previous_declaration);
20305 }
20306}
20307
20309 const FunctionEffectsRef &FX, const FunctionEffectWithCondition &NewEC,
20310 SourceLocation NewAttrLoc) {
20311 // If the new effect has a condition, we can't detect conflicts until the
20312 // condition is resolved.
20313 if (NewEC.Cond.getCondition() != nullptr)
20314 return false;
20315
20316 // Diagnose the new attribute as incompatible with a previous one.
20317 auto Incompatible = [&](const FunctionEffectWithCondition &PrevEC) {
20318 Diag(NewAttrLoc, diag::err_attributes_are_not_compatible)
20319 << ("'" + NewEC.description() + "'")
20320 << ("'" + PrevEC.description() + "'") << false;
20321 // We don't necessarily have the location of the previous attribute,
20322 // so no note.
20323 return true;
20324 };
20325
20326 // Compare against previous attributes.
20327 FunctionEffect::Kind NewKind = NewEC.Effect.kind();
20328
20329 for (const FunctionEffectWithCondition &PrevEC : FX) {
20330 // Again, can't check yet when the effect is conditional.
20331 if (PrevEC.Cond.getCondition() != nullptr)
20332 continue;
20333
20334 FunctionEffect::Kind PrevKind = PrevEC.Effect.kind();
20335 // Note that we allow PrevKind == NewKind; it's redundant and ignored.
20336
20337 if (PrevEC.Effect.oppositeKind() == NewKind)
20338 return Incompatible(PrevEC);
20339
20340 // A new allocating is incompatible with a previous nonblocking.
20341 if (PrevKind == FunctionEffect::Kind::NonBlocking &&
20343 return Incompatible(PrevEC);
20344
20345 // A new nonblocking is incompatible with a previous allocating.
20346 if (PrevKind == FunctionEffect::Kind::Allocating &&
20348 return Incompatible(PrevEC);
20349 }
20350
20351 return false;
20352}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
#define SM(sm)
Definition: Cuda.cpp:83
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
const Decl * D
IndirectLocalPath & Path
enum clang::sema::@1653::IndirectLocalPathEntry::EntryKind Kind
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
static bool isDeclExternC(const T &D)
Definition: Decl.cpp:2211
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines helper utilities for supporting the HLSL runtime environment.
unsigned Iter
Definition: HTMLLogger.cpp:154
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:58
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.
Definition: Redeclaration.h:18
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
uint32_t Id
Definition: SemaARM.cpp:1144
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:15764
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6811
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:153
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15279
static bool isMainVar(DeclarationName Name, VarDecl *VD)
Definition: SemaDecl.cpp:7369
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:11296
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:208
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:3329
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
Definition: SemaDecl.cpp:3496
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:795
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:6509
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
Definition: SemaDecl.cpp:1470
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...
Definition: SemaDecl.cpp:6547
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:2269
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:9119
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
Definition: SemaDecl.cpp:3443
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2783
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
Definition: SemaDecl.cpp:8126
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:9468
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
Definition: SemaDecl.cpp:3227
void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
Definition: SemaDecl.cpp:7341
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
Definition: SemaDecl.cpp:8494
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
Definition: SemaDecl.cpp:11700
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...
Definition: SemaDecl.cpp:2672
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:4431
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
Definition: SemaDecl.cpp:11790
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15263
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
Definition: SemaDecl.cpp:11416
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:2036
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
Definition: SemaDecl.cpp:14911
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:561
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
Definition: SemaDecl.cpp:11305
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...
Definition: SemaDecl.cpp:7110
static bool isRepresentableIntegerValue(ASTContext &Context, llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
Definition: SemaDecl.cpp:19373
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:19737
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
Definition: SemaDecl.cpp:4975
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
Definition: SemaDecl.cpp:2911
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
Definition: SemaDecl.cpp:16795
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:3478
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6858
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
Definition: SemaDecl.cpp:5911
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
Definition: SemaDecl.cpp:4845
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:9155
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...
Definition: SemaDecl.cpp:9651
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
Definition: SemaDecl.cpp:15793
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:3385
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:8463
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2641
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
Definition: SemaDecl.cpp:9340
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
Definition: SemaDecl.cpp:3026
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:8151
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 ...
Definition: SemaDecl.cpp:16955
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...
Definition: SemaDecl.cpp:5262
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...
Definition: SemaDecl.cpp:8380
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
Definition: SemaDecl.cpp:1912
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
Definition: SemaDecl.cpp:9662
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 ...
Definition: SemaDecl.cpp:5338
OpenCLParamType
Definition: SemaDecl.cpp:9331
@ InvalidAddrSpacePtrKernelParam
Definition: SemaDecl.cpp:9335
@ ValidKernelParam
Definition: SemaDecl.cpp:9332
@ InvalidKernelParam
Definition: SemaDecl.cpp:9336
@ RecordKernelParam
Definition: SemaDecl.cpp:9337
@ PtrKernelParam
Definition: SemaDecl.cpp:9334
@ PtrPtrKernelParam
Definition: SemaDecl.cpp:9333
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
Definition: SemaDecl.cpp:6020
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:
Definition: SemaDecl.cpp:18727
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:581
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...
Definition: SemaDecl.cpp:18661
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:7155
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:5422
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11221
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
Definition: SemaDecl.cpp:9642
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
Definition: SemaDecl.cpp:3290
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:3422
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:16779
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
Definition: SemaDecl.cpp:2163
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:4328
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
Definition: SemaDecl.cpp:8967
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
Definition: SemaDecl.cpp:5946
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:
Definition: SemaDecl.cpp:18754
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:810
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
Definition: SemaDecl.cpp:7182
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:8115
@ SDK_StructuredBinding
Definition: SemaDecl.cpp:8122
@ SDK_Field
Definition: SemaDecl.cpp:8119
@ SDK_Global
Definition: SemaDecl.cpp:8117
@ SDK_Local
Definition: SemaDecl.cpp:8116
@ SDK_Typedef
Definition: SemaDecl.cpp:8120
@ SDK_StaticMember
Definition: SemaDecl.cpp:8118
@ SDK_Using
Definition: SemaDecl.cpp:8121
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4791
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:3406
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:9362
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:5436
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
Definition: SemaDecl.cpp:12404
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
Definition: SemaDecl.cpp:7233
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
Definition: SemaDecl.cpp:1781
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
Definition: SemaDecl.cpp:18820
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11034
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
Definition: SemaDecl.cpp:1770
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2885
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...
Definition: SemaDecl.cpp:6431
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:14719
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
Definition: SemaDecl.cpp:7329
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:5893
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1823
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
Definition: SemaDecl.cpp:10984
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
Definition: SemaDecl.cpp:6772
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:5401
static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T, SourceLocation NameLoc, bool WantNontrivialTypeSourceInfo=true)
Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
Definition: SemaDecl.cpp:250
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...
Definition: SemaDecl.cpp:11447
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const VarDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
Definition: SemaDecl.cpp:8142
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
Definition: SemaDecl.cpp:11267
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:6961
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11052
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...
Definition: SemaDecl.cpp:2396
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:19701
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:19390
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:7141
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2660
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
Definition: SemaDecl.cpp:10891
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Definition: SemaDecl.cpp:11319
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1797
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...
Definition: SemaDecl.cpp:16992
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
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 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)
Definition: SourceCode.cpp:152
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
const NestedNameSpecifier * Specifier
StateNode * Previous
std::string Label
__device__ int
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
Definition: SemaDecl.cpp:15751
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:15753
llvm::APInt getValue() const
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:73
virtual void HandleInlineFunctionDefinition(FunctionDecl *D)
This callback is invoked each time an inline (method or friend) function definition in a class is com...
Definition: ASTConsumer.h:58
virtual bool shouldSkipFunctionBody(Decl *D)
This callback is called for each function if the Parser was initialized with SkipFunctionBodies set t...
Definition: ASTConsumer.h:146
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:113
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
SourceManager & getSourceManager()
Definition: ASTContext.h:721
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2825
QualType getParenType(QualType NamedType) const
CanQualType LongTy
Definition: ASTContext.h:1128
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
ExternCContextDecl * getExternCContextDecl() const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:664
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2139
QualType getRecordType(const RecordDecl *Decl) const
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
void setObjCIdRedefinitionType(QualType RedefType)
Set the user-written type that redefines id.
Definition: ASTContext.h:1925
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2628
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2644
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:2029
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
void setObjCSelRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1951
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:2007
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2831
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
CanQualType DependentTy
Definition: ASTContext.h:1147
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1637
IdentifierTable & Idents
Definition: ASTContext.h:660
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:662
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:797
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:498
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2127
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:2041
CanQualType UnsignedLongTy
Definition: ASTContext.h:1129
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:2924
CanQualType CharTy
Definition: ASTContext.h:1121
CanQualType IntTy
Definition: ASTContext.h:1128
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2210
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType SignedCharTy
Definition: ASTContext.h:1128
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
void setNonKeyFunction(const CXXMethodDecl *method)
Observe that the given method cannot be a key function.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2117
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2675
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2394
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
CanQualType VoidTy
Definition: ASTContext.h:1119
CanQualType UnsignedCharTy
Definition: ASTContext.h:1129
CanQualType UnsignedIntTy
Definition: ASTContext.h:1129
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
CanQualType UnknownAnyTy
Definition: ASTContext.h:1148
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1130
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1129
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1615
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1467
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2828
CanQualType ShortTy
Definition: ASTContext.h:1128
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1938
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2233
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:2017
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
Definition: ASTContext.h:1128
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
Definition: ASTContext.h:2296
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2302
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2299
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2308
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2305
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2425
The result of parsing/analyzing an expression, statement etc.
Definition: Ownership.h:153
bool isUnset() const
Definition: Ownership.h:167
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3346
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1563
Expr * getSizeExpr() const
Definition: TypeLoc.h:1583
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1591
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1571
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3566
QualType getElementType() const
Definition: Type.h:3578
Attr - This represents one attribute.
Definition: Attr.h:42
attr::Kind getKind() const
Definition: Attr.h:88
bool isInherited() const
Definition: Attr.h:97
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition: Attr.h:102
SourceLocation getLocation() const
Definition: Attr.h:95
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:639
AttributeFactory & getFactory() const
Definition: ParsedAttr.h:735
Type source information for an attributed type.
Definition: TypeLoc.h:875
const T * getAttrAs()
Definition: TypeLoc.h:905
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:889
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:6020
QualType getModifiedType() const
Definition: Type.h:6042
bool isCallingConv() const
Definition: Type.cpp:4147
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:6075
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6375
AutoTypeKeyword getKeyword() const
Definition: Type.h:6406
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4275
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
A binding in a decomposition declaration.
Definition: DeclCXX.h:4111
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4471
bool doesNotEscape() const
Definition: Decl.h:4622
This class is used for builtin types like 'int'.
Definition: Type.h:3023
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
bool performsCallback(unsigned ID, llvm::SmallVectorImpl< int > &Encoding) const
Determine whether this builtin has callback behavior (see llvm::AbstractCallSites for details).
Definition: Builtins.cpp:215
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:262
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:222
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
bool isReturnsTwice(unsigned ID) const
Return true if we know this builtin can return twice.
Definition: Builtins.h:137
bool isImmediate(unsigned ID) const
Returns true if this is an immediate (consteval) function.
Definition: Builtins.h:284
bool isConstWithoutErrnoAndExceptions(unsigned ID) const
Return true if this function has no side effects and doesn't read memory, except for possibly errno o...
Definition: Builtins.h:247
bool allowTypeMismatch(unsigned ID) const
Determines whether a declaration of this builtin should be recognized even if the type doesn't match ...
Definition: Builtins.h:202
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:111
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition: Builtins.h:167
bool isScanfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like scanf in its formatting rules and, if so, set the index to the...
Definition: Builtins.cpp:210
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:182
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:160
bool isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like printf in its formatting rules and, if so, set the index to th...
Definition: Builtins.cpp:205
bool isConstWithoutExceptions(unsigned ID) const
Definition: Builtins.h:251
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache",...
Definition: Builtins.h:174
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition: Builtins.h:116
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:127
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition: Builtins.h:122
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
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2539
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(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2761
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2866
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, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2928
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)
Definition: DeclCXX.cpp:2195
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2803
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2895
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:2064
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:2493
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2547
bool isVirtual() const
Definition: DeclCXX.h:2119
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2614
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2190
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2526
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, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2312
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2225
bool isConst() const
Definition: DeclCXX.h:2116
bool isStatic() const
Definition: DeclCXX.cpp:2224
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2504
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2160
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition: DeclCXX.h:1339
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1245
base_class_iterator bases_end()
Definition: DeclCXX.h:629
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1371
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1552
base_class_range bases()
Definition: DeclCXX.h:620
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1381
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1969
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:627
capture_const_range captures() const
Definition: DeclCXX.h:1102
bool hasDefinition() const
Definition: DeclCXX.h:572
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1936
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1064
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1940
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1293
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:236
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
static CharSourceRange getCharRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Declaration of a class template.
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4213
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:178
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:218
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3660
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
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)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2370
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2219
bool isFileContext() const
Definition: DeclBase.h:2161
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2043
bool isObjCContainer() const
Definition: DeclBase.h:2129
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1399
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
bool isClosure() const
Definition: DeclBase.h:2123
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2106
bool isNamespace() const
Definition: DeclBase.h:2179
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1852
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1300
bool isTranslationUnit() const
Definition: DeclBase.h:2166
bool isRecord() const
Definition: DeclBase.h:2170
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1988
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1685
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1766
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1635
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2006
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1423
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2350
bool isFunctionOrMethod() const
Definition: DeclBase.h:2142
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1284
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1384
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1403
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2083
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1414
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:68
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
ValueDecl * getDecl()
Definition: Expr.h:1333
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool isVirtualSpecified() const
Definition: DeclSpec.h:648
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:829
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:309
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:595
static const TST TST_typename
Definition: DeclSpec.h:306
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:648
bool isNoreturnSpecified() const
Definition: DeclSpec.h:661
TST getTypeSpecType() const
Definition: DeclSpec.h:537
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:510
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:863
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:575
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:574
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:709
static const TST TST_interface
Definition: DeclSpec.h:304
static const TST TST_typeofExpr
Definition: DeclSpec.h:308
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:616
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:708
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:662
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:505
static const TST TST_union
Definition: DeclSpec.h:302
SCS
storage-class-specifier
Definition: DeclSpec.h:251
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:654
static const TST TST_int
Definition: DeclSpec.h:285
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:830
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1504
ParsedType getRepAsType() const
Definition: DeclSpec.h:547
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:788
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:502
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:873
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:626
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:617
Expr * getRepAsExpr() const
Definition: DeclSpec.h:555
static const TST TST_enum
Definition: DeclSpec.h:301
static const TST TST_decltype
Definition: DeclSpec.h:311
static bool isDeclRep(TST T)
Definition: DeclSpec.h:469
bool isInlineSpecified() const
Definition: DeclSpec.h:637
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:618
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:310
static const TST TST_class
Definition: DeclSpec.h:305
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:561
static const TST TST_atomic
Definition: DeclSpec.h:321
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:511
Decl * getRepAsDecl() const
Definition: DeclSpec.h:551
static const TST TST_unspecified
Definition: DeclSpec.h:278
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:620
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:649
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:836
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:582
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:792
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:267
static const TST TST_error
Definition: DeclSpec.h:328
bool isTypeSpecOwned() const
Definition: DeclSpec.h:541
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:640
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:621
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:619
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:821
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:651
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:837
static const TST TST_typeofType
Definition: DeclSpec.h:307
static const TST TST_auto
Definition: DeclSpec.h:318
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:832
static const TST TST_struct
Definition: DeclSpec.h:303
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:1051
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1066
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:317
bool isInStdNamespace() const
Definition: DeclBase.cpp:425
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:442
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
T * getAttr() const
Definition: DeclBase.h:580
bool hasAttrs() const
Definition: DeclBase.h:525
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
void addAttr(Attr *A)
Definition: DeclBase.cpp:1013
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:600
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:527
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:765
bool isInNamedModule() const
Whether this declaration comes from a named module.
Definition: DeclBase.cpp:1167
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1141
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:639
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:883
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1209
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
@ FOK_Declared
A friend of a previously-declared entity.
Definition: DeclBase.h:1208
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:284
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1112
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:577
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:836
bool isFromExplicitGlobalModule() const
Whether this declaration comes from explicit global module.
Definition: DeclBase.cpp:1159
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:249
void dropAttrs()
Definition: DeclBase.cpp:1006
@ 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:1170
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2767
bool isInvalidDecl() const
Definition: DeclBase.h:595
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1159
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:566
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:509
SourceLocation getLocation() const
Definition: DeclBase.h:446
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:823
void setImplicit(bool I=true)
Definition: DeclBase.h:601
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:615
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:552
DeclContext * getDeclContext()
Definition: DeclBase.h:455
attr_range attrs() const
Definition: DeclBase.h:542
AccessSpecifier getAccess() const
Definition: DeclBase.h:514
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:438
void dropAttr()
Definition: DeclBase.h:563
AttrVec & getAttrs()
Definition: DeclBase.h:531
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:358
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1624
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:584
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1225
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:362
Kind getKind() const
Definition: DeclBase.h:449
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:434
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
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:731
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:789
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:774
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2032
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2072
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1970
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:819
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:766
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1982
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:807
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:760
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2016
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2401
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2050
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2686
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2342
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2397
const ParsedAttributesView & getDeclarationAttributes() const
Definition: DeclSpec.h:2689
A decomposition declaration.
Definition: DeclCXX.h:4170
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3375
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1792
SourceRange getSourceRange() const
Definition: DeclSpec.h:1839
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1837
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6341
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:6362
bool isDeduced() const
Definition: Type.h:6363
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:931
Expr * getCondition() const
Definition: Type.h:4810
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3274
llvm::APSInt getInitVal() const
Definition: Decl.h:3294
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5452
const Expr * getInitExpr() const
Definition: Decl.h:3292
Represents an enum.
Definition: Decl.h:3844
enumerator_range enumerators() const
Definition: Decl.h:3977
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4049
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:4013
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:4016
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4063
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4851
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4896
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4058
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4871
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:3999
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4004
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5991
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1901
This represents one expression.
Definition: Expr.h:110
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:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3070
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3066
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3050
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:947
void applyChanges(FPOptionsOverride FPO)
Definition: LangOptions.h:1060
bool isFPConstrained() const
Definition: LangOptions.h:875
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
Definition: LangOptions.h:1054
Represents a member of a struct/union/class.
Definition: Decl.h:3030
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3121
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4546
bool isZeroLengthBitField(const ASTContext &Ctx) const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition: Decl.cpp:4583
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3247
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:4531
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5585
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
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:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
Represents a function declaration or definition.
Definition: Decl.h:1932
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2562
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2401
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4040
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3589
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4033
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4028
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3243
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2246
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2574
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2553
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3859
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3618
param_iterator param_end()
Definition: Decl.h:2659
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2793
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2568
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3562
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2314
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2302
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3474
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4148
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2373
void setWillHaveBody(bool V=true)
Definition: Decl.h:2559
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2368
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4158
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3603
param_iterator param_begin()
Definition: Decl.h:2658
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2695
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3077
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2465
FunctionEffectsRef getFunctionEffects() const
Definition: Decl.h:3006
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3300
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4092
@ TK_MemberSpecialization
Definition: Decl.h:1944
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2760
bool isStatic() const
Definition: Decl.h:2801
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4358
void setTrivial(bool IT)
Definition: Decl.h:2303
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3979
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2395
bool isDeletedAsWritten() const
Definition: Decl.h:2469
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition: Decl.h:2390
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2285
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3478
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2289
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2353
bool isImmediateEscalating() const
Definition: Decl.cpp:3256
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2281
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2552
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2214
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3294
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2788
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3352
bool param_empty() const
Definition: Decl.h:2657
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, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2121
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3168
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2150
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3558
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2310
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2346
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4381
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2805
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:3973
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3965
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2398
void setDefaulted(bool D=true)
Definition: Decl.h:2311
bool isConsteval() const
Definition: Decl.h:2407
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:2734
void setBody(Stmt *B)
Definition: Decl.cpp:3236
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3492
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3114
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition: Decl.h:2384
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4000
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3678
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2143
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3144
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2360
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:3191
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2771
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3544
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2558
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4939
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5289
Kind kind() const
The kind of the effect.
Definition: Type.h:4743
Kind
Identifies the particular effect.
Definition: Type.h:4706
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4882
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
unsigned getNumParams() const
Definition: Type.h:5255
QualType getParamType(unsigned i) const
Definition: Type.h:5257
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:5461
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5288
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5379
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5266
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5262
ArrayRef< QualType > param_types() const
Definition: Type.h:5411
Declaration of a template function.
Definition: DeclTemplate.h:957
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,...
Definition: DeclTemplate.h:536
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4419
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4534
CallingConv getCC() const
Definition: Type.h:4481
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4500
unsigned getRegParm() const
Definition: Type.h:4474
bool getNoCallerSavedRegs() const
Definition: Type.h:4470
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4493
bool getHasRegParm() const
Definition: Type.h:4472
bool getNoReturn() const
Definition: Type.h:4467
bool getProducesResult() const
Definition: Type.h:4468
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:4514
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:4528
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4308
ExtInfo getExtInfo() const
Definition: Type.h:4642
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3492
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4600
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4596
unsigned getRegParmType() const
Definition: Type.h:4633
CallingConv getCallConv() const
Definition: Type.h:4641
QualType getReturnType() const
Definition: Type.h:4630
bool getCmseNSCallAttr() const
Definition: Type.h:4640
@ SME_PStateSMEnabledMask
Definition: Type.h:4574
@ SME_PStateSMCompatibleMask
Definition: Type.h:4575
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.
bool isPlaceholder() const
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
iterator begin(DeclarationName Name)
Returns an iterator over decls with the name 'Name'.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
void InsertDeclAfter(iterator Pos, NamedDecl *D)
Insert the given declaration after the given iterator position.
iterator end()
Returns the end iterator.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
bool isDeclInScope(Decl *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',...
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3675
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
Represents a C array with an unspecified size.
Definition: Type.h:3751
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3318
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5480
void setInherited(bool I)
Definition: Attr.h:154
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2510
Describes an C or C++ initializer list.
Definition: Expr.h:5039
child_range children()
Definition: Expr.h:5231
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...
Describes the sequence of initializations required to initialize a given object or reference with a s...
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.
Definition: SemaInit.cpp:7521
@ 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:977
Represents the declaration of a label.
Definition: Decl.h:499
bool isResolvedMSAsmLabel() const
Definition: Decl.h:534
LabelStmt * getStmt() const
Definition: Decl.h:523
bool isMSAsmLabel() const
Definition: Decl.h:533
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:278
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:476
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:649
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:785
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:690
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:511
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
Definition: LangOptions.cpp:79
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
Definition: LangOptions.h:568
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
Definition: LangOptions.h:696
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:550
void push_back(const T &LocalValue)
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:1358
Represents a linkage specification.
Definition: DeclCXX.h:2938
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2958
void InstantiatedLocal(const Decl *D, Decl *Inst)
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
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:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
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:670
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition: Lookup.h:146
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.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3508
Describes a module or submodule.
Definition: Module.h:105
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:111
Module * Parent
The parent of this module.
Definition: Module.h:154
bool isPrivateModule() const
Definition: Module.h:210
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition: Module.h:592
bool isModuleImplementation() const
Is this a module implementation.
Definition: Module.h:608
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:597
bool isImplicitGlobalModule() const
Definition: Module.h:206
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:244
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:185
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:666
@ ClassId_NSObject
Definition: NSAPI.h:30
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Decl.cpp:1079
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition: Decl.h:454
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:404
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:700
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1912
bool isExternallyVisible() const
Definition: Decl.h:408
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:372
Represent a C++ namespace.
Definition: Decl.h:547
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:598
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.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
SourceRange getLocalSourceRange() const
Retrieve the source range covering just the last part of this nested-name-specifier,...
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool containsErrors() const
Whether this nested name specifier contains an error.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2328
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2774
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition: DeclObjC.cpp:81
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2596
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1761
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
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)
Definition: DeclObjC.cpp:1833
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
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
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:97
Wrapper for void* pointer.
Definition: Ownership.h:50
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(PtrTy P)
Definition: Ownership.h:60
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
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:1008
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
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.
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
MapType::iterator iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
Expr ** getExprs()
Definition: Expr.h:5856
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5845
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1203
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1216
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1199
Sugar for parentheses used when specifying types.
Definition: Type.h:3161
Represents a parameter to a function.
Definition: Decl.h:1722
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1782
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1786
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1755
QualType getOriginalType() const
Definition: Decl.cpp:2912
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:2903
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:838
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:918
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:958
AttributePool & getPool() const
Definition: ParsedAttr.h:965
PipeType - OpenCL20.
Definition: Type.h:7599
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1282
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1307
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3187
QualType getPointeeType() const
Definition: Type.h:3197
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
HeaderSearch & getHeaderSearchInfo() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
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: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7834
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7828
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:7897
@ DK_nontrivial_c_struct
Definition: Type.h:1535
PrimitiveDefaultInitializeKind
Definition: Type.h:1463
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2822
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:75
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1221
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1303
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
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:2870
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7750
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7876
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:7891
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7790
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
QualType getCanonicalType() const
Definition: Type.h:7802
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7844
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition: Type.cpp:2854
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1439
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7823
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1542
bool isCanonical() const
Definition: Type.h:7807
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1316
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1339
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1448
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2596
NonConstantStorageReason
Definition: Type.h:1025
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: Type.h:1493
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: Type.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:7885
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7690
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7697
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4356
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:341
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:337
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:351
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:354
bool hasConst() const
Definition: Type.h:444
void removeConst()
Definition: Type.h:446
void addConst()
Definition: Type.h:447
ObjCLifetime getObjCLifetime() const
Definition: Type.h:532
bool empty() const
Definition: Type.h:634
Represents a struct/union/class.
Definition: Decl.h:4145
bool hasObjectMember() const
Definition: Decl.h:4205
field_range fields() const
Definition: Decl.h:4351
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5014
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5034
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5080
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4336
field_iterator field_begin() const
Definition: Decl.cpp:5068
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5965
RecordDecl * getDecl() const
Definition: Type.h:5975
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:7101
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:865
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:217
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:205
redecl_iterator redecls_end() const
Definition: Redeclarable.h:304
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:227
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4978
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:224
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:297
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3428
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3029
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:3077
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition: Scope.h:381
void RemoveDecl(Decl *D)
Definition: Scope.h:353
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:384
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:581
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:270
@ 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
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
void checkAllowedInitializer(VarDecl *VD)
Definition: SemaCUDA.cpp:658
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
Definition: SemaCUDA.cpp:1070
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
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:740
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
Definition: SemaCUDA.cpp:1005
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition: SemaCUDA.cpp:805
void CheckEntryPoint(FunctionDecl *FD)
Definition: SemaHLSL.cpp:214
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition: SemaHLSL.cpp:133
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition: SemaHLSL.cpp:181
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition: SemaHLSL.cpp:148
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.
Definition: SemaObjC.cpp:1161
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,...
Definition: SemaObjC.cpp:1447
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:601
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)
Definition: SemaRISCV.cpp:1380
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition: SemaSwift.cpp:26
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition: SemaWasm.cpp:266
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition: SemaWasm.cpp:245
bool IsAlignAttr() const
Definition: Sema.h:1552
Mode getAlignMode() const
Definition: Sema.h:1554
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3023
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:1038
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:1050
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition: Sema.h:3267
static NameClassification VarTemplate(TemplateName Name)
Definition: Sema.h:3277
static NameClassification Unknown()
Definition: Sema.h:3247
static NameClassification OverloadSet(ExprResult E)
Definition: Sema.h:3251
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition: Sema.h:3295
static NameClassification FunctionTemplate(TemplateName Name)
Definition: Sema.h:3283
static NameClassification NonType(NamedDecl *D)
Definition: Sema.h:3257
static NameClassification Concept(TemplateName Name)
Definition: Sema.h:3289
static NameClassification UndeclaredNonType()
Definition: Sema.h:3263
static NameClassification TypeTemplate(TemplateName Name)
Definition: Sema.h:3271
static NameClassification Error()
Definition: Sema.h:3245
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12099
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12129
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:14176
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.
Definition: SemaDecl.cpp:10917
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6329
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition: Sema.h:3115
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6666
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12656
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:763
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...
Definition: SemaDecl.cpp:2468
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
Definition: SemaType.cpp:8921
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
Definition: SemaDecl.cpp:6586
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9689
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',...
Definition: SemaDecl.cpp:1558
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.
Definition: SemaDecl.cpp:15054
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:7873
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:5845
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:9011
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9015
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:9034
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:9050
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:9047
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9023
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:9018
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6602
void ActOnPopScope(SourceLocation Loc, Scope *S)
Definition: SemaDecl.cpp:2179
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5295
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15735
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12822
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:37
NonTrivialCUnionContext
Definition: Sema.h:3635
@ NTCUC_CopyInit
Definition: Sema.h:3645
@ NTCUC_AutoVar
Definition: Sema.h:3643
@ NTCUC_DefaultInitializedObject
Definition: Sema.h:3641
@ NTCUC_FunctionReturn
Definition: Sema.h:3639
@ NTCUC_FunctionParam
Definition: Sema.h:3637
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...
Definition: SemaDecl.cpp:3536
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.
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.
Definition: SemaDecl.cpp:6079
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
Definition: SemaLookup.cpp:991
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:18148
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
SemaOpenMP & OpenMP()
Definition: Sema.h:1179
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,...
Definition: SemaDecl.cpp:6064
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:918
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:18080
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition: Sema.h:4336
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:3097
PragmaClangSection PragmaClangRodataSection
Definition: Sema.h:1478
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
Definition: SemaDecl.cpp:16274
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:6042
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:14933
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
Definition: SemaAttr.cpp:1094
SemaCUDA & CUDA()
Definition: Sema.h:1124
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)
Definition: SemaExpr.cpp:17182
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()
Definition: SemaDecl.cpp:1454
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
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:2296
Preprocessor & getPreprocessor() const
Definition: Sema.h:559
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6817
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1709
PragmaStack< StringLiteral * > CodeSegStack
Definition: Sema.h:1703
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
Definition: SemaAttr.cpp:1162
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)
Definition: SemaDecl.cpp:6207
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:16940
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)
Definition: SemaDecl.cpp:4797
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:53
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)
Definition: SemaDecl.cpp:12236
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:16475
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
Definition: SemaDecl.cpp:2098
@ Delete
deleted-function-body
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,...
Definition: SemaDecl.cpp:18167
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.
Definition: SemaDecl.cpp:18263
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)
Definition: SemaDecl.cpp:14549
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.
Definition: SemaDecl.cpp:1430
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15389
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:1567
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3414
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:640
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
Definition: SemaDecl.cpp:1656
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)
Definition: SemaDecl.cpp:20119
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15041
ASTContext & Context
Definition: Sema.h:962
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14569
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5771
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:557
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20140
bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX, const FunctionEffectWithCondition &EC, SourceLocation NewAttrLoc)
Warn and return true if adding an effect to a set would create a conflict.
Definition: SemaDecl.cpp:20308
void * SkippedDefinitionContext
Definition: Sema.h:3960
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:917
SemaObjC & ObjC()
Definition: Sema.h:1164
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
Definition: SemaDecl.cpp:5300
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4907
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:72
@ AllowFold
Definition: Sema.h:7265
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1496
PragmaStack< bool > StrictGuardStackCheckStack
Definition: Sema.h:1706
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:3105
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
Definition: SemaDecl.cpp:2330
ASTContext & getASTContext() const
Definition: Sema.h:560
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)
Definition: SemaDecl.cpp:15807
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.
Definition: SemaDecl.cpp:1712
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.
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17603
PragmaStack< StringLiteral * > ConstSegStack
Definition: Sema.h:1702
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:702
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:664
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3087
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition: SemaAttr.cpp:111
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
Definition: SemaDecl.cpp:4754
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9274
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20286
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:868
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
Definition: SemaDecl.cpp:5453
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1572
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...
Definition: SemaDecl.cpp:16826
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:8954
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:11802
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:7987
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:694
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...
Definition: SemaDecl.cpp:4344
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2184
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.
Definition: SemaDecl.cpp:1246
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:167
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition: Sema.h:4175
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:16725
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition: Sema.h:555
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:84
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2202
void PopCompoundScope()
Definition: Sema.cpp:2334
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:19595
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition: Sema.h:13908
@ UPPC_EnumeratorValue
The enumerator value.
Definition: Sema.h:13911
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13923
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:13917
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13896
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:13935
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition: Sema.h:13920
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:13899
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition: Sema.h:13902
const LangOptions & getLangOpts() const
Definition: Sema.h:553
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:1742
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition: Sema.h:3122
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1387
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.
Definition: SemaDecl.cpp:6562
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.
Definition: SemaDecl.cpp:6596
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1597
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:961
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 ...
Definition: SemaDecl.cpp:8175
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:1984
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
const LangOptions & LangOpts
Definition: Sema.h:960
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2409
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition: Sema.h:14989
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15229
SemaHLSL & HLSL()
Definition: Sema.h:1129
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1829
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11816
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.
Definition: SemaDecl.cpp:18358
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:1479
SemaRISCV & RISCV()
Definition: Sema.h:1194
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
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....
Definition: SemaStmt.cpp:3626
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:205
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.
Definition: SemaExpr.cpp:19813
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:1204
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
Definition: SemaAttr.cpp:1206
PragmaStack< AlignPackInfo > AlignPackStack
Definition: Sema.h:1691
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
Definition: SemaDecl.cpp:15693
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6487
PragmaStack< StringLiteral * > BSSSegStack
Definition: Sema.h:1701
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition: Sema.h:767
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9370
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 CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
Definition: SemaType.cpp:7991
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:859
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...
Definition: SemaDecl.cpp:16801
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1374
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8314
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.
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
Definition: SemaDecl.cpp:12423
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:19621
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:993
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2329
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:14799
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Definition: SemaDecl.cpp:2286
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:2261
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:20174
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:18556
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6484
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1216
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
Definition: SemaDecl.cpp:18038
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)
Definition: SemaInit.cpp:9725
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:8829
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3175
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:14983
StringLiteral * CurInitSeg
Last section used with #pragma init_seg.
Definition: Sema.h:1741
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20204
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:9613
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,...
Definition: SemaDecl.cpp:8849
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:15335
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:18029
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15259
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1097
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:14839
SemaOpenCL & OpenCL()
Definition: Sema.h:1174
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5776
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)
Definition: SemaDecl.cpp:15096
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.
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:7680
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
Definition: SemaDecl.cpp:8355
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1288
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4699
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
Definition: SemaDecl.cpp:15668
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition: Sema.h:3119
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9029
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...
Definition: SemaDecl.cpp:15717
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.
Definition: SemaDecl.cpp:10929
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13490
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3853
@ NTK_Typedef
Definition: Sema.h:3858
@ NTK_NonUnion
Definition: Sema.h:3856
@ NTK_TypeAlias
Definition: Sema.h:3859
@ NTK_NonClass
Definition: Sema.h:3855
@ NTK_NonEnum
Definition: Sema.h:3857
@ NTK_NonStruct
Definition: Sema.h:3854
@ NTK_TemplateTemplateArgument
Definition: Sema.h:3862
@ NTK_TypeAliasTemplate
Definition: Sema.h:3861
@ NTK_Template
Definition: Sema.h:3860
SourceManager & getSourceManager() const
Definition: Sema.h:558
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:3072
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
Definition: SemaDecl.cpp:4269
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:19876
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1339
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.
Definition: SemaDecl.cpp:11095
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:18015
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:1480
@ NTCUK_Destruct
Definition: Sema.h:3665
@ NTCUK_Init
Definition: Sema.h:3664
@ NTCUK_Copy
Definition: Sema.h:3666
PragmaClangSection PragmaClangDataSection
Definition: Sema.h:1477
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20001
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15745
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=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:13795
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.
Definition: SemaDecl.cpp:1227
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname.
Definition: SemaDecl.cpp:20147
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:89
MaybeODRUseExprSet MaybeODRUseExprs
Definition: Sema.h:6297
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:216
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)
Definition: SemaDecl.cpp:20131
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8198
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...
@ CTK_NonError
Definition: Sema.h:9408
@ CTK_ErrorRecovery
Definition: Sema.h:9409
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14205
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14724
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2350
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...
Definition: SemaDecl.cpp:4460
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:6064
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:591
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
@ CCEK_Enumerator
Enumerator value with fixed underlying type.
Definition: Sema.h:10025
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
Definition: SemaDecl.cpp:18619
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3078
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
Definition: SemaDecl.cpp:1892
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition: Sema.h:3093
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:288
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:19414
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12458
ASTConsumer & Consumer
Definition: Sema.h:963
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4238
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:9812
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:9804
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:9808
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:6491
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2049
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:998
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1690
@ FirstDecl
Parsing the first decl in a TU.
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....
Definition: SemaDecl.cpp:16406
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition: Sema.h:4054
@ AMK_None
Don't merge availability attributes at all.
Definition: Sema.h:4056
@ AMK_Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition: Sema.h:4062
@ AMK_ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition: Sema.h:4065
@ AMK_OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition: Sema.h:4068
@ AMK_Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition: Sema.h:4059
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14843
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5653
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14512
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 {'.
Definition: SemaDecl.cpp:17010
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....
Definition: SemaDecl.cpp:4777
SemaPPC & PPC()
Definition: Sema.h:1184
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:79
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8907
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:15181
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:923
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1335
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20647
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18865
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,...
Definition: SemaAttr.cpp:1185
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
Definition: SemaDecl.cpp:10953
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:3112
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17681
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7946
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1307
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.
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:965
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.
Definition: SemaDecl.cpp:5729
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15802
DiagnosticsEngine & Diags
Definition: Sema.h:964
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:554
FPOptions CurFPFeatures
Definition: Sema.h:958
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15798
NamespaceDecl * getStdNamespace() const
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:6619
PragmaStack< StringLiteral * > DataSegStack
Definition: Sema.h:1700
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:691
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7200
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 ...
Definition: SemaDecl.cpp:14874
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11300
@ TPC_ClassTemplateMember
Definition: Sema.h:11298
@ TPC_FunctionTemplate
Definition: Sema.h:11297
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11301
@ TPC_VarTemplate
Definition: Sema.h:11296
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
Definition: SemaDecl.cpp:6703
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:16261
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2067
void PopDeclContext()
Definition: SemaDecl.cpp:1314
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:6076
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.
Definition: SemaDecl.cpp:1578
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)
Definition: SemaExpr.cpp:8808
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:13837
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
Definition: SemaDecl.cpp:13004
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1563
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:16669
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition: Sema.cpp:2392
OffsetOfKind
Definition: Sema.h:3877
@ OOK_Outside
Definition: Sema.h:3879
@ OOK_Macro
Definition: Sema.h:3884
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13277
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...
Definition: SemaDecl.cpp:18255
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)
Definition: SemaDecl.cpp:4305
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)
Definition: SemaDecl.cpp:14122
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.
Definition: SemaLambda.cpp:282
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
Definition: SemaDecl.cpp:20298
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:3087
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1967
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:20914
PragmaClangSection PragmaClangBSSSection
Definition: Sema.h:1476
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6038
@ AbstractVariableType
Definition: Sema.h:5769
@ AbstractReturnType
Definition: Sema.h:5767
@ AbstractFieldType
Definition: Sema.h:5770
@ AbstractIvarType
Definition: Sema.h:5771
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.
Definition: SemaDecl.cpp:1702
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:7991
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.
Definition: SemaDecl.cpp:1236
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.
Definition: SemaType.cpp:8005
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:20186
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:8526
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.
Definition: SemaDecl.cpp:1321
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12970
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)
Definition: SemaDecl.cpp:2434
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2731
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:3068
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
Definition: SemaAttr.cpp:1169
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
Definition: SemaDecl.cpp:15682
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...
Definition: SemaDecl.cpp:13256
SemaWasm & Wasm()
Definition: Sema.h:1214
IdentifierResolver IdResolver
Definition: Sema.h:3016
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.
Definition: SemaDecl.cpp:19847
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2341
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:680
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...
Definition: SemaDecl.cpp:15070
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:7954
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:3388
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6025
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
Definition: SemaDecl.cpp:16742
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:219
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=std::nullopt)
Definition: SemaDecl.cpp:7377
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8293
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Definition: SemaDecl.cpp:1263
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.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
child_range children()
Definition: Stmt.cpp:287
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition: Expr.h:1931
StringRef getString() const
Definition: Expr.h:1855
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3561
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3836
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3684
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3659
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3645
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3664
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4736
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4727
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4719
bool isUnion() const
Definition: Decl.h:3767
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4782
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4819
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3785
TagKind getTagKind() const
Definition: Decl.h:3756
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Definition: TargetCXXABI.h:238
Exposes information about the current target.
Definition: TargetInfo.h:218
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1533
unsigned getShortWidth() const
Return the size of 'signed short' and 'unsigned short' for this target, in bits.
Definition: TargetInfo.h:501
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:509
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
Definition: TargetInfo.h:1812
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:519
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1576
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1584
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1519
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1393
unsigned getCharWidth() const
Definition: TargetInfo.h:496
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:548
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:514
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
Definition: TargetInfo.h:1498
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1294
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1487
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:639
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
TemplateDecl * getAsTemplateDecl() 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.
Definition: DeclTemplate.h:73
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6480
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4277
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:99
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:101
bool isNot(tok::TokenKind K) const
Definition: Token.h:100
A declaration that models statements at global scope.
Definition: Decl.h:4434
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5600
Represents a declaration of a type.
Definition: Decl.h:3367
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3392
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
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:338
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:1225
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:206
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
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:744
SourceLocation getTemplateKeywordLoc() const
Get the SourceLocation of the template keyword (if any).
Definition: TypeLoc.cpp:751
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7721
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7732
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6743
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3133
The base class of the type hierarchy.
Definition: Type.h:1829
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2477
bool isStructureType() const
Definition: Type.cpp:629
bool isDecltypeType() const
Definition: Type.h:8200
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isDependentSizedArrayType() const
Definition: Type.h:8095
bool isBlockPointerType() const
Definition: Type.h:8017
bool isVoidType() const
Definition: Type.h:8319
bool isBooleanType() const
Definition: Type.h:8447
bool isFunctionReferenceType() const
Definition: Type.h:8050
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2167
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8497
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2892
bool isIncompleteArrayType() const
Definition: Type.h:8083
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8616
bool isDependentAddressSpaceType() const
Definition: Type.h:8141
bool isConstantArrayType() const
Definition: Type.h:8079
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8477
bool isVoidPointerType() const
Definition: Type.cpp:665
bool isArrayType() const
Definition: Type.h:8075
bool isFunctionPointerType() const
Definition: Type.h:8043
bool isPointerType() const
Definition: Type.h:8003
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2483
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
bool isReferenceType() const
Definition: Type.h:8021
bool isEnumeralType() const
Definition: Type.h:8107
bool isScalarType() const
Definition: Type.h:8418
bool isVariableArrayType() const
Definition: Type.h:8087
bool isClkEventT() const
Definition: Type.h:8218
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2058
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8434
bool isImageType() const
Definition: Type.h:8230
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2800
bool isPipeType() const
Definition: Type.h:8237
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2703
bool isBitIntType() const
Definition: Type.h:8241
bool isOpenCLSpecificType() const
Definition: Type.h:8266
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2338
bool isHalfType() const
Definition: Type.h:8323
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2011
bool isHLSLSpecificType() const
Definition: Type.h:8277
const RecordType * getAsStructureType() const
Definition: Type.cpp:721
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2467
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2689
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8490
bool isAtomicType() const
Definition: Type.h:8158
bool isFunctionProtoType() const
Definition: Type.h:2528
bool isObjCIdType() const
Definition: Type.h:8178
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2713
bool isObjCObjectType() const
Definition: Type.h:8149
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4970
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8453
bool isEventT() const
Definition: Type.h:8214
bool isPointerOrReferenceType() const
Definition: Type.h:8007
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4913
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:8557
bool isFunctionType() const
Definition: Type.h:7999
bool isObjCObjectPointerType() const
Definition: Type.h:8145
bool isMemberFunctionPointerType() const
Definition: Type.h:8061
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2497
bool isFloatingType() const
Definition: Type.cpp:2249
bool isAnyPointerType() const
Definition: Type.h:8011
TypeClass getTypeClass() const
Definition: Type.h:2334
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:2016
bool isSamplerT() const
Definition: Type.h:8210
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:605
bool isNullPtrType() const
Definition: Type.h:8352
bool isRecordType() const
Definition: Type.h:8103
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4693
bool isUnionType() const
Definition: Type.cpp:671
bool isFunctionNoProtoType() const
Definition: Type.h:2527
bool isReserveIDT() const
Definition: Type.h:8226
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1890
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2479
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1886
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3511
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5502
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3409
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3459
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:3475
QualType getUnderlyingType() const
Definition: Decl.h:3464
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3471
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5511
TypedefNameDecl * getDecl() const
Definition: Type.h:5640
QualType desugar() const
Definition: Type.cpp:3875
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 end()
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.
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
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:420
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3324
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3388
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3128
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
void setType(QualType newType)
Definition: Decl.h:679
QualType getType() const
Definition: Decl.h:678
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5370
Represents a variable declaration or definition.
Definition: Decl.h:879
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2775
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2133
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1466
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1510
TLSKind getTLSKind() const
Definition: Decl.cpp:2150
bool hasInit() const
Definition: Decl.cpp:2380
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1393
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2242
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2172
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:2426
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2239
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1519
bool isCXXCondDecl() const
Definition: Decl.h:1556
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:890
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition: Decl.h:893
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:887
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2145
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1538
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1231
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1174
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2348
void setInlineSpecified()
Definition: Decl.h:1499
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1156
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2737
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1290
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1121
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1492
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1125
const Expr * getInit() const
Definition: Decl.h:1316
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1165
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1132
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2411
void setConstexpr(bool IC)
Definition: Decl.h:1513
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:902
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:905
void setInit(Expr *I)
Definition: Decl.cpp:2442
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2327
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1246
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1243
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1249
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2780
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2227
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1201
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1116
void setImplicitlyInline()
Definition: Decl.h:1504
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1417
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1533
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2671
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1210
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:2744
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition: Decl.h:1427
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2651
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: Type.h:3795
Expr * getSizeExpr() const
Definition: Type.h:3814
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:739
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:729
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:749
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1093
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:731
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:878
ParmVarDecl * ExplicitObjectParameter
Definition: ScopeInfo.h:875
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition: ScopeInfo.h:948
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:865
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:873
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:890
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
Definition: Randstruct.cpp:175
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:32
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ 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:1886
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
@ GNUMode
Definition: LangStandard.h:64
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
@ CPlusPlus14
Definition: LangStandard.h:58
@ CPlusPlus17
Definition: LangStandard.h:59
@ 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
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
Definition: AttrIterator.h:28
CUDAFunctionTarget
Definition: Cuda.h:140
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:35
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
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
@ LCK_ByRef
Capturing by reference.
Definition: Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition: Lambda.h:35
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:40
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
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:235
@ 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
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
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...
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Parameter
The parameter type of a method or function.
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:50
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:307
TagUseKind
Definition: Sema.h:427
TagTypeKind
The kind of a tag type.
Definition: Type.h:6690
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
@ Union
The "union" keyword.
@ Enum
The "enum" keyword.
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition: CharInfo.h:108
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
ExprResult ExprError()
Definition: Ownership.h:264
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1542
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
@ TU_Complete
The translation unit is a complete translation unit.
Definition: LangOptions.h:1067
int hasAttribute(AttributeCommonInfo::Syntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:31
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:403
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
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
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:229
const FunctionProtoType * T
MultiVersionKind
Definition: Decl.h:1911
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:345
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ 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
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_C
Definition: Specifiers.h:279
@ CC_X86StdCall
Definition: Specifiers.h:280
@ None
The alignment was not explicit in code.
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition: Decl.cpp:5759
ReservedIdentifierStatus
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
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
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
#define bool
Definition: stdbool.h:24
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:1428
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition: DeclSpec.h:1579
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1403
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1362
const IdentifierInfo * Ident
Definition: DeclSpec.h:1334
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1251
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1663
enum clang::DeclaratorChunk::@222 Kind
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:161
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1644
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1687
RetTy visit(QualType FT, Ts &&... Args)
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition: Type.h:4820
EffectConditionExpr Cond
Definition: Type.h:4822
std::string description() const
Return a textual description of the effect, and its condition, if any.
Definition: Type.cpp:5332
Extra information about a function prototype.
Definition: Type.h:5087
FunctionEffectsRef FunctionEffects
Definition: Type.h:5097
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:5107
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:57
std::vector< std::string > Features
Definition: TargetInfo.h:58
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
SourceLocation PragmaLocation
Definition: Sema.h:1473
ValueType CurrentValue
Definition: Sema.h:1676
bool CheckSameAsPrevious
Definition: Sema.h:331
NamedDecl * Previous
Definition: Sema.h:332
NamedDecl * New
Definition: Sema.h:333
Information about a template-id annotation token.
unsigned NumArgs
NumArgs - The number of template arguments.
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.