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"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
36#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41#include "clang/Sema/DeclSpec.h"
44#include "clang/Sema/Lookup.h"
46#include "clang/Sema/Scope.h"
48#include "clang/Sema/SemaARM.h"
49#include "clang/Sema/SemaCUDA.h"
50#include "clang/Sema/SemaHLSL.h"
52#include "clang/Sema/SemaObjC.h"
54#include "clang/Sema/SemaPPC.h"
56#include "clang/Sema/SemaSYCL.h"
58#include "clang/Sema/SemaWasm.h"
59#include "clang/Sema/Template.h"
60#include "llvm/ADT/STLForwardCompat.h"
61#include "llvm/ADT/SmallString.h"
62#include "llvm/ADT/StringExtras.h"
63#include "llvm/TargetParser/Triple.h"
64#include <algorithm>
65#include <cstring>
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 // In the case where we know that the identifier is a class name, we know that
361 // it is a type declaration (struct, class, union or enum) so we can use tag
362 // name lookup.
363 //
364 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
365 // the component name of the type-name or simple-template-id is type-only.
366 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
367 LookupResult Result(*this, &II, NameLoc, Kind);
368 if (LookupCtx) {
369 // Perform "qualified" name lookup into the declaration context we
370 // computed, which is either the type of the base of a member access
371 // expression or the declaration context associated with a prior
372 // nested-name-specifier.
373 LookupQualifiedName(Result, LookupCtx);
374
375 if (ObjectTypePtr && Result.empty()) {
376 // C++ [basic.lookup.classref]p3:
377 // If the unqualified-id is ~type-name, the type-name is looked up
378 // in the context of the entire postfix-expression. If the type T of
379 // the object expression is of a class type C, the type-name is also
380 // looked up in the scope of class C. At least one of the lookups shall
381 // find a name that refers to (possibly cv-qualified) T.
382 LookupName(Result, S);
383 }
384 } else {
385 // Perform unqualified name lookup.
386 LookupName(Result, S);
387
388 // For unqualified lookup in a class template in MSVC mode, look into
389 // dependent base classes where the primary class template is known.
390 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
391 if (ParsedType TypeInBase =
392 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
393 return TypeInBase;
394 }
395 }
396
397 NamedDecl *IIDecl = nullptr;
398 UsingShadowDecl *FoundUsingShadow = nullptr;
399 switch (Result.getResultKind()) {
401 if (CorrectedII) {
402 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
403 AllowDeducedTemplate);
404 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
405 S, SS, CCC, CTK_ErrorRecovery);
406 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
407 TemplateTy Template;
408 bool MemberOfUnknownSpecialization;
410 TemplateName.setIdentifier(NewII, NameLoc);
412 CXXScopeSpec NewSS, *NewSSPtr = SS;
413 if (SS && NNS) {
414 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
415 NewSSPtr = &NewSS;
416 }
417 if (Correction && (NNS || NewII != &II) &&
418 // Ignore a correction to a template type as the to-be-corrected
419 // identifier is not a template (typo correction for template names
420 // is handled elsewhere).
421 !(getLangOpts().CPlusPlus && NewSSPtr &&
422 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
423 Template, MemberOfUnknownSpecialization))) {
424 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
425 isClassName, HasTrailingDot, ObjectTypePtr,
426 IsCtorOrDtorName,
427 WantNontrivialTypeSourceInfo,
428 IsClassTemplateDeductionContext);
429 if (Ty) {
430 diagnoseTypo(Correction,
431 PDiag(diag::err_unknown_type_or_class_name_suggest)
432 << Result.getLookupName() << isClassName);
433 if (SS && NNS)
434 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
435 *CorrectedII = NewII;
436 return Ty;
437 }
438 }
439 }
440 Result.suppressDiagnostics();
441 return nullptr;
443 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
445 SS->getScopeRep(), &II);
446 TypeLocBuilder TLB;
450 TL.setNameLoc(NameLoc);
452 }
453 [[fallthrough]];
456 Result.suppressDiagnostics();
457 return nullptr;
458
460 // Recover from type-hiding ambiguities by hiding the type. We'll
461 // do the lookup again when looking for an object, and we can
462 // diagnose the error then. If we don't do this, then the error
463 // about hiding the type will be immediately followed by an error
464 // that only makes sense if the identifier was treated like a type.
465 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
466 Result.suppressDiagnostics();
467 return nullptr;
468 }
469
470 // Look to see if we have a type anywhere in the list of results.
471 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
472 Res != ResEnd; ++Res) {
473 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
474 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
475 RealRes) ||
476 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
477 if (!IIDecl ||
478 // Make the selection of the recovery decl deterministic.
479 RealRes->getLocation() < IIDecl->getLocation()) {
480 IIDecl = RealRes;
481 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
482 }
483 }
484 }
485
486 if (!IIDecl) {
487 // None of the entities we found is a type, so there is no way
488 // to even assume that the result is a type. In this case, don't
489 // complain about the ambiguity. The parser will either try to
490 // perform this lookup again (e.g., as an object name), which
491 // will produce the ambiguity, or will complain that it expected
492 // a type name.
493 Result.suppressDiagnostics();
494 return nullptr;
495 }
496
497 // We found a type within the ambiguous lookup; diagnose the
498 // ambiguity and then return that type. This might be the right
499 // answer, or it might not be, but it suppresses any attempt to
500 // perform the name lookup again.
501 break;
502
504 IIDecl = Result.getFoundDecl();
505 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
506 break;
507 }
508
509 assert(IIDecl && "Didn't find decl");
510
511 QualType T;
512 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
513 // C++ [class.qual]p2: A lookup that would find the injected-class-name
514 // instead names the constructors of the class, except when naming a class.
515 // This is ill-formed when we're not actually forming a ctor or dtor name.
516 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
517 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
518 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
519 FoundRD->isInjectedClassName() &&
520 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
521 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
522 << &II << /*Type*/1;
523
524 DiagnoseUseOfDecl(IIDecl, NameLoc);
525
527 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
528 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
529 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
530 if (!HasTrailingDot)
532 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
533 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
534 (void)DiagnoseUseOfDecl(UD, NameLoc);
535 // Recover with 'int'
537 } else if (AllowDeducedTemplate) {
538 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
539 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
541 SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false,
542 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
544 false);
545 // Don't wrap in a further UsingType.
546 FoundUsingShadow = nullptr;
547 }
548 }
549
550 if (T.isNull()) {
551 // If it's not plausibly a type, suppress diagnostics.
552 Result.suppressDiagnostics();
553 return nullptr;
554 }
555
556 if (FoundUsingShadow)
557 T = Context.getUsingType(FoundUsingShadow, T);
558
559 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
560}
561
562// Builds a fake NNS for the given decl context.
563static NestedNameSpecifier *
565 for (;; DC = DC->getLookupParent()) {
566 DC = DC->getPrimaryContext();
567 auto *ND = dyn_cast<NamespaceDecl>(DC);
568 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
569 return NestedNameSpecifier::Create(Context, nullptr, ND);
570 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
571 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
572 RD->getTypeForDecl());
573 else if (isa<TranslationUnitDecl>(DC))
575 }
576 llvm_unreachable("something isn't in TU scope?");
577}
578
579/// Find the parent class with dependent bases of the innermost enclosing method
580/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
581/// up allowing unqualified dependent type names at class-level, which MSVC
582/// correctly rejects.
583static const CXXRecordDecl *
585 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
586 DC = DC->getPrimaryContext();
587 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
588 if (MD->getParent()->hasAnyDependentBases())
589 return MD->getParent();
590 }
591 return nullptr;
592}
593
595 SourceLocation NameLoc,
596 bool IsTemplateTypeArg) {
597 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
598
599 NestedNameSpecifier *NNS = nullptr;
600 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
601 // If we weren't able to parse a default template argument, delay lookup
602 // until instantiation time by making a non-dependent DependentTypeName. We
603 // pretend we saw a NestedNameSpecifier referring to the current scope, and
604 // lookup is retried.
605 // FIXME: This hurts our diagnostic quality, since we get errors like "no
606 // type named 'Foo' in 'current_namespace'" when the user didn't write any
607 // name specifiers.
609 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
610 } else if (const CXXRecordDecl *RD =
612 // Build a DependentNameType that will perform lookup into RD at
613 // instantiation time.
614 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
615 RD->getTypeForDecl());
616
617 // Diagnose that this identifier was undeclared, and retry the lookup during
618 // template instantiation.
619 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
620 << RD;
621 } else {
622 // This is not a situation that we should recover from.
623 return ParsedType();
624 }
625
626 QualType T =
628
629 // Build type location information. We synthesized the qualifier, so we have
630 // to build a fake NestedNameSpecifierLoc.
631 NestedNameSpecifierLocBuilder NNSLocBuilder;
632 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
633 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
634
635 TypeLocBuilder Builder;
636 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
637 DepTL.setNameLoc(NameLoc);
639 DepTL.setQualifierLoc(QualifierLoc);
640 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
641}
642
644 // Do a tag name lookup in this scope.
645 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
646 LookupName(R, S, false);
649 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
650 switch (TD->getTagKind()) {
656 return DeclSpec::TST_union;
658 return DeclSpec::TST_class;
660 return DeclSpec::TST_enum;
661 }
662 }
663
665}
666
668 if (CurContext->isRecord()) {
670 return true;
671
672 const Type *Ty = SS->getScopeRep()->getAsType();
673
674 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
675 for (const auto &Base : RD->bases())
676 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
677 return true;
678 return S->isFunctionPrototypeScope();
679 }
680 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
681}
682
684 SourceLocation IILoc,
685 Scope *S,
686 CXXScopeSpec *SS,
687 ParsedType &SuggestedType,
688 bool IsTemplateName) {
689 // Don't report typename errors for editor placeholders.
690 if (II->isEditorPlaceholder())
691 return;
692 // We don't have anything to suggest (yet).
693 SuggestedType = nullptr;
694
695 // There may have been a typo in the name of the type. Look up typo
696 // results, in case we have something that we can suggest.
697 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
698 /*AllowTemplates=*/IsTemplateName,
699 /*AllowNonTemplates=*/!IsTemplateName);
700 if (TypoCorrection Corrected =
702 CCC, CTK_ErrorRecovery)) {
703 // FIXME: Support error recovery for the template-name case.
704 bool CanRecover = !IsTemplateName;
705 if (Corrected.isKeyword()) {
706 // We corrected to a keyword.
707 diagnoseTypo(Corrected,
708 PDiag(IsTemplateName ? diag::err_no_template_suggest
709 : diag::err_unknown_typename_suggest)
710 << II);
711 II = Corrected.getCorrectionAsIdentifierInfo();
712 } else {
713 // We found a similarly-named type or interface; suggest that.
714 if (!SS || !SS->isSet()) {
715 diagnoseTypo(Corrected,
716 PDiag(IsTemplateName ? diag::err_no_template_suggest
717 : diag::err_unknown_typename_suggest)
718 << II, CanRecover);
719 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
720 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
721 bool DroppedSpecifier =
722 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
723 diagnoseTypo(Corrected,
724 PDiag(IsTemplateName
725 ? diag::err_no_member_template_suggest
726 : diag::err_unknown_nested_typename_suggest)
727 << II << DC << DroppedSpecifier << SS->getRange(),
728 CanRecover);
729 } else {
730 llvm_unreachable("could not have corrected a typo here");
731 }
732
733 if (!CanRecover)
734 return;
735
736 CXXScopeSpec tmpSS;
737 if (Corrected.getCorrectionSpecifier())
738 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
739 SourceRange(IILoc));
740 // FIXME: Support class template argument deduction here.
741 SuggestedType =
742 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
743 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
744 /*IsCtorOrDtorName=*/false,
745 /*WantNontrivialTypeSourceInfo=*/true);
746 }
747 return;
748 }
749
750 if (getLangOpts().CPlusPlus && !IsTemplateName) {
751 // See if II is a class template that the user forgot to pass arguments to.
752 UnqualifiedId Name;
753 Name.setIdentifier(II, IILoc);
754 CXXScopeSpec EmptySS;
755 TemplateTy TemplateResult;
756 bool MemberOfUnknownSpecialization;
757 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
758 Name, nullptr, true, TemplateResult,
759 MemberOfUnknownSpecialization) == TNK_Type_template) {
760 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
761 return;
762 }
763 }
764
765 // FIXME: Should we move the logic that tries to recover from a missing tag
766 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
767
768 if (!SS || (!SS->isSet() && !SS->isInvalid()))
769 Diag(IILoc, IsTemplateName ? diag::err_no_template
770 : diag::err_unknown_typename)
771 << II;
772 else if (DeclContext *DC = computeDeclContext(*SS, false))
773 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
774 : diag::err_typename_nested_not_found)
775 << II << DC << SS->getRange();
776 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
777 SuggestedType =
778 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
779 } else if (isDependentScopeSpecifier(*SS)) {
780 unsigned DiagID = diag::err_typename_missing;
781 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
782 DiagID = diag::ext_typename_missing;
783
784 Diag(SS->getRange().getBegin(), DiagID)
785 << SS->getScopeRep() << II->getName()
786 << SourceRange(SS->getRange().getBegin(), IILoc)
787 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
788 SuggestedType = ActOnTypenameType(S, SourceLocation(),
789 *SS, *II, IILoc).get();
790 } else {
791 assert(SS && SS->isInvalid() &&
792 "Invalid scope specifier has already been diagnosed");
793 }
794}
795
796/// Determine whether the given result set contains either a type name
797/// or
798static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
799 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
800 NextToken.is(tok::less);
801
802 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
803 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
804 return true;
805
806 if (CheckTemplate && isa<TemplateDecl>(*I))
807 return true;
808 }
809
810 return false;
811}
812
814 Scope *S, CXXScopeSpec &SS,
815 IdentifierInfo *&Name,
816 SourceLocation NameLoc) {
817 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
818 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
819 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
820 StringRef FixItTagName;
821 switch (Tag->getTagKind()) {
823 FixItTagName = "class ";
824 break;
825
827 FixItTagName = "enum ";
828 break;
829
831 FixItTagName = "struct ";
832 break;
833
835 FixItTagName = "__interface ";
836 break;
837
839 FixItTagName = "union ";
840 break;
841 }
842
843 StringRef TagName = FixItTagName.drop_back();
844 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
845 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
846 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
847
848 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
849 I != IEnd; ++I)
850 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
851 << Name << TagName;
852
853 // Replace lookup results with just the tag decl.
855 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
856 return true;
857 }
858
859 return false;
860}
861
863 IdentifierInfo *&Name,
864 SourceLocation NameLoc,
865 const Token &NextToken,
867 DeclarationNameInfo NameInfo(Name, NameLoc);
868 ObjCMethodDecl *CurMethod = getCurMethodDecl();
869
870 assert(NextToken.isNot(tok::coloncolon) &&
871 "parse nested name specifiers before calling ClassifyName");
872 if (getLangOpts().CPlusPlus && SS.isSet() &&
873 isCurrentClassName(*Name, S, &SS)) {
874 // Per [class.qual]p2, this names the constructors of SS, not the
875 // injected-class-name. We don't have a classification for that.
876 // There's not much point caching this result, since the parser
877 // will reject it later.
879 }
880
881 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
882 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
883 /*AllowBuiltinCreation=*/!CurMethod);
884
885 if (SS.isInvalid())
887
888 // For unqualified lookup in a class template in MSVC mode, look into
889 // dependent base classes where the primary class template is known.
890 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
891 if (ParsedType TypeInBase =
892 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
893 return TypeInBase;
894 }
895
896 // Perform lookup for Objective-C instance variables (including automatically
897 // synthesized instance variables), if we're in an Objective-C method.
898 // FIXME: This lookup really, really needs to be folded in to the normal
899 // unqualified lookup mechanism.
900 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
901 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
902 if (Ivar.isInvalid())
904 if (Ivar.isUsable())
905 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
906
907 // We defer builtin creation until after ivar lookup inside ObjC methods.
908 if (Result.empty())
910 }
911
912 bool SecondTry = false;
913 bool IsFilteredTemplateName = false;
914
915Corrected:
916 switch (Result.getResultKind()) {
918 // If an unqualified-id is followed by a '(', then we have a function
919 // call.
920 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
921 // In C++, this is an ADL-only call.
922 // FIXME: Reference?
925
926 // C90 6.3.2.2:
927 // If the expression that precedes the parenthesized argument list in a
928 // function call consists solely of an identifier, and if no
929 // declaration is visible for this identifier, the identifier is
930 // implicitly declared exactly as if, in the innermost block containing
931 // the function call, the declaration
932 //
933 // extern int identifier ();
934 //
935 // appeared.
936 //
937 // We also allow this in C99 as an extension. However, this is not
938 // allowed in all language modes as functions without prototypes may not
939 // be supported.
940 if (getLangOpts().implicitFunctionsAllowed()) {
941 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
943 }
944 }
945
946 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
947 // In C++20 onwards, this could be an ADL-only call to a function
948 // template, and we're required to assume that this is a template name.
949 //
950 // FIXME: Find a way to still do typo correction in this case.
951 TemplateName Template =
954 }
955
956 // In C, we first see whether there is a tag type by the same name, in
957 // which case it's likely that the user just forgot to write "enum",
958 // "struct", or "union".
959 if (!getLangOpts().CPlusPlus && !SecondTry &&
960 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
961 break;
962 }
963
964 // Perform typo correction to determine if there is another name that is
965 // close to this name.
966 if (!SecondTry && CCC) {
967 SecondTry = true;
968 if (TypoCorrection Corrected =
969 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
970 &SS, *CCC, CTK_ErrorRecovery)) {
971 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
972 unsigned QualifiedDiag = diag::err_no_member_suggest;
973
974 NamedDecl *FirstDecl = Corrected.getFoundDecl();
975 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
976 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
977 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
978 UnqualifiedDiag = diag::err_no_template_suggest;
979 QualifiedDiag = diag::err_no_member_template_suggest;
980 } else if (UnderlyingFirstDecl &&
981 (isa<TypeDecl>(UnderlyingFirstDecl) ||
982 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
983 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
984 UnqualifiedDiag = diag::err_unknown_typename_suggest;
985 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
986 }
987
988 if (SS.isEmpty()) {
989 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
990 } else {// FIXME: is this even reachable? Test it.
991 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
992 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
993 Name->getName() == CorrectedStr;
994 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
995 << Name << computeDeclContext(SS, false)
996 << DroppedSpecifier << SS.getRange());
997 }
998
999 // Update the name, so that the caller has the new name.
1000 Name = Corrected.getCorrectionAsIdentifierInfo();
1001
1002 // Typo correction corrected to a keyword.
1003 if (Corrected.isKeyword())
1004 return Name;
1005
1006 // Also update the LookupResult...
1007 // FIXME: This should probably go away at some point
1008 Result.clear();
1009 Result.setLookupName(Corrected.getCorrection());
1010 if (FirstDecl)
1011 Result.addDecl(FirstDecl);
1012
1013 // If we found an Objective-C instance variable, let
1014 // LookupInObjCMethod build the appropriate expression to
1015 // reference the ivar.
1016 // FIXME: This is a gross hack.
1017 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1018 DeclResult R =
1019 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1020 if (R.isInvalid())
1022 if (R.isUsable())
1023 return NameClassification::NonType(Ivar);
1024 }
1025
1026 goto Corrected;
1027 }
1028 }
1029
1030 // We failed to correct; just fall through and let the parser deal with it.
1031 Result.suppressDiagnostics();
1033
1035 // We performed name lookup into the current instantiation, and there were
1036 // dependent bases, so we treat this result the same way as any other
1037 // dependent nested-name-specifier.
1038
1039 // C++ [temp.res]p2:
1040 // A name used in a template declaration or definition and that is
1041 // dependent on a template-parameter is assumed not to name a type
1042 // unless the applicable name lookup finds a type name or the name is
1043 // qualified by the keyword typename.
1044 //
1045 // FIXME: If the next token is '<', we might want to ask the parser to
1046 // perform some heroics to see if we actually have a
1047 // template-argument-list, which would indicate a missing 'template'
1048 // keyword here.
1050 }
1051
1055 break;
1056
1058 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1059 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1060 /*AllowDependent=*/false)) {
1061 // C++ [temp.local]p3:
1062 // A lookup that finds an injected-class-name (10.2) can result in an
1063 // ambiguity in certain cases (for example, if it is found in more than
1064 // one base class). If all of the injected-class-names that are found
1065 // refer to specializations of the same class template, and if the name
1066 // is followed by a template-argument-list, the reference refers to the
1067 // class template itself and not a specialization thereof, and is not
1068 // ambiguous.
1069 //
1070 // This filtering can make an ambiguous result into an unambiguous one,
1071 // so try again after filtering out template names.
1073 if (!Result.isAmbiguous()) {
1074 IsFilteredTemplateName = true;
1075 break;
1076 }
1077 }
1078
1079 // Diagnose the ambiguity and return an error.
1081 }
1082
1083 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1084 (IsFilteredTemplateName ||
1086 Result, /*AllowFunctionTemplates=*/true,
1087 /*AllowDependent=*/false,
1088 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1090 // C++ [temp.names]p3:
1091 // After name lookup (3.4) finds that a name is a template-name or that
1092 // an operator-function-id or a literal- operator-id refers to a set of
1093 // overloaded functions any member of which is a function template if
1094 // this is followed by a <, the < is always taken as the delimiter of a
1095 // template-argument-list and never as the less-than operator.
1096 // C++2a [temp.names]p2:
1097 // A name is also considered to refer to a template if it is an
1098 // unqualified-id followed by a < and name lookup finds either one
1099 // or more functions or finds nothing.
1100 if (!IsFilteredTemplateName)
1102
1103 bool IsFunctionTemplate;
1104 bool IsVarTemplate;
1105 TemplateName Template;
1106 if (Result.end() - Result.begin() > 1) {
1107 IsFunctionTemplate = true;
1108 Template = Context.getOverloadedTemplateName(Result.begin(),
1109 Result.end());
1110 } else if (!Result.empty()) {
1111 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1112 *Result.begin(), /*AllowFunctionTemplates=*/true,
1113 /*AllowDependent=*/false));
1114 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1115 IsVarTemplate = isa<VarTemplateDecl>(TD);
1116
1117 UsingShadowDecl *FoundUsingShadow =
1118 dyn_cast<UsingShadowDecl>(*Result.begin());
1119 assert(!FoundUsingShadow ||
1120 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1122 SS.getScopeRep(),
1123 /*TemplateKeyword=*/false,
1124 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1125 } else {
1126 // All results were non-template functions. This is a function template
1127 // name.
1128 IsFunctionTemplate = true;
1129 Template = Context.getAssumedTemplateName(NameInfo.getName());
1130 }
1131
1132 if (IsFunctionTemplate) {
1133 // Function templates always go through overload resolution, at which
1134 // point we'll perform the various checks (e.g., accessibility) we need
1135 // to based on which function we selected.
1136 Result.suppressDiagnostics();
1137
1138 return NameClassification::FunctionTemplate(Template);
1139 }
1140
1141 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1143 }
1144
1145 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1147 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1148 T = Context.getUsingType(USD, T);
1149 return buildNamedType(*this, &SS, T, NameLoc);
1150 };
1151
1152 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1153 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1154 DiagnoseUseOfDecl(Type, NameLoc);
1155 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1156 return BuildTypeFor(Type, *Result.begin());
1157 }
1158
1159 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1160 if (!Class) {
1161 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1162 if (ObjCCompatibleAliasDecl *Alias =
1163 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1164 Class = Alias->getClassInterface();
1165 }
1166
1167 if (Class) {
1168 DiagnoseUseOfDecl(Class, NameLoc);
1169
1170 if (NextToken.is(tok::period)) {
1171 // Interface. <something> is parsed as a property reference expression.
1172 // Just return "unknown" as a fall-through for now.
1173 Result.suppressDiagnostics();
1175 }
1176
1178 return ParsedType::make(T);
1179 }
1180
1181 if (isa<ConceptDecl>(FirstDecl)) {
1182 // We want to preserve the UsingShadowDecl for concepts.
1183 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1186 TemplateName(cast<TemplateDecl>(FirstDecl)));
1187 }
1188
1189 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1190 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1192 }
1193
1194 // We can have a type template here if we're classifying a template argument.
1195 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1196 !isa<VarTemplateDecl>(FirstDecl))
1198 TemplateName(cast<TemplateDecl>(FirstDecl)));
1199
1200 // Check for a tag type hidden by a non-type decl in a few cases where it
1201 // seems likely a type is wanted instead of the non-type that was found.
1202 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1203 if ((NextToken.is(tok::identifier) ||
1204 (NextIsOp &&
1205 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1206 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1207 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1208 DiagnoseUseOfDecl(Type, NameLoc);
1209 return BuildTypeFor(Type, *Result.begin());
1210 }
1211
1212 // If we already know which single declaration is referenced, just annotate
1213 // that declaration directly. Defer resolving even non-overloaded class
1214 // member accesses, as we need to defer certain access checks until we know
1215 // the context.
1216 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1217 if (Result.isSingleResult() && !ADL &&
1218 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1219 return NameClassification::NonType(Result.getRepresentativeDecl());
1220
1221 // Otherwise, this is an overload set that we will need to resolve later.
1222 Result.suppressDiagnostics();
1224 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1225 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1226 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1227}
1228
1231 SourceLocation NameLoc) {
1232 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1233 CXXScopeSpec SS;
1234 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1235 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1236}
1237
1240 IdentifierInfo *Name,
1241 SourceLocation NameLoc,
1242 bool IsAddressOfOperand) {
1243 DeclarationNameInfo NameInfo(Name, NameLoc);
1244 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1245 NameInfo, IsAddressOfOperand,
1246 /*TemplateArgs=*/nullptr);
1247}
1248
1251 SourceLocation NameLoc,
1252 const Token &NextToken) {
1253 if (getCurMethodDecl() && SS.isEmpty())
1254 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1255 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1256
1257 // Reconstruct the lookup result.
1258 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1259 Result.addDecl(Found);
1260 Result.resolveKind();
1261
1262 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1263 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1264}
1265
1267 // For an implicit class member access, transform the result into a member
1268 // access expression if necessary.
1269 auto *ULE = cast<UnresolvedLookupExpr>(E);
1270 if ((*ULE->decls_begin())->isCXXClassMember()) {
1271 CXXScopeSpec SS;
1272 SS.Adopt(ULE->getQualifierLoc());
1273
1274 // Reconstruct the lookup result.
1275 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1277 Result.setNamingClass(ULE->getNamingClass());
1278 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1279 Result.addDecl(*I, I.getAccess());
1280 Result.resolveKind();
1282 nullptr, S);
1283 }
1284
1285 // Otherwise, this is already in the form we needed, and no further checks
1286 // are necessary.
1287 return ULE;
1288}
1289
1292 auto *TD = Name.getAsTemplateDecl();
1293 if (!TD)
1295 if (isa<ClassTemplateDecl>(TD))
1297 if (isa<FunctionTemplateDecl>(TD))
1299 if (isa<VarTemplateDecl>(TD))
1301 if (isa<TypeAliasTemplateDecl>(TD))
1303 if (isa<TemplateTemplateParmDecl>(TD))
1305 if (isa<ConceptDecl>(TD))
1308}
1309
1311 assert(DC->getLexicalParent() == CurContext &&
1312 "The next DeclContext should be lexically contained in the current one.");
1313 CurContext = DC;
1314 S->setEntity(DC);
1315}
1316
1318 assert(CurContext && "DeclContext imbalance!");
1319
1321 assert(CurContext && "Popped translation unit!");
1322}
1323
1325 Decl *D) {
1326 // Unlike PushDeclContext, the context to which we return is not necessarily
1327 // the containing DC of TD, because the new context will be some pre-existing
1328 // TagDecl definition instead of a fresh one.
1329 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1330 CurContext = cast<TagDecl>(D)->getDefinition();
1331 assert(CurContext && "skipping definition of undefined tag");
1332 // Start lookups from the parent of the current context; we don't want to look
1333 // into the pre-existing complete definition.
1334 S->setEntity(CurContext->getLookupParent());
1335 return Result;
1336}
1337
1339 CurContext = static_cast<decltype(CurContext)>(Context);
1340}
1341
1343 // C++0x [basic.lookup.unqual]p13:
1344 // A name used in the definition of a static data member of class
1345 // X (after the qualified-id of the static member) is looked up as
1346 // if the name was used in a member function of X.
1347 // C++0x [basic.lookup.unqual]p14:
1348 // If a variable member of a namespace is defined outside of the
1349 // scope of its namespace then any name used in the definition of
1350 // the variable member (after the declarator-id) is looked up as
1351 // if the definition of the variable member occurred in its
1352 // namespace.
1353 // Both of these imply that we should push a scope whose context
1354 // is the semantic context of the declaration. We can't use
1355 // PushDeclContext here because that context is not necessarily
1356 // lexically contained in the current context. Fortunately,
1357 // the containing scope should have the appropriate information.
1358
1359 assert(!S->getEntity() && "scope already has entity");
1360
1361#ifndef NDEBUG
1362 Scope *Ancestor = S->getParent();
1363 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1364 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1365#endif
1366
1367 CurContext = DC;
1368 S->setEntity(DC);
1369
1370 if (S->getParent()->isTemplateParamScope()) {
1371 // Also set the corresponding entities for all immediately-enclosing
1372 // template parameter scopes.
1373 EnterTemplatedContext(S->getParent(), DC);
1374 }
1375}
1376
1378 assert(S->getEntity() == CurContext && "Context imbalance!");
1379
1380 // Switch back to the lexical context. The safety of this is
1381 // enforced by an assert in EnterDeclaratorContext.
1382 Scope *Ancestor = S->getParent();
1383 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1384 CurContext = Ancestor->getEntity();
1385
1386 // We don't need to do anything with the scope, which is going to
1387 // disappear.
1388}
1389
1391 assert(S->isTemplateParamScope() &&
1392 "expected to be initializing a template parameter scope");
1393
1394 // C++20 [temp.local]p7:
1395 // In the definition of a member of a class template that appears outside
1396 // of the class template definition, the name of a member of the class
1397 // template hides the name of a template-parameter of any enclosing class
1398 // templates (but not a template-parameter of the member if the member is a
1399 // class or function template).
1400 // C++20 [temp.local]p9:
1401 // In the definition of a class template or in the definition of a member
1402 // of such a template that appears outside of the template definition, for
1403 // each non-dependent base class (13.8.2.1), if the name of the base class
1404 // or the name of a member of the base class is the same as the name of a
1405 // template-parameter, the base class name or member name hides the
1406 // template-parameter name (6.4.10).
1407 //
1408 // This means that a template parameter scope should be searched immediately
1409 // after searching the DeclContext for which it is a template parameter
1410 // scope. For example, for
1411 // template<typename T> template<typename U> template<typename V>
1412 // void N::A<T>::B<U>::f(...)
1413 // we search V then B<U> (and base classes) then U then A<T> (and base
1414 // classes) then T then N then ::.
1415 unsigned ScopeDepth = getTemplateDepth(S);
1416 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1417 DeclContext *SearchDCAfterScope = DC;
1418 for (; DC; DC = DC->getLookupParent()) {
1419 if (const TemplateParameterList *TPL =
1420 cast<Decl>(DC)->getDescribedTemplateParams()) {
1421 unsigned DCDepth = TPL->getDepth() + 1;
1422 if (DCDepth > ScopeDepth)
1423 continue;
1424 if (ScopeDepth == DCDepth)
1425 SearchDCAfterScope = DC = DC->getLookupParent();
1426 break;
1427 }
1428 }
1429 S->setLookupEntity(SearchDCAfterScope);
1430 }
1431}
1432
1434 // We assume that the caller has already called
1435 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1436 FunctionDecl *FD = D->getAsFunction();
1437 if (!FD)
1438 return;
1439
1440 // Same implementation as PushDeclContext, but enters the context
1441 // from the lexical parent, rather than the top-level class.
1442 assert(CurContext == FD->getLexicalParent() &&
1443 "The next DeclContext should be lexically contained in the current one.");
1444 CurContext = FD;
1445 S->setEntity(CurContext);
1446
1447 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1448 ParmVarDecl *Param = FD->getParamDecl(P);
1449 // If the parameter has an identifier, then add it to the scope
1450 if (Param->getIdentifier()) {
1451 S->AddDecl(Param);
1452 IdResolver.AddDecl(Param);
1453 }
1454 }
1455}
1456
1458 // Same implementation as PopDeclContext, but returns to the lexical parent,
1459 // rather than the top-level class.
1460 assert(CurContext && "DeclContext imbalance!");
1462 assert(CurContext && "Popped translation unit!");
1463}
1464
1465/// Determine whether overloading is allowed for a new function
1466/// declaration considering prior declarations of the same name.
1467///
1468/// This routine determines whether overloading is possible, not
1469/// whether a new declaration actually overloads a previous one.
1470/// It will return true in C++ (where overloads are always permitted)
1471/// or, as a C extension, when either the new declaration or a
1472/// previous one is declared with the 'overloadable' attribute.
1474 ASTContext &Context,
1475 const FunctionDecl *New) {
1476 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1477 return true;
1478
1479 // Multiversion function declarations are not overloads in the
1480 // usual sense of that term, but lookup will report that an
1481 // overload set was found if more than one multiversion function
1482 // declaration is present for the same name. It is therefore
1483 // inadequate to assume that some prior declaration(s) had
1484 // the overloadable attribute; checking is required. Since one
1485 // declaration is permitted to omit the attribute, it is necessary
1486 // to check at least two; hence the 'any_of' check below. Note that
1487 // the overloadable attribute is implicitly added to declarations
1488 // that were required to have it but did not.
1489 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1490 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1491 return ND->hasAttr<OverloadableAttr>();
1492 });
1493 } else if (Previous.getResultKind() == LookupResult::Found)
1494 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1495
1496 return false;
1497}
1498
1499void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1500 // Move up the scope chain until we find the nearest enclosing
1501 // non-transparent context. The declaration will be introduced into this
1502 // scope.
1503 while (S->getEntity() && S->getEntity()->isTransparentContext())
1504 S = S->getParent();
1505
1506 // Add scoped declarations into their context, so that they can be
1507 // found later. Declarations without a context won't be inserted
1508 // into any context.
1509 if (AddToContext)
1511
1512 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1513 // are function-local declarations.
1514 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1515 return;
1516
1517 // Template instantiations should also not be pushed into scope.
1518 if (isa<FunctionDecl>(D) &&
1519 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1520 return;
1521
1522 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1523 S->AddDecl(D);
1524 return;
1525 }
1526 // If this replaces anything in the current scope,
1527 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1528 IEnd = IdResolver.end();
1529 for (; I != IEnd; ++I) {
1530 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1531 S->RemoveDecl(*I);
1533
1534 // Should only need to replace one decl.
1535 break;
1536 }
1537 }
1538
1539 S->AddDecl(D);
1540
1541 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1542 // Implicitly-generated labels may end up getting generated in an order that
1543 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1544 // the label at the appropriate place in the identifier chain.
1545 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1546 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1547 if (IDC == CurContext) {
1548 if (!S->isDeclScope(*I))
1549 continue;
1550 } else if (IDC->Encloses(CurContext))
1551 break;
1552 }
1553
1555 } else {
1557 }
1559}
1560
1562 bool AllowInlineNamespace) const {
1563 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1564}
1565
1567 DeclContext *TargetDC = DC->getPrimaryContext();
1568 do {
1569 if (DeclContext *ScopeDC = S->getEntity())
1570 if (ScopeDC->getPrimaryContext() == TargetDC)
1571 return S;
1572 } while ((S = S->getParent()));
1573
1574 return nullptr;
1575}
1576
1578 DeclContext*,
1579 ASTContext&);
1580
1582 bool ConsiderLinkage,
1583 bool AllowInlineNamespace) {
1585 while (F.hasNext()) {
1586 NamedDecl *D = F.next();
1587
1588 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1589 continue;
1590
1591 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1592 continue;
1593
1594 F.erase();
1595 }
1596
1597 F.done();
1598}
1599
1601 // [module.interface]p7:
1602 // A declaration is attached to a module as follows:
1603 // - If the declaration is a non-dependent friend declaration that nominates a
1604 // function with a declarator-id that is a qualified-id or template-id or that
1605 // nominates a class other than with an elaborated-type-specifier with neither
1606 // a nested-name-specifier nor a simple-template-id, it is attached to the
1607 // module to which the friend is attached ([basic.link]).
1608 if (New->getFriendObjectKind() &&
1612 return false;
1613 }
1614
1615 Module *NewM = New->getOwningModule();
1616 Module *OldM = Old->getOwningModule();
1617
1618 if (NewM && NewM->isPrivateModule())
1619 NewM = NewM->Parent;
1620 if (OldM && OldM->isPrivateModule())
1621 OldM = OldM->Parent;
1622
1623 if (NewM == OldM)
1624 return false;
1625
1626 if (NewM && OldM) {
1627 // A module implementation unit has visibility of the decls in its
1628 // implicitly imported interface.
1629 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1630 return false;
1631
1632 // Partitions are part of the module, but a partition could import another
1633 // module, so verify that the PMIs agree.
1634 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1635 getASTContext().isInSameModule(NewM, OldM))
1636 return false;
1637 }
1638
1639 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1640 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1641 if (NewIsModuleInterface || OldIsModuleInterface) {
1642 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1643 // if a declaration of D [...] appears in the purview of a module, all
1644 // other such declarations shall appear in the purview of the same module
1645 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1646 << New
1647 << NewIsModuleInterface
1648 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1649 << OldIsModuleInterface
1650 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1651 Diag(Old->getLocation(), diag::note_previous_declaration);
1652 New->setInvalidDecl();
1653 return true;
1654 }
1655
1656 return false;
1657}
1658
1660 // [module.interface]p1:
1661 // An export-declaration shall inhabit a namespace scope.
1662 //
1663 // So it is meaningless to talk about redeclaration which is not at namespace
1664 // scope.
1665 if (!New->getLexicalDeclContext()
1667 ->isFileContext() ||
1668 !Old->getLexicalDeclContext()
1670 ->isFileContext())
1671 return false;
1672
1673 bool IsNewExported = New->isInExportDeclContext();
1674 bool IsOldExported = Old->isInExportDeclContext();
1675
1676 // It should be irrevelant if both of them are not exported.
1677 if (!IsNewExported && !IsOldExported)
1678 return false;
1679
1680 if (IsOldExported)
1681 return false;
1682
1683 // If the Old declaration are not attached to named modules
1684 // and the New declaration are attached to global module.
1685 // It should be fine to allow the export since it doesn't change
1686 // the linkage of declarations. See
1687 // https://github.com/llvm/llvm-project/issues/98583 for details.
1688 if (!Old->isInNamedModule() && New->getOwningModule() &&
1690 return false;
1691
1692 assert(IsNewExported);
1693
1694 auto Lk = Old->getFormalLinkage();
1695 int S = 0;
1696 if (Lk == Linkage::Internal)
1697 S = 1;
1698 else if (Lk == Linkage::Module)
1699 S = 2;
1700 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1701 Diag(Old->getLocation(), diag::note_previous_declaration);
1702 return true;
1703}
1704
1707 return true;
1708
1709 if (CheckRedeclarationExported(New, Old))
1710 return true;
1711
1712 return false;
1713}
1714
1716 const NamedDecl *Old) const {
1717 assert(getASTContext().isSameEntity(New, Old) &&
1718 "New and Old are not the same definition, we should diagnostic it "
1719 "immediately instead of checking it.");
1720 assert(const_cast<Sema *>(this)->isReachable(New) &&
1721 const_cast<Sema *>(this)->isReachable(Old) &&
1722 "We shouldn't see unreachable definitions here.");
1723
1724 Module *NewM = New->getOwningModule();
1725 Module *OldM = Old->getOwningModule();
1726
1727 // We only checks for named modules here. The header like modules is skipped.
1728 // FIXME: This is not right if we import the header like modules in the module
1729 // purview.
1730 //
1731 // For example, assuming "header.h" provides definition for `D`.
1732 // ```C++
1733 // //--- M.cppm
1734 // export module M;
1735 // import "header.h"; // or #include "header.h" but import it by clang modules
1736 // actually.
1737 //
1738 // //--- Use.cpp
1739 // import M;
1740 // import "header.h"; // or uses clang modules.
1741 // ```
1742 //
1743 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1744 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1745 // reject it. But the current implementation couldn't detect the case since we
1746 // don't record the information about the importee modules.
1747 //
1748 // But this might not be painful in practice. Since the design of C++20 Named
1749 // Modules suggests us to use headers in global module fragment instead of
1750 // module purview.
1751 if (NewM && NewM->isHeaderLikeModule())
1752 NewM = nullptr;
1753 if (OldM && OldM->isHeaderLikeModule())
1754 OldM = nullptr;
1755
1756 if (!NewM && !OldM)
1757 return true;
1758
1759 // [basic.def.odr]p14.3
1760 // Each such definition shall not be attached to a named module
1761 // ([module.unit]).
1762 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1763 return true;
1764
1765 // Then New and Old lives in the same TU if their share one same module unit.
1766 if (NewM)
1767 NewM = NewM->getTopLevelModule();
1768 if (OldM)
1769 OldM = OldM->getTopLevelModule();
1770 return OldM == NewM;
1771}
1772
1774 if (D->getDeclContext()->isFileContext())
1775 return false;
1776
1777 return isa<UsingShadowDecl>(D) ||
1778 isa<UnresolvedUsingTypenameDecl>(D) ||
1779 isa<UnresolvedUsingValueDecl>(D);
1780}
1781
1782/// Removes using shadow declarations not at class scope from the lookup
1783/// results.
1786 while (F.hasNext())
1788 F.erase();
1789
1790 F.done();
1791}
1792
1793/// Check for this common pattern:
1794/// @code
1795/// class S {
1796/// S(const S&); // DO NOT IMPLEMENT
1797/// void operator=(const S&); // DO NOT IMPLEMENT
1798/// };
1799/// @endcode
1801 // FIXME: Should check for private access too but access is set after we get
1802 // the decl here.
1803 if (D->doesThisDeclarationHaveABody())
1804 return false;
1805
1806 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1807 return CD->isCopyConstructor();
1808 return D->isCopyAssignmentOperator();
1809}
1810
1811bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1812 const DeclContext *DC = D->getDeclContext();
1813 while (!DC->isTranslationUnit()) {
1814 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1815 if (!RD->hasNameForLinkage())
1816 return true;
1817 }
1818 DC = DC->getParent();
1819 }
1820
1821 return !D->isExternallyVisible();
1822}
1823
1824// FIXME: This needs to be refactored; some other isInMainFile users want
1825// these semantics.
1826static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1828 return false;
1829 return S.SourceMgr.isInMainFile(Loc);
1830}
1831
1833 assert(D);
1834
1835 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1836 return false;
1837
1838 // Ignore all entities declared within templates, and out-of-line definitions
1839 // of members of class templates.
1842 return false;
1843
1844 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1845 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1846 return false;
1847 // A non-out-of-line declaration of a member specialization was implicitly
1848 // instantiated; it's the out-of-line declaration that we're interested in.
1849 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1850 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1851 return false;
1852
1853 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1854 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1855 return false;
1856 } else {
1857 // 'static inline' functions are defined in headers; don't warn.
1858 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1859 return false;
1860 }
1861
1862 if (FD->doesThisDeclarationHaveABody() &&
1864 return false;
1865 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1866 // Constants and utility variables are defined in headers with internal
1867 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1868 // like "inline".)
1869 if (!isMainFileLoc(*this, VD->getLocation()))
1870 return false;
1871
1872 if (Context.DeclMustBeEmitted(VD))
1873 return false;
1874
1875 if (VD->isStaticDataMember() &&
1876 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1877 return false;
1878 if (VD->isStaticDataMember() &&
1879 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1880 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1881 return false;
1882
1883 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1884 return false;
1885 } else {
1886 return false;
1887 }
1888
1889 // Only warn for unused decls internal to the translation unit.
1890 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1891 // for inline functions defined in the main source file, for instance.
1892 return mightHaveNonExternalLinkage(D);
1893}
1894
1896 if (!D)
1897 return;
1898
1899 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1900 const FunctionDecl *First = FD->getFirstDecl();
1902 return; // First should already be in the vector.
1903 }
1904
1905 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1906 const VarDecl *First = VD->getFirstDecl();
1908 return; // First should already be in the vector.
1909 }
1910
1913}
1914
1915static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1916 const NamedDecl *D) {
1917 if (D->isInvalidDecl())
1918 return false;
1919
1920 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1921 // For a decomposition declaration, warn if none of the bindings are
1922 // referenced, instead of if the variable itself is referenced (which
1923 // it is, by the bindings' expressions).
1924 bool IsAllPlaceholders = true;
1925 for (const auto *BD : DD->bindings()) {
1926 if (BD->isReferenced() || BD->hasAttr<UnusedAttr>())
1927 return false;
1928 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1929 }
1930 if (IsAllPlaceholders)
1931 return false;
1932 } else if (!D->getDeclName()) {
1933 return false;
1934 } else if (D->isReferenced() || D->isUsed()) {
1935 return false;
1936 }
1937
1938 if (D->isPlaceholderVar(LangOpts))
1939 return false;
1940
1941 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1942 D->hasAttr<CleanupAttr>())
1943 return false;
1944
1945 if (isa<LabelDecl>(D))
1946 return true;
1947
1948 // Except for labels, we only care about unused decls that are local to
1949 // functions.
1950 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1951 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1952 // For dependent types, the diagnostic is deferred.
1953 WithinFunction =
1954 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1955 if (!WithinFunction)
1956 return false;
1957
1958 if (isa<TypedefNameDecl>(D))
1959 return true;
1960
1961 // White-list anything that isn't a local variable.
1962 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1963 return false;
1964
1965 // Types of valid local variables should be complete, so this should succeed.
1966 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1967
1968 const Expr *Init = VD->getInit();
1969 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
1970 Init = Cleanups->getSubExpr();
1971
1972 const auto *Ty = VD->getType().getTypePtr();
1973
1974 // Only look at the outermost level of typedef.
1975 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1976 // Allow anything marked with __attribute__((unused)).
1977 if (TT->getDecl()->hasAttr<UnusedAttr>())
1978 return false;
1979 }
1980
1981 // Warn for reference variables whose initializtion performs lifetime
1982 // extension.
1983 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
1984 MTE && MTE->getExtendingDecl()) {
1985 Ty = VD->getType().getNonReferenceType().getTypePtr();
1986 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1987 }
1988
1989 // If we failed to complete the type for some reason, or if the type is
1990 // dependent, don't diagnose the variable.
1991 if (Ty->isIncompleteType() || Ty->isDependentType())
1992 return false;
1993
1994 // Look at the element type to ensure that the warning behaviour is
1995 // consistent for both scalars and arrays.
1996 Ty = Ty->getBaseElementTypeUnsafe();
1997
1998 if (const TagType *TT = Ty->getAs<TagType>()) {
1999 const TagDecl *Tag = TT->getDecl();
2000 if (Tag->hasAttr<UnusedAttr>())
2001 return false;
2002
2003 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2004 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2005 return false;
2006
2007 if (Init) {
2008 const auto *Construct =
2009 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2010 if (Construct && !Construct->isElidable()) {
2011 const CXXConstructorDecl *CD = Construct->getConstructor();
2012 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2013 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2014 return false;
2015 }
2016
2017 // Suppress the warning if we don't know how this is constructed, and
2018 // it could possibly be non-trivial constructor.
2019 if (Init->isTypeDependent()) {
2020 for (const CXXConstructorDecl *Ctor : RD->ctors())
2021 if (!Ctor->isTrivial())
2022 return false;
2023 }
2024
2025 // Suppress the warning if the constructor is unresolved because
2026 // its arguments are dependent.
2027 if (isa<CXXUnresolvedConstructExpr>(Init))
2028 return false;
2029 }
2030 }
2031 }
2032
2033 // TODO: __attribute__((unused)) templates?
2034 }
2035
2036 return true;
2037}
2038
2040 FixItHint &Hint) {
2041 if (isa<LabelDecl>(D)) {
2043 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2044 /*SkipTrailingWhitespaceAndNewline=*/false);
2045 if (AfterColon.isInvalid())
2046 return;
2049 }
2050}
2051
2054 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2055}
2056
2058 DiagReceiverTy DiagReceiver) {
2059 if (D->getTypeForDecl()->isDependentType())
2060 return;
2061
2062 for (auto *TmpD : D->decls()) {
2063 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2064 DiagnoseUnusedDecl(T, DiagReceiver);
2065 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2066 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2067 }
2068}
2069
2072 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2073}
2074
2077 return;
2078
2079 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2080 // typedefs can be referenced later on, so the diagnostics are emitted
2081 // at end-of-translation-unit.
2083 return;
2084 }
2085
2086 FixItHint Hint;
2088
2089 unsigned DiagID;
2090 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2091 DiagID = diag::warn_unused_exception_param;
2092 else if (isa<LabelDecl>(D))
2093 DiagID = diag::warn_unused_label;
2094 else
2095 DiagID = diag::warn_unused_variable;
2096
2097 SourceLocation DiagLoc = D->getLocation();
2098 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2099}
2100
2102 DiagReceiverTy DiagReceiver) {
2103 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2104 // it's not really unused.
2105 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2106 return;
2107
2108 // In C++, `_` variables behave as if they were maybe_unused
2109 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2110 return;
2111
2112 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2113
2114 if (Ty->isReferenceType() || Ty->isDependentType())
2115 return;
2116
2117 if (const TagType *TT = Ty->getAs<TagType>()) {
2118 const TagDecl *Tag = TT->getDecl();
2119 if (Tag->hasAttr<UnusedAttr>())
2120 return;
2121 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2122 // mimic gcc's behavior.
2123 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2124 RD && !RD->hasAttr<WarnUnusedAttr>())
2125 return;
2126 }
2127
2128 // Don't warn about __block Objective-C pointer variables, as they might
2129 // be assigned in the block but not used elsewhere for the purpose of lifetime
2130 // extension.
2131 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2132 return;
2133
2134 // Don't warn about Objective-C pointer variables with precise lifetime
2135 // semantics; they can be used to ensure ARC releases the object at a known
2136 // time, which may mean assignment but no other references.
2137 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2138 return;
2139
2140 auto iter = RefsMinusAssignments.find(VD);
2141 if (iter == RefsMinusAssignments.end())
2142 return;
2143
2144 assert(iter->getSecond() >= 0 &&
2145 "Found a negative number of references to a VarDecl");
2146 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2147 // Assume the given VarDecl is "used" if its ref count stored in
2148 // `RefMinusAssignments` is positive, with one exception.
2149 //
2150 // For a C++ variable whose decl (with initializer) entirely consist the
2151 // condition expression of a if/while/for construct,
2152 // Clang creates a DeclRefExpr for the condition expression rather than a
2153 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2154 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2155 // used in the body of the if/while/for construct.
2156 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2157 if (!UnusedCXXCondDecl)
2158 return;
2159 }
2160
2161 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2162 : diag::warn_unused_but_set_variable;
2163 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2164}
2165
2167 Sema::DiagReceiverTy DiagReceiver) {
2168 // Verify that we have no forward references left. If so, there was a goto
2169 // or address of a label taken, but no definition of it. Label fwd
2170 // definitions are indicated with a null substmt which is also not a resolved
2171 // MS inline assembly label name.
2172 bool Diagnose = false;
2173 if (L->isMSAsmLabel())
2174 Diagnose = !L->isResolvedMSAsmLabel();
2175 else
2176 Diagnose = L->getStmt() == nullptr;
2177 if (Diagnose)
2178 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2179 << L);
2180}
2181
2183 S->applyNRVO();
2184
2185 if (S->decl_empty()) return;
2186 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2187 "Scope shouldn't contain decls!");
2188
2189 /// We visit the decls in non-deterministic order, but we want diagnostics
2190 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2191 /// and sort the diagnostics before emitting them, after we visited all decls.
2192 struct LocAndDiag {
2194 std::optional<SourceLocation> PreviousDeclLoc;
2196 };
2198 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2199 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2200 };
2201 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2202 SourceLocation PreviousDeclLoc,
2203 PartialDiagnostic PD) {
2204 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2205 };
2206
2207 for (auto *TmpD : S->decls()) {
2208 assert(TmpD && "This decl didn't get pushed??");
2209
2210 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2211 NamedDecl *D = cast<NamedDecl>(TmpD);
2212
2213 // Diagnose unused variables in this scope.
2214 if (!S->hasUnrecoverableErrorOccurred()) {
2215 DiagnoseUnusedDecl(D, addDiag);
2216 if (const auto *RD = dyn_cast<RecordDecl>(D))
2217 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2218 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2219 DiagnoseUnusedButSetDecl(VD, addDiag);
2220 RefsMinusAssignments.erase(VD);
2221 }
2222 }
2223
2224 if (!D->getDeclName()) continue;
2225
2226 // If this was a forward reference to a label, verify it was defined.
2227 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2228 CheckPoppedLabel(LD, *this, addDiag);
2229
2230 // Partial translation units that are created in incremental processing must
2231 // not clean up the IdResolver because PTUs should take into account the
2232 // declarations that came from previous PTUs.
2236
2237 // Warn on it if we are shadowing a declaration.
2238 auto ShadowI = ShadowingDecls.find(D);
2239 if (ShadowI != ShadowingDecls.end()) {
2240 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2241 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2242 PDiag(diag::warn_ctor_parm_shadows_field)
2243 << D << FD << FD->getParent());
2244 }
2245 ShadowingDecls.erase(ShadowI);
2246 }
2247 }
2248
2249 llvm::sort(DeclDiags,
2250 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2251 // The particular order for diagnostics is not important, as long
2252 // as the order is deterministic. Using the raw location is going
2253 // to generally be in source order unless there are macro
2254 // expansions involved.
2255 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2256 });
2257 for (const LocAndDiag &D : DeclDiags) {
2258 Diag(D.Loc, D.PD);
2259 if (D.PreviousDeclLoc)
2260 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2261 }
2262}
2263
2265 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2266 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2267 (S->isClassScope() && !getLangOpts().CPlusPlus))
2268 S = S->getParent();
2269 return S;
2270}
2271
2272static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2274 switch (Error) {
2276 return "";
2278 return BuiltinInfo.getHeaderName(ID);
2280 return "stdio.h";
2282 return "setjmp.h";
2284 return "ucontext.h";
2285 }
2286 llvm_unreachable("unhandled error kind");
2287}
2288
2290 unsigned ID, SourceLocation Loc) {
2292
2293 if (getLangOpts().CPlusPlus) {
2296 CLinkageDecl->setImplicit();
2297 Parent->addDecl(CLinkageDecl);
2298 Parent = CLinkageDecl;
2299 }
2300
2303 assert(getLangOpts().CPlusPlus20 &&
2304 "consteval builtins should only be available in C++20 mode");
2305 ConstexprKind = ConstexprSpecKind::Consteval;
2306 }
2307
2309 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2310 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2311 Type->isFunctionProtoType(), ConstexprKind);
2312 New->setImplicit();
2313 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2314
2315 // Create Decl objects for each parameter, adding them to the
2316 // FunctionDecl.
2317 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2319 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2321 Context, New, SourceLocation(), SourceLocation(), nullptr,
2322 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2323 parm->setScopeInfo(0, i);
2324 Params.push_back(parm);
2325 }
2326 New->setParams(Params);
2327 }
2328
2330 return New;
2331}
2332
2334 Scope *S, bool ForRedeclaration,
2337
2339 QualType R = Context.GetBuiltinType(ID, Error);
2340 if (Error) {
2341 if (!ForRedeclaration)
2342 return nullptr;
2343
2344 // If we have a builtin without an associated type we should not emit a
2345 // warning when we were not able to find a type for it.
2346 if (Error == ASTContext::GE_Missing_type ||
2348 return nullptr;
2349
2350 // If we could not find a type for setjmp it is because the jmp_buf type was
2351 // not defined prior to the setjmp declaration.
2352 if (Error == ASTContext::GE_Missing_setjmp) {
2353 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2355 return nullptr;
2356 }
2357
2358 // Generally, we emit a warning that the declaration requires the
2359 // appropriate header.
2360 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2361 << getHeaderName(Context.BuiltinInfo, ID, Error)
2363 return nullptr;
2364 }
2365
2366 if (!ForRedeclaration &&
2369 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2370 : diag::ext_implicit_lib_function_decl)
2371 << Context.BuiltinInfo.getName(ID) << R;
2372 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2373 Diag(Loc, diag::note_include_header_or_declare)
2374 << Header << Context.BuiltinInfo.getName(ID);
2375 }
2376
2377 if (R.isNull())
2378 return nullptr;
2379
2380 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2382
2383 // TUScope is the translation-unit scope to insert this function into.
2384 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2385 // relate Scopes to DeclContexts, and probably eliminate CurContext
2386 // entirely, but we're not there yet.
2387 DeclContext *SavedContext = CurContext;
2388 CurContext = New->getDeclContext();
2390 CurContext = SavedContext;
2391 return New;
2392}
2393
2394/// Typedef declarations don't have linkage, but they still denote the same
2395/// entity if their types are the same.
2396/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2397/// isSameEntity.
2398static void
2401 // This is only interesting when modules are enabled.
2402 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2403 return;
2404
2405 // Empty sets are uninteresting.
2406 if (Previous.empty())
2407 return;
2408
2409 LookupResult::Filter Filter = Previous.makeFilter();
2410 while (Filter.hasNext()) {
2411 NamedDecl *Old = Filter.next();
2412
2413 // Non-hidden declarations are never ignored.
2414 if (S.isVisible(Old))
2415 continue;
2416
2417 // Declarations of the same entity are not ignored, even if they have
2418 // different linkages.
2419 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2420 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2421 Decl->getUnderlyingType()))
2422 continue;
2423
2424 // If both declarations give a tag declaration a typedef name for linkage
2425 // purposes, then they declare the same entity.
2426 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2427 Decl->getAnonDeclWithTypedefName())
2428 continue;
2429 }
2430
2431 Filter.erase();
2432 }
2433
2434 Filter.done();
2435}
2436
2438 QualType OldType;
2439 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2440 OldType = OldTypedef->getUnderlyingType();
2441 else
2442 OldType = Context.getTypeDeclType(Old);
2443 QualType NewType = New->getUnderlyingType();
2444
2445 if (NewType->isVariablyModifiedType()) {
2446 // Must not redefine a typedef with a variably-modified type.
2447 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2448 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2449 << Kind << NewType;
2450 if (Old->getLocation().isValid())
2452 New->setInvalidDecl();
2453 return true;
2454 }
2455
2456 if (OldType != NewType &&
2457 !OldType->isDependentType() &&
2458 !NewType->isDependentType() &&
2459 !Context.hasSameType(OldType, NewType)) {
2460 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2461 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2462 << Kind << NewType << OldType;
2463 if (Old->getLocation().isValid())
2465 New->setInvalidDecl();
2466 return true;
2467 }
2468 return false;
2469}
2470
2472 LookupResult &OldDecls) {
2473 // If the new decl is known invalid already, don't bother doing any
2474 // merging checks.
2475 if (New->isInvalidDecl()) return;
2476
2477 // Allow multiple definitions for ObjC built-in typedefs.
2478 // FIXME: Verify the underlying types are equivalent!
2479 if (getLangOpts().ObjC) {
2480 const IdentifierInfo *TypeID = New->getIdentifier();
2481 switch (TypeID->getLength()) {
2482 default: break;
2483 case 2:
2484 {
2485 if (!TypeID->isStr("id"))
2486 break;
2487 QualType T = New->getUnderlyingType();
2488 if (!T->isPointerType())
2489 break;
2490 if (!T->isVoidPointerType()) {
2492 if (!PT->isStructureType())
2493 break;
2494 }
2496 // Install the built-in type for 'id', ignoring the current definition.
2498 return;
2499 }
2500 case 5:
2501 if (!TypeID->isStr("Class"))
2502 break;
2504 // Install the built-in type for 'Class', ignoring the current definition.
2506 return;
2507 case 3:
2508 if (!TypeID->isStr("SEL"))
2509 break;
2511 // Install the built-in type for 'SEL', ignoring the current definition.
2513 return;
2514 }
2515 // Fall through - the typedef name was not a builtin type.
2516 }
2517
2518 // Verify the old decl was also a type.
2519 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2520 if (!Old) {
2521 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2522 << New->getDeclName();
2523
2524 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2525 if (OldD->getLocation().isValid())
2526 notePreviousDefinition(OldD, New->getLocation());
2527
2528 return New->setInvalidDecl();
2529 }
2530
2531 // If the old declaration is invalid, just give up here.
2532 if (Old->isInvalidDecl())
2533 return New->setInvalidDecl();
2534
2535 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2536 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2537 auto *NewTag = New->getAnonDeclWithTypedefName();
2538 NamedDecl *Hidden = nullptr;
2539 if (OldTag && NewTag &&
2540 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2541 !hasVisibleDefinition(OldTag, &Hidden)) {
2542 // There is a definition of this tag, but it is not visible. Use it
2543 // instead of our tag.
2544 New->setTypeForDecl(OldTD->getTypeForDecl());
2545 if (OldTD->isModed())
2546 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2547 OldTD->getUnderlyingType());
2548 else
2549 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2550
2551 // Make the old tag definition visible.
2553
2554 // If this was an unscoped enumeration, yank all of its enumerators
2555 // out of the scope.
2556 if (isa<EnumDecl>(NewTag)) {
2557 Scope *EnumScope = getNonFieldDeclScope(S);
2558 for (auto *D : NewTag->decls()) {
2559 auto *ED = cast<EnumConstantDecl>(D);
2560 assert(EnumScope->isDeclScope(ED));
2561 EnumScope->RemoveDecl(ED);
2563 ED->getLexicalDeclContext()->removeDecl(ED);
2564 }
2565 }
2566 }
2567 }
2568
2569 // If the typedef types are not identical, reject them in all languages and
2570 // with any extensions enabled.
2571 if (isIncompatibleTypedef(Old, New))
2572 return;
2573
2574 // The types match. Link up the redeclaration chain and merge attributes if
2575 // the old declaration was a typedef.
2576 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2577 New->setPreviousDecl(Typedef);
2578 mergeDeclAttributes(New, Old);
2579 }
2580
2581 if (getLangOpts().MicrosoftExt)
2582 return;
2583
2584 if (getLangOpts().CPlusPlus) {
2585 // C++ [dcl.typedef]p2:
2586 // In a given non-class scope, a typedef specifier can be used to
2587 // redefine the name of any type declared in that scope to refer
2588 // to the type to which it already refers.
2589 if (!isa<CXXRecordDecl>(CurContext))
2590 return;
2591
2592 // C++0x [dcl.typedef]p4:
2593 // In a given class scope, a typedef specifier can be used to redefine
2594 // any class-name declared in that scope that is not also a typedef-name
2595 // to refer to the type to which it already refers.
2596 //
2597 // This wording came in via DR424, which was a correction to the
2598 // wording in DR56, which accidentally banned code like:
2599 //
2600 // struct S {
2601 // typedef struct A { } A;
2602 // };
2603 //
2604 // in the C++03 standard. We implement the C++0x semantics, which
2605 // allow the above but disallow
2606 //
2607 // struct S {
2608 // typedef int I;
2609 // typedef int I;
2610 // };
2611 //
2612 // since that was the intent of DR56.
2613 if (!isa<TypedefNameDecl>(Old))
2614 return;
2615
2616 Diag(New->getLocation(), diag::err_redefinition)
2617 << New->getDeclName();
2619 return New->setInvalidDecl();
2620 }
2621
2622 // Modules always permit redefinition of typedefs, as does C11.
2623 if (getLangOpts().Modules || getLangOpts().C11)
2624 return;
2625
2626 // If we have a redefinition of a typedef in C, emit a warning. This warning
2627 // is normally mapped to an error, but can be controlled with
2628 // -Wtypedef-redefinition. If either the original or the redefinition is
2629 // in a system header, don't emit this for compatibility with GCC.
2630 if (getDiagnostics().getSuppressSystemWarnings() &&
2631 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2632 (Old->isImplicit() ||
2635 return;
2636
2637 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2638 << New->getDeclName();
2640}
2641
2642/// DeclhasAttr - returns true if decl Declaration already has the target
2643/// attribute.
2644static bool DeclHasAttr(const Decl *D, const Attr *A) {
2645 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2646 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2647 for (const auto *i : D->attrs())
2648 if (i->getKind() == A->getKind()) {
2649 if (Ann) {
2650 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2651 return true;
2652 continue;
2653 }
2654 // FIXME: Don't hardcode this check
2655 if (OA && isa<OwnershipAttr>(i))
2656 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2657 return true;
2658 }
2659
2660 return false;
2661}
2662
2664 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2665 return VD->isThisDeclarationADefinition();
2666 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2667 return TD->isCompleteDefinition() || TD->isBeingDefined();
2668 return true;
2669}
2670
2671/// Merge alignment attributes from \p Old to \p New, taking into account the
2672/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2673///
2674/// \return \c true if any attributes were added to \p New.
2675static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2676 // Look for alignas attributes on Old, and pick out whichever attribute
2677 // specifies the strictest alignment requirement.
2678 AlignedAttr *OldAlignasAttr = nullptr;
2679 AlignedAttr *OldStrictestAlignAttr = nullptr;
2680 unsigned OldAlign = 0;
2681 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2682 // FIXME: We have no way of representing inherited dependent alignments
2683 // in a case like:
2684 // template<int A, int B> struct alignas(A) X;
2685 // template<int A, int B> struct alignas(B) X {};
2686 // For now, we just ignore any alignas attributes which are not on the
2687 // definition in such a case.
2688 if (I->isAlignmentDependent())
2689 return false;
2690
2691 if (I->isAlignas())
2692 OldAlignasAttr = I;
2693
2694 unsigned Align = I->getAlignment(S.Context);
2695 if (Align > OldAlign) {
2696 OldAlign = Align;
2697 OldStrictestAlignAttr = I;
2698 }
2699 }
2700
2701 // Look for alignas attributes on New.
2702 AlignedAttr *NewAlignasAttr = nullptr;
2703 unsigned NewAlign = 0;
2704 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2705 if (I->isAlignmentDependent())
2706 return false;
2707
2708 if (I->isAlignas())
2709 NewAlignasAttr = I;
2710
2711 unsigned Align = I->getAlignment(S.Context);
2712 if (Align > NewAlign)
2713 NewAlign = Align;
2714 }
2715
2716 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2717 // Both declarations have 'alignas' attributes. We require them to match.
2718 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2719 // fall short. (If two declarations both have alignas, they must both match
2720 // every definition, and so must match each other if there is a definition.)
2721
2722 // If either declaration only contains 'alignas(0)' specifiers, then it
2723 // specifies the natural alignment for the type.
2724 if (OldAlign == 0 || NewAlign == 0) {
2725 QualType Ty;
2726 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2727 Ty = VD->getType();
2728 else
2729 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2730
2731 if (OldAlign == 0)
2732 OldAlign = S.Context.getTypeAlign(Ty);
2733 if (NewAlign == 0)
2734 NewAlign = S.Context.getTypeAlign(Ty);
2735 }
2736
2737 if (OldAlign != NewAlign) {
2738 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2741 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2742 }
2743 }
2744
2745 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2746 // C++11 [dcl.align]p6:
2747 // if any declaration of an entity has an alignment-specifier,
2748 // every defining declaration of that entity shall specify an
2749 // equivalent alignment.
2750 // C11 6.7.5/7:
2751 // If the definition of an object does not have an alignment
2752 // specifier, any other declaration of that object shall also
2753 // have no alignment specifier.
2754 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2755 << OldAlignasAttr;
2756 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2757 << OldAlignasAttr;
2758 }
2759
2760 bool AnyAdded = false;
2761
2762 // Ensure we have an attribute representing the strictest alignment.
2763 if (OldAlign > NewAlign) {
2764 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2765 Clone->setInherited(true);
2766 New->addAttr(Clone);
2767 AnyAdded = true;
2768 }
2769
2770 // Ensure we have an alignas attribute if the old declaration had one.
2771 if (OldAlignasAttr && !NewAlignasAttr &&
2772 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2773 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2774 Clone->setInherited(true);
2775 New->addAttr(Clone);
2776 AnyAdded = true;
2777 }
2778
2779 return AnyAdded;
2780}
2781
2782#define WANT_DECL_MERGE_LOGIC
2783#include "clang/Sema/AttrParsedAttrImpl.inc"
2784#undef WANT_DECL_MERGE_LOGIC
2785
2787 const InheritableAttr *Attr,
2789 // Diagnose any mutual exclusions between the attribute that we want to add
2790 // and attributes that already exist on the declaration.
2791 if (!DiagnoseMutualExclusions(S, D, Attr))
2792 return false;
2793
2794 // This function copies an attribute Attr from a previous declaration to the
2795 // new declaration D if the new declaration doesn't itself have that attribute
2796 // yet or if that attribute allows duplicates.
2797 // If you're adding a new attribute that requires logic different from
2798 // "use explicit attribute on decl if present, else use attribute from
2799 // previous decl", for example if the attribute needs to be consistent
2800 // between redeclarations, you need to call a custom merge function here.
2801 InheritableAttr *NewAttr = nullptr;
2802 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2803 NewAttr = S.mergeAvailabilityAttr(
2804 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2805 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2806 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2807 AA->getPriority(), AA->getEnvironment());
2808 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2809 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2810 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2811 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2812 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2813 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2814 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2815 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2816 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2817 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2818 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2819 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2820 FA->getFirstArg());
2821 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2822 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2823 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2824 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2825 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2826 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2827 IA->getInheritanceModel());
2828 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2829 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2830 &S.Context.Idents.get(AA->getSpelling()));
2831 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2832 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2833 isa<CUDAGlobalAttr>(Attr))) {
2834 // CUDA target attributes are part of function signature for
2835 // overloading purposes and must not be merged.
2836 return false;
2837 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2838 NewAttr = S.mergeMinSizeAttr(D, *MA);
2839 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2840 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2841 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2842 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2843 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2844 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2845 else if (isa<AlignedAttr>(Attr))
2846 // AlignedAttrs are handled separately, because we need to handle all
2847 // such attributes on a declaration at the same time.
2848 NewAttr = nullptr;
2849 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2850 (AMK == Sema::AMK_Override ||
2853 NewAttr = nullptr;
2854 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2855 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2856 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2857 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2858 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2859 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2860 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2861 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2862 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2863 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2864 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2865 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2866 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2867 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2868 NT->getZ());
2869 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2870 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2871 WS->getPreferred(),
2872 WS->getSpelledArgsCount());
2873 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2874 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2875 else if (isa<SuppressAttr>(Attr))
2876 // Do nothing. Each redeclaration should be suppressed separately.
2877 NewAttr = nullptr;
2878 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2879 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2880
2881 if (NewAttr) {
2882 NewAttr->setInherited(true);
2883 D->addAttr(NewAttr);
2884 if (isa<MSInheritanceAttr>(NewAttr))
2885 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2886 return true;
2887 }
2888
2889 return false;
2890}
2891
2892static const NamedDecl *getDefinition(const Decl *D) {
2893 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2894 return TD->getDefinition();
2895 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2896 const VarDecl *Def = VD->getDefinition();
2897 if (Def)
2898 return Def;
2899 return VD->getActingDefinition();
2900 }
2901 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2902 const FunctionDecl *Def = nullptr;
2903 if (FD->isDefined(Def, true))
2904 return Def;
2905 }
2906 return nullptr;
2907}
2908
2909static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2910 for (const auto *Attribute : D->attrs())
2911 if (Attribute->getKind() == Kind)
2912 return true;
2913 return false;
2914}
2915
2916/// checkNewAttributesAfterDef - If we already have a definition, check that
2917/// there are no new attributes in this declaration.
2918static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2919 if (!New->hasAttrs())
2920 return;
2921
2922 const NamedDecl *Def = getDefinition(Old);
2923 if (!Def || Def == New)
2924 return;
2925
2926 AttrVec &NewAttributes = New->getAttrs();
2927 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2928 Attr *NewAttribute = NewAttributes[I];
2929
2930 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2931 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2932 SkipBodyInfo SkipBody;
2933 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2934
2935 // If we're skipping this definition, drop the "alias" attribute.
2936 if (SkipBody.ShouldSkip) {
2937 NewAttributes.erase(NewAttributes.begin() + I);
2938 --E;
2939 continue;
2940 }
2941 } else {
2942 VarDecl *VD = cast<VarDecl>(New);
2943 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2945 ? diag::err_alias_after_tentative
2946 : diag::err_redefinition;
2947 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2948 if (Diag == diag::err_redefinition)
2949 S.notePreviousDefinition(Def, VD->getLocation());
2950 else
2951 S.Diag(Def->getLocation(), diag::note_previous_definition);
2952 VD->setInvalidDecl();
2953 }
2954 ++I;
2955 continue;
2956 }
2957
2958 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2959 // Tentative definitions are only interesting for the alias check above.
2960 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2961 ++I;
2962 continue;
2963 }
2964 }
2965
2966 if (hasAttribute(Def, NewAttribute->getKind())) {
2967 ++I;
2968 continue; // regular attr merging will take care of validating this.
2969 }
2970
2971 if (isa<C11NoReturnAttr>(NewAttribute)) {
2972 // C's _Noreturn is allowed to be added to a function after it is defined.
2973 ++I;
2974 continue;
2975 } else if (isa<UuidAttr>(NewAttribute)) {
2976 // msvc will allow a subsequent definition to add an uuid to a class
2977 ++I;
2978 continue;
2979 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2980 if (AA->isAlignas()) {
2981 // C++11 [dcl.align]p6:
2982 // if any declaration of an entity has an alignment-specifier,
2983 // every defining declaration of that entity shall specify an
2984 // equivalent alignment.
2985 // C11 6.7.5/7:
2986 // If the definition of an object does not have an alignment
2987 // specifier, any other declaration of that object shall also
2988 // have no alignment specifier.
2989 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2990 << AA;
2991 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2992 << AA;
2993 NewAttributes.erase(NewAttributes.begin() + I);
2994 --E;
2995 continue;
2996 }
2997 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2998 // If there is a C definition followed by a redeclaration with this
2999 // attribute then there are two different definitions. In C++, prefer the
3000 // standard diagnostics.
3001 if (!S.getLangOpts().CPlusPlus) {
3002 S.Diag(NewAttribute->getLocation(),
3003 diag::err_loader_uninitialized_redeclaration);
3004 S.Diag(Def->getLocation(), diag::note_previous_definition);
3005 NewAttributes.erase(NewAttributes.begin() + I);
3006 --E;
3007 continue;
3008 }
3009 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3010 cast<VarDecl>(New)->isInline() &&
3011 !cast<VarDecl>(New)->isInlineSpecified()) {
3012 // Don't warn about applying selectany to implicitly inline variables.
3013 // Older compilers and language modes would require the use of selectany
3014 // to make such variables inline, and it would have no effect if we
3015 // honored it.
3016 ++I;
3017 continue;
3018 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3019 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3020 // declarations after definitions.
3021 ++I;
3022 continue;
3023 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3024 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3025 // error since the definition will have already been created without
3026 // the semantic effects of the attribute having been applied.
3027 S.Diag(NewAttribute->getLocation(),
3028 diag::err_sycl_entry_point_after_definition);
3029 S.Diag(Def->getLocation(), diag::note_previous_definition);
3030 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3031 ++I;
3032 continue;
3033 }
3034
3035 S.Diag(NewAttribute->getLocation(),
3036 diag::warn_attribute_precede_definition);
3037 S.Diag(Def->getLocation(), diag::note_previous_definition);
3038 NewAttributes.erase(NewAttributes.begin() + I);
3039 --E;
3040 }
3041}
3042
3043static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3044 const ConstInitAttr *CIAttr,
3045 bool AttrBeforeInit) {
3046 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3047
3048 // Figure out a good way to write this specifier on the old declaration.
3049 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3050 // enough of the attribute list spelling information to extract that without
3051 // heroics.
3052 std::string SuitableSpelling;
3053 if (S.getLangOpts().CPlusPlus20)
3054 SuitableSpelling = std::string(
3055 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3056 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3057 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3058 InsertLoc, {tok::l_square, tok::l_square,
3059 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3060 S.PP.getIdentifierInfo("require_constant_initialization"),
3061 tok::r_square, tok::r_square}));
3062 if (SuitableSpelling.empty())
3063 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3064 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3065 S.PP.getIdentifierInfo("require_constant_initialization"),
3066 tok::r_paren, tok::r_paren}));
3067 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3068 SuitableSpelling = "constinit";
3069 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3070 SuitableSpelling = "[[clang::require_constant_initialization]]";
3071 if (SuitableSpelling.empty())
3072 SuitableSpelling = "__attribute__((require_constant_initialization))";
3073 SuitableSpelling += " ";
3074
3075 if (AttrBeforeInit) {
3076 // extern constinit int a;
3077 // int a = 0; // error (missing 'constinit'), accepted as extension
3078 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3079 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3080 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3081 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3082 } else {
3083 // int a = 0;
3084 // constinit extern int a; // error (missing 'constinit')
3085 S.Diag(CIAttr->getLocation(),
3086 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3087 : diag::warn_require_const_init_added_too_late)
3088 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3089 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3090 << CIAttr->isConstinit()
3091 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3092 }
3093}
3094
3097 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3098 UsedAttr *NewAttr = OldAttr->clone(Context);
3099 NewAttr->setInherited(true);
3100 New->addAttr(NewAttr);
3101 }
3102 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3103 RetainAttr *NewAttr = OldAttr->clone(Context);
3104 NewAttr->setInherited(true);
3105 New->addAttr(NewAttr);
3106 }
3107
3108 if (!Old->hasAttrs() && !New->hasAttrs())
3109 return;
3110
3111 // [dcl.constinit]p1:
3112 // If the [constinit] specifier is applied to any declaration of a
3113 // variable, it shall be applied to the initializing declaration.
3114 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3115 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3116 if (bool(OldConstInit) != bool(NewConstInit)) {
3117 const auto *OldVD = cast<VarDecl>(Old);
3118 auto *NewVD = cast<VarDecl>(New);
3119
3120 // Find the initializing declaration. Note that we might not have linked
3121 // the new declaration into the redeclaration chain yet.
3122 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3123 if (!InitDecl &&
3124 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3125 InitDecl = NewVD;
3126
3127 if (InitDecl == NewVD) {
3128 // This is the initializing declaration. If it would inherit 'constinit',
3129 // that's ill-formed. (Note that we do not apply this to the attribute
3130 // form).
3131 if (OldConstInit && OldConstInit->isConstinit())
3132 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3133 /*AttrBeforeInit=*/true);
3134 } else if (NewConstInit) {
3135 // This is the first time we've been told that this declaration should
3136 // have a constant initializer. If we already saw the initializing
3137 // declaration, this is too late.
3138 if (InitDecl && InitDecl != NewVD) {
3139 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3140 /*AttrBeforeInit=*/false);
3141 NewVD->dropAttr<ConstInitAttr>();
3142 }
3143 }
3144 }
3145
3146 // Attributes declared post-definition are currently ignored.
3147 checkNewAttributesAfterDef(*this, New, Old);
3148
3149 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3150 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3151 if (!OldA->isEquivalent(NewA)) {
3152 // This redeclaration changes __asm__ label.
3153 Diag(New->getLocation(), diag::err_different_asm_label);
3154 Diag(OldA->getLocation(), diag::note_previous_declaration);
3155 }
3156 } else if (Old->isUsed()) {
3157 // This redeclaration adds an __asm__ label to a declaration that has
3158 // already been ODR-used.
3159 Diag(New->getLocation(), diag::err_late_asm_label_name)
3160 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3161 }
3162 }
3163
3164 // Re-declaration cannot add abi_tag's.
3165 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3166 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3167 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3168 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3169 Diag(NewAbiTagAttr->getLocation(),
3170 diag::err_new_abi_tag_on_redeclaration)
3171 << NewTag;
3172 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3173 }
3174 }
3175 } else {
3176 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3177 Diag(Old->getLocation(), diag::note_previous_declaration);
3178 }
3179 }
3180
3181 // This redeclaration adds a section attribute.
3182 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3183 if (auto *VD = dyn_cast<VarDecl>(New)) {
3184 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3185 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3186 Diag(Old->getLocation(), diag::note_previous_declaration);
3187 }
3188 }
3189 }
3190
3191 // Redeclaration adds code-seg attribute.
3192 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3193 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3194 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3195 Diag(New->getLocation(), diag::warn_mismatched_section)
3196 << 0 /*codeseg*/;
3197 Diag(Old->getLocation(), diag::note_previous_declaration);
3198 }
3199
3200 if (!Old->hasAttrs())
3201 return;
3202
3203 bool foundAny = New->hasAttrs();
3204
3205 // Ensure that any moving of objects within the allocated map is done before
3206 // we process them.
3207 if (!foundAny) New->setAttrs(AttrVec());
3208
3209 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3210 // Ignore deprecated/unavailable/availability attributes if requested.
3212 if (isa<DeprecatedAttr>(I) ||
3213 isa<UnavailableAttr>(I) ||
3214 isa<AvailabilityAttr>(I)) {
3215 switch (AMK) {
3216 case AMK_None:
3217 continue;
3218
3219 case AMK_Redeclaration:
3220 case AMK_Override:
3223 LocalAMK = AMK;
3224 break;
3225 }
3226 }
3227
3228 // Already handled.
3229 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3230 continue;
3231
3232 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3233 foundAny = true;
3234 }
3235
3236 if (mergeAlignedAttrs(*this, New, Old))
3237 foundAny = true;
3238
3239 if (!foundAny) New->dropAttrs();
3240}
3241
3242/// mergeParamDeclAttributes - Copy attributes from the old parameter
3243/// to the new one.
3245 const ParmVarDecl *oldDecl,
3246 Sema &S) {
3247 // C++11 [dcl.attr.depend]p2:
3248 // The first declaration of a function shall specify the
3249 // carries_dependency attribute for its declarator-id if any declaration
3250 // of the function specifies the carries_dependency attribute.
3251 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3252 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3253 S.Diag(CDA->getLocation(),
3254 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3255 // Find the first declaration of the parameter.
3256 // FIXME: Should we build redeclaration chains for function parameters?
3257 const FunctionDecl *FirstFD =
3258 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3259 const ParmVarDecl *FirstVD =
3260 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3261 S.Diag(FirstVD->getLocation(),
3262 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3263 }
3264
3265 if (!oldDecl->hasAttrs())
3266 return;
3267
3268 bool foundAny = newDecl->hasAttrs();
3269
3270 // Ensure that any moving of objects within the allocated map is
3271 // done before we process them.
3272 if (!foundAny) newDecl->setAttrs(AttrVec());
3273
3274 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3275 if (!DeclHasAttr(newDecl, I)) {
3276 InheritableAttr *newAttr =
3277 cast<InheritableParamAttr>(I->clone(S.Context));
3278 newAttr->setInherited(true);
3279 newDecl->addAttr(newAttr);
3280 foundAny = true;
3281 }
3282 }
3283
3284 if (!foundAny) newDecl->dropAttrs();
3285}
3286
3288 const ASTContext &Ctx) {
3289
3290 auto NoSizeInfo = [&Ctx](QualType Ty) {
3291 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3292 return true;
3293 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3294 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3295 return false;
3296 };
3297
3298 // `type[]` is equivalent to `type *` and `type[*]`.
3299 if (NoSizeInfo(Old) && NoSizeInfo(New))
3300 return true;
3301
3302 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3303 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3304 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3305 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3306 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3307 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3308 return false;
3309 return true;
3310 }
3311
3312 // Only compare size, ignore Size modifiers and CVR.
3313 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3314 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3315 Ctx.getAsConstantArrayType(New)->getSize();
3316 }
3317
3318 // Don't try to compare dependent sized array
3320 return true;
3321 }
3322
3323 return Old == New;
3324}
3325
3326static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3327 const ParmVarDecl *OldParam,
3328 Sema &S) {
3329 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3330 if (auto Newnullability = NewParam->getType()->getNullability()) {
3331 if (*Oldnullability != *Newnullability) {
3332 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3334 *Newnullability,
3336 != 0))
3338 *Oldnullability,
3340 != 0));
3341 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3342 }
3343 } else {
3344 QualType NewT = NewParam->getType();
3345 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3346 NewParam->setType(NewT);
3347 }
3348 }
3349 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3350 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3351 if (OldParamDT && NewParamDT &&
3352 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3353 QualType OldParamOT = OldParamDT->getOriginalType();
3354 QualType NewParamOT = NewParamDT->getOriginalType();
3355 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3356 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3357 << NewParam << NewParamOT;
3358 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3359 << OldParamOT;
3360 }
3361 }
3362}
3363
3364namespace {
3365
3366/// Used in MergeFunctionDecl to keep track of function parameters in
3367/// C.
3368struct GNUCompatibleParamWarning {
3369 ParmVarDecl *OldParm;
3370 ParmVarDecl *NewParm;
3371 QualType PromotedType;
3372};
3373
3374} // end anonymous namespace
3375
3376// Determine whether the previous declaration was a definition, implicit
3377// declaration, or a declaration.
3378template <typename T>
3379static std::pair<diag::kind, SourceLocation>
3380getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3381 diag::kind PrevDiag;
3382 SourceLocation OldLocation = Old->getLocation();
3383 if (Old->isThisDeclarationADefinition())
3384 PrevDiag = diag::note_previous_definition;
3385 else if (Old->isImplicit()) {
3386 PrevDiag = diag::note_previous_implicit_declaration;
3387 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3388 if (FD->getBuiltinID())
3389 PrevDiag = diag::note_previous_builtin_declaration;
3390 }
3391 if (OldLocation.isInvalid())
3392 OldLocation = New->getLocation();
3393 } else
3394 PrevDiag = diag::note_previous_declaration;
3395 return std::make_pair(PrevDiag, OldLocation);
3396}
3397
3398/// canRedefineFunction - checks if a function can be redefined. Currently,
3399/// only extern inline functions can be redefined, and even then only in
3400/// GNU89 mode.
3401static bool canRedefineFunction(const FunctionDecl *FD,
3402 const LangOptions& LangOpts) {
3403 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3404 !LangOpts.CPlusPlus &&
3405 FD->isInlineSpecified() &&
3406 FD->getStorageClass() == SC_Extern);
3407}
3408
3410 const AttributedType *AT = T->getAs<AttributedType>();
3411 while (AT && !AT->isCallingConv())
3412 AT = AT->getModifiedType()->getAs<AttributedType>();
3413 return AT;
3414}
3415
3416template <typename T>
3417static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3418 const DeclContext *DC = Old->getDeclContext();
3419 if (DC->isRecord())
3420 return false;
3421
3422 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3423 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3424 return true;
3425 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3426 return true;
3427 return false;
3428}
3429
3430template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3431static bool isExternC(VarTemplateDecl *) { return false; }
3432static bool isExternC(FunctionTemplateDecl *) { return false; }
3433
3434/// Check whether a redeclaration of an entity introduced by a
3435/// using-declaration is valid, given that we know it's not an overload
3436/// (nor a hidden tag declaration).
3437template<typename ExpectedDecl>
3439 ExpectedDecl *New) {
3440 // C++11 [basic.scope.declarative]p4:
3441 // Given a set of declarations in a single declarative region, each of
3442 // which specifies the same unqualified name,
3443 // -- they shall all refer to the same entity, or all refer to functions
3444 // and function templates; or
3445 // -- exactly one declaration shall declare a class name or enumeration
3446 // name that is not a typedef name and the other declarations shall all
3447 // refer to the same variable or enumerator, or all refer to functions
3448 // and function templates; in this case the class name or enumeration
3449 // name is hidden (3.3.10).
3450
3451 // C++11 [namespace.udecl]p14:
3452 // If a function declaration in namespace scope or block scope has the
3453 // same name and the same parameter-type-list as a function introduced
3454 // by a using-declaration, and the declarations do not declare the same
3455 // function, the program is ill-formed.
3456
3457 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3458 if (Old &&
3459 !Old->getDeclContext()->getRedeclContext()->Equals(
3460 New->getDeclContext()->getRedeclContext()) &&
3461 !(isExternC(Old) && isExternC(New)))
3462 Old = nullptr;
3463
3464 if (!Old) {
3465 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3466 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3467 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3468 return true;
3469 }
3470 return false;
3471}
3472
3474 const FunctionDecl *B) {
3475 assert(A->getNumParams() == B->getNumParams());
3476
3477 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3478 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3479 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3480 if (AttrA == AttrB)
3481 return true;
3482 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3483 AttrA->isDynamic() == AttrB->isDynamic();
3484 };
3485
3486 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3487}
3488
3489/// If necessary, adjust the semantic declaration context for a qualified
3490/// declaration to name the correct inline namespace within the qualifier.
3492 DeclaratorDecl *OldD) {
3493 // The only case where we need to update the DeclContext is when
3494 // redeclaration lookup for a qualified name finds a declaration
3495 // in an inline namespace within the context named by the qualifier:
3496 //
3497 // inline namespace N { int f(); }
3498 // int ::f(); // Sema DC needs adjusting from :: to N::.
3499 //
3500 // For unqualified declarations, the semantic context *can* change
3501 // along the redeclaration chain (for local extern declarations,
3502 // extern "C" declarations, and friend declarations in particular).
3503 if (!NewD->getQualifier())
3504 return;
3505
3506 // NewD is probably already in the right context.
3507 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3508 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3509 if (NamedDC->Equals(SemaDC))
3510 return;
3511
3512 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3513 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3514 "unexpected context for redeclaration");
3515
3516 auto *LexDC = NewD->getLexicalDeclContext();
3517 auto FixSemaDC = [=](NamedDecl *D) {
3518 if (!D)
3519 return;
3520 D->setDeclContext(SemaDC);
3521 D->setLexicalDeclContext(LexDC);
3522 };
3523
3524 FixSemaDC(NewD);
3525 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3526 FixSemaDC(FD->getDescribedFunctionTemplate());
3527 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3528 FixSemaDC(VD->getDescribedVarTemplate());
3529}
3530
3532 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3533 // Verify the old decl was also a function.
3534 FunctionDecl *Old = OldD->getAsFunction();
3535 if (!Old) {
3536 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3537 if (New->getFriendObjectKind()) {
3538 Diag(New->getLocation(), diag::err_using_decl_friend);
3539 Diag(Shadow->getTargetDecl()->getLocation(),
3540 diag::note_using_decl_target);
3541 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3542 << 0;
3543 return true;
3544 }
3545
3546 // Check whether the two declarations might declare the same function or
3547 // function template.
3548 if (FunctionTemplateDecl *NewTemplate =
3550 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3551 NewTemplate))
3552 return true;
3553 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3554 ->getAsFunction();
3555 } else {
3556 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3557 return true;
3558 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3559 }
3560 } else {
3561 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3562 << New->getDeclName();
3563 notePreviousDefinition(OldD, New->getLocation());
3564 return true;
3565 }
3566 }
3567
3568 // If the old declaration was found in an inline namespace and the new
3569 // declaration was qualified, update the DeclContext to match.
3571
3572 // If the old declaration is invalid, just give up here.
3573 if (Old->isInvalidDecl())
3574 return true;
3575
3576 // Disallow redeclaration of some builtins.
3577 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3578 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3579 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3580 << Old << Old->getType();
3581 return true;
3582 }
3583
3584 diag::kind PrevDiag;
3585 SourceLocation OldLocation;
3586 std::tie(PrevDiag, OldLocation) =
3588
3589 // Don't complain about this if we're in GNU89 mode and the old function
3590 // is an extern inline function.
3591 // Don't complain about specializations. They are not supposed to have
3592 // storage classes.
3593 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3594 New->getStorageClass() == SC_Static &&
3595 Old->hasExternalFormalLinkage() &&
3598 if (getLangOpts().MicrosoftExt) {
3599 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3600 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3601 } else {
3602 Diag(New->getLocation(), diag::err_static_non_static) << New;
3603 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3604 return true;
3605 }
3606 }
3607
3608 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3609 if (!Old->hasAttr<InternalLinkageAttr>()) {
3610 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3611 << ILA;
3612 Diag(Old->getLocation(), diag::note_previous_declaration);
3613 New->dropAttr<InternalLinkageAttr>();
3614 }
3615
3616 if (auto *EA = New->getAttr<ErrorAttr>()) {
3617 if (!Old->hasAttr<ErrorAttr>()) {
3618 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3619 Diag(Old->getLocation(), diag::note_previous_declaration);
3620 New->dropAttr<ErrorAttr>();
3621 }
3622 }
3623
3624 if (CheckRedeclarationInModule(New, Old))
3625 return true;
3626
3627 if (!getLangOpts().CPlusPlus) {
3628 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3629 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3630 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3631 << New << OldOvl;
3632
3633 // Try our best to find a decl that actually has the overloadable
3634 // attribute for the note. In most cases (e.g. programs with only one
3635 // broken declaration/definition), this won't matter.
3636 //
3637 // FIXME: We could do this if we juggled some extra state in
3638 // OverloadableAttr, rather than just removing it.
3639 const Decl *DiagOld = Old;
3640 if (OldOvl) {
3641 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3642 const auto *A = D->getAttr<OverloadableAttr>();
3643 return A && !A->isImplicit();
3644 });
3645 // If we've implicitly added *all* of the overloadable attrs to this
3646 // chain, emitting a "previous redecl" note is pointless.
3647 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3648 }
3649
3650 if (DiagOld)
3651 Diag(DiagOld->getLocation(),
3652 diag::note_attribute_overloadable_prev_overload)
3653 << OldOvl;
3654
3655 if (OldOvl)
3656 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3657 else
3658 New->dropAttr<OverloadableAttr>();
3659 }
3660 }
3661
3662 // It is not permitted to redeclare an SME function with different SME
3663 // attributes.
3664 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3665 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3666 << New->getType() << Old->getType();
3667 Diag(OldLocation, diag::note_previous_declaration);
3668 return true;
3669 }
3670
3671 // If a function is first declared with a calling convention, but is later
3672 // declared or defined without one, all following decls assume the calling
3673 // convention of the first.
3674 //
3675 // It's OK if a function is first declared without a calling convention,
3676 // but is later declared or defined with the default calling convention.
3677 //
3678 // To test if either decl has an explicit calling convention, we look for
3679 // AttributedType sugar nodes on the type as written. If they are missing or
3680 // were canonicalized away, we assume the calling convention was implicit.
3681 //
3682 // Note also that we DO NOT return at this point, because we still have
3683 // other tests to run.
3684 QualType OldQType = Context.getCanonicalType(Old->getType());
3685 QualType NewQType = Context.getCanonicalType(New->getType());
3686 const FunctionType *OldType = cast<FunctionType>(OldQType);
3687 const FunctionType *NewType = cast<FunctionType>(NewQType);
3688 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3689 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3690 bool RequiresAdjustment = false;
3691
3692 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3694 const FunctionType *FT =
3695 First->getType().getCanonicalType()->castAs<FunctionType>();
3697 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3698 if (!NewCCExplicit) {
3699 // Inherit the CC from the previous declaration if it was specified
3700 // there but not here.
3701 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3702 RequiresAdjustment = true;
3703 } else if (Old->getBuiltinID()) {
3704 // Builtin attribute isn't propagated to the new one yet at this point,
3705 // so we check if the old one is a builtin.
3706
3707 // Calling Conventions on a Builtin aren't really useful and setting a
3708 // default calling convention and cdecl'ing some builtin redeclarations is
3709 // common, so warn and ignore the calling convention on the redeclaration.
3710 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3711 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3713 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3714 RequiresAdjustment = true;
3715 } else {
3716 // Calling conventions aren't compatible, so complain.
3717 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3718 Diag(New->getLocation(), diag::err_cconv_change)
3719 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3720 << !FirstCCExplicit
3721 << (!FirstCCExplicit ? "" :
3723
3724 // Put the note on the first decl, since it is the one that matters.
3725 Diag(First->getLocation(), diag::note_previous_declaration);
3726 return true;
3727 }
3728 }
3729
3730 // FIXME: diagnose the other way around?
3731 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3732 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3733 RequiresAdjustment = true;
3734 }
3735
3736 // Merge regparm attribute.
3737 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3738 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3739 if (NewTypeInfo.getHasRegParm()) {
3740 Diag(New->getLocation(), diag::err_regparm_mismatch)
3741 << NewType->getRegParmType()
3742 << OldType->getRegParmType();
3743 Diag(OldLocation, diag::note_previous_declaration);
3744 return true;
3745 }
3746
3747 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3748 RequiresAdjustment = true;
3749 }
3750
3751 // Merge ns_returns_retained attribute.
3752 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3753 if (NewTypeInfo.getProducesResult()) {
3754 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3755 << "'ns_returns_retained'";
3756 Diag(OldLocation, diag::note_previous_declaration);
3757 return true;
3758 }
3759
3760 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3761 RequiresAdjustment = true;
3762 }
3763
3764 if (OldTypeInfo.getNoCallerSavedRegs() !=
3765 NewTypeInfo.getNoCallerSavedRegs()) {
3766 if (NewTypeInfo.getNoCallerSavedRegs()) {
3767 AnyX86NoCallerSavedRegistersAttr *Attr =
3768 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3769 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3770 Diag(OldLocation, diag::note_previous_declaration);
3771 return true;
3772 }
3773
3774 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3775 RequiresAdjustment = true;
3776 }
3777
3778 if (RequiresAdjustment) {
3781 New->setType(QualType(AdjustedType, 0));
3782 NewQType = Context.getCanonicalType(New->getType());
3783 }
3784
3785 // If this redeclaration makes the function inline, we may need to add it to
3786 // UndefinedButUsed.
3787 if (!Old->isInlined() && New->isInlined() &&
3788 !New->hasAttr<GNUInlineAttr>() &&
3789 !getLangOpts().GNUInline &&
3790 Old->isUsed(false) &&
3791 !Old->isDefined() && !New->isThisDeclarationADefinition())
3792 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3793 SourceLocation()));
3794
3795 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3796 // about it.
3797 if (New->hasAttr<GNUInlineAttr>() &&
3798 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3799 UndefinedButUsed.erase(Old->getCanonicalDecl());
3800 }
3801
3802 // If pass_object_size params don't match up perfectly, this isn't a valid
3803 // redeclaration.
3804 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3806 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3807 << New->getDeclName();
3808 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3809 return true;
3810 }
3811
3812 QualType OldQTypeForComparison = OldQType;
3814 const auto OldFX = Old->getFunctionEffects();
3815 const auto NewFX = New->getFunctionEffects();
3816 if (OldFX != NewFX) {
3817 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3818 for (const auto &Diff : Diffs) {
3819 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3820 Diag(New->getLocation(),
3821 diag::warn_mismatched_func_effect_redeclaration)
3822 << Diff.effectName();
3823 Diag(Old->getLocation(), diag::note_previous_declaration);
3824 }
3825 }
3826 // Following a warning, we could skip merging effects from the previous
3827 // declaration, but that would trigger an additional "conflicting types"
3828 // error.
3829 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3831 FunctionEffectSet MergedFX =
3832 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3833 if (!MergeErrs.empty())
3835 Old->getLocation());
3836
3837 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3838 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3839 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
3840 NewFPT->getParamTypes(), EPI);
3841
3842 New->setType(ModQT);
3843 NewQType = New->getType();
3844
3845 // Revise OldQTForComparison to include the merged effects,
3846 // so as not to fail due to differences later.
3847 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3848 EPI = OldFPT->getExtProtoInfo();
3849 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3850 OldQTypeForComparison = Context.getFunctionType(
3851 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
3852 }
3853 if (OldFX.empty()) {
3854 // A redeclaration may add the attribute to a previously seen function
3855 // body which needs to be verified.
3856 maybeAddDeclWithEffects(Old, MergedFX);
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 if (Old->isExternC() && New->isExternC() &&
3886 !Old->hasAttr<OverloadableAttr>() &&
3887 !New->hasAttr<OverloadableAttr>())
3888 Diag(New->getLocation(), diag::err_conflicting_types) << New;
3889 else
3890 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3891 << New->getReturnTypeSourceRange();
3892 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3893 << Old->getReturnTypeSourceRange();
3894 return true;
3895 }
3896 else
3897 NewQType = ResQT;
3898 }
3899
3900 QualType OldReturnType = OldType->getReturnType();
3901 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3902 if (OldReturnType != NewReturnType) {
3903 // If this function has a deduced return type and has already been
3904 // defined, copy the deduced value from the old declaration.
3905 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3906 if (OldAT && OldAT->isDeduced()) {
3907 QualType DT = OldAT->getDeducedType();
3908 if (DT.isNull()) {
3910 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3911 } else {
3912 New->setType(SubstAutoType(New->getType(), DT));
3913 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3914 }
3915 }
3916 }
3917
3918 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3919 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3920 if (OldMethod && NewMethod) {
3921 // Preserve triviality.
3922 NewMethod->setTrivial(OldMethod->isTrivial());
3923
3924 // MSVC allows explicit template specialization at class scope:
3925 // 2 CXXMethodDecls referring to the same function will be injected.
3926 // We don't want a redeclaration error.
3927 bool IsClassScopeExplicitSpecialization =
3928 OldMethod->isFunctionTemplateSpecialization() &&
3930 bool isFriend = NewMethod->getFriendObjectKind();
3931
3932 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3933 !IsClassScopeExplicitSpecialization) {
3934 // -- Member function declarations with the same name and the
3935 // same parameter types cannot be overloaded if any of them
3936 // is a static member function declaration.
3937 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3938 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3939 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3940 return true;
3941 }
3942
3943 // C++ [class.mem]p1:
3944 // [...] A member shall not be declared twice in the
3945 // member-specification, except that a nested class or member
3946 // class template can be declared and then later defined.
3947 if (!inTemplateInstantiation()) {
3948 unsigned NewDiag;
3949 if (isa<CXXConstructorDecl>(OldMethod))
3950 NewDiag = diag::err_constructor_redeclared;
3951 else if (isa<CXXDestructorDecl>(NewMethod))
3952 NewDiag = diag::err_destructor_redeclared;
3953 else if (isa<CXXConversionDecl>(NewMethod))
3954 NewDiag = diag::err_conv_function_redeclared;
3955 else
3956 NewDiag = diag::err_member_redeclared;
3957
3958 Diag(New->getLocation(), NewDiag);
3959 } else {
3960 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3961 << New << New->getType();
3962 }
3963 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3964 return true;
3965
3966 // Complain if this is an explicit declaration of a special
3967 // member that was initially declared implicitly.
3968 //
3969 // As an exception, it's okay to befriend such methods in order
3970 // to permit the implicit constructor/destructor/operator calls.
3971 } else if (OldMethod->isImplicit()) {
3972 if (isFriend) {
3973 NewMethod->setImplicit();
3974 } else {
3975 Diag(NewMethod->getLocation(),
3976 diag::err_definition_of_implicitly_declared_member)
3977 << New << llvm::to_underlying(getSpecialMember(OldMethod));
3978 return true;
3979 }
3980 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3981 Diag(NewMethod->getLocation(),
3982 diag::err_definition_of_explicitly_defaulted_member)
3983 << llvm::to_underlying(getSpecialMember(OldMethod));
3984 return true;
3985 }
3986 }
3987
3988 // C++1z [over.load]p2
3989 // Certain function declarations cannot be overloaded:
3990 // -- Function declarations that differ only in the return type,
3991 // the exception specification, or both cannot be overloaded.
3992
3993 // Check the exception specifications match. This may recompute the type of
3994 // both Old and New if it resolved exception specifications, so grab the
3995 // types again after this. Because this updates the type, we do this before
3996 // any of the other checks below, which may update the "de facto" NewQType
3997 // but do not necessarily update the type of New.
3998 if (CheckEquivalentExceptionSpec(Old, New))
3999 return true;
4000
4001 // C++11 [dcl.attr.noreturn]p1:
4002 // The first declaration of a function shall specify the noreturn
4003 // attribute if any declaration of that function specifies the noreturn
4004 // attribute.
4005 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4006 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4007 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4008 << NRA;
4009 Diag(Old->getLocation(), diag::note_previous_declaration);
4010 }
4011
4012 // C++11 [dcl.attr.depend]p2:
4013 // The first declaration of a function shall specify the
4014 // carries_dependency attribute for its declarator-id if any declaration
4015 // of the function specifies the carries_dependency attribute.
4016 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4017 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4018 Diag(CDA->getLocation(),
4019 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4020 Diag(Old->getFirstDecl()->getLocation(),
4021 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4022 }
4023
4024 // (C++98 8.3.5p3):
4025 // All declarations for a function shall agree exactly in both the
4026 // return type and the parameter-type-list.
4027 // We also want to respect all the extended bits except noreturn.
4028
4029 // noreturn should now match unless the old type info didn't have it.
4030 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4031 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4032 const FunctionType *OldTypeForComparison
4033 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4034 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4035 assert(OldQTypeForComparison.isCanonical());
4036 }
4037
4038 if (haveIncompatibleLanguageLinkages(Old, New)) {
4039 // As a special case, retain the language linkage from previous
4040 // declarations of a friend function as an extension.
4041 //
4042 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4043 // and is useful because there's otherwise no way to specify language
4044 // linkage within class scope.
4045 //
4046 // Check cautiously as the friend object kind isn't yet complete.
4047 if (New->getFriendObjectKind() != Decl::FOK_None) {
4048 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4049 Diag(OldLocation, PrevDiag);
4050 } else {
4051 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4052 Diag(OldLocation, PrevDiag);
4053 return true;
4054 }
4055 }
4056
4057 // HLSL check parameters for matching ABI specifications.
4058 if (getLangOpts().HLSL) {
4059 if (HLSL().CheckCompatibleParameterABI(New, Old))
4060 return true;
4061
4062 // If no errors are generated when checking parameter ABIs we can check if
4063 // the two declarations have the same type ignoring the ABIs and if so,
4064 // the declarations can be merged. This case for merging is only valid in
4065 // HLSL because there are no valid cases of merging mismatched parameter
4066 // ABIs except the HLSL implicit in and explicit in.
4067 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4068 NewQType))
4069 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4070 // Fall through for conflicting redeclarations and redefinitions.
4071 }
4072
4073 // If the function types are compatible, merge the declarations. Ignore the
4074 // exception specifier because it was already checked above in
4075 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4076 // about incompatible types under -fms-compatibility.
4077 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4078 NewQType))
4079 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4080
4081 // If the types are imprecise (due to dependent constructs in friends or
4082 // local extern declarations), it's OK if they differ. We'll check again
4083 // during instantiation.
4084 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4085 return false;
4086
4087 // Fall through for conflicting redeclarations and redefinitions.
4088 }
4089
4090 // C: Function types need to be compatible, not identical. This handles
4091 // duplicate function decls like "void f(int); void f(enum X);" properly.
4092 if (!getLangOpts().CPlusPlus) {
4093 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4094 // type is specified by a function definition that contains a (possibly
4095 // empty) identifier list, both shall agree in the number of parameters
4096 // and the type of each parameter shall be compatible with the type that
4097 // results from the application of default argument promotions to the
4098 // type of the corresponding identifier. ...
4099 // This cannot be handled by ASTContext::typesAreCompatible() because that
4100 // doesn't know whether the function type is for a definition or not when
4101 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4102 // we need to cover here is that the number of arguments agree as the
4103 // default argument promotion rules were already checked by
4104 // ASTContext::typesAreCompatible().
4105 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4106 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4107 if (Old->hasInheritedPrototype())
4108 Old = Old->getCanonicalDecl();
4109 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4110 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4111 return true;
4112 }
4113
4114 // If we are merging two functions where only one of them has a prototype,
4115 // we may have enough information to decide to issue a diagnostic that the
4116 // function without a prototype will change behavior in C23. This handles
4117 // cases like:
4118 // void i(); void i(int j);
4119 // void i(int j); void i();
4120 // void i(); void i(int j) {}
4121 // See ActOnFinishFunctionBody() for other cases of the behavior change
4122 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4123 // type without a prototype.
4124 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4125 !New->isImplicit() && !Old->isImplicit()) {
4126 const FunctionDecl *WithProto, *WithoutProto;
4127 if (New->hasWrittenPrototype()) {
4128 WithProto = New;
4129 WithoutProto = Old;
4130 } else {
4131 WithProto = Old;
4132 WithoutProto = New;
4133 }
4134
4135 if (WithProto->getNumParams() != 0) {
4136 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4137 // The one without the prototype will be changing behavior in C23, so
4138 // warn about that one so long as it's a user-visible declaration.
4139 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4140 if (WithoutProto == New)
4141 IsWithoutProtoADef = NewDeclIsDefn;
4142 else
4143 IsWithProtoADef = NewDeclIsDefn;
4144 Diag(WithoutProto->getLocation(),
4145 diag::warn_non_prototype_changes_behavior)
4146 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4147 << (WithoutProto == Old) << IsWithProtoADef;
4148
4149 // The reason the one without the prototype will be changing behavior
4150 // is because of the one with the prototype, so note that so long as
4151 // it's a user-visible declaration. There is one exception to this:
4152 // when the new declaration is a definition without a prototype, the
4153 // old declaration with a prototype is not the cause of the issue,
4154 // and that does not need to be noted because the one with a
4155 // prototype will not change behavior in C23.
4156 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4157 !IsWithoutProtoADef)
4158 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4159 }
4160 }
4161 }
4162
4163 if (Context.typesAreCompatible(OldQType, NewQType)) {
4164 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4165 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4166 const FunctionProtoType *OldProto = nullptr;
4167 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4168 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4169 // The old declaration provided a function prototype, but the
4170 // new declaration does not. Merge in the prototype.
4171 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4172 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4173 OldProto->getParamTypes(),
4174 OldProto->getExtProtoInfo());
4175 New->setType(NewQType);
4177
4178 // Synthesize parameters with the same types.
4180 for (const auto &ParamType : OldProto->param_types()) {
4182 Context, New, SourceLocation(), SourceLocation(), nullptr,
4183 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4184 Param->setScopeInfo(0, Params.size());
4185 Param->setImplicit();
4186 Params.push_back(Param);
4187 }
4188
4189 New->setParams(Params);
4190 }
4191
4192 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4193 }
4194 }
4195
4196 // Check if the function types are compatible when pointer size address
4197 // spaces are ignored.
4198 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4199 return false;
4200
4201 // GNU C permits a K&R definition to follow a prototype declaration
4202 // if the declared types of the parameters in the K&R definition
4203 // match the types in the prototype declaration, even when the
4204 // promoted types of the parameters from the K&R definition differ
4205 // from the types in the prototype. GCC then keeps the types from
4206 // the prototype.
4207 //
4208 // If a variadic prototype is followed by a non-variadic K&R definition,
4209 // the K&R definition becomes variadic. This is sort of an edge case, but
4210 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4211 // C99 6.9.1p8.
4212 if (!getLangOpts().CPlusPlus &&
4213 Old->hasPrototype() && !New->hasPrototype() &&
4214 New->getType()->getAs<FunctionProtoType>() &&
4215 Old->getNumParams() == New->getNumParams()) {
4218 const FunctionProtoType *OldProto
4219 = Old->getType()->getAs<FunctionProtoType>();
4220 const FunctionProtoType *NewProto
4221 = New->getType()->getAs<FunctionProtoType>();
4222
4223 // Determine whether this is the GNU C extension.
4224 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4225 NewProto->getReturnType());
4226 bool LooseCompatible = !MergedReturn.isNull();
4227 for (unsigned Idx = 0, End = Old->getNumParams();
4228 LooseCompatible && Idx != End; ++Idx) {
4229 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4230 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4231 if (Context.typesAreCompatible(OldParm->getType(),
4232 NewProto->getParamType(Idx))) {
4233 ArgTypes.push_back(NewParm->getType());
4234 } else if (Context.typesAreCompatible(OldParm->getType(),
4235 NewParm->getType(),
4236 /*CompareUnqualified=*/true)) {
4237 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4238 NewProto->getParamType(Idx) };
4239 Warnings.push_back(Warn);
4240 ArgTypes.push_back(NewParm->getType());
4241 } else
4242 LooseCompatible = false;
4243 }
4244
4245 if (LooseCompatible) {
4246 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4247 Diag(Warnings[Warn].NewParm->getLocation(),
4248 diag::ext_param_promoted_not_compatible_with_prototype)
4249 << Warnings[Warn].PromotedType
4250 << Warnings[Warn].OldParm->getType();
4251 if (Warnings[Warn].OldParm->getLocation().isValid())
4252 Diag(Warnings[Warn].OldParm->getLocation(),
4253 diag::note_previous_declaration);
4254 }
4255
4256 if (MergeTypeWithOld)
4257 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4258 OldProto->getExtProtoInfo()));
4259 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4260 }
4261
4262 // Fall through to diagnose conflicting types.
4263 }
4264
4265 // A function that has already been declared has been redeclared or
4266 // defined with a different type; show an appropriate diagnostic.
4267
4268 // If the previous declaration was an implicitly-generated builtin
4269 // declaration, then at the very least we should use a specialized note.
4270 unsigned BuiltinID;
4271 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4272 // If it's actually a library-defined builtin function like 'malloc'
4273 // or 'printf', just warn about the incompatible redeclaration.
4275 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4276 Diag(OldLocation, diag::note_previous_builtin_declaration)
4277 << Old << Old->getType();
4278 return false;
4279 }
4280
4281 PrevDiag = diag::note_previous_builtin_declaration;
4282 }
4283
4284 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4285 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4286 return true;
4287}
4288
4290 Scope *S, bool MergeTypeWithOld) {
4291 // Merge the attributes
4292 mergeDeclAttributes(New, Old);
4293
4294 // Merge "pure" flag.
4295 if (Old->isPureVirtual())
4296 New->setIsPureVirtual();
4297
4298 // Merge "used" flag.
4299 if (Old->getMostRecentDecl()->isUsed(false))
4300 New->setIsUsed();
4301
4302 // Merge attributes from the parameters. These can mismatch with K&R
4303 // declarations.
4304 if (New->getNumParams() == Old->getNumParams())
4305 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4306 ParmVarDecl *NewParam = New->getParamDecl(i);
4307 ParmVarDecl *OldParam = Old->getParamDecl(i);
4308 mergeParamDeclAttributes(NewParam, OldParam, *this);
4309 mergeParamDeclTypes(NewParam, OldParam, *this);
4310 }
4311
4312 if (getLangOpts().CPlusPlus)
4313 return MergeCXXFunctionDecl(New, Old, S);
4314
4315 // Merge the function types so the we get the composite types for the return
4316 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4317 // was visible.
4318 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4319 if (!Merged.isNull() && MergeTypeWithOld)
4320 New->setType(Merged);
4321
4322 return false;
4323}
4324
4326 ObjCMethodDecl *oldMethod) {
4327 // Merge the attributes, including deprecated/unavailable
4328 AvailabilityMergeKind MergeKind =
4329 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4332 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4333 : AMK_Override;
4334
4335 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4336
4337 // Merge attributes from the parameters.
4339 oe = oldMethod->param_end();
4341 ni = newMethod->param_begin(), ne = newMethod->param_end();
4342 ni != ne && oi != oe; ++ni, ++oi)
4343 mergeParamDeclAttributes(*ni, *oi, *this);
4344
4345 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4346}
4347
4349 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4350
4352 ? diag::err_redefinition_different_type
4353 : diag::err_redeclaration_different_type)
4354 << New->getDeclName() << New->getType() << Old->getType();
4355
4356 diag::kind PrevDiag;
4357 SourceLocation OldLocation;
4358 std::tie(PrevDiag, OldLocation)
4360 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4361 New->setInvalidDecl();
4362}
4363
4365 bool MergeTypeWithOld) {
4366 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4367 return;
4368
4369 QualType MergedT;
4370 if (getLangOpts().CPlusPlus) {
4371 if (New->getType()->isUndeducedType()) {
4372 // We don't know what the new type is until the initializer is attached.
4373 return;
4374 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4375 // These could still be something that needs exception specs checked.
4376 return MergeVarDeclExceptionSpecs(New, Old);
4377 }
4378 // C++ [basic.link]p10:
4379 // [...] the types specified by all declarations referring to a given
4380 // object or function shall be identical, except that declarations for an
4381 // array object can specify array types that differ by the presence or
4382 // absence of a major array bound (8.3.4).
4383 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4384 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4385 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4386
4387 // We are merging a variable declaration New into Old. If it has an array
4388 // bound, and that bound differs from Old's bound, we should diagnose the
4389 // mismatch.
4390 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4391 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4392 PrevVD = PrevVD->getPreviousDecl()) {
4393 QualType PrevVDTy = PrevVD->getType();
4394 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4395 continue;
4396
4397 if (!Context.hasSameType(New->getType(), PrevVDTy))
4398 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4399 }
4400 }
4401
4402 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4403 if (Context.hasSameType(OldArray->getElementType(),
4404 NewArray->getElementType()))
4405 MergedT = New->getType();
4406 }
4407 // FIXME: Check visibility. New is hidden but has a complete type. If New
4408 // has no array bound, it should not inherit one from Old, if Old is not
4409 // visible.
4410 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4411 if (Context.hasSameType(OldArray->getElementType(),
4412 NewArray->getElementType()))
4413 MergedT = Old->getType();
4414 }
4415 }
4416 else if (New->getType()->isObjCObjectPointerType() &&
4417 Old->getType()->isObjCObjectPointerType()) {
4418 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4419 Old->getType());
4420 }
4421 } else {
4422 // C 6.2.7p2:
4423 // All declarations that refer to the same object or function shall have
4424 // compatible type.
4425 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4426 }
4427 if (MergedT.isNull()) {
4428 // It's OK if we couldn't merge types if either type is dependent, for a
4429 // block-scope variable. In other cases (static data members of class
4430 // templates, variable templates, ...), we require the types to be
4431 // equivalent.
4432 // FIXME: The C++ standard doesn't say anything about this.
4433 if ((New->getType()->isDependentType() ||
4434 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4435 // If the old type was dependent, we can't merge with it, so the new type
4436 // becomes dependent for now. We'll reproduce the original type when we
4437 // instantiate the TypeSourceInfo for the variable.
4438 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4440 return;
4441 }
4442 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4443 }
4444
4445 // Don't actually update the type on the new declaration if the old
4446 // declaration was an extern declaration in a different scope.
4447 if (MergeTypeWithOld)
4448 New->setType(MergedT);
4449}
4450
4451static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4453 // C11 6.2.7p4:
4454 // For an identifier with internal or external linkage declared
4455 // in a scope in which a prior declaration of that identifier is
4456 // visible, if the prior declaration specifies internal or
4457 // external linkage, the type of the identifier at the later
4458 // declaration becomes the composite type.
4459 //
4460 // If the variable isn't visible, we do not merge with its type.
4461 if (Previous.isShadowed())
4462 return false;
4463
4464 if (S.getLangOpts().CPlusPlus) {
4465 // C++11 [dcl.array]p3:
4466 // If there is a preceding declaration of the entity in the same
4467 // scope in which the bound was specified, an omitted array bound
4468 // is taken to be the same as in that earlier declaration.
4469 return NewVD->isPreviousDeclInSameBlockScope() ||
4472 } else {
4473 // If the old declaration was function-local, don't merge with its
4474 // type unless we're in the same function.
4475 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4476 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4477 }
4478}
4479
4481 // If the new decl is already invalid, don't do any other checking.
4482 if (New->isInvalidDecl())
4483 return;
4484
4485 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4486 return;
4487
4488 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4489
4490 // Verify the old decl was also a variable or variable template.
4491 VarDecl *Old = nullptr;
4492 VarTemplateDecl *OldTemplate = nullptr;
4493 if (Previous.isSingleResult()) {
4494 if (NewTemplate) {
4495 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4496 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4497
4498 if (auto *Shadow =
4499 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4500 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4501 return New->setInvalidDecl();
4502 } else {
4503 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4504
4505 if (auto *Shadow =
4506 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4507 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4508 return New->setInvalidDecl();
4509 }
4510 }
4511 if (!Old) {
4512 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4513 << New->getDeclName();
4514 notePreviousDefinition(Previous.getRepresentativeDecl(),
4515 New->getLocation());
4516 return New->setInvalidDecl();
4517 }
4518
4519 // If the old declaration was found in an inline namespace and the new
4520 // declaration was qualified, update the DeclContext to match.
4522
4523 // Ensure the template parameters are compatible.
4524 if (NewTemplate &&
4526 OldTemplate->getTemplateParameters(),
4527 /*Complain=*/true, TPL_TemplateMatch))
4528 return New->setInvalidDecl();
4529
4530 // C++ [class.mem]p1:
4531 // A member shall not be declared twice in the member-specification [...]
4532 //
4533 // Here, we need only consider static data members.
4534 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4535 Diag(New->getLocation(), diag::err_duplicate_member)
4536 << New->getIdentifier();
4537 Diag(Old->getLocation(), diag::note_previous_declaration);
4538 New->setInvalidDecl();
4539 }
4540
4541 mergeDeclAttributes(New, Old);
4542 // Warn if an already-defined variable is made a weak_import in a subsequent
4543 // declaration
4544 if (New->hasAttr<WeakImportAttr>())
4545 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4546 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4547 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4548 Diag(D->getLocation(), diag::note_previous_definition);
4549 // Remove weak_import attribute on new declaration.
4550 New->dropAttr<WeakImportAttr>();
4551 break;
4552 }
4553 }
4554
4555 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4556 if (!Old->hasAttr<InternalLinkageAttr>()) {
4557 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4558 << ILA;
4559 Diag(Old->getLocation(), diag::note_previous_declaration);
4560 New->dropAttr<InternalLinkageAttr>();
4561 }
4562
4563 // Merge the types.
4564 VarDecl *MostRecent = Old->getMostRecentDecl();
4565 if (MostRecent != Old) {
4566 MergeVarDeclTypes(New, MostRecent,
4567 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4568 if (New->isInvalidDecl())
4569 return;
4570 }
4571
4572 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4573 if (New->isInvalidDecl())
4574 return;
4575
4576 diag::kind PrevDiag;
4577 SourceLocation OldLocation;
4578 std::tie(PrevDiag, OldLocation) =
4580
4581 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4582 if (New->getStorageClass() == SC_Static &&
4583 !New->isStaticDataMember() &&
4584 Old->hasExternalFormalLinkage()) {
4585 if (getLangOpts().MicrosoftExt) {
4586 Diag(New->getLocation(), diag::ext_static_non_static)
4587 << New->getDeclName();
4588 Diag(OldLocation, PrevDiag);
4589 } else {
4590 Diag(New->getLocation(), diag::err_static_non_static)
4591 << New->getDeclName();
4592 Diag(OldLocation, PrevDiag);
4593 return New->setInvalidDecl();
4594 }
4595 }
4596 // C99 6.2.2p4:
4597 // For an identifier declared with the storage-class specifier
4598 // extern in a scope in which a prior declaration of that
4599 // identifier is visible,23) if the prior declaration specifies
4600 // internal or external linkage, the linkage of the identifier at
4601 // the later declaration is the same as the linkage specified at
4602 // the prior declaration. If no prior declaration is visible, or
4603 // if the prior declaration specifies no linkage, then the
4604 // identifier has external linkage.
4605 if (New->hasExternalStorage() && Old->hasLinkage())
4606 /* Okay */;
4607 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4608 !New->isStaticDataMember() &&
4610 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4611 Diag(OldLocation, PrevDiag);
4612 return New->setInvalidDecl();
4613 }
4614
4615 // Check if extern is followed by non-extern and vice-versa.
4616 if (New->hasExternalStorage() &&
4617 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4618 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4619 Diag(OldLocation, PrevDiag);
4620 return New->setInvalidDecl();
4621 }
4622 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4623 !New->hasExternalStorage()) {
4624 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4625 Diag(OldLocation, PrevDiag);
4626 return New->setInvalidDecl();
4627 }
4628
4629 if (CheckRedeclarationInModule(New, Old))
4630 return;
4631
4632 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4633
4634 // FIXME: The test for external storage here seems wrong? We still
4635 // need to check for mismatches.
4636 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4637 // Don't complain about out-of-line definitions of static members.
4638 !(Old->getLexicalDeclContext()->isRecord() &&
4639 !New->getLexicalDeclContext()->isRecord())) {
4640 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4641 Diag(OldLocation, PrevDiag);
4642 return New->setInvalidDecl();
4643 }
4644
4645 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4646 if (VarDecl *Def = Old->getDefinition()) {
4647 // C++1z [dcl.fcn.spec]p4:
4648 // If the definition of a variable appears in a translation unit before
4649 // its first declaration as inline, the program is ill-formed.
4650 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4651 Diag(Def->getLocation(), diag::note_previous_definition);
4652 }
4653 }
4654
4655 // If this redeclaration makes the variable inline, we may need to add it to
4656 // UndefinedButUsed.
4657 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4659 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4660 SourceLocation()));
4661
4662 if (New->getTLSKind() != Old->getTLSKind()) {
4663 if (!Old->getTLSKind()) {
4664 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4665 Diag(OldLocation, PrevDiag);
4666 } else if (!New->getTLSKind()) {
4667 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4668 Diag(OldLocation, PrevDiag);
4669 } else {
4670 // Do not allow redeclaration to change the variable between requiring
4671 // static and dynamic initialization.
4672 // FIXME: GCC allows this, but uses the TLS keyword on the first
4673 // declaration to determine the kind. Do we need to be compatible here?
4674 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4675 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4676 Diag(OldLocation, PrevDiag);
4677 }
4678 }
4679
4680 // C++ doesn't have tentative definitions, so go right ahead and check here.
4681 if (getLangOpts().CPlusPlus) {
4682 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4683 Old->getCanonicalDecl()->isConstexpr()) {
4684 // This definition won't be a definition any more once it's been merged.
4685 Diag(New->getLocation(),
4686 diag::warn_deprecated_redundant_constexpr_static_def);
4688 VarDecl *Def = Old->getDefinition();
4689 if (Def && checkVarDeclRedefinition(Def, New))
4690 return;
4691 }
4692 }
4693
4694 if (haveIncompatibleLanguageLinkages(Old, New)) {
4695 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4696 Diag(OldLocation, PrevDiag);
4697 New->setInvalidDecl();
4698 return;
4699 }
4700
4701 // Merge "used" flag.
4702 if (Old->getMostRecentDecl()->isUsed(false))
4703 New->setIsUsed();
4704
4705 // Keep a chain of previous declarations.
4706 New->setPreviousDecl(Old);
4707 if (NewTemplate)
4708 NewTemplate->setPreviousDecl(OldTemplate);
4709
4710 // Inherit access appropriately.
4711 New->setAccess(Old->getAccess());
4712 if (NewTemplate)
4713 NewTemplate->setAccess(New->getAccess());
4714
4715 if (Old->isInline())
4716 New->setImplicitlyInline();
4717}
4718
4720 SourceManager &SrcMgr = getSourceManager();
4721 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4722 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4723 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4724 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4725 auto &HSI = PP.getHeaderSearchInfo();
4726 StringRef HdrFilename =
4727 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4728
4729 auto noteFromModuleOrInclude = [&](Module *Mod,
4730 SourceLocation IncLoc) -> bool {
4731 // Redefinition errors with modules are common with non modular mapped
4732 // headers, example: a non-modular header H in module A that also gets
4733 // included directly in a TU. Pointing twice to the same header/definition
4734 // is confusing, try to get better diagnostics when modules is on.
4735 if (IncLoc.isValid()) {
4736 if (Mod) {
4737 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4738 << HdrFilename.str() << Mod->getFullModuleName();
4739 if (!Mod->DefinitionLoc.isInvalid())
4740 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4741 << Mod->getFullModuleName();
4742 } else {
4743 Diag(IncLoc, diag::note_redefinition_include_same_file)
4744 << HdrFilename.str();
4745 }
4746 return true;
4747 }
4748
4749 return false;
4750 };
4751
4752 // Is it the same file and same offset? Provide more information on why
4753 // this leads to a redefinition error.
4754 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4755 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4756 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4757 bool EmittedDiag =
4758 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4759 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4760
4761 // If the header has no guards, emit a note suggesting one.
4762 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4763 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4764
4765 if (EmittedDiag)
4766 return;
4767 }
4768
4769 // Redefinition coming from different files or couldn't do better above.
4770 if (Old->getLocation().isValid())
4771 Diag(Old->getLocation(), diag::note_previous_definition);
4772}
4773
4775 if (!hasVisibleDefinition(Old) &&
4776 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4777 isa<VarTemplateSpecializationDecl>(New) ||
4780 // The previous definition is hidden, and multiple definitions are
4781 // permitted (in separate TUs). Demote this to a declaration.
4783
4784 // Make the canonical definition visible.
4785 if (auto *OldTD = Old->getDescribedVarTemplate())
4788 return false;
4789 } else {
4790 Diag(New->getLocation(), diag::err_redefinition) << New;
4792 New->setInvalidDecl();
4793 return true;
4794 }
4795}
4796
4798 DeclSpec &DS,
4799 const ParsedAttributesView &DeclAttrs,
4800 RecordDecl *&AnonRecord) {
4802 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4803}
4804
4805// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4806// disambiguate entities defined in different scopes.
4807// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4808// compatibility.
4809// We will pick our mangling number depending on which version of MSVC is being
4810// targeted.
4811static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4813 ? S->getMSCurManglingNumber()
4814 : S->getMSLastManglingNumber();
4815}
4816
4817void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4818 if (!Context.getLangOpts().CPlusPlus)
4819 return;
4820
4821 if (isa<CXXRecordDecl>(Tag->getParent())) {
4822 // If this tag is the direct child of a class, number it if
4823 // it is anonymous.
4824 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4825 return;
4827 Context.getManglingNumberContext(Tag->getParent());
4829 Tag, MCtx.getManglingNumber(
4830 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4831 return;
4832 }
4833
4834 // If this tag isn't a direct child of a class, number it if it is local.
4836 Decl *ManglingContextDecl;
4837 std::tie(MCtx, ManglingContextDecl) =
4838 getCurrentMangleNumberContext(Tag->getDeclContext());
4839 if (MCtx) {
4841 Tag, MCtx->getManglingNumber(
4842 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4843 }
4844}
4845
4846namespace {
4847struct NonCLikeKind {
4848 enum {
4849 None,
4850 BaseClass,
4851 DefaultMemberInit,
4852 Lambda,
4853 Friend,
4854 OtherMember,
4855 Invalid,
4856 } Kind = None;
4858
4859 explicit operator bool() { return Kind != None; }
4860};
4861}
4862
4863/// Determine whether a class is C-like, according to the rules of C++
4864/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4865static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4866 if (RD->isInvalidDecl())
4867 return {NonCLikeKind::Invalid, {}};
4868
4869 // C++ [dcl.typedef]p9: [P1766R1]
4870 // An unnamed class with a typedef name for linkage purposes shall not
4871 //
4872 // -- have any base classes
4873 if (RD->getNumBases())
4874 return {NonCLikeKind::BaseClass,
4876 RD->bases_end()[-1].getEndLoc())};
4877 bool Invalid = false;
4878 for (Decl *D : RD->decls()) {
4879 // Don't complain about things we already diagnosed.
4880 if (D->isInvalidDecl()) {
4881 Invalid = true;
4882 continue;
4883 }
4884
4885 // -- have any [...] default member initializers
4886 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4887 if (FD->hasInClassInitializer()) {
4888 auto *Init = FD->getInClassInitializer();
4889 return {NonCLikeKind::DefaultMemberInit,
4890 Init ? Init->getSourceRange() : D->getSourceRange()};
4891 }
4892 continue;
4893 }
4894
4895 // FIXME: We don't allow friend declarations. This violates the wording of
4896 // P1766, but not the intent.
4897 if (isa<FriendDecl>(D))
4898 return {NonCLikeKind::Friend, D->getSourceRange()};
4899
4900 // -- declare any members other than non-static data members, member
4901 // enumerations, or member classes,
4902 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4903 isa<EnumDecl>(D))
4904 continue;
4905 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4906 if (!MemberRD) {
4907 if (D->isImplicit())
4908 continue;
4909 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4910 }
4911
4912 // -- contain a lambda-expression,
4913 if (MemberRD->isLambda())
4914 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4915
4916 // and all member classes shall also satisfy these requirements
4917 // (recursively).
4918 if (MemberRD->isThisDeclarationADefinition()) {
4919 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4920 return Kind;
4921 }
4922 }
4923
4924 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4925}
4926
4928 TypedefNameDecl *NewTD) {
4929 if (TagFromDeclSpec->isInvalidDecl())
4930 return;
4931
4932 // Do nothing if the tag already has a name for linkage purposes.
4933 if (TagFromDeclSpec->hasNameForLinkage())
4934 return;
4935
4936 // A well-formed anonymous tag must always be a TagUseKind::Definition.
4937 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4938
4939 // The type must match the tag exactly; no qualifiers allowed.
4941 Context.getTagDeclType(TagFromDeclSpec))) {
4942 if (getLangOpts().CPlusPlus)
4943 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4944 return;
4945 }
4946
4947 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4948 // An unnamed class with a typedef name for linkage purposes shall [be
4949 // C-like].
4950 //
4951 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4952 // shouldn't happen, but there are constructs that the language rule doesn't
4953 // disallow for which we can't reasonably avoid computing linkage early.
4954 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4955 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4956 : NonCLikeKind();
4957 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4958 if (NonCLike || ChangesLinkage) {
4959 if (NonCLike.Kind == NonCLikeKind::Invalid)
4960 return;
4961
4962 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4963 if (ChangesLinkage) {
4964 // If the linkage changes, we can't accept this as an extension.
4965 if (NonCLike.Kind == NonCLikeKind::None)
4966 DiagID = diag::err_typedef_changes_linkage;
4967 else
4968 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4969 }
4970
4971 SourceLocation FixitLoc =
4972 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4973 llvm::SmallString<40> TextToInsert;
4974 TextToInsert += ' ';
4975 TextToInsert += NewTD->getIdentifier()->getName();
4976
4977 Diag(FixitLoc, DiagID)
4978 << isa<TypeAliasDecl>(NewTD)
4979 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4980 if (NonCLike.Kind != NonCLikeKind::None) {
4981 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4982 << NonCLike.Kind - 1 << NonCLike.Range;
4983 }
4984 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4985 << NewTD << isa<TypeAliasDecl>(NewTD);
4986
4987 if (ChangesLinkage)
4988 return;
4989 }
4990
4991 // Otherwise, set this as the anon-decl typedef for the tag.
4992 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4993
4994 // Now that we have a name for the tag, process API notes again.
4995 ProcessAPINotes(TagFromDeclSpec);
4996}
4997
4998static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5000 switch (T) {
5002 return 0;
5004 return 1;
5006 return 2;
5008 return 3;
5009 case DeclSpec::TST_enum:
5010 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5011 if (ED->isScopedUsingClassTag())
5012 return 5;
5013 if (ED->isScoped())
5014 return 6;
5015 }
5016 return 4;
5017 default:
5018 llvm_unreachable("unexpected type specifier");
5019 }
5020}
5021
5023 DeclSpec &DS,
5024 const ParsedAttributesView &DeclAttrs,
5025 MultiTemplateParamsArg TemplateParams,
5026 bool IsExplicitInstantiation,
5027 RecordDecl *&AnonRecord,
5028 SourceLocation EllipsisLoc) {
5029 Decl *TagD = nullptr;
5030 TagDecl *Tag = nullptr;
5036 TagD = DS.getRepAsDecl();
5037
5038 if (!TagD) // We probably had an error
5039 return nullptr;
5040
5041 // Note that the above type specs guarantee that the
5042 // type rep is a Decl, whereas in many of the others
5043 // it's a Type.
5044 if (isa<TagDecl>(TagD))
5045 Tag = cast<TagDecl>(TagD);
5046 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5047 Tag = CTD->getTemplatedDecl();
5048 }
5049
5050 if (Tag) {
5051 handleTagNumbering(Tag, S);
5052 Tag->setFreeStanding();
5053 if (Tag->isInvalidDecl())
5054 return Tag;
5055 }
5056
5057 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5058 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5059 // or incomplete types shall not be restrict-qualified."
5060 if (TypeQuals & DeclSpec::TQ_restrict)
5062 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5063 << DS.getSourceRange();
5064 }
5065
5066 if (DS.isInlineSpecified())
5067 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5068 << getLangOpts().CPlusPlus17;
5069
5070 if (DS.hasConstexprSpecifier()) {
5071 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5072 // and definitions of functions and variables.
5073 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5074 // the declaration of a function or function template
5075 if (Tag)
5076 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5078 << static_cast<int>(DS.getConstexprSpecifier());
5079 else if (getLangOpts().C23)
5080 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5081 else
5082 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5083 << static_cast<int>(DS.getConstexprSpecifier());
5084 // Don't emit warnings after this error.
5085 return TagD;
5086 }
5087
5089
5090 if (DS.isFriendSpecified()) {
5091 // If we're dealing with a decl but not a TagDecl, assume that
5092 // whatever routines created it handled the friendship aspect.
5093 if (TagD && !Tag)
5094 return nullptr;
5095 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5096 }
5097
5098 assert(EllipsisLoc.isInvalid() &&
5099 "Friend ellipsis but not friend-specified?");
5100
5101 // Track whether this decl-specifier declares anything.
5102 bool DeclaresAnything = true;
5103
5104 // Handle anonymous struct definitions.
5105 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5106 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5108 if (getLangOpts().CPlusPlus ||
5109 Record->getDeclContext()->isRecord()) {
5110 // If CurContext is a DeclContext that can contain statements,
5111 // RecursiveASTVisitor won't visit the decls that
5112 // BuildAnonymousStructOrUnion() will put into CurContext.
5113 // Also store them here so that they can be part of the
5114 // DeclStmt that gets created in this case.
5115 // FIXME: Also return the IndirectFieldDecls created by
5116 // BuildAnonymousStructOr union, for the same reason?
5118 AnonRecord = Record;
5119 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5121 }
5122
5123 DeclaresAnything = false;
5124 }
5125 }
5126
5127 // C11 6.7.2.1p2:
5128 // A struct-declaration that does not declare an anonymous structure or
5129 // anonymous union shall contain a struct-declarator-list.
5130 //
5131 // This rule also existed in C89 and C99; the grammar for struct-declaration
5132 // did not permit a struct-declaration without a struct-declarator-list.
5135 // Check for Microsoft C extension: anonymous struct/union member.
5136 // Handle 2 kinds of anonymous struct/union:
5137 // struct STRUCT;
5138 // union UNION;
5139 // and
5140 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5141 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5142 if ((Tag && Tag->getDeclName()) ||
5144 RecordDecl *Record = nullptr;
5145 if (Tag)
5146 Record = dyn_cast<RecordDecl>(Tag);
5147 else if (const RecordType *RT =
5149 Record = RT->getDecl();
5150 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5151 Record = UT->getDecl();
5152
5153 if (Record && getLangOpts().MicrosoftExt) {
5154 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5155 << Record->isUnion() << DS.getSourceRange();
5157 }
5158
5159 DeclaresAnything = false;
5160 }
5161 }
5162
5163 // Skip all the checks below if we have a type error.
5165 (TagD && TagD->isInvalidDecl()))
5166 return TagD;
5167
5168 if (getLangOpts().CPlusPlus &&
5170 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5171 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5172 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5173 DeclaresAnything = false;
5174
5175 if (!DS.isMissingDeclaratorOk()) {
5176 // Customize diagnostic for a typedef missing a name.
5178 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5179 << DS.getSourceRange();
5180 else
5181 DeclaresAnything = false;
5182 }
5183
5184 if (DS.isModulePrivateSpecified() &&
5185 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5186 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5187 << llvm::to_underlying(Tag->getTagKind())
5189
5191
5192 // C 6.7/2:
5193 // A declaration [...] shall declare at least a declarator [...], a tag,
5194 // or the members of an enumeration.
5195 // C++ [dcl.dcl]p3:
5196 // [If there are no declarators], and except for the declaration of an
5197 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5198 // names into the program, or shall redeclare a name introduced by a
5199 // previous declaration.
5200 if (!DeclaresAnything) {
5201 // In C, we allow this as a (popular) extension / bug. Don't bother
5202 // producing further diagnostics for redundant qualifiers after this.
5203 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5204 ? diag::err_no_declarators
5205 : diag::ext_no_declarators)
5206 << DS.getSourceRange();
5207 return TagD;
5208 }
5209
5210 // C++ [dcl.stc]p1:
5211 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5212 // init-declarator-list of the declaration shall not be empty.
5213 // C++ [dcl.fct.spec]p1:
5214 // If a cv-qualifier appears in a decl-specifier-seq, the
5215 // init-declarator-list of the declaration shall not be empty.
5216 //
5217 // Spurious qualifiers here appear to be valid in C.
5218 unsigned DiagID = diag::warn_standalone_specifier;
5219 if (getLangOpts().CPlusPlus)
5220 DiagID = diag::ext_standalone_specifier;
5221
5222 // Note that a linkage-specification sets a storage class, but
5223 // 'extern "C" struct foo;' is actually valid and not theoretically
5224 // useless.
5225 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5226 if (SCS == DeclSpec::SCS_mutable)
5227 // Since mutable is not a viable storage class specifier in C, there is
5228 // no reason to treat it as an extension. Instead, diagnose as an error.
5229 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5230 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5231 Diag(DS.getStorageClassSpecLoc(), DiagID)
5233 }
5234
5238 if (DS.getTypeQualifiers()) {
5240 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5242 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5243 // Restrict is covered above.
5245 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5247 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5248 }
5249
5250 // Warn about ignored type attributes, for example:
5251 // __attribute__((aligned)) struct A;
5252 // Attributes should be placed after tag to apply to type declaration.
5253 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5254 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5255 if (TypeSpecType == DeclSpec::TST_class ||
5256 TypeSpecType == DeclSpec::TST_struct ||
5257 TypeSpecType == DeclSpec::TST_interface ||
5258 TypeSpecType == DeclSpec::TST_union ||
5259 TypeSpecType == DeclSpec::TST_enum) {
5260
5261 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5262 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5263 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5264 DiagnosticId = diag::warn_attribute_ignored;
5265 else if (AL.isRegularKeywordAttribute())
5266 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5267 else
5268 DiagnosticId = diag::warn_declspec_attribute_ignored;
5269 Diag(AL.getLoc(), DiagnosticId)
5270 << AL << GetDiagnosticTypeSpecifierID(DS);
5271 };
5272
5273 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5274 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5275 }
5276 }
5277
5278 return TagD;
5279}
5280
5281/// We are trying to inject an anonymous member into the given scope;
5282/// check if there's an existing declaration that can't be overloaded.
5283///
5284/// \return true if this is a forbidden redeclaration
5285static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5286 DeclContext *Owner,
5287 DeclarationName Name,
5288 SourceLocation NameLoc, bool IsUnion,
5289 StorageClass SC) {
5290 LookupResult R(SemaRef, Name, NameLoc,
5293 RedeclarationKind::ForVisibleRedeclaration);
5294 if (!SemaRef.LookupName(R, S)) return false;
5295
5296 // Pick a representative declaration.
5298 assert(PrevDecl && "Expected a non-null Decl");
5299
5300 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5301 return false;
5302
5303 if (SC == StorageClass::SC_None &&
5304 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5305 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5306 if (!Owner->isRecord())
5307 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5308 return false;
5309 }
5310
5311 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5312 << IsUnion << Name;
5313 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5314
5315 return true;
5316}
5317
5319 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5321}
5322
5324 if (!getLangOpts().CPlusPlus)
5325 return;
5326
5327 // This function can be parsed before we have validated the
5328 // structure as an anonymous struct
5329 if (Record->isAnonymousStructOrUnion())
5330 return;
5331
5332 const NamedDecl *First = 0;
5333 for (const Decl *D : Record->decls()) {
5334 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5335 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5336 continue;
5337 if (!First)
5338 First = ND;
5339 else
5341 }
5342}
5343
5344/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5345/// anonymous struct or union AnonRecord into the owning context Owner
5346/// and scope S. This routine will be invoked just after we realize
5347/// that an unnamed union or struct is actually an anonymous union or
5348/// struct, e.g.,
5349///
5350/// @code
5351/// union {
5352/// int i;
5353/// float f;
5354/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5355/// // f into the surrounding scope.x
5356/// @endcode
5357///
5358/// This routine is recursive, injecting the names of nested anonymous
5359/// structs/unions into the owning context and scope as well.
5360static bool
5362 RecordDecl *AnonRecord, AccessSpecifier AS,
5363 StorageClass SC,
5364 SmallVectorImpl<NamedDecl *> &Chaining) {
5365 bool Invalid = false;
5366
5367 // Look every FieldDecl and IndirectFieldDecl with a name.
5368 for (auto *D : AnonRecord->decls()) {
5369 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5370 cast<NamedDecl>(D)->getDeclName()) {
5371 ValueDecl *VD = cast<ValueDecl>(D);
5372 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5373 VD->getLocation(), AnonRecord->isUnion(),
5374 SC)) {
5375 // C++ [class.union]p2:
5376 // The names of the members of an anonymous union shall be
5377 // distinct from the names of any other entity in the
5378 // scope in which the anonymous union is declared.
5379 Invalid = true;
5380 } else {
5381 // C++ [class.union]p2:
5382 // For the purpose of name lookup, after the anonymous union
5383 // definition, the members of the anonymous union are
5384 // considered to have been defined in the scope in which the
5385 // anonymous union is declared.
5386 unsigned OldChainingSize = Chaining.size();
5387 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5388 Chaining.append(IF->chain_begin(), IF->chain_end());
5389 else
5390 Chaining.push_back(VD);
5391
5392 assert(Chaining.size() >= 2);
5393 NamedDecl **NamedChain =
5394 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5395 for (unsigned i = 0; i < Chaining.size(); i++)
5396 NamedChain[i] = Chaining[i];
5397
5399 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5400 VD->getType(), {NamedChain, Chaining.size()});
5401
5402 for (const auto *Attr : VD->attrs())
5403 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5404
5405 IndirectField->setAccess(AS);
5406 IndirectField->setImplicit();
5407 SemaRef.PushOnScopeChains(IndirectField, S);
5408
5409 // That includes picking up the appropriate access specifier.
5410 if (AS != AS_none) IndirectField->setAccess(AS);
5411
5412 Chaining.resize(OldChainingSize);
5413 }
5414 }
5415 }
5416
5417 return Invalid;
5418}
5419
5420/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5421/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5422/// illegal input values are mapped to SC_None.
5423static StorageClass
5425 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5426 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5427 "Parser allowed 'typedef' as storage class VarDecl.");
5428 switch (StorageClassSpec) {
5431 if (DS.isExternInLinkageSpec())
5432 return SC_None;
5433 return SC_Extern;
5434 case DeclSpec::SCS_static: return SC_Static;
5435 case DeclSpec::SCS_auto: return SC_Auto;
5438 // Illegal SCSs map to None: error reporting is up to the caller.
5439 case DeclSpec::SCS_mutable: // Fall through.
5440 case DeclSpec::SCS_typedef: return SC_None;
5441 }
5442 llvm_unreachable("unknown storage class specifier");
5443}
5444
5446 assert(Record->hasInClassInitializer());
5447
5448 for (const auto *I : Record->decls()) {
5449 const auto *FD = dyn_cast<FieldDecl>(I);
5450 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5451 FD = IFD->getAnonField();
5452 if (FD && FD->hasInClassInitializer())
5453 return FD->getLocation();
5454 }
5455
5456 llvm_unreachable("couldn't find in-class initializer");
5457}
5458
5460 SourceLocation DefaultInitLoc) {
5461 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5462 return;
5463
5464 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5465 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5466}
5467
5469 CXXRecordDecl *AnonUnion) {
5470 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5471 return;
5472
5474}
5475
5477 AccessSpecifier AS,
5479 const PrintingPolicy &Policy) {
5480 DeclContext *Owner = Record->getDeclContext();
5481
5482 // Diagnose whether this anonymous struct/union is an extension.
5483 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5484 Diag(Record->getLocation(), diag::ext_anonymous_union);
5485 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5486 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5487 else if (!Record->isUnion() && !getLangOpts().C11)
5488 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5489
5490 // C and C++ require different kinds of checks for anonymous
5491 // structs/unions.
5492 bool Invalid = false;
5493 if (getLangOpts().CPlusPlus) {
5494 const char *PrevSpec = nullptr;
5495 if (Record->isUnion()) {
5496 // C++ [class.union]p6:
5497 // C++17 [class.union.anon]p2:
5498 // Anonymous unions declared in a named namespace or in the
5499 // global namespace shall be declared static.
5500 unsigned DiagID;
5501 DeclContext *OwnerScope = Owner->getRedeclContext();
5503 (OwnerScope->isTranslationUnit() ||
5504 (OwnerScope->isNamespace() &&
5505 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5506 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5507 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5508
5509 // Recover by adding 'static'.
5511 PrevSpec, DiagID, Policy);
5512 }
5513 // C++ [class.union]p6:
5514 // A storage class is not allowed in a declaration of an
5515 // anonymous union in a class scope.
5517 isa<RecordDecl>(Owner)) {
5519 diag::err_anonymous_union_with_storage_spec)
5521
5522 // Recover by removing the storage specifier.
5525 PrevSpec, DiagID, Context.getPrintingPolicy());
5526 }
5527 }
5528
5529 // Ignore const/volatile/restrict qualifiers.
5530 if (DS.getTypeQualifiers()) {
5532 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5533 << Record->isUnion() << "const"
5537 diag::ext_anonymous_struct_union_qualified)
5538 << Record->isUnion() << "volatile"
5542 diag::ext_anonymous_struct_union_qualified)
5543 << Record->isUnion() << "restrict"
5547 diag::ext_anonymous_struct_union_qualified)
5548 << Record->isUnion() << "_Atomic"
5552 diag::ext_anonymous_struct_union_qualified)
5553 << Record->isUnion() << "__unaligned"
5555
5557 }
5558
5559 // C++ [class.union]p2:
5560 // The member-specification of an anonymous union shall only
5561 // define non-static data members. [Note: nested types and
5562 // functions cannot be declared within an anonymous union. ]
5563 for (auto *Mem : Record->decls()) {
5564 // Ignore invalid declarations; we already diagnosed them.
5565 if (Mem->isInvalidDecl())
5566 continue;
5567
5568 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5569 // C++ [class.union]p3:
5570 // An anonymous union shall not have private or protected
5571 // members (clause 11).
5572 assert(FD->getAccess() != AS_none);
5573 if (FD->getAccess() != AS_public) {
5574 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5575 << Record->isUnion() << (FD->getAccess() == AS_protected);
5576 Invalid = true;
5577 }
5578
5579 // C++ [class.union]p1
5580 // An object of a class with a non-trivial constructor, a non-trivial
5581 // copy constructor, a non-trivial destructor, or a non-trivial copy
5582 // assignment operator cannot be a member of a union, nor can an
5583 // array of such objects.
5584 if (CheckNontrivialField(FD))
5585 Invalid = true;
5586 } else if (Mem->isImplicit()) {
5587 // Any implicit members are fine.
5588 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5589 // This is a type that showed up in an
5590 // elaborated-type-specifier inside the anonymous struct or
5591 // union, but which actually declares a type outside of the
5592 // anonymous struct or union. It's okay.
5593 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5594 if (!MemRecord->isAnonymousStructOrUnion() &&
5595 MemRecord->getDeclName()) {
5596 // Visual C++ allows type definition in anonymous struct or union.
5597 if (getLangOpts().MicrosoftExt)
5598 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5599 << Record->isUnion();
5600 else {
5601 // This is a nested type declaration.
5602 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5603 << Record->isUnion();
5604 Invalid = true;
5605 }
5606 } else {
5607 // This is an anonymous type definition within another anonymous type.
5608 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5609 // not part of standard C++.
5610 Diag(MemRecord->getLocation(),
5611 diag::ext_anonymous_record_with_anonymous_type)
5612 << Record->isUnion();
5613 }
5614 } else if (isa<AccessSpecDecl>(Mem)) {
5615 // Any access specifier is fine.
5616 } else if (isa<StaticAssertDecl>(Mem)) {
5617 // In C++1z, static_assert declarations are also fine.
5618 } else {
5619 // We have something that isn't a non-static data
5620 // member. Complain about it.
5621 unsigned DK = diag::err_anonymous_record_bad_member;
5622 if (isa<TypeDecl>(Mem))
5623 DK = diag::err_anonymous_record_with_type;
5624 else if (isa<FunctionDecl>(Mem))
5625 DK = diag::err_anonymous_record_with_function;
5626 else if (isa<VarDecl>(Mem))
5627 DK = diag::err_anonymous_record_with_static;
5628
5629 // Visual C++ allows type definition in anonymous struct or union.
5630 if (getLangOpts().MicrosoftExt &&
5631 DK == diag::err_anonymous_record_with_type)
5632 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5633 << Record->isUnion();
5634 else {
5635 Diag(Mem->getLocation(), DK) << Record->isUnion();
5636 Invalid = true;
5637 }
5638 }
5639 }
5640
5641 // C++11 [class.union]p8 (DR1460):
5642 // At most one variant member of a union may have a
5643 // brace-or-equal-initializer.
5644 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5645 Owner->isRecord())
5646 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5647 cast<CXXRecordDecl>(Record));
5648 }
5649
5650 if (!Record->isUnion() && !Owner->isRecord()) {
5651 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5652 << getLangOpts().CPlusPlus;
5653 Invalid = true;
5654 }
5655
5656 // C++ [dcl.dcl]p3:
5657 // [If there are no declarators], and except for the declaration of an
5658 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5659 // names into the program
5660 // C++ [class.mem]p2:
5661 // each such member-declaration shall either declare at least one member
5662 // name of the class or declare at least one unnamed bit-field
5663 //
5664 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5665 if (getLangOpts().CPlusPlus && Record->field_empty())
5666 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5667
5668 // Mock up a declarator.
5672 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5673
5674 // Create a declaration for this anonymous struct/union.
5675 NamedDecl *Anon = nullptr;
5676 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5677 Anon = FieldDecl::Create(
5678 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5679 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5680 /*BitWidth=*/nullptr, /*Mutable=*/false,
5681 /*InitStyle=*/ICIS_NoInit);
5682 Anon->setAccess(AS);
5683 ProcessDeclAttributes(S, Anon, Dc);
5684
5685 if (getLangOpts().CPlusPlus)
5686 FieldCollector->Add(cast<FieldDecl>(Anon));
5687 } else {
5688 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5689 if (SCSpec == DeclSpec::SCS_mutable) {
5690 // mutable can only appear on non-static class members, so it's always
5691 // an error here
5692 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5693 Invalid = true;
5694 SC = SC_None;
5695 }
5696
5697 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5698 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5699 Context.getTypeDeclType(Record), TInfo, SC);
5700 if (Invalid)
5701 Anon->setInvalidDecl();
5702
5703 ProcessDeclAttributes(S, Anon, Dc);
5704
5705 // Default-initialize the implicit variable. This initialization will be
5706 // trivial in almost all cases, except if a union member has an in-class
5707 // initializer:
5708 // union { int n = 0; };
5710 }
5711 Anon->setImplicit();
5712
5713 // Mark this as an anonymous struct/union type.
5714 Record->setAnonymousStructOrUnion(true);
5715
5716 // Add the anonymous struct/union object to the current
5717 // context. We'll be referencing this object when we refer to one of
5718 // its members.
5719 Owner->addDecl(Anon);
5720
5721 // Inject the members of the anonymous struct/union into the owning
5722 // context and into the identifier resolver chain for name lookup
5723 // purposes.
5725 Chain.push_back(Anon);
5726
5727 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5728 Chain))
5729 Invalid = true;
5730
5731 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5732 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5734 Decl *ManglingContextDecl;
5735 std::tie(MCtx, ManglingContextDecl) =
5736 getCurrentMangleNumberContext(NewVD->getDeclContext());
5737 if (MCtx) {
5739 NewVD, MCtx->getManglingNumber(
5740 NewVD, getMSManglingNumber(getLangOpts(), S)));
5742 }
5743 }
5744 }
5745
5746 if (Invalid)
5747 Anon->setInvalidDecl();
5748
5749 return Anon;
5750}
5751
5753 RecordDecl *Record) {
5754 assert(Record && "expected a record!");
5755
5756 // Mock up a declarator.
5759 assert(TInfo && "couldn't build declarator info for anonymous struct");
5760
5761 auto *ParentDecl = cast<RecordDecl>(CurContext);
5763
5764 // Create a declaration for this anonymous struct.
5765 NamedDecl *Anon =
5766 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5767 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5768 /*BitWidth=*/nullptr, /*Mutable=*/false,
5769 /*InitStyle=*/ICIS_NoInit);
5770 Anon->setImplicit();
5771
5772 // Add the anonymous struct object to the current context.
5773 CurContext->addDecl(Anon);
5774
5775 // Inject the members of the anonymous struct into the current
5776 // context and into the identifier resolver chain for name lookup
5777 // purposes.
5779 Chain.push_back(Anon);
5780
5781 RecordDecl *RecordDef = Record->getDefinition();
5782 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5783 diag::err_field_incomplete_or_sizeless) ||
5785 *this, S, CurContext, RecordDef, AS_none,
5787 Anon->setInvalidDecl();
5788 ParentDecl->setInvalidDecl();
5789 }
5790
5791 return Anon;
5792}
5793
5795 return GetNameFromUnqualifiedId(D.getName());
5796}
5797
5800 DeclarationNameInfo NameInfo;
5801 NameInfo.setLoc(Name.StartLocation);
5802
5803 switch (Name.getKind()) {
5804
5807 NameInfo.setName(Name.Identifier);
5808 return NameInfo;
5809
5811 // C++ [temp.deduct.guide]p3:
5812 // The simple-template-id shall name a class template specialization.
5813 // The template-name shall be the same identifier as the template-name
5814 // of the simple-template-id.
5815 // These together intend to imply that the template-name shall name a
5816 // class template.
5817 // FIXME: template<typename T> struct X {};
5818 // template<typename T> using Y = X<T>;
5819 // Y(int) -> Y<int>;
5820 // satisfies these rules but does not name a class template.
5821 TemplateName TN = Name.TemplateName.get().get();
5822 auto *Template = TN.getAsTemplateDecl();
5823 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5824 Diag(Name.StartLocation,
5825 diag::err_deduction_guide_name_not_class_template)
5827 if (Template)
5828 NoteTemplateLocation(*Template);
5829 return DeclarationNameInfo();
5830 }
5831
5832 NameInfo.setName(
5834 return NameInfo;
5835 }
5836
5839 Name.OperatorFunctionId.Operator));
5841 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5842 return NameInfo;
5843
5846 Name.Identifier));
5847 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5848 return NameInfo;
5849
5851 TypeSourceInfo *TInfo;
5852 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5853 if (Ty.isNull())
5854 return DeclarationNameInfo();
5857 NameInfo.setNamedTypeInfo(TInfo);
5858 return NameInfo;
5859 }
5860
5862 TypeSourceInfo *TInfo;
5863 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5864 if (Ty.isNull())
5865 return DeclarationNameInfo();
5868 NameInfo.setNamedTypeInfo(TInfo);
5869 return NameInfo;
5870 }
5871
5873 // In well-formed code, we can only have a constructor
5874 // template-id that refers to the current context, so go there
5875 // to find the actual type being constructed.
5876 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5877 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5878 return DeclarationNameInfo();
5879
5880 // Determine the type of the class being constructed.
5881 QualType CurClassType = Context.getTypeDeclType(CurClass);
5882
5883 // FIXME: Check two things: that the template-id names the same type as
5884 // CurClassType, and that the template-id does not occur when the name
5885 // was qualified.
5886
5888 Context.getCanonicalType(CurClassType)));
5889 // FIXME: should we retrieve TypeSourceInfo?
5890 NameInfo.setNamedTypeInfo(nullptr);
5891 return NameInfo;
5892 }
5893
5895 TypeSourceInfo *TInfo;
5896 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5897 if (Ty.isNull())
5898 return DeclarationNameInfo();
5901 NameInfo.setNamedTypeInfo(TInfo);
5902 return NameInfo;
5903 }
5904
5906 TemplateName TName = Name.TemplateId->Template.get();
5907 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5908 return Context.getNameForTemplate(TName, TNameLoc);
5909 }
5910
5911 } // switch (Name.getKind())
5912
5913 llvm_unreachable("Unknown name kind");
5914}
5915
5917 do {
5918 if (Ty->isPointerOrReferenceType())
5919 Ty = Ty->getPointeeType();
5920 else if (Ty->isArrayType())
5922 else
5923 return Ty.withoutLocalFastQualifiers();
5924 } while (true);
5925}
5926
5927/// hasSimilarParameters - Determine whether the C++ functions Declaration
5928/// and Definition have "nearly" matching parameters. This heuristic is
5929/// used to improve diagnostics in the case where an out-of-line function
5930/// definition doesn't match any declaration within the class or namespace.
5931/// Also sets Params to the list of indices to the parameters that differ
5932/// between the declaration and the definition. If hasSimilarParameters
5933/// returns true and Params is empty, then all of the parameters match.
5937 SmallVectorImpl<unsigned> &Params) {
5938 Params.clear();
5939 if (Declaration->param_size() != Definition->param_size())
5940 return false;
5941 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5942 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5943 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5944
5945 // The parameter types are identical
5946 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5947 continue;
5948
5949 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5950 QualType DefParamBaseTy = getCoreType(DefParamTy);
5951 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5952 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5953
5954 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5955 (DeclTyName && DeclTyName == DefTyName))
5956 Params.push_back(Idx);
5957 else // The two parameters aren't even close
5958 return false;
5959 }
5960
5961 return true;
5962}
5963
5964/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5965/// declarator needs to be rebuilt in the current instantiation.
5966/// Any bits of declarator which appear before the name are valid for
5967/// consideration here. That's specifically the type in the decl spec
5968/// and the base type in any member-pointer chunks.
5970 DeclarationName Name) {
5971 // The types we specifically need to rebuild are:
5972 // - typenames, typeofs, and decltypes
5973 // - types which will become injected class names
5974 // Of course, we also need to rebuild any type referencing such a
5975 // type. It's safest to just say "dependent", but we call out a
5976 // few cases here.
5977
5978 DeclSpec &DS = D.getMutableDeclSpec();
5979 switch (DS.getTypeSpecType()) {
5983#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
5984#include "clang/Basic/TransformTypeTraits.def"
5985 case DeclSpec::TST_atomic: {
5986 // Grab the type from the parser.
5987 TypeSourceInfo *TSI = nullptr;
5988 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5989 if (T.isNull() || !T->isInstantiationDependentType()) break;
5990
5991 // Make sure there's a type source info. This isn't really much
5992 // of a waste; most dependent types should have type source info
5993 // attached already.
5994 if (!TSI)
5996
5997 // Rebuild the type in the current instantiation.
5998 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5999 if (!TSI) return true;
6000
6001 // Store the new type back in the decl spec.
6002 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6003 DS.UpdateTypeRep(LocType);
6004 break;
6005 }
6006
6010 Expr *E = DS.getRepAsExpr();
6012 if (Result.isInvalid()) return true;
6013 DS.UpdateExprRep(Result.get());
6014 break;
6015 }
6016
6017 default:
6018 // Nothing to do for these decl specs.
6019 break;
6020 }
6021
6022 // It doesn't matter what order we do this in.
6023 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6024 DeclaratorChunk &Chunk = D.getTypeObject(I);
6025
6026 // The only type information in the declarator which can come
6027 // before the declaration name is the base type of a member
6028 // pointer.
6030 continue;
6031
6032 // Rebuild the scope specifier in-place.
6033 CXXScopeSpec &SS = Chunk.Mem.Scope();
6035 return true;
6036 }
6037
6038 return false;
6039}
6040
6041/// Returns true if the declaration is declared in a system header or from a
6042/// system macro.
6044 return SM.isInSystemHeader(D->getLocation()) ||
6045 SM.isInSystemMacro(D->getLocation());
6046}
6047
6049 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6050 // of system decl.
6051 if (D->getPreviousDecl() || D->isImplicit())
6052 return;
6053 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6056 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6057 << D << static_cast<int>(Status);
6058 }
6059}
6060
6062 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6063
6064 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6065 // declaration only if the `bind_to_declaration` extension is set.
6067 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6068 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6069 llvm::omp::TraitProperty::
6070 implementation_extension_bind_to_declaration))
6072 S, D, MultiTemplateParamsArg(), Bases);
6073
6075
6077 Dcl && Dcl->getDeclContext()->isFileContext())
6079
6080 if (!Bases.empty())
6082 Bases);
6083
6084 return Dcl;
6085}
6086
6088 DeclarationNameInfo NameInfo) {
6089 DeclarationName Name = NameInfo.getName();
6090
6091 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6092 while (Record && Record->isAnonymousStructOrUnion())
6093 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6094 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6095 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6096 return true;
6097 }
6098
6099 return false;
6100}
6101
6103 DeclarationName Name,
6105 TemplateIdAnnotation *TemplateId,
6106 bool IsMemberSpecialization) {
6107 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6108 "without nested-name-specifier");
6109 DeclContext *Cur = CurContext;
6110 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6111 Cur = Cur->getParent();
6112
6113 // If the user provided a superfluous scope specifier that refers back to the
6114 // class in which the entity is already declared, diagnose and ignore it.
6115 //
6116 // class X {
6117 // void X::f();
6118 // };
6119 //
6120 // Note, it was once ill-formed to give redundant qualification in all
6121 // contexts, but that rule was removed by DR482.
6122 if (Cur->Equals(DC)) {
6123 if (Cur->isRecord()) {
6124 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6125 : diag::err_member_extra_qualification)
6126 << Name << FixItHint::CreateRemoval(SS.getRange());
6127 SS.clear();
6128 } else {
6129 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6130 }
6131 return false;
6132 }
6133
6134 // Check whether the qualifying scope encloses the scope of the original
6135 // declaration. For a template-id, we perform the checks in
6136 // CheckTemplateSpecializationScope.
6137 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6138 if (Cur->isRecord())
6139 Diag(Loc, diag::err_member_qualification)
6140 << Name << SS.getRange();
6141 else if (isa<TranslationUnitDecl>(DC))
6142 Diag(Loc, diag::err_invalid_declarator_global_scope)
6143 << Name << SS.getRange();
6144 else if (isa<FunctionDecl>(Cur))
6145 Diag(Loc, diag::err_invalid_declarator_in_function)
6146 << Name << SS.getRange();
6147 else if (isa<BlockDecl>(Cur))
6148 Diag(Loc, diag::err_invalid_declarator_in_block)
6149 << Name << SS.getRange();
6150 else if (isa<ExportDecl>(Cur)) {
6151 if (!isa<NamespaceDecl>(DC))
6152 Diag(Loc, diag::err_export_non_namespace_scope_name)
6153 << Name << SS.getRange();
6154 else
6155 // The cases that DC is not NamespaceDecl should be handled in
6156 // CheckRedeclarationExported.
6157 return false;
6158 } else
6159 Diag(Loc, diag::err_invalid_declarator_scope)
6160 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6161
6162 return true;
6163 }
6164
6165 if (Cur->isRecord()) {
6166 // Cannot qualify members within a class.
6167 Diag(Loc, diag::err_member_qualification)
6168 << Name << SS.getRange();
6169 SS.clear();
6170
6171 // C++ constructors and destructors with incorrect scopes can break
6172 // our AST invariants by having the wrong underlying types. If
6173 // that's the case, then drop this declaration entirely.
6174 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6175 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6176 !Context.hasSameType(Name.getCXXNameType(),
6177 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6178 return true;
6179
6180 return false;
6181 }
6182
6183 // C++23 [temp.names]p5:
6184 // The keyword template shall not appear immediately after a declarative
6185 // nested-name-specifier.
6186 //
6187 // First check the template-id (if any), and then check each component of the
6188 // nested-name-specifier in reverse order.
6189 //
6190 // FIXME: nested-name-specifiers in friend declarations are declarative,
6191 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6192 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6193 Diag(Loc, diag::ext_template_after_declarative_nns)
6195
6197 do {
6198 if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6200 Diag(Loc, diag::ext_template_after_declarative_nns)
6202 SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6203
6204 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6205 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6206 // C++23 [expr.prim.id.qual]p3:
6207 // [...] If a nested-name-specifier N is declarative and has a
6208 // simple-template-id with a template argument list A that involves a
6209 // template parameter, let T be the template nominated by N without A.
6210 // T shall be a class template.
6211 if (TST->isDependentType() && TST->isTypeAlias())
6212 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6213 << SpecLoc.getLocalSourceRange();
6214 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6215 // C++23 [expr.prim.id.qual]p2:
6216 // [...] A declarative nested-name-specifier shall not have a
6217 // computed-type-specifier.
6218 //
6219 // CWG2858 changed this from 'decltype-specifier' to
6220 // 'computed-type-specifier'.
6221 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6222 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6223 }
6224 }
6225 } while ((SpecLoc = SpecLoc.getPrefix()));
6226
6227 return false;
6228}
6229
6231 MultiTemplateParamsArg TemplateParamLists) {
6232 // TODO: consider using NameInfo for diagnostic.
6234 DeclarationName Name = NameInfo.getName();
6235
6236 // All of these full declarators require an identifier. If it doesn't have
6237 // one, the ParsedFreeStandingDeclSpec action should be used.
6238 if (D.isDecompositionDeclarator()) {
6239 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6240 } else if (!Name) {
6241 if (!D.isInvalidType()) // Reject this if we think it is valid.
6242 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6243 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6244 return nullptr;
6246 return nullptr;
6247
6248 DeclContext *DC = CurContext;
6249 if (D.getCXXScopeSpec().isInvalid())
6250 D.setInvalidType();
6251 else if (D.getCXXScopeSpec().isSet()) {
6252 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6254 return nullptr;
6255
6256 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6257 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6258 if (!DC || isa<EnumDecl>(DC)) {
6259 // If we could not compute the declaration context, it's because the
6260 // declaration context is dependent but does not refer to a class,
6261 // class template, or class template partial specialization. Complain
6262 // and return early, to avoid the coming semantic disaster.
6263 Diag(D.getIdentifierLoc(),
6264 diag::err_template_qualified_declarator_no_match)
6265 << D.getCXXScopeSpec().getScopeRep()
6266 << D.getCXXScopeSpec().getRange();
6267 return nullptr;
6268 }
6269 bool IsDependentContext = DC->isDependentContext();
6270
6271 if (!IsDependentContext &&
6272 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6273 return nullptr;
6274
6275 // If a class is incomplete, do not parse entities inside it.
6276 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6277 Diag(D.getIdentifierLoc(),
6278 diag::err_member_def_undefined_record)
6279 << Name << DC << D.getCXXScopeSpec().getRange();
6280 return nullptr;
6281 }
6282 if (!D.getDeclSpec().isFriendSpecified()) {
6283 TemplateIdAnnotation *TemplateId =
6285 ? D.getName().TemplateId
6286 : nullptr;
6287 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name,
6288 D.getIdentifierLoc(), TemplateId,
6289 /*IsMemberSpecialization=*/false)) {
6290 if (DC->isRecord())
6291 return nullptr;
6292
6293 D.setInvalidType();
6294 }
6295 }
6296
6297 // Check whether we need to rebuild the type of the given
6298 // declaration in the current instantiation.
6299 if (EnteringContext && IsDependentContext &&
6300 TemplateParamLists.size() != 0) {
6301 ContextRAII SavedContext(*this, DC);
6303 D.setInvalidType();
6304 }
6305 }
6306
6308 QualType R = TInfo->getType();
6309
6310 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6312 D.setInvalidType();
6313
6314 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6316
6317 // See if this is a redefinition of a variable in the same scope.
6318 if (!D.getCXXScopeSpec().isSet()) {
6319 bool IsLinkageLookup = false;
6320 bool CreateBuiltins = false;
6321
6322 // If the declaration we're planning to build will be a function
6323 // or object with linkage, then look for another declaration with
6324 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6325 //
6326 // If the declaration we're planning to build will be declared with
6327 // external linkage in the translation unit, create any builtin with
6328 // the same name.
6329 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6330 /* Do nothing*/;
6331 else if (CurContext->isFunctionOrMethod() &&
6332 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6333 R->isFunctionType())) {
6334 IsLinkageLookup = true;
6335 CreateBuiltins =
6338 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6339 CreateBuiltins = true;
6340
6341 if (IsLinkageLookup) {
6343 Previous.setRedeclarationKind(
6344 RedeclarationKind::ForExternalRedeclaration);
6345 }
6346
6347 LookupName(Previous, S, CreateBuiltins);
6348 } else { // Something like "int foo::x;"
6350
6351 // C++ [dcl.meaning]p1:
6352 // When the declarator-id is qualified, the declaration shall refer to a
6353 // previously declared member of the class or namespace to which the
6354 // qualifier refers (or, in the case of a namespace, of an element of the
6355 // inline namespace set of that namespace (7.3.1)) or to a specialization
6356 // thereof; [...]
6357 //
6358 // Note that we already checked the context above, and that we do not have
6359 // enough information to make sure that Previous contains the declaration
6360 // we want to match. For example, given:
6361 //
6362 // class X {
6363 // void f();
6364 // void f(float);
6365 // };
6366 //
6367 // void X::f(int) { } // ill-formed
6368 //
6369 // In this case, Previous will point to the overload set
6370 // containing the two f's declared in X, but neither of them
6371 // matches.
6372
6374 }
6375
6376 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6377 TPD && TPD->isTemplateParameter()) {
6378 // Older versions of clang allowed the names of function/variable templates
6379 // to shadow the names of their template parameters. For the compatibility
6380 // purposes we detect such cases and issue a default-to-error warning that
6381 // can be disabled with -Wno-strict-primary-template-shadow.
6382 if (!D.isInvalidType()) {
6383 bool AllowForCompatibility = false;
6384 if (Scope *DeclParent = S->getDeclParent();
6385 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6386 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6387 TemplateParamParent->isDeclScope(TPD);
6388 }
6389 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
6390 AllowForCompatibility);
6391 }
6392
6393 // Just pretend that we didn't see the previous declaration.
6394 Previous.clear();
6395 }
6396
6397 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6398 // Forget that the previous declaration is the injected-class-name.
6399 Previous.clear();
6400
6401 // In C++, the previous declaration we find might be a tag type
6402 // (class or enum). In this case, the new declaration will hide the
6403 // tag type. Note that this applies to functions, function templates, and
6404 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6405 if (Previous.isSingleTagDecl() &&
6406 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6407 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6408 Previous.clear();
6409
6410 // Check that there are no default arguments other than in the parameters
6411 // of a function declaration (C++ only).
6412 if (getLangOpts().CPlusPlus)
6414
6415 /// Get the innermost enclosing declaration scope.
6416 S = S->getDeclParent();
6417
6418 NamedDecl *New;
6419
6420 bool AddToScope = true;
6421 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6422 if (TemplateParamLists.size()) {
6423 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6424 return nullptr;
6425 }
6426
6427 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6428 } else if (R->isFunctionType()) {
6429 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6430 TemplateParamLists,
6431 AddToScope);
6432 } else {
6433 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6434 AddToScope);
6435 }
6436
6437 if (!New)
6438 return nullptr;
6439
6440 // If this has an identifier and is not a function template specialization,
6441 // add it to the scope stack.
6442 if (New->getDeclName() && AddToScope)
6443 PushOnScopeChains(New, S);
6444
6445 if (OpenMP().isInOpenMPDeclareTargetContext())
6447
6448 return New;
6449}
6450
6451/// Helper method to turn variable array types into constant array
6452/// types in certain situations which would otherwise be errors (for
6453/// GCC compatibility).
6455 ASTContext &Context,
6456 bool &SizeIsNegative,
6457 llvm::APSInt &Oversized) {
6458 // This method tries to turn a variable array into a constant
6459 // array even when the size isn't an ICE. This is necessary
6460 // for compatibility with code that depends on gcc's buggy
6461 // constant expression folding, like struct {char x[(int)(char*)2];}
6462 SizeIsNegative = false;
6463 Oversized = 0;
6464
6465 if (T->isDependentType())
6466 return QualType();
6467
6469 const Type *Ty = Qs.strip(T);
6470
6471 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6472 QualType Pointee = PTy->getPointeeType();
6473 QualType FixedType =
6474 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6475 Oversized);
6476 if (FixedType.isNull()) return FixedType;
6477 FixedType = Context.getPointerType(FixedType);
6478 return Qs.apply(Context, FixedType);
6479 }
6480 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6481 QualType Inner = PTy->getInnerType();
6482 QualType FixedType =
6483 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6484 Oversized);
6485 if (FixedType.isNull()) return FixedType;
6486 FixedType = Context.getParenType(FixedType);
6487 return Qs.apply(Context, FixedType);
6488 }
6489
6490 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6491 if (!VLATy)
6492 return QualType();
6493
6494 QualType ElemTy = VLATy->getElementType();
6495 if (ElemTy->isVariablyModifiedType()) {
6496 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6497 SizeIsNegative, Oversized);
6498 if (ElemTy.isNull())
6499 return QualType();
6500 }
6501
6503 if (!VLATy->getSizeExpr() ||
6504 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6505 return QualType();
6506
6507 llvm::APSInt Res = Result.Val.getInt();
6508
6509 // Check whether the array size is negative.
6510 if (Res.isSigned() && Res.isNegative()) {
6511 SizeIsNegative = true;
6512 return QualType();
6513 }
6514
6515 // Check whether the array is too large to be addressed.
6516 unsigned ActiveSizeBits =
6517 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6518 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6519 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6520 : Res.getActiveBits();
6521 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6522 Oversized = Res;
6523 return QualType();
6524 }
6525
6526 QualType FoldedArrayType = Context.getConstantArrayType(
6527 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6528 return Qs.apply(Context, FoldedArrayType);
6529}
6530
6531static void
6533 SrcTL = SrcTL.getUnqualifiedLoc();
6534 DstTL = DstTL.getUnqualifiedLoc();
6535 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6536 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6537 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6538 DstPTL.getPointeeLoc());
6539 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6540 return;
6541 }
6542 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6543 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6544 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6545 DstPTL.getInnerLoc());
6546 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6547 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6548 return;
6549 }
6550 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6551 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6552 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6553 TypeLoc DstElemTL = DstATL.getElementLoc();
6554 if (VariableArrayTypeLoc SrcElemATL =
6555 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6556 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6557 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6558 } else {
6559 DstElemTL.initializeFullCopy(SrcElemTL);
6560 }
6561 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6562 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6563 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6564}
6565
6566/// Helper method to turn variable array types into constant array
6567/// types in certain situations which would otherwise be errors (for
6568/// GCC compatibility).
6569static TypeSourceInfo*
6571 ASTContext &Context,
6572 bool &SizeIsNegative,
6573 llvm::APSInt &Oversized) {
6574 QualType FixedTy
6575 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6576 SizeIsNegative, Oversized);
6577 if (FixedTy.isNull())
6578 return nullptr;
6579 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6581 FixedTInfo->getTypeLoc());
6582 return FixedTInfo;
6583}
6584
6587 unsigned FailedFoldDiagID) {
6588 bool SizeIsNegative;
6589 llvm::APSInt Oversized;
6591 TInfo, Context, SizeIsNegative, Oversized);
6592 if (FixedTInfo) {
6593 Diag(Loc, diag::ext_vla_folded_to_constant);
6594 TInfo = FixedTInfo;
6595 T = FixedTInfo->getType();
6596 return true;
6597 }
6598
6599 if (SizeIsNegative)
6600 Diag(Loc, diag::err_typecheck_negative_array_size);
6601 else if (Oversized.getBoolValue())
6602 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6603 else if (FailedFoldDiagID)
6604 Diag(Loc, FailedFoldDiagID);
6605 return false;
6606}
6607
6608void
6610 if (!getLangOpts().CPlusPlus &&
6612 // Don't need to track declarations in the TU in C.
6613 return;
6614
6615 // Note that we have a locally-scoped external with this name.
6617}
6618
6620 // FIXME: We can have multiple results via __attribute__((overloadable)).
6622 return Result.empty() ? nullptr : *Result.begin();
6623}
6624
6626 // FIXME: We should probably indicate the identifier in question to avoid
6627 // confusion for constructs like "virtual int a(), b;"
6628 if (DS.isVirtualSpecified())
6630 diag::err_virtual_non_function);
6631
6632 if (DS.hasExplicitSpecifier())
6634 diag::err_explicit_non_function);
6635
6636 if (DS.isNoreturnSpecified())
6638 diag::err_noreturn_non_function);
6639}
6640
6641NamedDecl*
6644 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6645 if (D.getCXXScopeSpec().isSet()) {
6646 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6647 << D.getCXXScopeSpec().getRange();
6648 D.setInvalidType();
6649 // Pretend we didn't see the scope specifier.
6650 DC = CurContext;
6651 Previous.clear();
6652 }
6653
6654 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6655
6656 if (D.getDeclSpec().isInlineSpecified())
6657 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6658 << getLangOpts().CPlusPlus17;
6659 if (D.getDeclSpec().hasConstexprSpecifier())
6660 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6661 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6662
6663 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6665 Diag(D.getName().StartLocation,
6666 diag::err_deduction_guide_invalid_specifier)
6667 << "typedef";
6668 else
6669 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6670 << D.getName().getSourceRange();
6671 return nullptr;
6672 }
6673
6674 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6675 if (!NewTD) return nullptr;
6676
6677 // Handle attributes prior to checking for duplicates in MergeVarDecl
6678 ProcessDeclAttributes(S, NewTD, D);
6679
6681
6682 bool Redeclaration = D.isRedeclaration();
6683 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6684 D.setRedeclaration(Redeclaration);
6685 return ND;
6686}
6687
6688void
6690 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6691 // then it shall have block scope.
6692 // Note that variably modified types must be fixed before merging the decl so
6693 // that redeclarations will match.
6694 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6695 QualType T = TInfo->getType();
6696 if (T->isVariablyModifiedType()) {
6698
6699 if (S->getFnParent() == nullptr) {
6700 bool SizeIsNegative;
6701 llvm::APSInt Oversized;
6702 TypeSourceInfo *FixedTInfo =
6704 SizeIsNegative,
6705 Oversized);
6706 if (FixedTInfo) {
6707 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6708 NewTD->setTypeSourceInfo(FixedTInfo);
6709 } else {
6710 if (SizeIsNegative)
6711 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6712 else if (T->isVariableArrayType())
6713 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6714 else if (Oversized.getBoolValue())
6715 Diag(NewTD->getLocation(), diag::err_array_too_large)
6716 << toString(Oversized, 10);
6717 else
6718 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6719 NewTD->setInvalidDecl();
6720 }
6721 }
6722 }
6723}
6724
6725NamedDecl*
6727 LookupResult &Previous, bool &Redeclaration) {
6728
6729 // Find the shadowed declaration before filtering for scope.
6730 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6731
6732 // Merge the decl with the existing one if appropriate. If the decl is
6733 // in an outer scope, it isn't the same thing.
6734 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6735 /*AllowInlineNamespace*/false);
6737 if (!Previous.empty()) {
6738 Redeclaration = true;
6739 MergeTypedefNameDecl(S, NewTD, Previous);
6740 } else {
6742 }
6743
6744 if (ShadowedDecl && !Redeclaration)
6745 CheckShadow(NewTD, ShadowedDecl, Previous);
6746
6747 // If this is the C FILE type, notify the AST context.
6748 if (IdentifierInfo *II = NewTD->getIdentifier())
6749 if (!NewTD->isInvalidDecl() &&
6751 switch (II->getNotableIdentifierID()) {
6752 case tok::NotableIdentifierKind::FILE:
6753 Context.setFILEDecl(NewTD);
6754 break;
6755 case tok::NotableIdentifierKind::jmp_buf:
6756 Context.setjmp_bufDecl(NewTD);
6757 break;
6758 case tok::NotableIdentifierKind::sigjmp_buf:
6760 break;
6761 case tok::NotableIdentifierKind::ucontext_t:
6763 break;
6764 case tok::NotableIdentifierKind::float_t:
6765 case tok::NotableIdentifierKind::double_t:
6766 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6767 break;
6768 default:
6769 break;
6770 }
6771 }
6772
6773 return NewTD;
6774}
6775
6776/// Determines whether the given declaration is an out-of-scope
6777/// previous declaration.
6778///
6779/// This routine should be invoked when name lookup has found a
6780/// previous declaration (PrevDecl) that is not in the scope where a
6781/// new declaration by the same name is being introduced. If the new
6782/// declaration occurs in a local scope, previous declarations with
6783/// linkage may still be considered previous declarations (C99
6784/// 6.2.2p4-5, C++ [basic.link]p6).
6785///
6786/// \param PrevDecl the previous declaration found by name
6787/// lookup
6788///
6789/// \param DC the context in which the new declaration is being
6790/// declared.
6791///
6792/// \returns true if PrevDecl is an out-of-scope previous declaration
6793/// for a new delcaration with the same name.
6794static bool
6796 ASTContext &Context) {
6797 if (!PrevDecl)
6798 return false;
6799
6800 if (!PrevDecl->hasLinkage())
6801 return false;
6802
6803 if (Context.getLangOpts().CPlusPlus) {
6804 // C++ [basic.link]p6:
6805 // If there is a visible declaration of an entity with linkage
6806 // having the same name and type, ignoring entities declared
6807 // outside the innermost enclosing namespace scope, the block
6808 // scope declaration declares that same entity and receives the
6809 // linkage of the previous declaration.
6810 DeclContext *OuterContext = DC->getRedeclContext();
6811 if (!OuterContext->isFunctionOrMethod())
6812 // This rule only applies to block-scope declarations.
6813 return false;
6814
6815 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6816 if (PrevOuterContext->isRecord())
6817 // We found a member function: ignore it.
6818 return false;
6819
6820 // Find the innermost enclosing namespace for the new and
6821 // previous declarations.
6822 OuterContext = OuterContext->getEnclosingNamespaceContext();
6823 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6824
6825 // The previous declaration is in a different namespace, so it
6826 // isn't the same function.
6827 if (!OuterContext->Equals(PrevOuterContext))
6828 return false;
6829 }
6830
6831 return true;
6832}
6833
6835 CXXScopeSpec &SS = D.getCXXScopeSpec();
6836 if (!SS.isSet()) return;
6838}
6839
6841 if (Decl->getType().hasAddressSpace())
6842 return;
6843 if (Decl->getType()->isDependentType())
6844 return;
6845 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6846 QualType Type = Var->getType();
6847 if (Type->isSamplerT() || Type->isVoidType())
6848 return;
6850 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6851 // __opencl_c_program_scope_global_variables feature, the address space
6852 // for a variable at program scope or a static or extern variable inside
6853 // a function are inferred to be __global.
6854 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6855 Var->hasGlobalStorage())
6856 ImplAS = LangAS::opencl_global;
6857 // If the original type from a decayed type is an array type and that array
6858 // type has no address space yet, deduce it now.
6859 if (auto DT = dyn_cast<DecayedType>(Type)) {
6860 auto OrigTy = DT->getOriginalType();
6861 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6862 // Add the address space to the original array type and then propagate
6863 // that to the element type through `getAsArrayType`.
6864 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6865 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6866 // Re-generate the decayed type.
6867 Type = Context.getDecayedType(OrigTy);
6868 }
6869 }
6871 // Apply any qualifiers (including address space) from the array type to
6872 // the element type. This implements C99 6.7.3p8: "If the specification of
6873 // an array type includes any type qualifiers, the element type is so
6874 // qualified, not the array type."
6875 if (Type->isArrayType())
6877 Decl->setType(Type);
6878 }
6879}
6880
6881static void checkWeakAttr(Sema &S, NamedDecl &ND) {
6882 // 'weak' only applies to declarations with external linkage.
6883 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6884 if (!ND.isExternallyVisible()) {
6885 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6886 ND.dropAttr<WeakAttr>();
6887 }
6888 }
6889}
6890
6891static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
6892 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6893 if (ND.isExternallyVisible()) {
6894 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6895 ND.dropAttrs<WeakRefAttr, AliasAttr>();
6896 }
6897 }
6898}
6899
6900static void checkAliasAttr(Sema &S, NamedDecl &ND) {
6901 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6902 if (VD->hasInit()) {
6903 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6904 assert(VD->isThisDeclarationADefinition() &&
6905 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6906 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6907 VD->dropAttr<AliasAttr>();
6908 }
6909 }
6910 }
6911}
6912
6913static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
6914 // 'selectany' only applies to externally visible variable declarations.
6915 // It does not apply to functions.
6916 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6917 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6918 S.Diag(Attr->getLocation(),
6919 diag::err_attribute_selectany_non_extern_data);
6920 ND.dropAttr<SelectAnyAttr>();
6921 }
6922 }
6923}
6924
6926 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
6927 if (!ND.isExternallyVisible())
6928 S.Diag(Attr->getLocation(),
6929 diag::warn_attribute_hybrid_patchable_non_extern);
6930 }
6931}
6932
6934 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6935 auto *VD = dyn_cast<VarDecl>(&ND);
6936 bool IsAnonymousNS = false;
6937 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6938 if (VD) {
6939 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6940 while (NS && !IsAnonymousNS) {
6941 IsAnonymousNS = NS->isAnonymousNamespace();
6942 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6943 }
6944 }
6945 // dll attributes require external linkage. Static locals may have external
6946 // linkage but still cannot be explicitly imported or exported.
6947 // In Microsoft mode, a variable defined in anonymous namespace must have
6948 // external linkage in order to be exported.
6949 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6950 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6951 (!AnonNSInMicrosoftMode &&
6952 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6953 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6954 << &ND << Attr;
6955 ND.setInvalidDecl();
6956 }
6957 }
6958}
6959
6961 // Check the attributes on the function type and function params, if any.
6962 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6963 // Don't declare this variable in the second operand of the for-statement;
6964 // GCC miscompiles that by ending its lifetime before evaluating the
6965 // third operand. See gcc.gnu.org/PR86769.
6967 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6968 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6969 TL = ATL.getModifiedLoc()) {
6970 // The [[lifetimebound]] attribute can be applied to the implicit object
6971 // parameter of a non-static member function (other than a ctor or dtor)
6972 // by applying it to the function type.
6973 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6974 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6975 int NoImplicitObjectError = -1;
6976 if (!MD)
6977 NoImplicitObjectError = 0;
6978 else if (MD->isStatic())
6979 NoImplicitObjectError = 1;
6980 else if (MD->isExplicitObjectMemberFunction())
6981 NoImplicitObjectError = 2;
6982 if (NoImplicitObjectError != -1) {
6983 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6984 << NoImplicitObjectError << A->getRange();
6985 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6986 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6987 << isa<CXXDestructorDecl>(MD) << A->getRange();
6988 } else if (MD->getReturnType()->isVoidType()) {
6989 S.Diag(
6990 MD->getLocation(),
6991 diag::
6992 err_lifetimebound_implicit_object_parameter_void_return_type);
6993 }
6994 }
6995 }
6996
6997 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
6998 const ParmVarDecl *P = FD->getParamDecl(I);
6999
7000 // The [[lifetimebound]] attribute can be applied to a function parameter
7001 // only if the function returns a value.
7002 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7003 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7004 S.Diag(A->getLocation(),
7005 diag::err_lifetimebound_parameter_void_return_type);
7006 }
7007 }
7008 }
7009 }
7010}
7011
7013 // Ensure that an auto decl is deduced otherwise the checks below might cache
7014 // the wrong linkage.
7015 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7016
7017 checkWeakAttr(S, ND);
7018 checkWeakRefAttr(S, ND);
7019 checkAliasAttr(S, ND);
7020 checkSelectAnyAttr(S, ND);
7022 checkInheritableAttr(S, ND);
7024}
7025
7027 NamedDecl *NewDecl,
7028 bool IsSpecialization,
7029 bool IsDefinition) {
7030 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7031 return;
7032
7033 bool IsTemplate = false;
7034 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7035 OldDecl = OldTD->getTemplatedDecl();
7036 IsTemplate = true;
7037 if (!IsSpecialization)
7038 IsDefinition = false;
7039 }
7040 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7041 NewDecl = NewTD->getTemplatedDecl();
7042 IsTemplate = true;
7043 }
7044
7045 if (!OldDecl || !NewDecl)
7046 return;
7047
7048 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7049 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7050 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7051 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7052
7053 // dllimport and dllexport are inheritable attributes so we have to exclude
7054 // inherited attribute instances.
7055 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7056 (NewExportAttr && !NewExportAttr->isInherited());
7057
7058 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7059 // the only exception being explicit specializations.
7060 // Implicitly generated declarations are also excluded for now because there
7061 // is no other way to switch these to use dllimport or dllexport.
7062 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7063
7064 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7065 // Allow with a warning for free functions and global variables.
7066 bool JustWarn = false;
7067 if (!OldDecl->isCXXClassMember()) {
7068 auto *VD = dyn_cast<VarDecl>(OldDecl);
7069 if (VD && !VD->getDescribedVarTemplate())
7070 JustWarn = true;
7071 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7072 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7073 JustWarn = true;
7074 }
7075
7076 // We cannot change a declaration that's been used because IR has already
7077 // been emitted. Dllimported functions will still work though (modulo
7078 // address equality) as they can use the thunk.
7079 if (OldDecl->isUsed())
7080 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7081 JustWarn = false;
7082
7083 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7084 : diag::err_attribute_dll_redeclaration;
7085 S.Diag(NewDecl->getLocation(), DiagID)
7086 << NewDecl
7087 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7088 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7089 if (!JustWarn) {
7090 NewDecl->setInvalidDecl();
7091 return;
7092 }
7093 }
7094
7095 // A redeclaration is not allowed to drop a dllimport attribute, the only
7096 // exceptions being inline function definitions (except for function
7097 // templates), local extern declarations, qualified friend declarations or
7098 // special MSVC extension: in the last case, the declaration is treated as if
7099 // it were marked dllexport.
7100 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7101 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7102 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7103 // Ignore static data because out-of-line definitions are diagnosed
7104 // separately.
7105 IsStaticDataMember = VD->isStaticDataMember();
7106 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7108 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7109 IsInline = FD->isInlined();
7110 IsQualifiedFriend = FD->getQualifier() &&
7111 FD->getFriendObjectKind() == Decl::FOK_Declared;
7112 }
7113
7114 if (OldImportAttr && !HasNewAttr &&
7115 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7116 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7117 if (IsMicrosoftABI && IsDefinition) {
7118 if (IsSpecialization) {
7119 S.Diag(
7120 NewDecl->getLocation(),
7121 diag::err_attribute_dllimport_function_specialization_definition);
7122 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7123 NewDecl->dropAttr<DLLImportAttr>();
7124 } else {
7125 S.Diag(NewDecl->getLocation(),
7126 diag::warn_redeclaration_without_import_attribute)
7127 << NewDecl;
7128 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7129 NewDecl->dropAttr<DLLImportAttr>();
7130 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7131 S.Context, NewImportAttr->getRange()));
7132 }
7133 } else if (IsMicrosoftABI && IsSpecialization) {
7134 assert(!IsDefinition);
7135 // MSVC allows this. Keep the inherited attribute.
7136 } else {
7137 S.Diag(NewDecl->getLocation(),
7138 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7139 << NewDecl << OldImportAttr;
7140 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7141 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7142 OldDecl->dropAttr<DLLImportAttr>();
7143 NewDecl->dropAttr<DLLImportAttr>();
7144 }
7145 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7146 // In MinGW, seeing a function declared inline drops the dllimport
7147 // attribute.
7148 OldDecl->dropAttr<DLLImportAttr>();
7149 NewDecl->dropAttr<DLLImportAttr>();
7150 S.Diag(NewDecl->getLocation(),
7151 diag::warn_dllimport_dropped_from_inline_function)
7152 << NewDecl << OldImportAttr;
7153 }
7154
7155 // A specialization of a class template member function is processed here
7156 // since it's a redeclaration. If the parent class is dllexport, the
7157 // specialization inherits that attribute. This doesn't happen automatically
7158 // since the parent class isn't instantiated until later.
7159 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7160 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7161 !NewImportAttr && !NewExportAttr) {
7162 if (const DLLExportAttr *ParentExportAttr =
7163 MD->getParent()->getAttr<DLLExportAttr>()) {
7164 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7165 NewAttr->setInherited(true);
7166 NewDecl->addAttr(NewAttr);
7167 }
7168 }
7169 }
7170}
7171
7172/// Given that we are within the definition of the given function,
7173/// will that definition behave like C99's 'inline', where the
7174/// definition is discarded except for optimization purposes?
7176 // Try to avoid calling GetGVALinkageForFunction.
7177
7178 // All cases of this require the 'inline' keyword.
7179 if (!FD->isInlined()) return false;
7180
7181 // This is only possible in C++ with the gnu_inline attribute.
7182 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7183 return false;
7184
7185 // Okay, go ahead and call the relatively-more-expensive function.
7187}
7188
7189/// Determine whether a variable is extern "C" prior to attaching
7190/// an initializer. We can't just call isExternC() here, because that
7191/// will also compute and cache whether the declaration is externally
7192/// visible, which might change when we attach the initializer.
7193///
7194/// This can only be used if the declaration is known to not be a
7195/// redeclaration of an internal linkage declaration.
7196///
7197/// For instance:
7198///
7199/// auto x = []{};
7200///
7201/// Attaching the initializer here makes this declaration not externally
7202/// visible, because its type has internal linkage.
7203///
7204/// FIXME: This is a hack.
7205template<typename T>
7206static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7207 if (S.getLangOpts().CPlusPlus) {
7208 // In C++, the overloadable attribute negates the effects of extern "C".
7209 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7210 return false;
7211
7212 // So do CUDA's host/device attributes.
7213 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7214 D->template hasAttr<CUDAHostAttr>()))
7215 return false;
7216 }
7217 return D->isExternC();
7218}
7219
7220static bool shouldConsiderLinkage(const VarDecl *VD) {
7221 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7222 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7223 isa<OMPDeclareMapperDecl>(DC))
7224 return VD->hasExternalStorage();
7225 if (DC->isFileContext())
7226 return true;
7227 if (DC->isRecord())
7228 return false;
7229 if (DC->getDeclKind() == Decl::HLSLBuffer)
7230 return false;
7231
7232 if (isa<RequiresExprBodyDecl>(DC))
7233 return false;
7234 llvm_unreachable("Unexpected context");
7235}
7236
7237static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7238 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7239 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7240 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7241 return true;
7242 if (DC->isRecord())
7243 return false;
7244 llvm_unreachable("Unexpected context");
7245}
7246
7247static bool hasParsedAttr(Scope *S, const Declarator &PD,
7248 ParsedAttr::Kind Kind) {
7249 // Check decl attributes on the DeclSpec.
7250 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7251 return true;
7252
7253 // Walk the declarator structure, checking decl attributes that were in a type
7254 // position to the decl itself.
7255 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7256 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7257 return true;
7258 }
7259
7260 // Finally, check attributes on the decl itself.
7261 return PD.getAttributes().hasAttribute(Kind) ||
7263}
7264
7266 if (!DC->isFunctionOrMethod())
7267 return false;
7268
7269 // If this is a local extern function or variable declared within a function
7270 // template, don't add it into the enclosing namespace scope until it is
7271 // instantiated; it might have a dependent type right now.
7272 if (DC->isDependentContext())
7273 return true;
7274
7275 // C++11 [basic.link]p7:
7276 // When a block scope declaration of an entity with linkage is not found to
7277 // refer to some other declaration, then that entity is a member of the
7278 // innermost enclosing namespace.
7279 //
7280 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7281 // semantically-enclosing namespace, not a lexically-enclosing one.
7282 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7283 DC = DC->getParent();
7284 return true;
7285}
7286
7287/// Returns true if given declaration has external C language linkage.
7288static bool isDeclExternC(const Decl *D) {
7289 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7290 return FD->isExternC();
7291 if (const auto *VD = dyn_cast<VarDecl>(D))
7292 return VD->isExternC();
7293
7294 llvm_unreachable("Unknown type of decl!");
7295}
7296
7297/// Returns true if there hasn't been any invalid type diagnosed.
7298static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7299 DeclContext *DC = NewVD->getDeclContext();
7300 QualType R = NewVD->getType();
7301
7302 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7303 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7304 // argument.
7305 if (R->isImageType() || R->isPipeType()) {
7306 Se.Diag(NewVD->getLocation(),
7307 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7308 << R;
7309 NewVD->setInvalidDecl();
7310 return false;
7311 }
7312
7313 // OpenCL v1.2 s6.9.r:
7314 // The event type cannot be used to declare a program scope variable.
7315 // OpenCL v2.0 s6.9.q:
7316 // The clk_event_t and reserve_id_t types cannot be declared in program
7317 // scope.
7318 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7319 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7320 Se.Diag(NewVD->getLocation(),
7321 diag::err_invalid_type_for_program_scope_var)
7322 << R;
7323 NewVD->setInvalidDecl();
7324 return false;
7325 }
7326 }
7327
7328 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7329 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7330 Se.getLangOpts())) {
7331 QualType NR = R.getCanonicalType();
7332 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7333 NR->isReferenceType()) {
7336 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7337 << NR->isReferenceType();
7338 NewVD->setInvalidDecl();
7339 return false;
7340 }
7341 NR = NR->getPointeeType();
7342 }
7343 }
7344
7345 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7346 Se.getLangOpts())) {
7347 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7348 // half array type (unless the cl_khr_fp16 extension is enabled).
7349 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7350 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7351 NewVD->setInvalidDecl();
7352 return false;
7353 }
7354 }
7355
7356 // OpenCL v1.2 s6.9.r:
7357 // The event type cannot be used with the __local, __constant and __global
7358 // address space qualifiers.
7359 if (R->isEventT()) {
7361 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7362 NewVD->setInvalidDecl();
7363 return false;
7364 }
7365 }
7366
7367 if (R->isSamplerT()) {
7368 // OpenCL v1.2 s6.9.b p4:
7369 // The sampler type cannot be used with the __local and __global address
7370 // space qualifiers.
7373 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7374 NewVD->setInvalidDecl();
7375 }
7376
7377 // OpenCL v1.2 s6.12.14.1:
7378 // A global sampler must be declared with either the constant address
7379 // space qualifier or with the const qualifier.
7380 if (DC->isTranslationUnit() &&
7382 R.isConstQualified())) {
7383 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7384 NewVD->setInvalidDecl();
7385 }
7386 if (NewVD->isInvalidDecl())
7387 return false;
7388 }
7389
7390 return true;
7391}
7392
7393template <typename AttrTy>
7394static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7395 const TypedefNameDecl *TND = TT->getDecl();
7396 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7397 AttrTy *Clone = Attribute->clone(S.Context);
7398 Clone->setInherited(true);
7399 D->addAttr(Clone);
7400 }
7401}
7402
7403// This function emits warning and a corresponding note based on the
7404// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7405// declarations of an annotated type must be const qualified.
7407 QualType VarType = VD->getType().getCanonicalType();
7408
7409 // Ignore local declarations (for now) and those with const qualification.
7410 // TODO: Local variables should not be allowed if their type declaration has
7411 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7412 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7413 return;
7414
7415 if (VarType->isArrayType()) {
7416 // Retrieve element type for array declarations.
7417 VarType = S.getASTContext().getBaseElementType(VarType);
7418 }
7419
7420 const RecordDecl *RD = VarType->getAsRecordDecl();
7421
7422 // Check if the record declaration is present and if it has any attributes.
7423 if (RD == nullptr)
7424 return;
7425
7426 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7427 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7428 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7429 return;
7430 }
7431}
7432
7433// Checks if VD is declared at global scope or with C language linkage.
7434static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7435 return Name.getAsIdentifierInfo() &&
7436 Name.getAsIdentifierInfo()->isStr("main") &&
7437 !VD->getDescribedVarTemplate() &&
7439 VD->isExternC());
7440}
7441
7443 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7444 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7445 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7446 QualType R = TInfo->getType();
7448
7449 IdentifierInfo *II = Name.getAsIdentifierInfo();
7450 bool IsPlaceholderVariable = false;
7451
7452 if (D.isDecompositionDeclarator()) {
7453 // Take the name of the first declarator as our name for diagnostic
7454 // purposes.
7455 auto &Decomp = D.getDecompositionDeclarator();
7456 if (!Decomp.bindings().empty()) {
7457 II = Decomp.bindings()[0].Name;
7458 Name = II;
7459 }
7460 } else if (!II) {
7461 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7462 return nullptr;
7463 }
7464
7465
7466 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7468
7469 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7470 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7471 IsPlaceholderVariable = true;
7472 if (!Previous.empty()) {
7473 NamedDecl *PrevDecl = *Previous.begin();
7474 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7475 DC->getRedeclContext());
7476 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7477 DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7478 }
7479 }
7480
7481 // dllimport globals without explicit storage class are treated as extern. We
7482 // have to change the storage class this early to get the right DeclContext.
7483 if (SC == SC_None && !DC->isRecord() &&
7484 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7485 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7486 SC = SC_Extern;
7487
7488 DeclContext *OriginalDC = DC;
7489 bool IsLocalExternDecl = SC == SC_Extern &&
7491
7492 if (SCSpec == DeclSpec::SCS_mutable) {
7493 // mutable can only appear on non-static class members, so it's always
7494 // an error here
7495 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7496 D.setInvalidType();
7497 SC = SC_None;
7498 }
7499
7500 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7501 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7502 D.getDeclSpec().getStorageClassSpecLoc())) {
7503 // In C++11, the 'register' storage class specifier is deprecated.
7504 // Suppress the warning in system macros, it's used in macros in some
7505 // popular C system headers, such as in glibc's htonl() macro.
7506 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7507 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7508 : diag::warn_deprecated_register)
7509 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7510 }
7511
7512 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7513
7514 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7515 // C99 6.9p2: The storage-class specifiers auto and register shall not
7516 // appear in the declaration specifiers in an external declaration.
7517 // Global Register+Asm is a GNU extension we support.
7518 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7519 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7520 D.setInvalidType();
7521 }
7522 }
7523
7524 // If this variable has a VLA type and an initializer, try to
7525 // fold to a constant-sized type. This is otherwise invalid.
7526 if (D.hasInitializer() && R->isVariableArrayType())
7527 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7528 /*DiagID=*/0);
7529
7530 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7531 const AutoType *AT = TL.getTypePtr();
7532 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7533 }
7534
7535 bool IsMemberSpecialization = false;
7536 bool IsVariableTemplateSpecialization = false;
7537 bool IsPartialSpecialization = false;
7538 bool IsVariableTemplate = false;
7539 VarDecl *NewVD = nullptr;
7540 VarTemplateDecl *NewTemplate = nullptr;
7541 TemplateParameterList *TemplateParams = nullptr;
7542 if (!getLangOpts().CPlusPlus) {
7543 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7544 II, R, TInfo, SC);
7545
7546 if (R->getContainedDeducedType())
7547 ParsingInitForAutoVars.insert(NewVD);
7548
7549 if (D.isInvalidType())
7550 NewVD->setInvalidDecl();
7551
7553 NewVD->hasLocalStorage())
7554 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7556 } else {
7557 bool Invalid = false;
7558 // Match up the template parameter lists with the scope specifier, then
7559 // determine whether we have a template or a template specialization.
7561 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7562 D.getCXXScopeSpec(),
7564 ? D.getName().TemplateId
7565 : nullptr,
7566 TemplateParamLists,
7567 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7568
7569 if (TemplateParams) {
7570 if (DC->isDependentContext()) {
7571 ContextRAII SavedContext(*this, DC);
7573 Invalid = true;
7574 }
7575
7576 if (!TemplateParams->size() &&
7578 // There is an extraneous 'template<>' for this variable. Complain
7579 // about it, but allow the declaration of the variable.
7580 Diag(TemplateParams->getTemplateLoc(),
7581 diag::err_template_variable_noparams)
7582 << II
7583 << SourceRange(TemplateParams->getTemplateLoc(),
7584 TemplateParams->getRAngleLoc());
7585 TemplateParams = nullptr;
7586 } else {
7587 // Check that we can declare a template here.
7588 if (CheckTemplateDeclScope(S, TemplateParams))
7589 return nullptr;
7590
7591 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7592 // This is an explicit specialization or a partial specialization.
7593 IsVariableTemplateSpecialization = true;
7594 IsPartialSpecialization = TemplateParams->size() > 0;
7595 } else { // if (TemplateParams->size() > 0)
7596 // This is a template declaration.
7597 IsVariableTemplate = true;
7598
7599 // Only C++1y supports variable templates (N3651).
7600 Diag(D.getIdentifierLoc(),
7602 ? diag::warn_cxx11_compat_variable_template
7603 : diag::ext_variable_template);
7604 }
7605 }
7606 } else {
7607 // Check that we can declare a member specialization here.
7608 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7609 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7610 return nullptr;
7611 assert((Invalid ||
7612 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7613 "should have a 'template<>' for this decl");
7614 }
7615
7616 bool IsExplicitSpecialization =
7617 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7618
7619 // C++ [temp.expl.spec]p2:
7620 // The declaration in an explicit-specialization shall not be an
7621 // export-declaration. An explicit specialization shall not use a
7622 // storage-class-specifier other than thread_local.
7623 //
7624 // We use the storage-class-specifier from DeclSpec because we may have
7625 // added implicit 'extern' for declarations with __declspec(dllimport)!
7626 if (SCSpec != DeclSpec::SCS_unspecified &&
7627 (IsExplicitSpecialization || IsMemberSpecialization)) {
7628 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7629 diag::ext_explicit_specialization_storage_class)
7630 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7631 }
7632
7633 if (CurContext->isRecord()) {
7634 if (SC == SC_Static) {
7635 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7636 // Walk up the enclosing DeclContexts to check for any that are
7637 // incompatible with static data members.
7638 const DeclContext *FunctionOrMethod = nullptr;
7639 const CXXRecordDecl *AnonStruct = nullptr;
7640 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7641 if (Ctxt->isFunctionOrMethod()) {
7642 FunctionOrMethod = Ctxt;
7643 break;
7644 }
7645 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7646 if (ParentDecl && !ParentDecl->getDeclName()) {
7647 AnonStruct = ParentDecl;
7648 break;
7649 }
7650 }
7651 if (FunctionOrMethod) {
7652 // C++ [class.static.data]p5: A local class shall not have static
7653 // data members.
7654 Diag(D.getIdentifierLoc(),
7655 diag::err_static_data_member_not_allowed_in_local_class)
7656 << Name << RD->getDeclName()
7657 << llvm::to_underlying(RD->getTagKind());
7658 } else if (AnonStruct) {
7659 // C++ [class.static.data]p4: Unnamed classes and classes contained
7660 // directly or indirectly within unnamed classes shall not contain
7661 // static data members.
7662 Diag(D.getIdentifierLoc(),
7663 diag::err_static_data_member_not_allowed_in_anon_struct)
7664 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7665 Invalid = true;
7666 } else if (RD->isUnion()) {
7667 // C++98 [class.union]p1: If a union contains a static data member,
7668 // the program is ill-formed. C++11 drops this restriction.
7669 Diag(D.getIdentifierLoc(),
7671 ? diag::warn_cxx98_compat_static_data_member_in_union
7672 : diag::ext_static_data_member_in_union)
7673 << Name;
7674 }
7675 }
7676 } else if (IsVariableTemplate || IsPartialSpecialization) {
7677 // There is no such thing as a member field template.
7678 Diag(D.getIdentifierLoc(), diag::err_template_member)
7679 << II << TemplateParams->getSourceRange();
7680 // Recover by pretending this is a static data member template.
7681 SC = SC_Static;
7682 }
7683 } else if (DC->isRecord()) {
7684 // This is an out-of-line definition of a static data member.
7685 switch (SC) {
7686 case SC_None:
7687 break;
7688 case SC_Static:
7689 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7690 diag::err_static_out_of_line)
7692 D.getDeclSpec().getStorageClassSpecLoc());
7693 break;
7694 case SC_Auto:
7695 case SC_Register:
7696 case SC_Extern:
7697 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7698 // to names of variables declared in a block or to function parameters.
7699 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7700 // of class members
7701
7702 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7703 diag::err_storage_class_for_static_member)
7705 D.getDeclSpec().getStorageClassSpecLoc());
7706 break;
7707 case SC_PrivateExtern:
7708 llvm_unreachable("C storage class in c++!");
7709 }
7710 }
7711
7712 if (IsVariableTemplateSpecialization) {
7713 SourceLocation TemplateKWLoc =
7714 TemplateParamLists.size() > 0
7715 ? TemplateParamLists[0]->getTemplateLoc()
7716 : SourceLocation();
7718 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7720 if (Res.isInvalid())
7721 return nullptr;
7722 NewVD = cast<VarDecl>(Res.get());
7723 AddToScope = false;
7724 } else if (D.isDecompositionDeclarator()) {
7726 D.getIdentifierLoc(), R, TInfo, SC,
7727 Bindings);
7728 } else
7729 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7730 D.getIdentifierLoc(), II, R, TInfo, SC);
7731
7732 // If this is supposed to be a variable template, create it as such.
7733 if (IsVariableTemplate) {
7734 NewTemplate =
7735 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7736 TemplateParams, NewVD);
7737 NewVD->setDescribedVarTemplate(NewTemplate);
7738 }
7739
7740 // If this decl has an auto type in need of deduction, make a note of the
7741 // Decl so we can diagnose uses of it in its own initializer.
7742 if (R->getContainedDeducedType())
7743 ParsingInitForAutoVars.insert(NewVD);
7744
7745 if (D.isInvalidType() || Invalid) {
7746 NewVD->setInvalidDecl();
7747 if (NewTemplate)
7748 NewTemplate->setInvalidDecl();
7749 }
7750
7751 SetNestedNameSpecifier(*this, NewVD, D);
7752
7753 // If we have any template parameter lists that don't directly belong to
7754 // the variable (matching the scope specifier), store them.
7755 // An explicit variable template specialization does not own any template
7756 // parameter lists.
7757 unsigned VDTemplateParamLists =
7758 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7759 if (TemplateParamLists.size() > VDTemplateParamLists)
7761 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7762 }
7763
7764 if (D.getDeclSpec().isInlineSpecified()) {
7765 if (!getLangOpts().CPlusPlus) {
7766 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7767 << 0;
7768 } else if (CurContext->isFunctionOrMethod()) {
7769 // 'inline' is not allowed on block scope variable declaration.
7770 Diag(D.getDeclSpec().getInlineSpecLoc(),
7771 diag::err_inline_declaration_block_scope) << Name
7772 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7773 } else {
7774 Diag(D.getDeclSpec().getInlineSpecLoc(),
7775 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7776 : diag::ext_inline_variable);
7777 NewVD->setInlineSpecified();
7778 }
7779 }
7780
7781 // Set the lexical context. If the declarator has a C++ scope specifier, the
7782 // lexical context will be different from the semantic context.
7784 if (NewTemplate)
7785 NewTemplate->setLexicalDeclContext(CurContext);
7786
7787 if (IsLocalExternDecl) {
7788 if (D.isDecompositionDeclarator())
7789 for (auto *B : Bindings)
7790 B->setLocalExternDecl();
7791 else
7792 NewVD->setLocalExternDecl();
7793 }
7794
7795 bool EmitTLSUnsupportedError = false;
7796 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7797 // C++11 [dcl.stc]p4:
7798 // When thread_local is applied to a variable of block scope the
7799 // storage-class-specifier static is implied if it does not appear
7800 // explicitly.
7801 // Core issue: 'static' is not implied if the variable is declared
7802 // 'extern'.
7803 if (NewVD->hasLocalStorage() &&
7804 (SCSpec != DeclSpec::SCS_unspecified ||
7806 !DC->isFunctionOrMethod()))
7807 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7808 diag::err_thread_non_global)
7810 else if (!Context.getTargetInfo().isTLSSupported()) {
7811 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7812 getLangOpts().SYCLIsDevice) {
7813 // Postpone error emission until we've collected attributes required to
7814 // figure out whether it's a host or device variable and whether the
7815 // error should be ignored.
7816 EmitTLSUnsupportedError = true;
7817 // We still need to mark the variable as TLS so it shows up in AST with
7818 // proper storage class for other tools to use even if we're not going
7819 // to emit any code for it.
7820 NewVD->setTSCSpec(TSCS);
7821 } else
7822 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7823 diag::err_thread_unsupported);
7824 } else
7825 NewVD->setTSCSpec(TSCS);
7826 }
7827
7828 switch (D.getDeclSpec().getConstexprSpecifier()) {
7830 break;
7831
7833 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7834 diag::err_constexpr_wrong_decl_kind)
7835 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7836 [[fallthrough]];
7837
7839 NewVD->setConstexpr(true);
7840 // C++1z [dcl.spec.constexpr]p1:
7841 // A static data member declared with the constexpr specifier is
7842 // implicitly an inline variable.
7843 if (NewVD->isStaticDataMember() &&
7844 (getLangOpts().CPlusPlus17 ||
7846 NewVD->setImplicitlyInline();
7847 break;
7848
7850 if (!NewVD->hasGlobalStorage())
7851 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7852 diag::err_constinit_local_variable);
7853 else
7854 NewVD->addAttr(
7855 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7856 ConstInitAttr::Keyword_constinit));
7857 break;
7858 }
7859
7860 // C99 6.7.4p3
7861 // An inline definition of a function with external linkage shall
7862 // not contain a definition of a modifiable object with static or
7863 // thread storage duration...
7864 // We only apply this when the function is required to be defined
7865 // elsewhere, i.e. when the function is not 'extern inline'. Note
7866 // that a local variable with thread storage duration still has to
7867 // be marked 'static'. Also note that it's possible to get these
7868 // semantics in C++ using __attribute__((gnu_inline)).
7869 if (SC == SC_Static && S->getFnParent() != nullptr &&
7870 !NewVD->getType().isConstQualified()) {
7872 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7873 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7874 diag::warn_static_local_in_extern_inline);
7876 }
7877 }
7878
7879 if (D.getDeclSpec().isModulePrivateSpecified()) {
7880 if (IsVariableTemplateSpecialization)
7881 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7882 << (IsPartialSpecialization ? 1 : 0)
7884 D.getDeclSpec().getModulePrivateSpecLoc());
7885 else if (IsMemberSpecialization)
7886 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7887 << 2
7888 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7889 else if (NewVD->hasLocalStorage())
7890 Diag(NewVD->getLocation(), diag::err_module_private_local)
7891 << 0 << NewVD
7892 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7894 D.getDeclSpec().getModulePrivateSpecLoc());
7895 else {
7896 NewVD->setModulePrivate();
7897 if (NewTemplate)
7898 NewTemplate->setModulePrivate();
7899 for (auto *B : Bindings)
7900 B->setModulePrivate();
7901 }
7902 }
7903
7904 if (getLangOpts().OpenCL) {
7906
7907 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7908 if (TSC != TSCS_unspecified) {
7909 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7910 diag::err_opencl_unknown_type_specifier)
7912 << DeclSpec::getSpecifierName(TSC) << 1;
7913 NewVD->setInvalidDecl();
7914 }
7915 }
7916
7917 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7918 // address space if the table has local storage (semantic checks elsewhere
7919 // will produce an error anyway).
7920 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7921 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7922 !NewVD->hasLocalStorage()) {
7925 NewVD->setType(Type);
7926 }
7927 }
7928
7929 // Handle attributes prior to checking for duplicates in MergeVarDecl
7930 ProcessDeclAttributes(S, NewVD, D);
7931
7932 if (getLangOpts().HLSL)
7934
7935 // FIXME: This is probably the wrong location to be doing this and we should
7936 // probably be doing this for more attributes (especially for function
7937 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7938 // the code to copy attributes would be generated by TableGen.
7939 if (R->isFunctionPointerType())
7940 if (const auto *TT = R->getAs<TypedefType>())
7941 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7942
7943 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7944 getLangOpts().SYCLIsDevice) {
7945 if (EmitTLSUnsupportedError &&
7947 (getLangOpts().OpenMPIsTargetDevice &&
7948 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7949 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7950 diag::err_thread_unsupported);
7951
7952 if (EmitTLSUnsupportedError &&
7953 (LangOpts.SYCLIsDevice ||
7954 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7955 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7956 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7957 // storage [duration]."
7958 if (SC == SC_None && S->getFnParent() != nullptr &&
7959 (NewVD->hasAttr<CUDASharedAttr>() ||
7960 NewVD->hasAttr<CUDAConstantAttr>())) {
7961 NewVD->setStorageClass(SC_Static);
7962 }
7963 }
7964
7965 // Ensure that dllimport globals without explicit storage class are treated as
7966 // extern. The storage class is set above using parsed attributes. Now we can
7967 // check the VarDecl itself.
7968 assert(!NewVD->hasAttr<DLLImportAttr>() ||
7969 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7970 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7971
7972 // In auto-retain/release, infer strong retension for variables of
7973 // retainable type.
7974 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
7975 NewVD->setInvalidDecl();
7976
7977 // Handle GNU asm-label extension (encoded as an attribute).
7978 if (Expr *E = (Expr*)D.getAsmLabel()) {
7979 // The parser guarantees this is a string.
7980 StringLiteral *SE = cast<StringLiteral>(E);
7981 StringRef Label = SE->getString();
7982 if (S->getFnParent() != nullptr) {
7983 switch (SC) {
7984 case SC_None:
7985 case SC_Auto:
7986 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7987 break;
7988 case SC_Register:
7989 // Local Named register
7992 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7993 break;
7994 case SC_Static:
7995 case SC_Extern:
7996 case SC_PrivateExtern:
7997 break;
7998 }
7999 } else if (SC == SC_Register) {
8000 // Global Named register
8001 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8002 const auto &TI = Context.getTargetInfo();
8003 bool HasSizeMismatch;
8004
8005 if (!TI.isValidGCCRegisterName(Label))
8006 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8007 else if (!TI.validateGlobalRegisterVariable(Label,
8009 HasSizeMismatch))
8010 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8011 else if (HasSizeMismatch)
8012 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8013 }
8014
8015 if (!R->isIntegralType(Context) && !R->isPointerType()) {
8016 Diag(TInfo->getTypeLoc().getBeginLoc(),
8017 diag::err_asm_unsupported_register_type)
8018 << TInfo->getTypeLoc().getSourceRange();
8019 NewVD->setInvalidDecl(true);
8020 }
8021 }
8022
8023 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8024 /*IsLiteralLabel=*/true,
8025 SE->getStrTokenLoc(0)));
8026 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8027 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8029 if (I != ExtnameUndeclaredIdentifiers.end()) {
8030 if (isDeclExternC(NewVD)) {
8031 NewVD->addAttr(I->second);
8033 } else
8034 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8035 << /*Variable*/1 << NewVD;
8036 }
8037 }
8038
8039 // Find the shadowed declaration before filtering for scope.
8040 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8042 : nullptr;
8043
8044 // Don't consider existing declarations that are in a different
8045 // scope and are out-of-semantic-context declarations (if the new
8046 // declaration has linkage).
8048 D.getCXXScopeSpec().isNotEmpty() ||
8049 IsMemberSpecialization ||
8050 IsVariableTemplateSpecialization);
8051
8052 // Check whether the previous declaration is in the same block scope. This
8053 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8054 if (getLangOpts().CPlusPlus &&
8055 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8057 Previous.isSingleResult() && !Previous.isShadowed() &&
8058 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8059
8060 if (!getLangOpts().CPlusPlus) {
8061 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8062 } else {
8063 // If this is an explicit specialization of a static data member, check it.
8064 if (IsMemberSpecialization && !IsVariableTemplate &&
8065 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8067 NewVD->setInvalidDecl();
8068
8069 // Merge the decl with the existing one if appropriate.
8070 if (!Previous.empty()) {
8071 if (Previous.isSingleResult() &&
8072 isa<FieldDecl>(Previous.getFoundDecl()) &&
8073 D.getCXXScopeSpec().isSet()) {
8074 // The user tried to define a non-static data member
8075 // out-of-line (C++ [dcl.meaning]p1).
8076 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8077 << D.getCXXScopeSpec().getRange();
8078 Previous.clear();
8079 NewVD->setInvalidDecl();
8080 }
8081 } else if (D.getCXXScopeSpec().isSet() &&
8082 !IsVariableTemplateSpecialization) {
8083 // No previous declaration in the qualifying scope.
8084 Diag(D.getIdentifierLoc(), diag::err_no_member)
8085 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8086 << D.getCXXScopeSpec().getRange();
8087 NewVD->setInvalidDecl();
8088 }
8089
8090 if (!IsPlaceholderVariable)
8091 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8092
8093 // CheckVariableDeclaration will set NewVD as invalid if something is in
8094 // error like WebAssembly tables being declared as arrays with a non-zero
8095 // size, but then parsing continues and emits further errors on that line.
8096 // To avoid that we check here if it happened and return nullptr.
8097 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8098 return nullptr;
8099
8100 if (NewTemplate) {
8101 VarTemplateDecl *PrevVarTemplate =
8102 NewVD->getPreviousDecl()
8104 : nullptr;
8105
8106 // Check the template parameter list of this declaration, possibly
8107 // merging in the template parameter list from the previous variable
8108 // template declaration.
8110 TemplateParams,
8111 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8112 : nullptr,
8113 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8114 DC->isDependentContext())
8116 : TPC_VarTemplate))
8117 NewVD->setInvalidDecl();
8118
8119 // If we are providing an explicit specialization of a static variable
8120 // template, make a note of that.
8121 if (PrevVarTemplate &&
8122 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8123 PrevVarTemplate->setMemberSpecialization();
8124 }
8125 }
8126
8127 // Diagnose shadowed variables iff this isn't a redeclaration.
8128 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8129 CheckShadow(NewVD, ShadowedDecl, Previous);
8130
8131 ProcessPragmaWeak(S, NewVD);
8132
8133 // If this is the first declaration of an extern C variable, update
8134 // the map of such variables.
8135 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8136 isIncompleteDeclExternC(*this, NewVD))
8138
8139 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8141 Decl *ManglingContextDecl;
8142 std::tie(MCtx, ManglingContextDecl) =
8144 if (MCtx) {
8146 NewVD, MCtx->getManglingNumber(
8147 NewVD, getMSManglingNumber(getLangOpts(), S)));
8149 }
8150 }
8151
8152 // Special handling of variable named 'main'.
8153 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8154 // C++ [basic.start.main]p3:
8155 // A program that declares
8156 // - a variable main at global scope, or
8157 // - an entity named main with C language linkage (in any namespace)
8158 // is ill-formed
8159 if (getLangOpts().CPlusPlus)
8160 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8161 << NewVD->isExternC();
8162
8163 // In C, and external-linkage variable named main results in undefined
8164 // behavior.
8165 else if (NewVD->hasExternalFormalLinkage())
8166 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8167 }
8168
8169 if (D.isRedeclaration() && !Previous.empty()) {
8170 NamedDecl *Prev = Previous.getRepresentativeDecl();
8171 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8172 D.isFunctionDefinition());
8173 }
8174
8175 if (NewTemplate) {
8176 if (NewVD->isInvalidDecl())
8177 NewTemplate->setInvalidDecl();
8178 ActOnDocumentableDecl(NewTemplate);
8179 return NewTemplate;
8180 }
8181
8182 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8184
8186
8187 return NewVD;
8188}
8189
8190/// Enum describing the %select options in diag::warn_decl_shadow.
8200
8201/// Determine what kind of declaration we're shadowing.
8203 const DeclContext *OldDC) {
8204 if (isa<TypeAliasDecl>(ShadowedDecl))
8205 return SDK_Using;
8206 else if (isa<TypedefDecl>(ShadowedDecl))
8207 return SDK_Typedef;
8208 else if (isa<BindingDecl>(ShadowedDecl))
8209 return SDK_StructuredBinding;
8210 else if (isa<RecordDecl>(OldDC))
8211 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8212
8213 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8214}
8215
8216/// Return the location of the capture if the given lambda captures the given
8217/// variable \p VD, or an invalid source location otherwise.
8219 const VarDecl *VD) {
8220 for (const Capture &Capture : LSI->Captures) {
8222 return Capture.getLocation();
8223 }
8224 return SourceLocation();
8225}
8226
8228 const LookupResult &R) {
8229 // Only diagnose if we're shadowing an unambiguous field or variable.
8231 return false;
8232
8233 // Return false if warning is ignored.
8234 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8235}
8236
8238 const LookupResult &R) {
8240 return nullptr;
8241
8242 // Don't diagnose declarations at file scope.
8243 if (D->hasGlobalStorage() && !D->isStaticLocal())
8244 return nullptr;
8245
8246 NamedDecl *ShadowedDecl = R.getFoundDecl();
8247 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8248 : nullptr;
8249}
8250
8252 const LookupResult &R) {
8253 // Don't warn if typedef declaration is part of a class
8254 if (D->getDeclContext()->isRecord())
8255 return nullptr;
8256
8258 return nullptr;
8259
8260 NamedDecl *ShadowedDecl = R.getFoundDecl();
8261 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8262}
8263
8265 const LookupResult &R) {
8267 return nullptr;
8268
8269 NamedDecl *ShadowedDecl = R.getFoundDecl();
8270 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8271 : nullptr;
8272}
8273
8275 const LookupResult &R) {
8276 DeclContext *NewDC = D->getDeclContext();
8277
8278 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8279 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) {
8280 // Fields are not shadowed by variables in C++ static methods.
8281 if (MD->isStatic())
8282 return;
8283
8284 if (!MD->getParent()->isLambda() && MD->isExplicitObjectMemberFunction())
8285 return;
8286 }
8287 // Fields shadowed by constructor parameters are a special case. Usually
8288 // the constructor initializes the field with the parameter.
8289 if (isa<CXXConstructorDecl>(NewDC))
8290 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8291 // Remember that this was shadowed so we can either warn about its
8292 // modification or its existence depending on warning settings.
8293 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8294 return;
8295 }
8296 }
8297
8298 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8299 if (shadowedVar->isExternC()) {
8300 // For shadowing external vars, make sure that we point to the global
8301 // declaration, not a locally scoped extern declaration.
8302 for (auto *I : shadowedVar->redecls())
8303 if (I->isFileVarDecl()) {
8304 ShadowedDecl = I;
8305 break;
8306 }
8307 }
8308
8309 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8310
8311 unsigned WarningDiag = diag::warn_decl_shadow;
8312 SourceLocation CaptureLoc;
8313 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8314 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8315 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8316 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8317 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8318 if (RD->getLambdaCaptureDefault() == LCD_None) {
8319 // Try to avoid warnings for lambdas with an explicit capture
8320 // list. Warn only when the lambda captures the shadowed decl
8321 // explicitly.
8322 CaptureLoc = getCaptureLocation(LSI, VD);
8323 if (CaptureLoc.isInvalid())
8324 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8325 } else {
8326 // Remember that this was shadowed so we can avoid the warning if
8327 // the shadowed decl isn't captured and the warning settings allow
8328 // it.
8329 cast<LambdaScopeInfo>(getCurFunction())
8330 ->ShadowingDecls.push_back({D, VD});
8331 return;
8332 }
8333 }
8334 if (isa<FieldDecl>(ShadowedDecl)) {
8335 // If lambda can capture this, then emit default shadowing warning,
8336 // Otherwise it is not really a shadowing case since field is not
8337 // available in lambda's body.
8338 // At this point we don't know that lambda can capture this, so
8339 // remember that this was shadowed and delay until we know.
8340 cast<LambdaScopeInfo>(getCurFunction())
8341 ->ShadowingDecls.push_back({D, ShadowedDecl});
8342 return;
8343 }
8344 }
8345 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8346 VD && VD->hasLocalStorage()) {
8347 // A variable can't shadow a local variable in an enclosing scope, if
8348 // they are separated by a non-capturing declaration context.
8349 for (DeclContext *ParentDC = NewDC;
8350 ParentDC && !ParentDC->Equals(OldDC);
8351 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8352 // Only block literals, captured statements, and lambda expressions
8353 // can capture; other scopes don't.
8354 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8355 !isLambdaCallOperator(ParentDC)) {
8356 return;
8357 }
8358 }
8359 }
8360 }
8361 }
8362
8363 // Never warn about shadowing a placeholder variable.
8364 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8365 return;
8366
8367 // Only warn about certain kinds of shadowing for class members.
8368 if (NewDC) {
8369 // In particular, don't warn about shadowing non-class members.
8370 if (NewDC->isRecord() && !OldDC->isRecord())
8371 return;
8372
8373 // Skip shadowing check if we're in a class scope, dealing with an enum
8374 // constant in a different context.
8375 DeclContext *ReDC = NewDC->getRedeclContext();
8376 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8377 return;
8378
8379 // TODO: should we warn about static data members shadowing
8380 // static data members from base classes?
8381
8382 // TODO: don't diagnose for inaccessible shadowed members.
8383 // This is hard to do perfectly because we might friend the
8384 // shadowing context, but that's just a false negative.
8385 }
8386
8387 DeclarationName Name = R.getLookupName();
8388
8389 // Emit warning and note.
8390 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8391 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8392 if (!CaptureLoc.isInvalid())
8393 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8394 << Name << /*explicitly*/ 1;
8395 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8396}
8397
8399 for (const auto &Shadow : LSI->ShadowingDecls) {
8400 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8401 // Try to avoid the warning when the shadowed decl isn't captured.
8402 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8403 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8404 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8405 Diag(Shadow.VD->getLocation(),
8406 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8407 : diag::warn_decl_shadow)
8408 << Shadow.VD->getDeclName()
8409 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8410 if (CaptureLoc.isValid())
8411 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8412 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8413 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8414 } else if (isa<FieldDecl>(ShadowedDecl)) {
8415 Diag(Shadow.VD->getLocation(),
8416 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8417 : diag::warn_decl_shadow_uncaptured_local)
8418 << Shadow.VD->getDeclName()
8419 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8420 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8421 }
8422 }
8423}
8424
8426 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8427 return;
8428
8429 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8431 RedeclarationKind::ForVisibleRedeclaration);
8432 LookupName(R, S);
8433 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8434 CheckShadow(D, ShadowedDecl, R);
8435}
8436
8437/// Check if 'E', which is an expression that is about to be modified, refers
8438/// to a constructor parameter that shadows a field.
8440 // Quickly ignore expressions that can't be shadowing ctor parameters.
8441 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8442 return;
8443 E = E->IgnoreParenImpCasts();
8444 auto *DRE = dyn_cast<DeclRefExpr>(E);
8445 if (!DRE)
8446 return;
8447 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8448 auto I = ShadowingDecls.find(D);
8449 if (I == ShadowingDecls.end())
8450 return;
8451 const NamedDecl *ShadowedDecl = I->second;
8452 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8453 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8454 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8455 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8456
8457 // Avoid issuing multiple warnings about the same decl.
8458 ShadowingDecls.erase(I);
8459}
8460
8461/// Check for conflict between this global or extern "C" declaration and
8462/// previous global or extern "C" declarations. This is only used in C++.
8463template<typename T>
8465 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8466 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8467 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8468
8469 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8470 // The common case: this global doesn't conflict with any extern "C"
8471 // declaration.
8472 return false;
8473 }
8474
8475 if (Prev) {
8476 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8477 // Both the old and new declarations have C language linkage. This is a
8478 // redeclaration.
8479 Previous.clear();
8480 Previous.addDecl(Prev);
8481 return true;
8482 }
8483
8484 // This is a global, non-extern "C" declaration, and there is a previous
8485 // non-global extern "C" declaration. Diagnose if this is a variable
8486 // declaration.
8487 if (!isa<VarDecl>(ND))
8488 return false;
8489 } else {
8490 // The declaration is extern "C". Check for any declaration in the
8491 // translation unit which might conflict.
8492 if (IsGlobal) {
8493 // We have already performed the lookup into the translation unit.
8494 IsGlobal = false;
8495 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8496 I != E; ++I) {
8497 if (isa<VarDecl>(*I)) {
8498 Prev = *I;
8499 break;
8500 }
8501 }
8502 } else {
8504 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8505 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8506 I != E; ++I) {
8507 if (isa<VarDecl>(*I)) {
8508 Prev = *I;
8509 break;
8510 }
8511 // FIXME: If we have any other entity with this name in global scope,
8512 // the declaration is ill-formed, but that is a defect: it breaks the
8513 // 'stat' hack, for instance. Only variables can have mangled name
8514 // clashes with extern "C" declarations, so only they deserve a
8515 // diagnostic.
8516 }
8517 }
8518
8519 if (!Prev)
8520 return false;
8521 }
8522
8523 // Use the first declaration's location to ensure we point at something which
8524 // is lexically inside an extern "C" linkage-spec.
8525 assert(Prev && "should have found a previous declaration to diagnose");
8526 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8527 Prev = FD->getFirstDecl();
8528 else
8529 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8530
8531 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8532 << IsGlobal << ND;
8533 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8534 << IsGlobal;
8535 return false;
8536}
8537
8538/// Apply special rules for handling extern "C" declarations. Returns \c true
8539/// if we have found that this is a redeclaration of some prior entity.
8540///
8541/// Per C++ [dcl.link]p6:
8542/// Two declarations [for a function or variable] with C language linkage
8543/// with the same name that appear in different scopes refer to the same
8544/// [entity]. An entity with C language linkage shall not be declared with
8545/// the same name as an entity in global scope.
8546template<typename T>
8549 if (!S.getLangOpts().CPlusPlus) {
8550 // In C, when declaring a global variable, look for a corresponding 'extern'
8551 // variable declared in function scope. We don't need this in C++, because
8552 // we find local extern decls in the surrounding file-scope DeclContext.
8553 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8554 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8555 Previous.clear();
8556 Previous.addDecl(Prev);
8557 return true;
8558 }
8559 }
8560 return false;
8561 }
8562
8563 // A declaration in the translation unit can conflict with an extern "C"
8564 // declaration.
8565 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8566 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8567
8568 // An extern "C" declaration can conflict with a declaration in the
8569 // translation unit or can be a redeclaration of an extern "C" declaration
8570 // in another scope.
8571 if (isIncompleteDeclExternC(S,ND))
8572 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8573
8574 // Neither global nor extern "C": nothing to do.
8575 return false;
8576}
8577
8578static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8579 QualType T) {
8580 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8581 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8582 // any of its members, even recursively, shall not have an atomic type, or a
8583 // variably modified type, or a type that is volatile or restrict qualified.
8584 if (CanonT->isVariablyModifiedType()) {
8585 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8586 return true;
8587 }
8588
8589 // Arrays are qualified by their element type, so get the base type (this
8590 // works on non-arrays as well).
8591 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8592
8593 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8594 CanonT.isRestrictQualified()) {
8595 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8596 return true;
8597 }
8598
8599 if (CanonT->isRecordType()) {
8600 const RecordDecl *RD = CanonT->getAsRecordDecl();
8601 if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8602 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8603 }))
8604 return true;
8605 }
8606
8607 return false;
8608}
8609
8611 // If the decl is already known invalid, don't check it.
8612 if (NewVD->isInvalidDecl())
8613 return;
8614
8615 QualType T = NewVD->getType();
8616
8617 // Defer checking an 'auto' type until its initializer is attached.
8618 if (T->isUndeducedType())
8619 return;
8620
8621 if (NewVD->hasAttrs())
8623
8624 if (T->isObjCObjectType()) {
8625 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8626 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8628 NewVD->setType(T);
8629 }
8630
8631 // Emit an error if an address space was applied to decl with local storage.
8632 // This includes arrays of objects with address space qualifiers, but not
8633 // automatic variables that point to other address spaces.
8634 // ISO/IEC TR 18037 S5.1.2
8635 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8636 T.getAddressSpace() != LangAS::Default) {
8637 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8638 NewVD->setInvalidDecl();
8639 return;
8640 }
8641
8642 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8643 // scope.
8644 if (getLangOpts().OpenCLVersion == 120 &&
8645 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8646 getLangOpts()) &&
8647 NewVD->isStaticLocal()) {
8648 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8649 NewVD->setInvalidDecl();
8650 return;
8651 }
8652
8653 if (getLangOpts().OpenCL) {
8654 if (!diagnoseOpenCLTypes(*this, NewVD))
8655 return;
8656
8657 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8658 if (NewVD->hasAttr<BlocksAttr>()) {
8659 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8660 return;
8661 }
8662
8663 if (T->isBlockPointerType()) {
8664 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8665 // can't use 'extern' storage class.
8666 if (!T.isConstQualified()) {
8667 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8668 << 0 /*const*/;
8669 NewVD->setInvalidDecl();
8670 return;
8671 }
8672 if (NewVD->hasExternalStorage()) {
8673 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8674 NewVD->setInvalidDecl();
8675 return;
8676 }
8677 }
8678
8679 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8680 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8681 NewVD->hasExternalStorage()) {
8682 if (!T->isSamplerT() && !T->isDependentType() &&
8683 !(T.getAddressSpace() == LangAS::opencl_constant ||
8684 (T.getAddressSpace() == LangAS::opencl_global &&
8685 getOpenCLOptions().areProgramScopeVariablesSupported(
8686 getLangOpts())))) {
8687 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8688 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8689 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8690 << Scope << "global or constant";
8691 else
8692 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8693 << Scope << "constant";
8694 NewVD->setInvalidDecl();
8695 return;
8696 }
8697 } else {
8698 if (T.getAddressSpace() == LangAS::opencl_global) {
8699 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8700 << 1 /*is any function*/ << "global";
8701 NewVD->setInvalidDecl();
8702 return;
8703 }
8704 if (T.getAddressSpace() == LangAS::opencl_constant ||
8705 T.getAddressSpace() == LangAS::opencl_local) {
8707 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8708 // in functions.
8709 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8710 if (T.getAddressSpace() == LangAS::opencl_constant)
8711 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8712 << 0 /*non-kernel only*/ << "constant";
8713 else
8714 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8715 << 0 /*non-kernel only*/ << "local";
8716 NewVD->setInvalidDecl();
8717 return;
8718 }
8719 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8720 // in the outermost scope of a kernel function.
8721 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8722 if (!getCurScope()->isFunctionScope()) {
8723 if (T.getAddressSpace() == LangAS::opencl_constant)
8724 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8725 << "constant";
8726 else
8727 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8728 << "local";
8729 NewVD->setInvalidDecl();
8730 return;
8731 }
8732 }
8733 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8734 // If we are parsing a template we didn't deduce an addr
8735 // space yet.
8736 T.getAddressSpace() != LangAS::Default) {
8737 // Do not allow other address spaces on automatic variable.
8738 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8739 NewVD->setInvalidDecl();
8740 return;
8741 }
8742 }
8743 }
8744
8745 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8746 && !NewVD->hasAttr<BlocksAttr>()) {
8747 if (getLangOpts().getGC() != LangOptions::NonGC)
8748 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8749 else {
8750 assert(!getLangOpts().ObjCAutoRefCount);
8751 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8752 }
8753 }
8754
8755 // WebAssembly tables must be static with a zero length and can't be
8756 // declared within functions.
8757 if (T->isWebAssemblyTableType()) {
8758 if (getCurScope()->getParent()) { // Parent is null at top-level
8759 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8760 NewVD->setInvalidDecl();
8761 return;
8762 }
8763 if (NewVD->getStorageClass() != SC_Static) {
8764 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8765 NewVD->setInvalidDecl();
8766 return;
8767 }
8768 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8769 if (!ATy || ATy->getZExtSize() != 0) {
8770 Diag(NewVD->getLocation(),
8771 diag::err_typecheck_wasm_table_must_have_zero_length);
8772 NewVD->setInvalidDecl();
8773 return;
8774 }
8775 }
8776
8777 // zero sized static arrays are not allowed in HIP device functions
8778 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
8779 if (FunctionDecl *FD = getCurFunctionDecl();
8780 FD &&
8781 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
8782 if (const ConstantArrayType *ArrayT =
8784 ArrayT && ArrayT->isZeroSize()) {
8785 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
8786 }
8787 }
8788 }
8789
8790 bool isVM = T->isVariablyModifiedType();
8791 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8792 NewVD->hasAttr<BlocksAttr>())
8794
8795 if ((isVM && NewVD->hasLinkage()) ||
8796 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8797 bool SizeIsNegative;
8798 llvm::APSInt Oversized;
8800 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8801 QualType FixedT;
8802 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8803 FixedT = FixedTInfo->getType();
8804 else if (FixedTInfo) {
8805 // Type and type-as-written are canonically different. We need to fix up
8806 // both types separately.
8807 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8808 Oversized);
8809 }
8810 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8812 // FIXME: This won't give the correct result for
8813 // int a[10][n];
8814 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8815
8816 if (NewVD->isFileVarDecl())
8817 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8818 << SizeRange;
8819 else if (NewVD->isStaticLocal())
8820 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8821 << SizeRange;
8822 else
8823 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8824 << SizeRange;
8825 NewVD->setInvalidDecl();
8826 return;
8827 }
8828
8829 if (!FixedTInfo) {
8830 if (NewVD->isFileVarDecl())
8831 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8832 else
8833 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8834 NewVD->setInvalidDecl();
8835 return;
8836 }
8837
8838 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8839 NewVD->setType(FixedT);
8840 NewVD->setTypeSourceInfo(FixedTInfo);
8841 }
8842
8843 if (T->isVoidType()) {
8844 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8845 // of objects and functions.
8847 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8848 << T;
8849 NewVD->setInvalidDecl();
8850 return;
8851 }
8852 }
8853
8854 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8855 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8856 NewVD->setInvalidDecl();
8857 return;
8858 }
8859
8860 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8861 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
8862 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8863 NewVD->setInvalidDecl();
8864 return;
8865 }
8866
8867 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8868 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8869 NewVD->setInvalidDecl();
8870 return;
8871 }
8872
8873 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8874 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8875 NewVD->setInvalidDecl();
8876 return;
8877 }
8878
8879 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
8880 !T->isDependentType() &&
8882 diag::err_constexpr_var_non_literal)) {
8883 NewVD->setInvalidDecl();
8884 return;
8885 }
8886
8887 // PPC MMA non-pointer types are not allowed as non-local variable types.
8888 if (Context.getTargetInfo().getTriple().isPPC64() &&
8889 !NewVD->isLocalVarDecl() &&
8890 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
8891 NewVD->setInvalidDecl();
8892 return;
8893 }
8894
8895 // Check that SVE types are only used in functions with SVE available.
8896 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8897 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8898 llvm::StringMap<bool> CallerFeatureMap;
8899 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8900
8901 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
8902 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
8903 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8904 NewVD->setInvalidDecl();
8905 return;
8906 } else if (!IsArmStreamingFunction(FD,
8907 /*IncludeLocallyStreaming=*/true)) {
8908 Diag(NewVD->getLocation(),
8909 diag::err_sve_vector_in_non_streaming_function)
8910 << T;
8911 NewVD->setInvalidDecl();
8912 return;
8913 }
8914 }
8915 }
8916
8917 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8918 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8919 llvm::StringMap<bool> CallerFeatureMap;
8920 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8921 RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
8922 CallerFeatureMap);
8923 }
8924}
8925
8928
8929 // If the decl is already known invalid, don't check it.
8930 if (NewVD->isInvalidDecl())
8931 return false;
8932
8933 // If we did not find anything by this name, look for a non-visible
8934 // extern "C" declaration with the same name.
8935 if (Previous.empty() &&
8937 Previous.setShadowed();
8938
8939 if (!Previous.empty()) {
8940 MergeVarDecl(NewVD, Previous);
8941 return true;
8942 }
8943 return false;
8944}
8945
8948
8949 // Look for methods in base classes that this method might override.
8950 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8951 /*DetectVirtual=*/false);
8952 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8953 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8954 DeclarationName Name = MD->getDeclName();
8955
8956 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8957 // We really want to find the base class destructor here.
8958 QualType T = Context.getTypeDeclType(BaseRecord);
8961 }
8962
8963 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8964 CXXMethodDecl *BaseMD =
8965 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8966 if (!BaseMD || !BaseMD->isVirtual() ||
8967 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8968 /*ConsiderCudaAttrs=*/true))
8969 continue;
8970 if (!CheckExplicitObjectOverride(MD, BaseMD))
8971 continue;
8972 if (Overridden.insert(BaseMD).second) {
8973 MD->addOverriddenMethod(BaseMD);
8978 }
8979
8980 // A method can only override one function from each base class. We
8981 // don't track indirectly overridden methods from bases of bases.
8982 return true;
8983 }
8984
8985 return false;
8986 };
8987
8988 DC->lookupInBases(VisitBase, Paths);
8989 return !Overridden.empty();
8990}
8991
8992namespace {
8993 // Struct for holding all of the extra arguments needed by
8994 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8995 struct ActOnFDArgs {
8996 Scope *S;
8997 Declarator &D;
8998 MultiTemplateParamsArg TemplateParamLists;
8999 bool AddToScope;
9000 };
9001} // end anonymous namespace
9002
9003namespace {
9004
9005// Callback to only accept typo corrections that have a non-zero edit distance.
9006// Also only accept corrections that have the same parent decl.
9007class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9008 public:
9009 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9011 : Context(Context), OriginalFD(TypoFD),
9012 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9013
9014 bool ValidateCandidate(const TypoCorrection &candidate) override {
9015 if (candidate.getEditDistance() == 0)
9016 return false;
9017
9018 SmallVector<unsigned, 1> MismatchedParams;
9019 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9020 CDeclEnd = candidate.end();
9021 CDecl != CDeclEnd; ++CDecl) {
9022 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9023
9024 if (FD && !FD->hasBody() &&
9025 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9026 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9027 CXXRecordDecl *Parent = MD->getParent();
9028 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9029 return true;
9030 } else if (!ExpectedParent) {
9031 return true;
9032 }
9033 }
9034 }
9035
9036 return false;
9037 }
9038
9039 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9040 return std::make_unique<DifferentNameValidatorCCC>(*this);
9041 }
9042
9043 private:
9044 ASTContext &Context;
9045 FunctionDecl *OriginalFD;
9046 CXXRecordDecl *ExpectedParent;
9047};
9048
9049} // end anonymous namespace
9050
9053}
9054
9055/// Generate diagnostics for an invalid function redeclaration.
9056///
9057/// This routine handles generating the diagnostic messages for an invalid
9058/// function redeclaration, including finding possible similar declarations
9059/// or performing typo correction if there are no previous declarations with
9060/// the same name.
9061///
9062/// Returns a NamedDecl iff typo correction was performed and substituting in
9063/// the new declaration name does not cause new errors.
9065 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9066 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9067 DeclarationName Name = NewFD->getDeclName();
9068 DeclContext *NewDC = NewFD->getDeclContext();
9069 SmallVector<unsigned, 1> MismatchedParams;
9071 TypoCorrection Correction;
9072 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9073 unsigned DiagMsg =
9074 IsLocalFriend ? diag::err_no_matching_local_friend :
9075 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9076 diag::err_member_decl_does_not_match;
9077 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9078 IsLocalFriend ? Sema::LookupLocalFriendName
9080 RedeclarationKind::ForVisibleRedeclaration);
9081
9082 NewFD->setInvalidDecl();
9083 if (IsLocalFriend)
9084 SemaRef.LookupName(Prev, S);
9085 else
9086 SemaRef.LookupQualifiedName(Prev, NewDC);
9087 assert(!Prev.isAmbiguous() &&
9088 "Cannot have an ambiguity in previous-declaration lookup");
9089 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9090 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9091 MD ? MD->getParent() : nullptr);
9092 if (!Prev.empty()) {
9093 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9094 Func != FuncEnd; ++Func) {
9095 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9096 if (FD &&
9097 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9098 // Add 1 to the index so that 0 can mean the mismatch didn't
9099 // involve a parameter
9100 unsigned ParamNum =
9101 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9102 NearMatches.push_back(std::make_pair(FD, ParamNum));
9103 }
9104 }
9105 // If the qualified name lookup yielded nothing, try typo correction
9106 } else if ((Correction = SemaRef.CorrectTypo(
9107 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9108 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9109 IsLocalFriend ? nullptr : NewDC))) {
9110 // Set up everything for the call to ActOnFunctionDeclarator
9111 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9112 ExtraArgs.D.getIdentifierLoc());
9113 Previous.clear();
9114 Previous.setLookupName(Correction.getCorrection());
9115 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9116 CDeclEnd = Correction.end();
9117 CDecl != CDeclEnd; ++CDecl) {
9118 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9119 if (FD && !FD->hasBody() &&
9120 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9121 Previous.addDecl(FD);
9122 }
9123 }
9124 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9125
9127 // Retry building the function declaration with the new previous
9128 // declarations, and with errors suppressed.
9129 {
9130 // Trap errors.
9131 Sema::SFINAETrap Trap(SemaRef);
9132
9133 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9134 // pieces need to verify the typo-corrected C++ declaration and hopefully
9135 // eliminate the need for the parameter pack ExtraArgs.
9137 ExtraArgs.S, ExtraArgs.D,
9138 Correction.getCorrectionDecl()->getDeclContext(),
9139 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9140 ExtraArgs.AddToScope);
9141
9142 if (Trap.hasErrorOccurred())
9143 Result = nullptr;
9144 }
9145
9146 if (Result) {
9147 // Determine which correction we picked.
9148 Decl *Canonical = Result->getCanonicalDecl();
9149 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9150 I != E; ++I)
9151 if ((*I)->getCanonicalDecl() == Canonical)
9152 Correction.setCorrectionDecl(*I);
9153
9154 // Let Sema know about the correction.
9156 SemaRef.diagnoseTypo(
9157 Correction,
9158 SemaRef.PDiag(IsLocalFriend
9159 ? diag::err_no_matching_local_friend_suggest
9160 : diag::err_member_decl_does_not_match_suggest)
9161 << Name << NewDC << IsDefinition);
9162 return Result;
9163 }
9164
9165 // Pretend the typo correction never occurred
9166 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9167 ExtraArgs.D.getIdentifierLoc());
9168 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9169 Previous.clear();
9170 Previous.setLookupName(Name);
9171 }
9172
9173 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9174 << Name << NewDC << IsDefinition << NewFD->getLocation();
9175
9176 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9177 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9178 CXXRecordDecl *RD = NewMD->getParent();
9179 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9180 << RD->getName() << RD->getLocation();
9181 }
9182
9183 bool NewFDisConst = NewMD && NewMD->isConst();
9184
9185 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9186 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9187 NearMatch != NearMatchEnd; ++NearMatch) {
9188 FunctionDecl *FD = NearMatch->first;
9189 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9190 bool FDisConst = MD && MD->isConst();
9191 bool IsMember = MD || !IsLocalFriend;
9192
9193 // FIXME: These notes are poorly worded for the local friend case.
9194 if (unsigned Idx = NearMatch->second) {
9195 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9197 if (Loc.isInvalid()) Loc = FD->getLocation();
9198 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9199 : diag::note_local_decl_close_param_match)
9200 << Idx << FDParam->getType()
9201 << NewFD->getParamDecl(Idx - 1)->getType();
9202 } else if (FDisConst != NewFDisConst) {
9203 auto DB = SemaRef.Diag(FD->getLocation(),
9204 diag::note_member_def_close_const_match)
9205 << NewFDisConst << FD->getSourceRange().getEnd();
9206 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9207 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9208 " const");
9209 else if (FTI.hasMethodTypeQualifiers() &&
9210 FTI.getConstQualifierLoc().isValid())
9211 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9212 } else {
9213 SemaRef.Diag(FD->getLocation(),
9214 IsMember ? diag::note_member_def_close_match
9215 : diag::note_local_decl_close_match);
9216 }
9217 }
9218 return nullptr;
9219}
9220
9222 switch (D.getDeclSpec().getStorageClassSpec()) {
9223 default: llvm_unreachable("Unknown storage class!");
9224 case DeclSpec::SCS_auto:
9227 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9228 diag::err_typecheck_sclass_func);
9229 D.getMutableDeclSpec().ClearStorageClassSpecs();
9230 D.setInvalidType();
9231 break;
9232 case DeclSpec::SCS_unspecified: break;
9234 if (D.getDeclSpec().isExternInLinkageSpec())
9235 return SC_None;
9236 return SC_Extern;
9237 case DeclSpec::SCS_static: {
9239 // C99 6.7.1p5:
9240 // The declaration of an identifier for a function that has
9241 // block scope shall have no explicit storage-class specifier
9242 // other than extern
9243 // See also (C++ [dcl.stc]p4).
9244 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9245 diag::err_static_block_func);
9246 break;
9247 } else
9248 return SC_Static;
9249 }
9251 }
9252
9253 // No explicit storage class has already been returned
9254 return SC_None;
9255}
9256
9258 DeclContext *DC, QualType &R,
9259 TypeSourceInfo *TInfo,
9260 StorageClass SC,
9261 bool &IsVirtualOkay) {
9262 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9263 DeclarationName Name = NameInfo.getName();
9264
9265 FunctionDecl *NewFD = nullptr;
9266 bool isInline = D.getDeclSpec().isInlineSpecified();
9267
9268 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9269 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9270 (SemaRef.getLangOpts().C23 &&
9271 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9272
9273 if (SemaRef.getLangOpts().C23)
9274 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9275 diag::err_c23_constexpr_not_variable);
9276 else
9277 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9278 diag::err_constexpr_wrong_decl_kind)
9279 << static_cast<int>(ConstexprKind);
9280 ConstexprKind = ConstexprSpecKind::Unspecified;
9281 D.getMutableDeclSpec().ClearConstexprSpec();
9282 }
9283
9284 if (!SemaRef.getLangOpts().CPlusPlus) {
9285 // Determine whether the function was written with a prototype. This is
9286 // true when:
9287 // - there is a prototype in the declarator, or
9288 // - the type R of the function is some kind of typedef or other non-
9289 // attributed reference to a type name (which eventually refers to a
9290 // function type). Note, we can't always look at the adjusted type to
9291 // check this case because attributes may cause a non-function
9292 // declarator to still have a function type. e.g.,
9293 // typedef void func(int a);
9294 // __attribute__((noreturn)) func other_func; // This has a prototype
9295 bool HasPrototype =
9296 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9297 (D.getDeclSpec().isTypeRep() &&
9298 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9299 ->isFunctionProtoType()) ||
9301 assert(
9302 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9303 "Strict prototypes are required");
9304
9305 NewFD = FunctionDecl::Create(
9306 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9307 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9309 /*TrailingRequiresClause=*/nullptr);
9310 if (D.isInvalidType())
9311 NewFD->setInvalidDecl();
9312
9313 return NewFD;
9314 }
9315
9316 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9317 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9318
9319 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9320
9321 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9322 // This is a C++ constructor declaration.
9323 assert(DC->isRecord() &&
9324 "Constructors can only be declared in a member context");
9325
9326 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9328 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9330 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9331 InheritedConstructor(), TrailingRequiresClause);
9332
9333 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9334 // This is a C++ destructor declaration.
9335 if (DC->isRecord()) {
9336 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9337 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9339 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9340 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9341 /*isImplicitlyDeclared=*/false, ConstexprKind,
9342 TrailingRequiresClause);
9343 // User defined destructors start as not selected if the class definition is still
9344 // not done.
9345 if (Record->isBeingDefined())
9346 NewDD->setIneligibleOrNotSelected(true);
9347
9348 // If the destructor needs an implicit exception specification, set it
9349 // now. FIXME: It'd be nice to be able to create the right type to start
9350 // with, but the type needs to reference the destructor declaration.
9351 if (SemaRef.getLangOpts().CPlusPlus11)
9352 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9353
9354 IsVirtualOkay = true;
9355 return NewDD;
9356
9357 } else {
9358 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9359 D.setInvalidType();
9360
9361 // Create a FunctionDecl to satisfy the function definition parsing
9362 // code path.
9363 return FunctionDecl::Create(
9364 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9365 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9366 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9367 }
9368
9369 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9370 if (!DC->isRecord()) {
9371 SemaRef.Diag(D.getIdentifierLoc(),
9372 diag::err_conv_function_not_member);
9373 return nullptr;
9374 }
9375
9376 SemaRef.CheckConversionDeclarator(D, R, SC);
9377 if (D.isInvalidType())
9378 return nullptr;
9379
9380 IsVirtualOkay = true;
9382 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9383 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9384 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9385 TrailingRequiresClause);
9386
9387 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9388 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9389 return nullptr;
9391 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9392 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9393 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9394 } else if (DC->isRecord()) {
9395 // If the name of the function is the same as the name of the record,
9396 // then this must be an invalid constructor that has a return type.
9397 // (The parser checks for a return type and makes the declarator a
9398 // constructor if it has no return type).
9399 if (Name.getAsIdentifierInfo() &&
9400 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9401 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9402 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9403 << SourceRange(D.getIdentifierLoc());
9404 return nullptr;
9405 }
9406
9407 // This is a C++ method declaration.
9409 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9410 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9411 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9412 IsVirtualOkay = !Ret->isStatic();
9413 return Ret;
9414 } else {
9415 bool isFriend =
9416 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9417 if (!isFriend && SemaRef.CurContext->isRecord())
9418 return nullptr;
9419
9420 // Determine whether the function was written with a
9421 // prototype. This true when:
9422 // - we're in C++ (where every function has a prototype),
9423 return FunctionDecl::Create(
9424 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9425 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9426 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9427 }
9428}
9429
9438
9440 // Size dependent types are just typedefs to normal integer types
9441 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9442 // integers other than by their names.
9443 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9444
9445 // Remove typedefs one by one until we reach a typedef
9446 // for a size dependent type.
9447 QualType DesugaredTy = Ty;
9448 do {
9449 ArrayRef<StringRef> Names(SizeTypeNames);
9450 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9451 if (Names.end() != Match)
9452 return true;
9453
9454 Ty = DesugaredTy;
9455 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9456 } while (DesugaredTy != Ty);
9457
9458 return false;
9459}
9460
9462 if (PT->isDependentType())
9463 return InvalidKernelParam;
9464
9465 if (PT->isPointerOrReferenceType()) {
9466 QualType PointeeType = PT->getPointeeType();
9467 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9468 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9469 PointeeType.getAddressSpace() == LangAS::Default)
9471
9472 if (PointeeType->isPointerType()) {
9473 // This is a pointer to pointer parameter.
9474 // Recursively check inner type.
9475 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9476 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9477 ParamKind == InvalidKernelParam)
9478 return ParamKind;
9479
9480 // OpenCL v3.0 s6.11.a:
9481 // A restriction to pass pointers to pointers only applies to OpenCL C
9482 // v1.2 or below.
9484 return ValidKernelParam;
9485
9486 return PtrPtrKernelParam;
9487 }
9488
9489 // C++ for OpenCL v1.0 s2.4:
9490 // Moreover the types used in parameters of the kernel functions must be:
9491 // Standard layout types for pointer parameters. The same applies to
9492 // reference if an implementation supports them in kernel parameters.
9493 if (S.getLangOpts().OpenCLCPlusPlus &&
9495 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9496 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9497 bool IsStandardLayoutType = true;
9498 if (CXXRec) {
9499 // If template type is not ODR-used its definition is only available
9500 // in the template definition not its instantiation.
9501 // FIXME: This logic doesn't work for types that depend on template
9502 // parameter (PR58590).
9503 if (!CXXRec->hasDefinition())
9504 CXXRec = CXXRec->getTemplateInstantiationPattern();
9505 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9506 IsStandardLayoutType = false;
9507 }
9508 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9509 !IsStandardLayoutType)
9510 return InvalidKernelParam;
9511 }
9512
9513 // OpenCL v1.2 s6.9.p:
9514 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9516 return ValidKernelParam;
9517
9518 return PtrKernelParam;
9519 }
9520
9521 // OpenCL v1.2 s6.9.k:
9522 // Arguments to kernel functions in a program cannot be declared with the
9523 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9524 // uintptr_t or a struct and/or union that contain fields declared to be one
9525 // of these built-in scalar types.
9527 return InvalidKernelParam;
9528
9529 if (PT->isImageType())
9530 return PtrKernelParam;
9531
9532 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9533 return InvalidKernelParam;
9534
9535 // OpenCL extension spec v1.2 s9.5:
9536 // This extension adds support for half scalar and vector types as built-in
9537 // types that can be used for arithmetic operations, conversions etc.
9538 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9539 PT->isHalfType())
9540 return InvalidKernelParam;
9541
9542 // Look into an array argument to check if it has a forbidden type.
9543 if (PT->isArrayType()) {
9544 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9545 // Call ourself to check an underlying type of an array. Since the
9546 // getPointeeOrArrayElementType returns an innermost type which is not an
9547 // array, this recursive call only happens once.
9548 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9549 }
9550
9551 // C++ for OpenCL v1.0 s2.4:
9552 // Moreover the types used in parameters of the kernel functions must be:
9553 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9554 // types) for parameters passed by value;
9555 if (S.getLangOpts().OpenCLCPlusPlus &&
9557 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9558 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9559 return InvalidKernelParam;
9560
9561 if (PT->isRecordType())
9562 return RecordKernelParam;
9563
9564 return ValidKernelParam;
9565}
9566
9568 Sema &S,
9569 Declarator &D,
9570 ParmVarDecl *Param,
9571 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9572 QualType PT = Param->getType();
9573
9574 // Cache the valid types we encounter to avoid rechecking structs that are
9575 // used again
9576 if (ValidTypes.count(PT.getTypePtr()))
9577 return;
9578
9579 switch (getOpenCLKernelParameterType(S, PT)) {
9580 case PtrPtrKernelParam:
9581 // OpenCL v3.0 s6.11.a:
9582 // A kernel function argument cannot be declared as a pointer to a pointer
9583 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9584 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9585 D.setInvalidType();
9586 return;
9587
9589 // OpenCL v1.0 s6.5:
9590 // __kernel function arguments declared to be a pointer of a type can point
9591 // to one of the following address spaces only : __global, __local or
9592 // __constant.
9593 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9594 D.setInvalidType();
9595 return;
9596
9597 // OpenCL v1.2 s6.9.k:
9598 // Arguments to kernel functions in a program cannot be declared with the
9599 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9600 // uintptr_t or a struct and/or union that contain fields declared to be
9601 // one of these built-in scalar types.
9602
9603 case InvalidKernelParam:
9604 // OpenCL v1.2 s6.8 n:
9605 // A kernel function argument cannot be declared
9606 // of event_t type.
9607 // Do not diagnose half type since it is diagnosed as invalid argument
9608 // type for any function elsewhere.
9609 if (!PT->isHalfType()) {
9610 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9611
9612 // Explain what typedefs are involved.
9613 const TypedefType *Typedef = nullptr;
9614 while ((Typedef = PT->getAs<TypedefType>())) {
9615 SourceLocation Loc = Typedef->getDecl()->getLocation();
9616 // SourceLocation may be invalid for a built-in type.
9617 if (Loc.isValid())
9618 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9619 PT = Typedef->desugar();
9620 }
9621 }
9622
9623 D.setInvalidType();
9624 return;
9625
9626 case PtrKernelParam:
9627 case ValidKernelParam:
9628 ValidTypes.insert(PT.getTypePtr());
9629 return;
9630
9631 case RecordKernelParam:
9632 break;
9633 }
9634
9635 // Track nested structs we will inspect
9637
9638 // Track where we are in the nested structs. Items will migrate from
9639 // VisitStack to HistoryStack as we do the DFS for bad field.
9641 HistoryStack.push_back(nullptr);
9642
9643 // At this point we already handled everything except of a RecordType or
9644 // an ArrayType of a RecordType.
9645 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9646 const RecordType *RecTy =
9648 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9649
9650 VisitStack.push_back(RecTy->getDecl());
9651 assert(VisitStack.back() && "First decl null?");
9652
9653 do {
9654 const Decl *Next = VisitStack.pop_back_val();
9655 if (!Next) {
9656 assert(!HistoryStack.empty());
9657 // Found a marker, we have gone up a level
9658 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9659 ValidTypes.insert(Hist->getType().getTypePtr());
9660
9661 continue;
9662 }
9663
9664 // Adds everything except the original parameter declaration (which is not a
9665 // field itself) to the history stack.
9666 const RecordDecl *RD;
9667 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9668 HistoryStack.push_back(Field);
9669
9670 QualType FieldTy = Field->getType();
9671 // Other field types (known to be valid or invalid) are handled while we
9672 // walk around RecordDecl::fields().
9673 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9674 "Unexpected type.");
9675 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9676
9677 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9678 } else {
9679 RD = cast<RecordDecl>(Next);
9680 }
9681
9682 // Add a null marker so we know when we've gone back up a level
9683 VisitStack.push_back(nullptr);
9684
9685 for (const auto *FD : RD->fields()) {
9686 QualType QT = FD->getType();
9687
9688 if (ValidTypes.count(QT.getTypePtr()))
9689 continue;
9690
9692 if (ParamType == ValidKernelParam)
9693 continue;
9694
9695 if (ParamType == RecordKernelParam) {
9696 VisitStack.push_back(FD);
9697 continue;
9698 }
9699
9700 // OpenCL v1.2 s6.9.p:
9701 // Arguments to kernel functions that are declared to be a struct or union
9702 // do not allow OpenCL objects to be passed as elements of the struct or
9703 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9704 // of SVM.
9705 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9706 ParamType == InvalidAddrSpacePtrKernelParam) {
9707 S.Diag(Param->getLocation(),
9708 diag::err_record_with_pointers_kernel_param)
9709 << PT->isUnionType()
9710 << PT;
9711 } else {
9712 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9713 }
9714
9715 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9716 << OrigRecDecl->getDeclName();
9717
9718 // We have an error, now let's go back up through history and show where
9719 // the offending field came from
9721 I = HistoryStack.begin() + 1,
9722 E = HistoryStack.end();
9723 I != E; ++I) {
9724 const FieldDecl *OuterField = *I;
9725 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9726 << OuterField->getType();
9727 }
9728
9729 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9730 << QT->isPointerType()
9731 << QT;
9732 D.setInvalidType();
9733 return;
9734 }
9735 } while (!VisitStack.empty());
9736}
9737
9738/// Find the DeclContext in which a tag is implicitly declared if we see an
9739/// elaborated type specifier in the specified context, and lookup finds
9740/// nothing.
9742 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9743 DC = DC->getParent();
9744 return DC;
9745}
9746
9747/// Find the Scope in which a tag is implicitly declared if we see an
9748/// elaborated type specifier in the specified context, and lookup finds
9749/// nothing.
9750static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9751 while (S->isClassScope() ||
9752 (LangOpts.CPlusPlus &&
9753 S->isFunctionPrototypeScope()) ||
9754 ((S->getFlags() & Scope::DeclScope) == 0) ||
9755 (S->getEntity() && S->getEntity()->isTransparentContext()))
9756 S = S->getParent();
9757 return S;
9758}
9759
9760/// Determine whether a declaration matches a known function in namespace std.
9762 unsigned BuiltinID) {
9763 switch (BuiltinID) {
9764 case Builtin::BI__GetExceptionInfo:
9765 // No type checking whatsoever.
9766 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9767
9768 case Builtin::BIaddressof:
9769 case Builtin::BI__addressof:
9770 case Builtin::BIforward:
9771 case Builtin::BIforward_like:
9772 case Builtin::BImove:
9773 case Builtin::BImove_if_noexcept:
9774 case Builtin::BIas_const: {
9775 // Ensure that we don't treat the algorithm
9776 // OutputIt std::move(InputIt, InputIt, OutputIt)
9777 // as the builtin std::move.
9778 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9779 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9780 }
9781
9782 default:
9783 return false;
9784 }
9785}
9786
9787NamedDecl*
9790 MultiTemplateParamsArg TemplateParamListsRef,
9791 bool &AddToScope) {
9792 QualType R = TInfo->getType();
9793
9794 assert(R->isFunctionType());
9796 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9797
9798 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9799 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9800 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9801 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9802 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9803 TemplateParamLists.back() = Invented;
9804 else
9805 TemplateParamLists.push_back(Invented);
9806 }
9807
9808 // TODO: consider using NameInfo for diagnostic.
9810 DeclarationName Name = NameInfo.getName();
9812
9813 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9814 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9815 diag::err_invalid_thread)
9817
9818 if (D.isFirstDeclarationOfMember())
9820 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9821 D.isCtorOrDtor(), D.getIdentifierLoc());
9822
9823 bool isFriend = false;
9825 bool isMemberSpecialization = false;
9826 bool isFunctionTemplateSpecialization = false;
9827
9828 bool HasExplicitTemplateArgs = false;
9829 TemplateArgumentListInfo TemplateArgs;
9830
9831 bool isVirtualOkay = false;
9832
9833 DeclContext *OriginalDC = DC;
9834 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9835
9836 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9837 isVirtualOkay);
9838 if (!NewFD) return nullptr;
9839
9842
9843 // Set the lexical context. If this is a function-scope declaration, or has a
9844 // C++ scope specifier, or is the object of a friend declaration, the lexical
9845 // context will be different from the semantic context.
9847
9848 if (IsLocalExternDecl)
9849 NewFD->setLocalExternDecl();
9850
9851 if (getLangOpts().CPlusPlus) {
9852 // The rules for implicit inlines changed in C++20 for methods and friends
9853 // with an in-class definition (when such a definition is not attached to
9854 // the global module). This does not affect declarations that are already
9855 // inline (whether explicitly or implicitly by being declared constexpr,
9856 // consteval, etc).
9857 // FIXME: We need a better way to separate C++ standard and clang modules.
9858 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9859 !NewFD->getOwningModule() ||
9860 NewFD->isFromGlobalModule() ||
9862 bool isInline = D.getDeclSpec().isInlineSpecified();
9863 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9864 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9865 isFriend = D.getDeclSpec().isFriendSpecified();
9866 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
9867 // Pre-C++20 [class.friend]p5
9868 // A function can be defined in a friend declaration of a
9869 // class . . . . Such a function is implicitly inline.
9870 // Post C++20 [class.friend]p7
9871 // Such a function is implicitly an inline function if it is attached
9872 // to the global module.
9873 NewFD->setImplicitlyInline();
9874 }
9875
9876 // If this is a method defined in an __interface, and is not a constructor
9877 // or an overloaded operator, then set the pure flag (isVirtual will already
9878 // return true).
9879 if (const CXXRecordDecl *Parent =
9880 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9881 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9882 NewFD->setIsPureVirtual(true);
9883
9884 // C++ [class.union]p2
9885 // A union can have member functions, but not virtual functions.
9886 if (isVirtual && Parent->isUnion()) {
9887 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9888 NewFD->setInvalidDecl();
9889 }
9890 if ((Parent->isClass() || Parent->isStruct()) &&
9891 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9892 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9893 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9894 if (auto *Def = Parent->getDefinition())
9895 Def->setInitMethod(true);
9896 }
9897 }
9898
9899 SetNestedNameSpecifier(*this, NewFD, D);
9900 isMemberSpecialization = false;
9901 isFunctionTemplateSpecialization = false;
9902 if (D.isInvalidType())
9903 NewFD->setInvalidDecl();
9904
9905 // Match up the template parameter lists with the scope specifier, then
9906 // determine whether we have a template or a template specialization.
9907 bool Invalid = false;
9908 TemplateIdAnnotation *TemplateId =
9910 ? D.getName().TemplateId
9911 : nullptr;
9912 TemplateParameterList *TemplateParams =
9914 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9915 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
9916 isMemberSpecialization, Invalid);
9917 if (TemplateParams) {
9918 // Check that we can declare a template here.
9919 if (CheckTemplateDeclScope(S, TemplateParams))
9920 NewFD->setInvalidDecl();
9921
9922 if (TemplateParams->size() > 0) {
9923 // This is a function template
9924
9925 // A destructor cannot be a template.
9926 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9927 Diag(NewFD->getLocation(), diag::err_destructor_template);
9928 NewFD->setInvalidDecl();
9929 // Function template with explicit template arguments.
9930 } else if (TemplateId) {
9931 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9932 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9933 NewFD->setInvalidDecl();
9934 }
9935
9936 // If we're adding a template to a dependent context, we may need to
9937 // rebuilding some of the types used within the template parameter list,
9938 // now that we know what the current instantiation is.
9939 if (DC->isDependentContext()) {
9940 ContextRAII SavedContext(*this, DC);
9942 Invalid = true;
9943 }
9944
9946 NewFD->getLocation(),
9947 Name, TemplateParams,
9948 NewFD);
9949 FunctionTemplate->setLexicalDeclContext(CurContext);
9951
9952 // For source fidelity, store the other template param lists.
9953 if (TemplateParamLists.size() > 1) {
9955 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9956 .drop_back(1));
9957 }
9958 } else {
9959 // This is a function template specialization.
9960 isFunctionTemplateSpecialization = true;
9961 // For source fidelity, store all the template param lists.
9962 if (TemplateParamLists.size() > 0)
9963 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9964
9965 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9966 if (isFriend) {
9967 // We want to remove the "template<>", found here.
9968 SourceRange RemoveRange = TemplateParams->getSourceRange();
9969
9970 // If we remove the template<> and the name is not a
9971 // template-id, we're actually silently creating a problem:
9972 // the friend declaration will refer to an untemplated decl,
9973 // and clearly the user wants a template specialization. So
9974 // we need to insert '<>' after the name.
9975 SourceLocation InsertLoc;
9976 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9977 InsertLoc = D.getName().getSourceRange().getEnd();
9978 InsertLoc = getLocForEndOfToken(InsertLoc);
9979 }
9980
9981 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9982 << Name << RemoveRange
9983 << FixItHint::CreateRemoval(RemoveRange)
9984 << FixItHint::CreateInsertion(InsertLoc, "<>");
9985 Invalid = true;
9986
9987 // Recover by faking up an empty template argument list.
9988 HasExplicitTemplateArgs = true;
9989 TemplateArgs.setLAngleLoc(InsertLoc);
9990 TemplateArgs.setRAngleLoc(InsertLoc);
9991 }
9992 }
9993 } else {
9994 // Check that we can declare a template here.
9995 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9996 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9997 NewFD->setInvalidDecl();
9998
9999 // All template param lists were matched against the scope specifier:
10000 // this is NOT (an explicit specialization of) a template.
10001 if (TemplateParamLists.size() > 0)
10002 // For source fidelity, store all the template param lists.
10003 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10004
10005 // "friend void foo<>(int);" is an implicit specialization decl.
10006 if (isFriend && TemplateId)
10007 isFunctionTemplateSpecialization = true;
10008 }
10009
10010 // If this is a function template specialization and the unqualified-id of
10011 // the declarator-id is a template-id, convert the template argument list
10012 // into our AST format and check for unexpanded packs.
10013 if (isFunctionTemplateSpecialization && TemplateId) {
10014 HasExplicitTemplateArgs = true;
10015
10016 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10017 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10018 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10019 TemplateId->NumArgs);
10020 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10021
10022 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10023 // declaration of a function template partial specialization? Should we
10024 // consider the unexpanded pack context to be a partial specialization?
10025 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10027 ArgLoc, isFriend ? UPPC_FriendDeclaration
10029 NewFD->setInvalidDecl();
10030 }
10031 }
10032
10033 if (Invalid) {
10034 NewFD->setInvalidDecl();
10035 if (FunctionTemplate)
10036 FunctionTemplate->setInvalidDecl();
10037 }
10038
10039 // C++ [dcl.fct.spec]p5:
10040 // The virtual specifier shall only be used in declarations of
10041 // nonstatic class member functions that appear within a
10042 // member-specification of a class declaration; see 10.3.
10043 //
10044 if (isVirtual && !NewFD->isInvalidDecl()) {
10045 if (!isVirtualOkay) {
10046 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10047 diag::err_virtual_non_function);
10048 } else if (!CurContext->isRecord()) {
10049 // 'virtual' was specified outside of the class.
10050 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10051 diag::err_virtual_out_of_class)
10052 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10053 } else if (NewFD->getDescribedFunctionTemplate()) {
10054 // C++ [temp.mem]p3:
10055 // A member function template shall not be virtual.
10056 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10057 diag::err_virtual_member_function_template)
10058 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10059 } else {
10060 // Okay: Add virtual to the method.
10061 NewFD->setVirtualAsWritten(true);
10062 }
10063
10064 if (getLangOpts().CPlusPlus14 &&
10065 NewFD->getReturnType()->isUndeducedType())
10066 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10067 }
10068
10069 // C++ [dcl.fct.spec]p3:
10070 // The inline specifier shall not appear on a block scope function
10071 // declaration.
10072 if (isInline && !NewFD->isInvalidDecl()) {
10074 // 'inline' is not allowed on block scope function declaration.
10075 Diag(D.getDeclSpec().getInlineSpecLoc(),
10076 diag::err_inline_declaration_block_scope) << Name
10077 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10078 }
10079 }
10080
10081 // C++ [dcl.fct.spec]p6:
10082 // The explicit specifier shall be used only in the declaration of a
10083 // constructor or conversion function within its class definition;
10084 // see 12.3.1 and 12.3.2.
10085 if (hasExplicit && !NewFD->isInvalidDecl() &&
10086 !isa<CXXDeductionGuideDecl>(NewFD)) {
10087 if (!CurContext->isRecord()) {
10088 // 'explicit' was specified outside of the class.
10089 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10090 diag::err_explicit_out_of_class)
10091 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10092 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10093 !isa<CXXConversionDecl>(NewFD)) {
10094 // 'explicit' was specified on a function that wasn't a constructor
10095 // or conversion function.
10096 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10097 diag::err_explicit_non_ctor_or_conv_function)
10098 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10099 }
10100 }
10101
10102 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10103 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10104 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10105 // are implicitly inline.
10106 NewFD->setImplicitlyInline();
10107
10108 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10109 // be either constructors or to return a literal type. Therefore,
10110 // destructors cannot be declared constexpr.
10111 if (isa<CXXDestructorDecl>(NewFD) &&
10113 ConstexprKind == ConstexprSpecKind::Consteval)) {
10114 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10115 << static_cast<int>(ConstexprKind);
10116 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10119 }
10120 // C++20 [dcl.constexpr]p2: An allocation function, or a
10121 // deallocation function shall not be declared with the consteval
10122 // specifier.
10123 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10124 (NewFD->getOverloadedOperator() == OO_New ||
10125 NewFD->getOverloadedOperator() == OO_Array_New ||
10126 NewFD->getOverloadedOperator() == OO_Delete ||
10127 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10128 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10129 diag::err_invalid_consteval_decl_kind)
10130 << NewFD;
10132 }
10133 }
10134
10135 // If __module_private__ was specified, mark the function accordingly.
10136 if (D.getDeclSpec().isModulePrivateSpecified()) {
10137 if (isFunctionTemplateSpecialization) {
10138 SourceLocation ModulePrivateLoc
10139 = D.getDeclSpec().getModulePrivateSpecLoc();
10140 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10141 << 0
10142 << FixItHint::CreateRemoval(ModulePrivateLoc);
10143 } else {
10144 NewFD->setModulePrivate();
10145 if (FunctionTemplate)
10146 FunctionTemplate->setModulePrivate();
10147 }
10148 }
10149
10150 if (isFriend) {
10151 if (FunctionTemplate) {
10152 FunctionTemplate->setObjectOfFriendDecl();
10153 FunctionTemplate->setAccess(AS_public);
10154 }
10155 NewFD->setObjectOfFriendDecl();
10156 NewFD->setAccess(AS_public);
10157 }
10158
10159 // If a function is defined as defaulted or deleted, mark it as such now.
10160 // We'll do the relevant checks on defaulted / deleted functions later.
10161 switch (D.getFunctionDefinitionKind()) {
10164 break;
10165
10167 NewFD->setDefaulted();
10168 break;
10169
10171 NewFD->setDeletedAsWritten();
10172 break;
10173 }
10174
10175 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10176 D.isFunctionDefinition()) {
10177 // Pre C++20 [class.mfct]p2:
10178 // A member function may be defined (8.4) in its class definition, in
10179 // which case it is an inline member function (7.1.2)
10180 // Post C++20 [class.mfct]p1:
10181 // If a member function is attached to the global module and is defined
10182 // in its class definition, it is inline.
10183 NewFD->setImplicitlyInline();
10184 }
10185
10186 if (!isFriend && SC != SC_None) {
10187 // C++ [temp.expl.spec]p2:
10188 // The declaration in an explicit-specialization shall not be an
10189 // export-declaration. An explicit specialization shall not use a
10190 // storage-class-specifier other than thread_local.
10191 //
10192 // We diagnose friend declarations with storage-class-specifiers
10193 // elsewhere.
10194 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10195 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10196 diag::ext_explicit_specialization_storage_class)
10198 D.getDeclSpec().getStorageClassSpecLoc());
10199 }
10200
10201 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10202 assert(isa<CXXMethodDecl>(NewFD) &&
10203 "Out-of-line member function should be a CXXMethodDecl");
10204 // C++ [class.static]p1:
10205 // A data or function member of a class may be declared static
10206 // in a class definition, in which case it is a static member of
10207 // the class.
10208
10209 // Complain about the 'static' specifier if it's on an out-of-line
10210 // member function definition.
10211
10212 // MSVC permits the use of a 'static' storage specifier on an
10213 // out-of-line member function template declaration and class member
10214 // template declaration (MSVC versions before 2015), warn about this.
10215 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10216 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10217 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10218 (getLangOpts().MSVCCompat &&
10220 ? diag::ext_static_out_of_line
10221 : diag::err_static_out_of_line)
10223 D.getDeclSpec().getStorageClassSpecLoc());
10224 }
10225 }
10226
10227 // C++11 [except.spec]p15:
10228 // A deallocation function with no exception-specification is treated
10229 // as if it were specified with noexcept(true).
10230 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10231 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10232 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10233 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10235 FPT->getReturnType(), FPT->getParamTypes(),
10237
10238 // C++20 [dcl.inline]/7
10239 // If an inline function or variable that is attached to a named module
10240 // is declared in a definition domain, it shall be defined in that
10241 // domain.
10242 // So, if the current declaration does not have a definition, we must
10243 // check at the end of the TU (or when the PMF starts) to see that we
10244 // have a definition at that point.
10245 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10246 NewFD->isInNamedModule()) {
10247 PendingInlineFuncDecls.insert(NewFD);
10248 }
10249 }
10250
10251 // Filter out previous declarations that don't match the scope.
10253 D.getCXXScopeSpec().isNotEmpty() ||
10254 isMemberSpecialization ||
10255 isFunctionTemplateSpecialization);
10256
10257 // Handle GNU asm-label extension (encoded as an attribute).
10258 if (Expr *E = (Expr*) D.getAsmLabel()) {
10259 // The parser guarantees this is a string.
10260 StringLiteral *SE = cast<StringLiteral>(E);
10261 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10262 /*IsLiteralLabel=*/true,
10263 SE->getStrTokenLoc(0)));
10264 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10265 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10267 if (I != ExtnameUndeclaredIdentifiers.end()) {
10268 if (isDeclExternC(NewFD)) {
10269 NewFD->addAttr(I->second);
10271 } else
10272 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10273 << /*Variable*/0 << NewFD;
10274 }
10275 }
10276
10277 // Copy the parameter declarations from the declarator D to the function
10278 // declaration NewFD, if they are available. First scavenge them into Params.
10280 unsigned FTIIdx;
10281 if (D.isFunctionDeclarator(FTIIdx)) {
10282 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10283
10284 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10285 // function that takes no arguments, not a function that takes a
10286 // single void argument.
10287 // We let through "const void" here because Sema::GetTypeForDeclarator
10288 // already checks for that case.
10289 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10290 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10291 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10292 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10293 Param->setDeclContext(NewFD);
10294 Params.push_back(Param);
10295
10296 if (Param->isInvalidDecl())
10297 NewFD->setInvalidDecl();
10298 }
10299 }
10300
10301 if (!getLangOpts().CPlusPlus) {
10302 // In C, find all the tag declarations from the prototype and move them
10303 // into the function DeclContext. Remove them from the surrounding tag
10304 // injection context of the function, which is typically but not always
10305 // the TU.
10306 DeclContext *PrototypeTagContext =
10308 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10309 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10310
10311 // We don't want to reparent enumerators. Look at their parent enum
10312 // instead.
10313 if (!TD) {
10314 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10315 TD = cast<EnumDecl>(ECD->getDeclContext());
10316 }
10317 if (!TD)
10318 continue;
10319 DeclContext *TagDC = TD->getLexicalDeclContext();
10320 if (!TagDC->containsDecl(TD))
10321 continue;
10322 TagDC->removeDecl(TD);
10323 TD->setDeclContext(NewFD);
10324 NewFD->addDecl(TD);
10325
10326 // Preserve the lexical DeclContext if it is not the surrounding tag
10327 // injection context of the FD. In this example, the semantic context of
10328 // E will be f and the lexical context will be S, while both the
10329 // semantic and lexical contexts of S will be f:
10330 // void f(struct S { enum E { a } f; } s);
10331 if (TagDC != PrototypeTagContext)
10332 TD->setLexicalDeclContext(TagDC);
10333 }
10334 }
10335 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10336 // When we're declaring a function with a typedef, typeof, etc as in the
10337 // following example, we'll need to synthesize (unnamed)
10338 // parameters for use in the declaration.
10339 //
10340 // @code
10341 // typedef void fn(int);
10342 // fn f;
10343 // @endcode
10344
10345 // Synthesize a parameter for each argument type.
10346 for (const auto &AI : FT->param_types()) {
10347 ParmVarDecl *Param =
10348 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10349 Param->setScopeInfo(0, Params.size());
10350 Params.push_back(Param);
10351 }
10352 } else {
10353 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10354 "Should not need args for typedef of non-prototype fn");
10355 }
10356
10357 // Finally, we know we have the right number of parameters, install them.
10358 NewFD->setParams(Params);
10359
10360 if (D.getDeclSpec().isNoreturnSpecified())
10361 NewFD->addAttr(
10362 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10363
10364 // Functions returning a variably modified type violate C99 6.7.5.2p2
10365 // because all functions have linkage.
10366 if (!NewFD->isInvalidDecl() &&
10368 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10369 NewFD->setInvalidDecl();
10370 }
10371
10372 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10373 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10374 !NewFD->hasAttr<SectionAttr>())
10375 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10378
10379 // Apply an implicit SectionAttr if #pragma code_seg is active.
10380 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10381 !NewFD->hasAttr<SectionAttr>()) {
10382 NewFD->addAttr(SectionAttr::CreateImplicit(
10383 Context, CodeSegStack.CurrentValue->getString(),
10384 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10385 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10388 NewFD))
10389 NewFD->dropAttr<SectionAttr>();
10390 }
10391
10392 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10393 // active.
10394 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10395 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10396 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10398
10399 // Apply an implicit CodeSegAttr from class declspec or
10400 // apply an implicit SectionAttr from #pragma code_seg if active.
10401 if (!NewFD->hasAttr<CodeSegAttr>()) {
10403 D.isFunctionDefinition())) {
10404 NewFD->addAttr(SAttr);
10405 }
10406 }
10407
10408 // Handle attributes.
10409 ProcessDeclAttributes(S, NewFD, D);
10410 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10411 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10412 !NewTVA->isDefaultVersion() &&
10413 !Context.getTargetInfo().hasFeature("fmv")) {
10414 // Don't add to scope fmv functions declarations if fmv disabled
10415 AddToScope = false;
10416 return NewFD;
10417 }
10418
10419 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10420 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10421 // type.
10422 //
10423 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10424 // type declaration will generate a compilation error.
10425 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10426 if (AddressSpace != LangAS::Default) {
10427 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10428 NewFD->setInvalidDecl();
10429 }
10430 }
10431
10432 if (!getLangOpts().CPlusPlus) {
10433 // Perform semantic checking on the function declaration.
10434 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10435 CheckMain(NewFD, D.getDeclSpec());
10436
10437 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10438 CheckMSVCRTEntryPoint(NewFD);
10439
10440 if (!NewFD->isInvalidDecl())
10441 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10442 isMemberSpecialization,
10443 D.isFunctionDefinition()));
10444 else if (!Previous.empty())
10445 // Recover gracefully from an invalid redeclaration.
10446 D.setRedeclaration(true);
10447 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10448 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10449 "previous declaration set still overloaded");
10450
10451 // Diagnose no-prototype function declarations with calling conventions that
10452 // don't support variadic calls. Only do this in C and do it after merging
10453 // possibly prototyped redeclarations.
10454 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10455 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10456 CallingConv CC = FT->getExtInfo().getCC();
10457 if (!supportsVariadicCall(CC)) {
10458 // Windows system headers sometimes accidentally use stdcall without
10459 // (void) parameters, so we relax this to a warning.
10460 int DiagID =
10461 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10462 Diag(NewFD->getLocation(), DiagID)
10464 }
10465 }
10466
10472 } else {
10473 // C++11 [replacement.functions]p3:
10474 // The program's definitions shall not be specified as inline.
10475 //
10476 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10477 //
10478 // Suppress the diagnostic if the function is __attribute__((used)), since
10479 // that forces an external definition to be emitted.
10480 if (D.getDeclSpec().isInlineSpecified() &&
10482 !NewFD->hasAttr<UsedAttr>())
10483 Diag(D.getDeclSpec().getInlineSpecLoc(),
10484 diag::ext_operator_new_delete_declared_inline)
10485 << NewFD->getDeclName();
10486
10487 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10488 // C++20 [dcl.decl.general]p4:
10489 // The optional requires-clause in an init-declarator or
10490 // member-declarator shall be present only if the declarator declares a
10491 // templated function.
10492 //
10493 // C++20 [temp.pre]p8:
10494 // An entity is templated if it is
10495 // - a template,
10496 // - an entity defined or created in a templated entity,
10497 // - a member of a templated entity,
10498 // - an enumerator for an enumeration that is a templated entity, or
10499 // - the closure type of a lambda-expression appearing in the
10500 // declaration of a templated entity.
10501 //
10502 // [Note 6: A local class, a local or block variable, or a friend
10503 // function defined in a templated entity is a templated entity.
10504 // — end note]
10505 //
10506 // A templated function is a function template or a function that is
10507 // templated. A templated class is a class template or a class that is
10508 // templated. A templated variable is a variable template or a variable
10509 // that is templated.
10510 if (!FunctionTemplate) {
10511 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10512 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10513 // An explicit specialization shall not have a trailing
10514 // requires-clause unless it declares a function template.
10515 //
10516 // Since a friend function template specialization cannot be
10517 // definition, and since a non-template friend declaration with a
10518 // trailing requires-clause must be a definition, we diagnose
10519 // friend function template specializations with trailing
10520 // requires-clauses on the same path as explicit specializations
10521 // even though they aren't necessarily prohibited by the same
10522 // language rule.
10523 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10524 << isFriend;
10525 } else if (isFriend && NewFD->isTemplated() &&
10526 !D.isFunctionDefinition()) {
10527 // C++ [temp.friend]p9:
10528 // A non-template friend declaration with a requires-clause shall be
10529 // a definition.
10530 Diag(NewFD->getBeginLoc(),
10531 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10532 NewFD->setInvalidDecl();
10533 } else if (!NewFD->isTemplated() ||
10534 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10535 Diag(TRC->getBeginLoc(),
10536 diag::err_constrained_non_templated_function);
10537 }
10538 }
10539 }
10540
10541 // We do not add HD attributes to specializations here because
10542 // they may have different constexpr-ness compared to their
10543 // templates and, after maybeAddHostDeviceAttrs() is applied,
10544 // may end up with different effective targets. Instead, a
10545 // specialization inherits its target attributes from its template
10546 // in the CheckFunctionTemplateSpecialization() call below.
10547 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10549
10550 // Handle explicit specializations of function templates
10551 // and friend function declarations with an explicit
10552 // template argument list.
10553 if (isFunctionTemplateSpecialization) {
10554 bool isDependentSpecialization = false;
10555 if (isFriend) {
10556 // For friend function specializations, this is a dependent
10557 // specialization if its semantic context is dependent, its
10558 // type is dependent, or if its template-id is dependent.
10559 isDependentSpecialization =
10560 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10561 (HasExplicitTemplateArgs &&
10564 TemplateArgs.arguments()));
10565 assert((!isDependentSpecialization ||
10566 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10567 "dependent friend function specialization without template "
10568 "args");
10569 } else {
10570 // For class-scope explicit specializations of function templates,
10571 // if the lexical context is dependent, then the specialization
10572 // is dependent.
10573 isDependentSpecialization =
10575 }
10576
10577 TemplateArgumentListInfo *ExplicitTemplateArgs =
10578 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10579 if (isDependentSpecialization) {
10580 // If it's a dependent specialization, it may not be possible
10581 // to determine the primary template (for explicit specializations)
10582 // or befriended declaration (for friends) until the enclosing
10583 // template is instantiated. In such cases, we store the declarations
10584 // found by name lookup and defer resolution until instantiation.
10586 NewFD, ExplicitTemplateArgs, Previous))
10587 NewFD->setInvalidDecl();
10588 } else if (!NewFD->isInvalidDecl()) {
10589 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10590 Previous))
10591 NewFD->setInvalidDecl();
10592 }
10593 } else if (isMemberSpecialization && !FunctionTemplate) {
10595 NewFD->setInvalidDecl();
10596 }
10597
10598 // Perform semantic checking on the function declaration.
10599 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10600 CheckMain(NewFD, D.getDeclSpec());
10601
10602 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10603 CheckMSVCRTEntryPoint(NewFD);
10604
10605 if (!NewFD->isInvalidDecl())
10606 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10607 isMemberSpecialization,
10608 D.isFunctionDefinition()));
10609 else if (!Previous.empty())
10610 // Recover gracefully from an invalid redeclaration.
10611 D.setRedeclaration(true);
10612
10613 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10614 !D.isRedeclaration() ||
10615 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10616 "previous declaration set still overloaded");
10617
10618 NamedDecl *PrincipalDecl = (FunctionTemplate
10619 ? cast<NamedDecl>(FunctionTemplate)
10620 : NewFD);
10621
10622 if (isFriend && NewFD->getPreviousDecl()) {
10623 AccessSpecifier Access = AS_public;
10624 if (!NewFD->isInvalidDecl())
10625 Access = NewFD->getPreviousDecl()->getAccess();
10626
10627 NewFD->setAccess(Access);
10628 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10629 }
10630
10631 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10633 PrincipalDecl->setNonMemberOperator();
10634
10635 // If we have a function template, check the template parameter
10636 // list. This will check and merge default template arguments.
10637 if (FunctionTemplate) {
10638 FunctionTemplateDecl *PrevTemplate =
10639 FunctionTemplate->getPreviousDecl();
10640 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10641 PrevTemplate ? PrevTemplate->getTemplateParameters()
10642 : nullptr,
10643 D.getDeclSpec().isFriendSpecified()
10644 ? (D.isFunctionDefinition()
10647 : (D.getCXXScopeSpec().isSet() &&
10648 DC && DC->isRecord() &&
10649 DC->isDependentContext())
10652 }
10653
10654 if (NewFD->isInvalidDecl()) {
10655 // Ignore all the rest of this.
10656 } else if (!D.isRedeclaration()) {
10657 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10658 AddToScope };
10659 // Fake up an access specifier if it's supposed to be a class member.
10660 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10661 NewFD->setAccess(AS_public);
10662
10663 // Qualified decls generally require a previous declaration.
10664 if (D.getCXXScopeSpec().isSet()) {
10665 // ...with the major exception of templated-scope or
10666 // dependent-scope friend declarations.
10667
10668 // TODO: we currently also suppress this check in dependent
10669 // contexts because (1) the parameter depth will be off when
10670 // matching friend templates and (2) we might actually be
10671 // selecting a friend based on a dependent factor. But there
10672 // are situations where these conditions don't apply and we
10673 // can actually do this check immediately.
10674 //
10675 // Unless the scope is dependent, it's always an error if qualified
10676 // redeclaration lookup found nothing at all. Diagnose that now;
10677 // nothing will diagnose that error later.
10678 if (isFriend &&
10679 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10680 (!Previous.empty() && CurContext->isDependentContext()))) {
10681 // ignore these
10682 } else if (NewFD->isCPUDispatchMultiVersion() ||
10683 NewFD->isCPUSpecificMultiVersion()) {
10684 // ignore this, we allow the redeclaration behavior here to create new
10685 // versions of the function.
10686 } else {
10687 // The user tried to provide an out-of-line definition for a
10688 // function that is a member of a class or namespace, but there
10689 // was no such member function declared (C++ [class.mfct]p2,
10690 // C++ [namespace.memdef]p2). For example:
10691 //
10692 // class X {
10693 // void f() const;
10694 // };
10695 //
10696 // void X::f() { } // ill-formed
10697 //
10698 // Complain about this problem, and attempt to suggest close
10699 // matches (e.g., those that differ only in cv-qualifiers and
10700 // whether the parameter types are references).
10701
10703 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10704 AddToScope = ExtraArgs.AddToScope;
10705 return Result;
10706 }
10707 }
10708
10709 // Unqualified local friend declarations are required to resolve
10710 // to something.
10711 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10713 *this, Previous, NewFD, ExtraArgs, true, S)) {
10714 AddToScope = ExtraArgs.AddToScope;
10715 return Result;
10716 }
10717 }
10718 } else if (!D.isFunctionDefinition() &&
10719 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10720 !isFriend && !isFunctionTemplateSpecialization &&
10721 !isMemberSpecialization) {
10722 // An out-of-line member function declaration must also be a
10723 // definition (C++ [class.mfct]p2).
10724 // Note that this is not the case for explicit specializations of
10725 // function templates or member functions of class templates, per
10726 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10727 // extension for compatibility with old SWIG code which likes to
10728 // generate them.
10729 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10730 << D.getCXXScopeSpec().getRange();
10731 }
10732 }
10733
10734 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10735 // Any top level function could potentially be specified as an entry.
10736 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10737 HLSL().ActOnTopLevelFunction(NewFD);
10738
10739 if (NewFD->hasAttr<HLSLShaderAttr>())
10740 HLSL().CheckEntryPoint(NewFD);
10741 }
10742
10743 // If this is the first declaration of a library builtin function, add
10744 // attributes as appropriate.
10745 if (!D.isRedeclaration()) {
10746 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10747 if (unsigned BuiltinID = II->getBuiltinID()) {
10748 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10749 if (!InStdNamespace &&
10751 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10752 // Validate the type matches unless this builtin is specified as
10753 // matching regardless of its declared type.
10754 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10755 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10756 } else {
10758 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10759 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10760
10761 if (!Error && !BuiltinType.isNull() &&
10763 NewFD->getType(), BuiltinType))
10764 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10765 }
10766 }
10767 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10768 isStdBuiltin(Context, NewFD, BuiltinID)) {
10769 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10770 }
10771 }
10772 }
10773 }
10774
10775 ProcessPragmaWeak(S, NewFD);
10776 checkAttributesAfterMerging(*this, *NewFD);
10777
10779
10780 if (NewFD->hasAttr<OverloadableAttr>() &&
10781 !NewFD->getType()->getAs<FunctionProtoType>()) {
10782 Diag(NewFD->getLocation(),
10783 diag::err_attribute_overloadable_no_prototype)
10784 << NewFD;
10785 NewFD->dropAttr<OverloadableAttr>();
10786 }
10787
10788 // If there's a #pragma GCC visibility in scope, and this isn't a class
10789 // member, set the visibility of this function.
10790 if (!DC->isRecord() && NewFD->isExternallyVisible())
10792
10793 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10794 // marking the function.
10795 ObjC().AddCFAuditedAttribute(NewFD);
10796
10797 // If this is a function definition, check if we have to apply any
10798 // attributes (i.e. optnone and no_builtin) due to a pragma.
10799 if (D.isFunctionDefinition()) {
10800 AddRangeBasedOptnone(NewFD);
10802 AddSectionMSAllocText(NewFD);
10804 }
10805
10806 // If this is the first declaration of an extern C variable, update
10807 // the map of such variables.
10808 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10809 isIncompleteDeclExternC(*this, NewFD))
10811
10812 // Set this FunctionDecl's range up to the right paren.
10813 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10814
10815 if (D.isRedeclaration() && !Previous.empty()) {
10816 NamedDecl *Prev = Previous.getRepresentativeDecl();
10817 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10818 isMemberSpecialization ||
10819 isFunctionTemplateSpecialization,
10820 D.isFunctionDefinition());
10821 }
10822
10823 if (getLangOpts().CUDA) {
10824 IdentifierInfo *II = NewFD->getIdentifier();
10825 if (II && II->isStr(CUDA().getConfigureFuncName()) &&
10826 !NewFD->isInvalidDecl() &&
10829 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10832 }
10833
10834 // Variadic functions, other than a *declaration* of printf, are not allowed
10835 // in device-side CUDA code, unless someone passed
10836 // -fcuda-allow-variadic-functions.
10837 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10838 (NewFD->hasAttr<CUDADeviceAttr>() ||
10839 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10840 !(II && II->isStr("printf") && NewFD->isExternC() &&
10841 !D.isFunctionDefinition())) {
10842 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10843 }
10844 }
10845
10847
10848
10849
10850 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10851 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10852 if (SC == SC_Static) {
10853 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10854 D.setInvalidType();
10855 }
10856
10857 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10858 if (!NewFD->getReturnType()->isVoidType()) {
10859 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10860 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10861 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10862 : FixItHint());
10863 D.setInvalidType();
10864 }
10865
10867 for (auto *Param : NewFD->parameters())
10868 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10869
10870 if (getLangOpts().OpenCLCPlusPlus) {
10871 if (DC->isRecord()) {
10872 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10873 D.setInvalidType();
10874 }
10875 if (FunctionTemplate) {
10876 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10877 D.setInvalidType();
10878 }
10879 }
10880 }
10881
10882 if (getLangOpts().CPlusPlus) {
10883 // Precalculate whether this is a friend function template with a constraint
10884 // that depends on an enclosing template, per [temp.friend]p9.
10885 if (isFriend && FunctionTemplate &&
10888
10889 // C++ [temp.friend]p9:
10890 // A friend function template with a constraint that depends on a
10891 // template parameter from an enclosing template shall be a definition.
10892 if (!D.isFunctionDefinition()) {
10893 Diag(NewFD->getBeginLoc(),
10894 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10895 NewFD->setInvalidDecl();
10896 }
10897 }
10898
10899 if (FunctionTemplate) {
10900 if (NewFD->isInvalidDecl())
10901 FunctionTemplate->setInvalidDecl();
10902 return FunctionTemplate;
10903 }
10904
10905 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10907 }
10908
10909 for (const ParmVarDecl *Param : NewFD->parameters()) {
10910 QualType PT = Param->getType();
10911
10912 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10913 // types.
10914 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10915 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10916 QualType ElemTy = PipeTy->getElementType();
10917 if (ElemTy->isPointerOrReferenceType()) {
10918 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
10919 D.setInvalidType();
10920 }
10921 }
10922 }
10923 // WebAssembly tables can't be used as function parameters.
10924 if (Context.getTargetInfo().getTriple().isWasm()) {
10926 Diag(Param->getTypeSpecStartLoc(),
10927 diag::err_wasm_table_as_function_parameter);
10928 D.setInvalidType();
10929 }
10930 }
10931 }
10932
10933 // Diagnose availability attributes. Availability cannot be used on functions
10934 // that are run during load/unload.
10935 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10936 if (NewFD->hasAttr<ConstructorAttr>()) {
10937 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10938 << 1;
10939 NewFD->dropAttr<AvailabilityAttr>();
10940 }
10941 if (NewFD->hasAttr<DestructorAttr>()) {
10942 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10943 << 2;
10944 NewFD->dropAttr<AvailabilityAttr>();
10945 }
10946 }
10947
10948 // Diagnose no_builtin attribute on function declaration that are not a
10949 // definition.
10950 // FIXME: We should really be doing this in
10951 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10952 // the FunctionDecl and at this point of the code
10953 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10954 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10955 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10956 switch (D.getFunctionDefinitionKind()) {
10959 Diag(NBA->getLocation(),
10960 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10961 << NBA->getSpelling();
10962 break;
10964 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10965 << NBA->getSpelling();
10966 break;
10968 break;
10969 }
10970
10971 // Similar to no_builtin logic above, at this point of the code
10972 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
10973 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10975 !NewFD->isInvalidDecl() &&
10976 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
10977 ExternalDeclarations.push_back(NewFD);
10978
10979 return NewFD;
10980}
10981
10982/// Return a CodeSegAttr from a containing class. The Microsoft docs say
10983/// when __declspec(code_seg) "is applied to a class, all member functions of
10984/// the class and nested classes -- this includes compiler-generated special
10985/// member functions -- are put in the specified segment."
10986/// The actual behavior is a little more complicated. The Microsoft compiler
10987/// won't check outer classes if there is an active value from #pragma code_seg.
10988/// The CodeSeg is always applied from the direct parent but only from outer
10989/// classes when the #pragma code_seg stack is empty. See:
10990/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10991/// available since MS has removed the page.
10993 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10994 if (!Method)
10995 return nullptr;
10996 const CXXRecordDecl *Parent = Method->getParent();
10997 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10998 Attr *NewAttr = SAttr->clone(S.getASTContext());
10999 NewAttr->setImplicit(true);
11000 return NewAttr;
11001 }
11002
11003 // The Microsoft compiler won't check outer classes for the CodeSeg
11004 // when the #pragma code_seg stack is active.
11005 if (S.CodeSegStack.CurrentValue)
11006 return nullptr;
11007
11008 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11009 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11010 Attr *NewAttr = SAttr->clone(S.getASTContext());
11011 NewAttr->setImplicit(true);
11012 return NewAttr;
11013 }
11014 }
11015 return nullptr;
11016}
11017
11019 bool IsDefinition) {
11020 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11021 return A;
11022 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11023 CodeSegStack.CurrentValue)
11024 return SectionAttr::CreateImplicit(
11025 getASTContext(), CodeSegStack.CurrentValue->getString(),
11026 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11027 return nullptr;
11028}
11029
11031 QualType NewT, QualType OldT) {
11033 return true;
11034
11035 // For dependently-typed local extern declarations and friends, we can't
11036 // perform a correct type check in general until instantiation:
11037 //
11038 // int f();
11039 // template<typename T> void g() { T f(); }
11040 //
11041 // (valid if g() is only instantiated with T = int).
11042 if (NewT->isDependentType() &&
11043 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11044 return false;
11045
11046 // Similarly, if the previous declaration was a dependent local extern
11047 // declaration, we don't really know its type yet.
11048 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11049 return false;
11050
11051 return true;
11052}
11053
11056 return true;
11057
11058 // Don't chain dependent friend function definitions until instantiation, to
11059 // permit cases like
11060 //
11061 // void func();
11062 // template<typename T> class C1 { friend void func() {} };
11063 // template<typename T> class C2 { friend void func() {} };
11064 //
11065 // ... which is valid if only one of C1 and C2 is ever instantiated.
11066 //
11067 // FIXME: This need only apply to function definitions. For now, we proxy
11068 // this by checking for a file-scope function. We do not want this to apply
11069 // to friend declarations nominating member functions, because that gets in
11070 // the way of access checks.
11072 return false;
11073
11074 auto *VD = dyn_cast<ValueDecl>(D);
11075 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11076 return !VD || !PrevVD ||
11077 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11078 PrevVD->getType());
11079}
11080
11081/// Check the target or target_version attribute of the function for
11082/// MultiVersion validity.
11083///
11084/// Returns true if there was an error, false otherwise.
11085static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11086 const auto *TA = FD->getAttr<TargetAttr>();
11087 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11088
11089 assert((TA || TVA) && "Expecting target or target_version attribute");
11090
11092 enum ErrType { Feature = 0, Architecture = 1 };
11093
11094 if (TA) {
11095 ParsedTargetAttr ParseInfo =
11096 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11097 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11098 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11099 << Architecture << ParseInfo.CPU;
11100 return true;
11101 }
11102 for (const auto &Feat : ParseInfo.Features) {
11103 auto BareFeat = StringRef{Feat}.substr(1);
11104 if (Feat[0] == '-') {
11105 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11106 << Feature << ("no-" + BareFeat).str();
11107 return true;
11108 }
11109
11110 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11111 !TargetInfo.isValidFeatureName(BareFeat)) {
11112 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11113 << Feature << BareFeat;
11114 return true;
11115 }
11116 }
11117 }
11118
11119 if (TVA) {
11121 ParsedTargetAttr ParseInfo;
11122 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11123 ParseInfo =
11124 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11125 for (auto &Feat : ParseInfo.Features)
11126 Feats.push_back(StringRef{Feat}.substr(1));
11127 } else {
11128 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11129 TVA->getFeatures(Feats);
11130 }
11131 for (const auto &Feat : Feats) {
11132 if (!TargetInfo.validateCpuSupports(Feat)) {
11133 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11134 << Feature << Feat;
11135 return true;
11136 }
11137 }
11138 }
11139 return false;
11140}
11141
11142// Provide a white-list of attributes that are allowed to be combined with
11143// multiversion functions.
11145 MultiVersionKind MVKind) {
11146 // Note: this list/diagnosis must match the list in
11147 // checkMultiversionAttributesAllSame.
11148 switch (Kind) {
11149 default:
11150 return false;
11151 case attr::ArmLocallyStreaming:
11152 return MVKind == MultiVersionKind::TargetVersion ||
11154 case attr::Used:
11155 return MVKind == MultiVersionKind::Target;
11156 case attr::NonNull:
11157 case attr::NoThrow:
11158 return true;
11159 }
11160}
11161
11163 const FunctionDecl *FD,
11164 const FunctionDecl *CausedFD,
11165 MultiVersionKind MVKind) {
11166 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11167 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11168 << static_cast<unsigned>(MVKind) << A;
11169 if (CausedFD)
11170 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11171 return true;
11172 };
11173
11174 for (const Attr *A : FD->attrs()) {
11175 switch (A->getKind()) {
11176 case attr::CPUDispatch:
11177 case attr::CPUSpecific:
11178 if (MVKind != MultiVersionKind::CPUDispatch &&
11180 return Diagnose(S, A);
11181 break;
11182 case attr::Target:
11183 if (MVKind != MultiVersionKind::Target)
11184 return Diagnose(S, A);
11185 break;
11186 case attr::TargetVersion:
11187 if (MVKind != MultiVersionKind::TargetVersion &&
11189 return Diagnose(S, A);
11190 break;
11191 case attr::TargetClones:
11192 if (MVKind != MultiVersionKind::TargetClones &&
11194 return Diagnose(S, A);
11195 break;
11196 default:
11197 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11198 return Diagnose(S, A);
11199 break;
11200 }
11201 }
11202 return false;
11203}
11204
11206 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11207 const PartialDiagnostic &NoProtoDiagID,
11208 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11209 const PartialDiagnosticAt &NoSupportDiagIDAt,
11210 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11211 bool ConstexprSupported, bool CLinkageMayDiffer) {
11212 enum DoesntSupport {
11213 FuncTemplates = 0,
11214 VirtFuncs = 1,
11215 DeducedReturn = 2,
11216 Constructors = 3,
11217 Destructors = 4,
11218 DeletedFuncs = 5,
11219 DefaultedFuncs = 6,
11220 ConstexprFuncs = 7,
11221 ConstevalFuncs = 8,
11222 Lambda = 9,
11223 };
11224 enum Different {
11225 CallingConv = 0,
11226 ReturnType = 1,
11227 ConstexprSpec = 2,
11228 InlineSpec = 3,
11229 Linkage = 4,
11230 LanguageLinkage = 5,
11231 };
11232
11233 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11234 !OldFD->getType()->getAs<FunctionProtoType>()) {
11235 Diag(OldFD->getLocation(), NoProtoDiagID);
11236 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11237 return true;
11238 }
11239
11240 if (NoProtoDiagID.getDiagID() != 0 &&
11241 !NewFD->getType()->getAs<FunctionProtoType>())
11242 return Diag(NewFD->getLocation(), NoProtoDiagID);
11243
11244 if (!TemplatesSupported &&
11246 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11247 << FuncTemplates;
11248
11249 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11250 if (NewCXXFD->isVirtual())
11251 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11252 << VirtFuncs;
11253
11254 if (isa<CXXConstructorDecl>(NewCXXFD))
11255 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11256 << Constructors;
11257
11258 if (isa<CXXDestructorDecl>(NewCXXFD))
11259 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11260 << Destructors;
11261 }
11262
11263 if (NewFD->isDeleted())
11264 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11265 << DeletedFuncs;
11266
11267 if (NewFD->isDefaulted())
11268 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11269 << DefaultedFuncs;
11270
11271 if (!ConstexprSupported && NewFD->isConstexpr())
11272 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11273 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11274
11275 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11276 const auto *NewType = cast<FunctionType>(NewQType);
11277 QualType NewReturnType = NewType->getReturnType();
11278
11279 if (NewReturnType->isUndeducedType())
11280 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11281 << DeducedReturn;
11282
11283 // Ensure the return type is identical.
11284 if (OldFD) {
11285 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11286 const auto *OldType = cast<FunctionType>(OldQType);
11287 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11288 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11289
11290 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11291 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11292
11293 bool ArmStreamingCCMismatched = false;
11294 if (OldFPT && NewFPT) {
11295 unsigned Diff =
11297 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11298 // cannot be mixed.
11301 ArmStreamingCCMismatched = true;
11302 }
11303
11304 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11305 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11306
11307 QualType OldReturnType = OldType->getReturnType();
11308
11309 if (OldReturnType != NewReturnType)
11310 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11311
11312 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11313 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11314
11315 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11316 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11317
11318 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11319 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11320
11321 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11322 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11323
11324 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11325 NewFD->getLocation()))
11326 return true;
11327 }
11328 return false;
11329}
11330
11332 const FunctionDecl *NewFD,
11333 bool CausesMV,
11334 MultiVersionKind MVKind) {
11336 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11337 if (OldFD)
11338 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11339 return true;
11340 }
11341
11342 bool IsCPUSpecificCPUDispatchMVKind =
11345
11346 if (CausesMV && OldFD &&
11347 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11348 return true;
11349
11350 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11351 return true;
11352
11353 // Only allow transition to MultiVersion if it hasn't been used.
11354 if (OldFD && CausesMV && OldFD->isUsed(false))
11355 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11356
11358 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11360 S.PDiag(diag::note_multiversioning_caused_here)),
11362 S.PDiag(diag::err_multiversion_doesnt_support)
11363 << static_cast<unsigned>(MVKind)),
11365 S.PDiag(diag::err_multiversion_diff)),
11366 /*TemplatesSupported=*/false,
11367 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11368 /*CLinkageMayDiffer=*/false);
11369}
11370
11371/// Check the validity of a multiversion function declaration that is the
11372/// first of its kind. Also sets the multiversion'ness' of the function itself.
11373///
11374/// This sets NewFD->isInvalidDecl() to true if there was an error.
11375///
11376/// Returns true if there was an error, false otherwise.
11379 assert(MVKind != MultiVersionKind::None &&
11380 "Function lacks multiversion attribute");
11381 const auto *TA = FD->getAttr<TargetAttr>();
11382 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11383 // The target attribute only causes MV if this declaration is the default,
11384 // otherwise it is treated as a normal function.
11385 if (TA && !TA->isDefaultVersion())
11386 return false;
11387
11388 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11389 FD->setInvalidDecl();
11390 return true;
11391 }
11392
11393 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11394 FD->setInvalidDecl();
11395 return true;
11396 }
11397
11398 FD->setIsMultiVersion();
11399 return false;
11400}
11401
11403 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11405 return true;
11406 }
11407
11408 return false;
11409}
11410
11412 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11413 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11414 return;
11415
11416 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11417 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11418
11419 if (MVKindTo == MultiVersionKind::None &&
11420 (MVKindFrom == MultiVersionKind::TargetVersion ||
11421 MVKindFrom == MultiVersionKind::TargetClones))
11422 To->addAttr(TargetVersionAttr::CreateImplicit(
11423 To->getASTContext(), "default", To->getSourceRange()));
11424}
11425
11427 FunctionDecl *NewFD,
11428 bool &Redeclaration,
11429 NamedDecl *&OldDecl,
11431 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11432
11433 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11434 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11435 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11436 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11437
11438 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11439
11440 // The definitions should be allowed in any order. If we have discovered
11441 // a new target version and the preceeding was the default, then add the
11442 // corresponding attribute to it.
11443 patchDefaultTargetVersion(NewFD, OldFD);
11444
11445 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11446 // to change, this is a simple redeclaration.
11447 if (NewTA && !NewTA->isDefaultVersion() &&
11448 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11449 return false;
11450
11451 // Otherwise, this decl causes MultiVersioning.
11452 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11455 NewFD->setInvalidDecl();
11456 return true;
11457 }
11458
11459 if (CheckMultiVersionValue(S, NewFD)) {
11460 NewFD->setInvalidDecl();
11461 return true;
11462 }
11463
11464 // If this is 'default', permit the forward declaration.
11465 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11466 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11467 Redeclaration = true;
11468 OldDecl = OldFD;
11469 OldFD->setIsMultiVersion();
11470 NewFD->setIsMultiVersion();
11471 return false;
11472 }
11473
11474 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11475 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11476 NewFD->setInvalidDecl();
11477 return true;
11478 }
11479
11480 if (NewTA) {
11481 ParsedTargetAttr OldParsed =
11483 OldTA->getFeaturesStr());
11484 llvm::sort(OldParsed.Features);
11485 ParsedTargetAttr NewParsed =
11487 NewTA->getFeaturesStr());
11488 // Sort order doesn't matter, it just needs to be consistent.
11489 llvm::sort(NewParsed.Features);
11490 if (OldParsed == NewParsed) {
11491 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11492 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11493 NewFD->setInvalidDecl();
11494 return true;
11495 }
11496 }
11497
11498 for (const auto *FD : OldFD->redecls()) {
11499 const auto *CurTA = FD->getAttr<TargetAttr>();
11500 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11501 // We allow forward declarations before ANY multiversioning attributes, but
11502 // nothing after the fact.
11504 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11505 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11506 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11507 << (NewTA ? 0 : 2);
11508 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11509 NewFD->setInvalidDecl();
11510 return true;
11511 }
11512 }
11513
11514 OldFD->setIsMultiVersion();
11515 NewFD->setIsMultiVersion();
11516 Redeclaration = false;
11517 OldDecl = nullptr;
11518 Previous.clear();
11519 return false;
11520}
11521
11523 MultiVersionKind OldKind = Old->getMultiVersionKind();
11524 MultiVersionKind NewKind = New->getMultiVersionKind();
11525
11526 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11527 NewKind == MultiVersionKind::None)
11528 return true;
11529
11530 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11531 switch (OldKind) {
11533 return NewKind == MultiVersionKind::TargetClones;
11535 return NewKind == MultiVersionKind::TargetVersion;
11536 default:
11537 return false;
11538 }
11539 } else {
11540 switch (OldKind) {
11542 return NewKind == MultiVersionKind::CPUSpecific;
11544 return NewKind == MultiVersionKind::CPUDispatch;
11545 default:
11546 return false;
11547 }
11548 }
11549}
11550
11551/// Check the validity of a new function declaration being added to an existing
11552/// multiversioned declaration collection.
11554 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11555 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11556 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11558
11559 // Disallow mixing of multiversioning types.
11560 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11561 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11562 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11563 NewFD->setInvalidDecl();
11564 return true;
11565 }
11566
11567 // Add the default target_version attribute if it's missing.
11568 patchDefaultTargetVersion(OldFD, NewFD);
11569 patchDefaultTargetVersion(NewFD, OldFD);
11570
11571 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11572 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11573 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11574 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11575
11576 ParsedTargetAttr NewParsed;
11577 if (NewTA) {
11579 NewTA->getFeaturesStr());
11580 llvm::sort(NewParsed.Features);
11581 }
11583 if (NewTVA) {
11584 NewTVA->getFeatures(NewFeats);
11585 llvm::sort(NewFeats);
11586 }
11587
11588 bool UseMemberUsingDeclRules =
11589 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11590
11591 bool MayNeedOverloadableChecks =
11593
11594 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11595 // of a previous member of the MultiVersion set.
11596 for (NamedDecl *ND : Previous) {
11597 FunctionDecl *CurFD = ND->getAsFunction();
11598 if (!CurFD || CurFD->isInvalidDecl())
11599 continue;
11600 if (MayNeedOverloadableChecks &&
11601 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11602 continue;
11603
11604 switch (NewMVKind) {
11606 assert(OldMVKind == MultiVersionKind::TargetClones &&
11607 "Only target_clones can be omitted in subsequent declarations");
11608 break;
11610 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11611 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11612 NewFD->setIsMultiVersion();
11613 Redeclaration = true;
11614 OldDecl = ND;
11615 return false;
11616 }
11617
11618 ParsedTargetAttr CurParsed =
11620 CurTA->getFeaturesStr());
11621 llvm::sort(CurParsed.Features);
11622 if (CurParsed == NewParsed) {
11623 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11624 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11625 NewFD->setInvalidDecl();
11626 return true;
11627 }
11628 break;
11629 }
11631 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11632 if (CurTVA->getName() == NewTVA->getName()) {
11633 NewFD->setIsMultiVersion();
11634 Redeclaration = true;
11635 OldDecl = ND;
11636 return false;
11637 }
11639 CurTVA->getFeatures(CurFeats);
11640 llvm::sort(CurFeats);
11641
11642 if (CurFeats == NewFeats) {
11643 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11644 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11645 NewFD->setInvalidDecl();
11646 return true;
11647 }
11648 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11649 // Default
11650 if (NewFeats.empty())
11651 break;
11652
11653 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11655 CurClones->getFeatures(CurFeats, I);
11656 llvm::sort(CurFeats);
11657
11658 if (CurFeats == NewFeats) {
11659 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11660 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11661 NewFD->setInvalidDecl();
11662 return true;
11663 }
11664 }
11665 }
11666 break;
11667 }
11669 assert(NewClones && "MultiVersionKind does not match attribute type");
11670 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11671 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11672 !std::equal(CurClones->featuresStrs_begin(),
11673 CurClones->featuresStrs_end(),
11674 NewClones->featuresStrs_begin())) {
11675 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11676 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11677 NewFD->setInvalidDecl();
11678 return true;
11679 }
11680 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11682 CurTVA->getFeatures(CurFeats);
11683 llvm::sort(CurFeats);
11684
11685 // Default
11686 if (CurFeats.empty())
11687 break;
11688
11689 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11690 NewFeats.clear();
11691 NewClones->getFeatures(NewFeats, I);
11692 llvm::sort(NewFeats);
11693
11694 if (CurFeats == NewFeats) {
11695 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11696 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11697 NewFD->setInvalidDecl();
11698 return true;
11699 }
11700 }
11701 break;
11702 }
11703 Redeclaration = true;
11704 OldDecl = CurFD;
11705 NewFD->setIsMultiVersion();
11706 return false;
11707 }
11710 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11711 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11712 // Handle CPUDispatch/CPUSpecific versions.
11713 // Only 1 CPUDispatch function is allowed, this will make it go through
11714 // the redeclaration errors.
11715 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11716 CurFD->hasAttr<CPUDispatchAttr>()) {
11717 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11718 std::equal(
11719 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11720 NewCPUDisp->cpus_begin(),
11721 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11722 return Cur->getName() == New->getName();
11723 })) {
11724 NewFD->setIsMultiVersion();
11725 Redeclaration = true;
11726 OldDecl = ND;
11727 return false;
11728 }
11729
11730 // If the declarations don't match, this is an error condition.
11731 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11732 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11733 NewFD->setInvalidDecl();
11734 return true;
11735 }
11736 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11737 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11738 std::equal(
11739 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11740 NewCPUSpec->cpus_begin(),
11741 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11742 return Cur->getName() == New->getName();
11743 })) {
11744 NewFD->setIsMultiVersion();
11745 Redeclaration = true;
11746 OldDecl = ND;
11747 return false;
11748 }
11749
11750 // Only 1 version of CPUSpecific is allowed for each CPU.
11751 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11752 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11753 if (CurII == NewII) {
11754 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11755 << NewII;
11756 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11757 NewFD->setInvalidDecl();
11758 return true;
11759 }
11760 }
11761 }
11762 }
11763 break;
11764 }
11765 }
11766 }
11767
11768 // Else, this is simply a non-redecl case. Checking the 'value' is only
11769 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11770 // handled in the attribute adding step.
11771 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
11772 NewFD->setInvalidDecl();
11773 return true;
11774 }
11775
11776 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11777 !OldFD->isMultiVersion(), NewMVKind)) {
11778 NewFD->setInvalidDecl();
11779 return true;
11780 }
11781
11782 // Permit forward declarations in the case where these two are compatible.
11783 if (!OldFD->isMultiVersion()) {
11784 OldFD->setIsMultiVersion();
11785 NewFD->setIsMultiVersion();
11786 Redeclaration = true;
11787 OldDecl = OldFD;
11788 return false;
11789 }
11790
11791 NewFD->setIsMultiVersion();
11792 Redeclaration = false;
11793 OldDecl = nullptr;
11794 Previous.clear();
11795 return false;
11796}
11797
11798/// Check the validity of a mulitversion function declaration.
11799/// Also sets the multiversion'ness' of the function itself.
11800///
11801/// This sets NewFD->isInvalidDecl() to true if there was an error.
11802///
11803/// Returns true if there was an error, false otherwise.
11805 bool &Redeclaration, NamedDecl *&OldDecl,
11807 const TargetInfo &TI = S.getASTContext().getTargetInfo();
11808
11809 // Check if FMV is disabled.
11810 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
11811 return false;
11812
11813 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11814 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11815 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11816 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11817 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11818 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11819
11820 // Main isn't allowed to become a multiversion function, however it IS
11821 // permitted to have 'main' be marked with the 'target' optimization hint,
11822 // for 'target_version' only default is allowed.
11823 if (NewFD->isMain()) {
11824 if (MVKind != MultiVersionKind::None &&
11825 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11826 !(MVKind == MultiVersionKind::TargetVersion &&
11827 NewTVA->isDefaultVersion())) {
11828 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11829 NewFD->setInvalidDecl();
11830 return true;
11831 }
11832 return false;
11833 }
11834
11835 // Target attribute on AArch64 is not used for multiversioning
11836 if (NewTA && TI.getTriple().isAArch64())
11837 return false;
11838
11839 // Target attribute on RISCV is not used for multiversioning
11840 if (NewTA && TI.getTriple().isRISCV())
11841 return false;
11842
11843 if (!OldDecl || !OldDecl->getAsFunction() ||
11844 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
11845 NewFD->getDeclContext()->getRedeclContext())) {
11846 // If there's no previous declaration, AND this isn't attempting to cause
11847 // multiversioning, this isn't an error condition.
11848 if (MVKind == MultiVersionKind::None)
11849 return false;
11850 return CheckMultiVersionFirstFunction(S, NewFD);
11851 }
11852
11853 FunctionDecl *OldFD = OldDecl->getAsFunction();
11854
11855 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11856 return false;
11857
11858 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11859 // for target_clones and target_version.
11860 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11863 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11865 NewFD->setInvalidDecl();
11866 return true;
11867 }
11868
11869 if (!OldFD->isMultiVersion()) {
11870 switch (MVKind) {
11874 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
11876 if (OldFD->isUsed(false)) {
11877 NewFD->setInvalidDecl();
11878 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11879 }
11880 OldFD->setIsMultiVersion();
11881 break;
11882
11886 break;
11887 }
11888 }
11889
11890 // At this point, we have a multiversion function decl (in OldFD) AND an
11891 // appropriate attribute in the current function decl. Resolve that these are
11892 // still compatible with previous declarations.
11893 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11894 NewCPUSpec, NewClones, Redeclaration,
11895 OldDecl, Previous);
11896}
11897
11899 bool IsPure = NewFD->hasAttr<PureAttr>();
11900 bool IsConst = NewFD->hasAttr<ConstAttr>();
11901
11902 // If there are no pure or const attributes, there's nothing to check.
11903 if (!IsPure && !IsConst)
11904 return;
11905
11906 // If the function is marked both pure and const, we retain the const
11907 // attribute because it makes stronger guarantees than the pure attribute, and
11908 // we drop the pure attribute explicitly to prevent later confusion about
11909 // semantics.
11910 if (IsPure && IsConst) {
11911 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
11912 NewFD->dropAttrs<PureAttr>();
11913 }
11914
11915 // Constructors and destructors are functions which return void, so are
11916 // handled here as well.
11917 if (NewFD->getReturnType()->isVoidType()) {
11918 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
11919 << IsConst;
11920 NewFD->dropAttrs<PureAttr, ConstAttr>();
11921 }
11922}
11923
11926 bool IsMemberSpecialization,
11927 bool DeclIsDefn) {
11928 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11929 "Variably modified return types are not handled here");
11930
11931 // Determine whether the type of this function should be merged with
11932 // a previous visible declaration. This never happens for functions in C++,
11933 // and always happens in C if the previous declaration was visible.
11934 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11935 !Previous.isShadowed();
11936
11937 bool Redeclaration = false;
11938 NamedDecl *OldDecl = nullptr;
11939 bool MayNeedOverloadableChecks = false;
11940
11942 // Merge or overload the declaration with an existing declaration of
11943 // the same name, if appropriate.
11944 if (!Previous.empty()) {
11945 // Determine whether NewFD is an overload of PrevDecl or
11946 // a declaration that requires merging. If it's an overload,
11947 // there's no more work to do here; we'll just add the new
11948 // function to the scope.
11950 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11951 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11952 Redeclaration = true;
11953 OldDecl = Candidate;
11954 }
11955 } else {
11956 MayNeedOverloadableChecks = true;
11957 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11958 /*NewIsUsingDecl*/ false)) {
11959 case Ovl_Match:
11960 Redeclaration = true;
11961 break;
11962
11963 case Ovl_NonFunction:
11964 Redeclaration = true;
11965 break;
11966
11967 case Ovl_Overload:
11968 Redeclaration = false;
11969 break;
11970 }
11971 }
11972 }
11973
11974 // Check for a previous extern "C" declaration with this name.
11975 if (!Redeclaration &&
11977 if (!Previous.empty()) {
11978 // This is an extern "C" declaration with the same name as a previous
11979 // declaration, and thus redeclares that entity...
11980 Redeclaration = true;
11981 OldDecl = Previous.getFoundDecl();
11982 MergeTypeWithPrevious = false;
11983
11984 // ... except in the presence of __attribute__((overloadable)).
11985 if (OldDecl->hasAttr<OverloadableAttr>() ||
11986 NewFD->hasAttr<OverloadableAttr>()) {
11987 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11988 MayNeedOverloadableChecks = true;
11989 Redeclaration = false;
11990 OldDecl = nullptr;
11991 }
11992 }
11993 }
11994 }
11995
11996 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11997 return Redeclaration;
11998
11999 // PPC MMA non-pointer types are not allowed as function return types.
12000 if (Context.getTargetInfo().getTriple().isPPC64() &&
12001 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12002 NewFD->setInvalidDecl();
12003 }
12004
12005 CheckConstPureAttributesUsage(*this, NewFD);
12006
12007 // C++ [dcl.spec.auto.general]p12:
12008 // Return type deduction for a templated function with a placeholder in its
12009 // declared type occurs when the definition is instantiated even if the
12010 // function body contains a return statement with a non-type-dependent
12011 // operand.
12012 //
12013 // C++ [temp.dep.expr]p3:
12014 // An id-expression is type-dependent if it is a template-id that is not a
12015 // concept-id and is dependent; or if its terminal name is:
12016 // - [...]
12017 // - associated by name lookup with one or more declarations of member
12018 // functions of a class that is the current instantiation declared with a
12019 // return type that contains a placeholder type,
12020 // - [...]
12021 //
12022 // If this is a templated function with a placeholder in its return type,
12023 // make the placeholder type dependent since it won't be deduced until the
12024 // definition is instantiated. We do this here because it needs to happen
12025 // for implicitly instantiated member functions/member function templates.
12026 if (getLangOpts().CPlusPlus14 &&
12027 (NewFD->isDependentContext() &&
12028 NewFD->getReturnType()->isUndeducedType())) {
12029 const FunctionProtoType *FPT =
12030 NewFD->getType()->castAs<FunctionProtoType>();
12031 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12032 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12033 FPT->getExtProtoInfo()));
12034 }
12035
12036 // C++11 [dcl.constexpr]p8:
12037 // A constexpr specifier for a non-static member function that is not
12038 // a constructor declares that member function to be const.
12039 //
12040 // This needs to be delayed until we know whether this is an out-of-line
12041 // definition of a static member function.
12042 //
12043 // This rule is not present in C++1y, so we produce a backwards
12044 // compatibility warning whenever it happens in C++11.
12045 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12046 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12047 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12048 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
12049 CXXMethodDecl *OldMD = nullptr;
12050 if (OldDecl)
12051 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12052 if (!OldMD || !OldMD->isStatic()) {
12053 const FunctionProtoType *FPT =
12056 EPI.TypeQuals.addConst();
12058 FPT->getParamTypes(), EPI));
12059
12060 // Warn that we did this, if we're not performing template instantiation.
12061 // In that case, we'll have warned already when the template was defined.
12062 if (!inTemplateInstantiation()) {
12063 SourceLocation AddConstLoc;
12066 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12067
12068 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12069 << FixItHint::CreateInsertion(AddConstLoc, " const");
12070 }
12071 }
12072 }
12073
12074 if (Redeclaration) {
12075 // NewFD and OldDecl represent declarations that need to be
12076 // merged.
12077 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12078 DeclIsDefn)) {
12079 NewFD->setInvalidDecl();
12080 return Redeclaration;
12081 }
12082
12083 Previous.clear();
12084 Previous.addDecl(OldDecl);
12085
12086 if (FunctionTemplateDecl *OldTemplateDecl =
12087 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12088 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12089 FunctionTemplateDecl *NewTemplateDecl
12091 assert(NewTemplateDecl && "Template/non-template mismatch");
12092
12093 // The call to MergeFunctionDecl above may have created some state in
12094 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12095 // can add it as a redeclaration.
12096 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12097
12098 NewFD->setPreviousDeclaration(OldFD);
12099 if (NewFD->isCXXClassMember()) {
12100 NewFD->setAccess(OldTemplateDecl->getAccess());
12101 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12102 }
12103
12104 // If this is an explicit specialization of a member that is a function
12105 // template, mark it as a member specialization.
12106 if (IsMemberSpecialization &&
12107 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12108 NewTemplateDecl->setMemberSpecialization();
12109 assert(OldTemplateDecl->isMemberSpecialization());
12110 // Explicit specializations of a member template do not inherit deleted
12111 // status from the parent member template that they are specializing.
12112 if (OldFD->isDeleted()) {
12113 // FIXME: This assert will not hold in the presence of modules.
12114 assert(OldFD->getCanonicalDecl() == OldFD);
12115 // FIXME: We need an update record for this AST mutation.
12116 OldFD->setDeletedAsWritten(false);
12117 }
12118 }
12119
12120 } else {
12121 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12122 auto *OldFD = cast<FunctionDecl>(OldDecl);
12123 // This needs to happen first so that 'inline' propagates.
12124 NewFD->setPreviousDeclaration(OldFD);
12125 if (NewFD->isCXXClassMember())
12126 NewFD->setAccess(OldFD->getAccess());
12127 }
12128 }
12129 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12130 !NewFD->getAttr<OverloadableAttr>()) {
12131 assert((Previous.empty() ||
12132 llvm::any_of(Previous,
12133 [](const NamedDecl *ND) {
12134 return ND->hasAttr<OverloadableAttr>();
12135 })) &&
12136 "Non-redecls shouldn't happen without overloadable present");
12137
12138 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12139 const auto *FD = dyn_cast<FunctionDecl>(ND);
12140 return FD && !FD->hasAttr<OverloadableAttr>();
12141 });
12142
12143 if (OtherUnmarkedIter != Previous.end()) {
12144 Diag(NewFD->getLocation(),
12145 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12146 Diag((*OtherUnmarkedIter)->getLocation(),
12147 diag::note_attribute_overloadable_prev_overload)
12148 << false;
12149
12150 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12151 }
12152 }
12153
12154 if (LangOpts.OpenMP)
12156
12157 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12159
12160 // Semantic checking for this function declaration (in isolation).
12161
12162 if (getLangOpts().CPlusPlus) {
12163 // C++-specific checks.
12164 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12165 CheckConstructor(Constructor);
12166 } else if (CXXDestructorDecl *Destructor =
12167 dyn_cast<CXXDestructorDecl>(NewFD)) {
12168 // We check here for invalid destructor names.
12169 // If we have a friend destructor declaration that is dependent, we can't
12170 // diagnose right away because cases like this are still valid:
12171 // template <class T> struct A { friend T::X::~Y(); };
12172 // struct B { struct Y { ~Y(); }; using X = Y; };
12173 // template struct A<B>;
12175 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12176 CXXRecordDecl *Record = Destructor->getParent();
12178
12180 Context.getCanonicalType(ClassType));
12181 if (NewFD->getDeclName() != Name) {
12182 Diag(NewFD->getLocation(), diag::err_destructor_name);
12183 NewFD->setInvalidDecl();
12184 return Redeclaration;
12185 }
12186 }
12187 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12188 if (auto *TD = Guide->getDescribedFunctionTemplate())
12190
12191 // A deduction guide is not on the list of entities that can be
12192 // explicitly specialized.
12193 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12194 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12195 << /*explicit specialization*/ 1;
12196 }
12197
12198 // Find any virtual functions that this function overrides.
12199 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12200 if (!Method->isFunctionTemplateSpecialization() &&
12201 !Method->getDescribedFunctionTemplate() &&
12202 Method->isCanonicalDecl()) {
12203 AddOverriddenMethods(Method->getParent(), Method);
12204 }
12205 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12206 // C++2a [class.virtual]p6
12207 // A virtual method shall not have a requires-clause.
12209 diag::err_constrained_virtual_method);
12210
12211 if (Method->isStatic())
12213 }
12214
12215 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12216 ActOnConversionDeclarator(Conversion);
12217
12218 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12219 if (NewFD->isOverloadedOperator() &&
12221 NewFD->setInvalidDecl();
12222 return Redeclaration;
12223 }
12224
12225 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12226 if (NewFD->getLiteralIdentifier() &&
12228 NewFD->setInvalidDecl();
12229 return Redeclaration;
12230 }
12231
12232 // In C++, check default arguments now that we have merged decls. Unless
12233 // the lexical context is the class, because in this case this is done
12234 // during delayed parsing anyway.
12235 if (!CurContext->isRecord())
12237
12238 // If this function is declared as being extern "C", then check to see if
12239 // the function returns a UDT (class, struct, or union type) that is not C
12240 // compatible, and if it does, warn the user.
12241 // But, issue any diagnostic on the first declaration only.
12242 if (Previous.empty() && NewFD->isExternC()) {
12243 QualType R = NewFD->getReturnType();
12244 if (R->isIncompleteType() && !R->isVoidType())
12245 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12246 << NewFD << R;
12247 else if (!R.isPODType(Context) && !R->isVoidType() &&
12249 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12250 }
12251
12252 // C++1z [dcl.fct]p6:
12253 // [...] whether the function has a non-throwing exception-specification
12254 // [is] part of the function type
12255 //
12256 // This results in an ABI break between C++14 and C++17 for functions whose
12257 // declared type includes an exception-specification in a parameter or
12258 // return type. (Exception specifications on the function itself are OK in
12259 // most cases, and exception specifications are not permitted in most other
12260 // contexts where they could make it into a mangling.)
12261 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12262 auto HasNoexcept = [&](QualType T) -> bool {
12263 // Strip off declarator chunks that could be between us and a function
12264 // type. We don't need to look far, exception specifications are very
12265 // restricted prior to C++17.
12266 if (auto *RT = T->getAs<ReferenceType>())
12267 T = RT->getPointeeType();
12268 else if (T->isAnyPointerType())
12269 T = T->getPointeeType();
12270 else if (auto *MPT = T->getAs<MemberPointerType>())
12271 T = MPT->getPointeeType();
12272 if (auto *FPT = T->getAs<FunctionProtoType>())
12273 if (FPT->isNothrow())
12274 return true;
12275 return false;
12276 };
12277
12278 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12279 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12280 for (QualType T : FPT->param_types())
12281 AnyNoexcept |= HasNoexcept(T);
12282 if (AnyNoexcept)
12283 Diag(NewFD->getLocation(),
12284 diag::warn_cxx17_compat_exception_spec_in_signature)
12285 << NewFD;
12286 }
12287
12288 if (!Redeclaration && LangOpts.CUDA) {
12289 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12290 for (auto *Parm : NewFD->parameters()) {
12291 if (!Parm->getType()->isDependentType() &&
12292 Parm->hasAttr<CUDAGridConstantAttr>() &&
12293 !(IsKernel && Parm->getType().isConstQualified()))
12294 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12295 diag::err_cuda_grid_constant_not_allowed);
12296 }
12298 }
12299 }
12300
12301 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12303
12304 return Redeclaration;
12305}
12306
12308 // [basic.start.main]p3
12309 // The main function shall not be declared with a linkage-specification.
12310 if (FD->isExternCContext() ||
12311 (FD->isExternCXXContext() &&
12313 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification)
12314 << FD->getLanguageLinkage();
12315
12316 // C++11 [basic.start.main]p3:
12317 // A program that [...] declares main to be inline, static or
12318 // constexpr is ill-formed.
12319 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12320 // appear in a declaration of main.
12321 // static main is not an error under C99, but we should warn about it.
12322 // We accept _Noreturn main as an extension.
12323 if (FD->getStorageClass() == SC_Static)
12325 ? diag::err_static_main : diag::warn_static_main)
12327 if (FD->isInlineSpecified())
12328 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12330 if (DS.isNoreturnSpecified()) {
12331 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12332 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12333 Diag(NoreturnLoc, diag::ext_noreturn_main);
12334 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12335 << FixItHint::CreateRemoval(NoreturnRange);
12336 }
12337 if (FD->isConstexpr()) {
12338 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12339 << FD->isConsteval()
12342 }
12343
12344 if (getLangOpts().OpenCL) {
12345 Diag(FD->getLocation(), diag::err_opencl_no_main)
12346 << FD->hasAttr<OpenCLKernelAttr>();
12347 FD->setInvalidDecl();
12348 return;
12349 }
12350
12351 // Functions named main in hlsl are default entries, but don't have specific
12352 // signatures they are required to conform to.
12353 if (getLangOpts().HLSL)
12354 return;
12355
12356 QualType T = FD->getType();
12357 assert(T->isFunctionType() && "function decl is not of function type");
12358 const FunctionType* FT = T->castAs<FunctionType>();
12359
12360 // Set default calling convention for main()
12361 if (FT->getCallConv() != CC_C) {
12363 FD->setType(QualType(FT, 0));
12365 }
12366
12367 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12368 // In C with GNU extensions we allow main() to have non-integer return
12369 // type, but we should warn about the extension, and we disable the
12370 // implicit-return-zero rule.
12371
12372 // GCC in C mode accepts qualified 'int'.
12374 FD->setHasImplicitReturnZero(true);
12375 else {
12376 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12377 SourceRange RTRange = FD->getReturnTypeSourceRange();
12378 if (RTRange.isValid())
12379 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12380 << FixItHint::CreateReplacement(RTRange, "int");
12381 }
12382 } else {
12383 // In C and C++, main magically returns 0 if you fall off the end;
12384 // set the flag which tells us that.
12385 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12386
12387 // All the standards say that main() should return 'int'.
12389 FD->setHasImplicitReturnZero(true);
12390 else {
12391 // Otherwise, this is just a flat-out error.
12392 SourceRange RTRange = FD->getReturnTypeSourceRange();
12393 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12394 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12395 : FixItHint());
12396 FD->setInvalidDecl(true);
12397 }
12398 }
12399
12400 // Treat protoless main() as nullary.
12401 if (isa<FunctionNoProtoType>(FT)) return;
12402
12403 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12404 unsigned nparams = FTP->getNumParams();
12405 assert(FD->getNumParams() == nparams);
12406
12407 bool HasExtraParameters = (nparams > 3);
12408
12409 if (FTP->isVariadic()) {
12410 Diag(FD->getLocation(), diag::ext_variadic_main);
12411 // FIXME: if we had information about the location of the ellipsis, we
12412 // could add a FixIt hint to remove it as a parameter.
12413 }
12414
12415 // Darwin passes an undocumented fourth argument of type char**. If
12416 // other platforms start sprouting these, the logic below will start
12417 // getting shifty.
12418 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12419 HasExtraParameters = false;
12420
12421 if (HasExtraParameters) {
12422 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12423 FD->setInvalidDecl(true);
12424 nparams = 3;
12425 }
12426
12427 // FIXME: a lot of the following diagnostics would be improved
12428 // if we had some location information about types.
12429
12430 QualType CharPP =
12432 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12433
12434 for (unsigned i = 0; i < nparams; ++i) {
12435 QualType AT = FTP->getParamType(i);
12436
12437 bool mismatch = true;
12438
12440 mismatch = false;
12441 else if (Expected[i] == CharPP) {
12442 // As an extension, the following forms are okay:
12443 // char const **
12444 // char const * const *
12445 // char * const *
12446
12448 const PointerType* PT;
12449 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12450 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12452 Context.CharTy)) {
12453 qs.removeConst();
12454 mismatch = !qs.empty();
12455 }
12456 }
12457
12458 if (mismatch) {
12459 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12460 // TODO: suggest replacing given type with expected type
12461 FD->setInvalidDecl(true);
12462 }
12463 }
12464
12465 if (nparams == 1 && !FD->isInvalidDecl()) {
12466 Diag(FD->getLocation(), diag::warn_main_one_arg);
12467 }
12468
12469 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12470 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12471 FD->setInvalidDecl();
12472 }
12473}
12474
12475static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12476
12477 // Default calling convention for main and wmain is __cdecl
12478 if (FD->getName() == "main" || FD->getName() == "wmain")
12479 return false;
12480
12481 // Default calling convention for MinGW is __cdecl
12482 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12483 if (T.isWindowsGNUEnvironment())
12484 return false;
12485
12486 // Default calling convention for WinMain, wWinMain and DllMain
12487 // is __stdcall on 32 bit Windows
12488 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12489 return true;
12490
12491 return false;
12492}
12493
12495 QualType T = FD->getType();
12496 assert(T->isFunctionType() && "function decl is not of function type");
12497 const FunctionType *FT = T->castAs<FunctionType>();
12498
12499 // Set an implicit return of 'zero' if the function can return some integral,
12500 // enumeration, pointer or nullptr type.
12504 // DllMain is exempt because a return value of zero means it failed.
12505 if (FD->getName() != "DllMain")
12506 FD->setHasImplicitReturnZero(true);
12507
12508 // Explicitly specified calling conventions are applied to MSVC entry points
12509 if (!hasExplicitCallingConv(T)) {
12510 if (isDefaultStdCall(FD, *this)) {
12511 if (FT->getCallConv() != CC_X86StdCall) {
12514 FD->setType(QualType(FT, 0));
12515 }
12516 } else if (FT->getCallConv() != CC_C) {
12519 FD->setType(QualType(FT, 0));
12520 }
12521 }
12522
12523 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12524 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12525 FD->setInvalidDecl();
12526 }
12527}
12528
12530 // FIXME: Need strict checking. In C89, we need to check for
12531 // any assignment, increment, decrement, function-calls, or
12532 // commas outside of a sizeof. In C99, it's the same list,
12533 // except that the aforementioned are allowed in unevaluated
12534 // expressions. Everything else falls under the
12535 // "may accept other forms of constant expressions" exception.
12536 //
12537 // Regular C++ code will not end up here (exceptions: language extensions,
12538 // OpenCL C++ etc), so the constant expression rules there don't matter.
12539 if (Init->isValueDependent()) {
12540 assert(Init->containsErrors() &&
12541 "Dependent code should only occur in error-recovery path.");
12542 return true;
12543 }
12544 const Expr *Culprit;
12545 if (Init->isConstantInitializer(Context, false, &Culprit))
12546 return false;
12547 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12548 return true;
12549}
12550
12551namespace {
12552 // Visits an initialization expression to see if OrigDecl is evaluated in
12553 // its own initialization and throws a warning if it does.
12554 class SelfReferenceChecker
12555 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12556 Sema &S;
12557 Decl *OrigDecl;
12558 bool isRecordType;
12559 bool isPODType;
12560 bool isReferenceType;
12561
12562 bool isInitList;
12563 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12564
12565 public:
12567
12568 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12569 S(S), OrigDecl(OrigDecl) {
12570 isPODType = false;
12571 isRecordType = false;
12572 isReferenceType = false;
12573 isInitList = false;
12574 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12575 isPODType = VD->getType().isPODType(S.Context);
12576 isRecordType = VD->getType()->isRecordType();
12577 isReferenceType = VD->getType()->isReferenceType();
12578 }
12579 }
12580
12581 // For most expressions, just call the visitor. For initializer lists,
12582 // track the index of the field being initialized since fields are
12583 // initialized in order allowing use of previously initialized fields.
12584 void CheckExpr(Expr *E) {
12585 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12586 if (!InitList) {
12587 Visit(E);
12588 return;
12589 }
12590
12591 // Track and increment the index here.
12592 isInitList = true;
12593 InitFieldIndex.push_back(0);
12594 for (auto *Child : InitList->children()) {
12595 CheckExpr(cast<Expr>(Child));
12596 ++InitFieldIndex.back();
12597 }
12598 InitFieldIndex.pop_back();
12599 }
12600
12601 // Returns true if MemberExpr is checked and no further checking is needed.
12602 // Returns false if additional checking is required.
12603 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12605 Expr *Base = E;
12606 bool ReferenceField = false;
12607
12608 // Get the field members used.
12609 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12610 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12611 if (!FD)
12612 return false;
12613 Fields.push_back(FD);
12614 if (FD->getType()->isReferenceType())
12615 ReferenceField = true;
12616 Base = ME->getBase()->IgnoreParenImpCasts();
12617 }
12618
12619 // Keep checking only if the base Decl is the same.
12620 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12621 if (!DRE || DRE->getDecl() != OrigDecl)
12622 return false;
12623
12624 // A reference field can be bound to an unininitialized field.
12625 if (CheckReference && !ReferenceField)
12626 return true;
12627
12628 // Convert FieldDecls to their index number.
12629 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12630 for (const FieldDecl *I : llvm::reverse(Fields))
12631 UsedFieldIndex.push_back(I->getFieldIndex());
12632
12633 // See if a warning is needed by checking the first difference in index
12634 // numbers. If field being used has index less than the field being
12635 // initialized, then the use is safe.
12636 for (auto UsedIter = UsedFieldIndex.begin(),
12637 UsedEnd = UsedFieldIndex.end(),
12638 OrigIter = InitFieldIndex.begin(),
12639 OrigEnd = InitFieldIndex.end();
12640 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12641 if (*UsedIter < *OrigIter)
12642 return true;
12643 if (*UsedIter > *OrigIter)
12644 break;
12645 }
12646
12647 // TODO: Add a different warning which will print the field names.
12648 HandleDeclRefExpr(DRE);
12649 return true;
12650 }
12651
12652 // For most expressions, the cast is directly above the DeclRefExpr.
12653 // For conditional operators, the cast can be outside the conditional
12654 // operator if both expressions are DeclRefExpr's.
12655 void HandleValue(Expr *E) {
12656 E = E->IgnoreParens();
12657 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12658 HandleDeclRefExpr(DRE);
12659 return;
12660 }
12661
12662 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12663 Visit(CO->getCond());
12664 HandleValue(CO->getTrueExpr());
12665 HandleValue(CO->getFalseExpr());
12666 return;
12667 }
12668
12669 if (BinaryConditionalOperator *BCO =
12670 dyn_cast<BinaryConditionalOperator>(E)) {
12671 Visit(BCO->getCond());
12672 HandleValue(BCO->getFalseExpr());
12673 return;
12674 }
12675
12676 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12677 if (Expr *SE = OVE->getSourceExpr())
12678 HandleValue(SE);
12679 return;
12680 }
12681
12682 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12683 if (BO->getOpcode() == BO_Comma) {
12684 Visit(BO->getLHS());
12685 HandleValue(BO->getRHS());
12686 return;
12687 }
12688 }
12689
12690 if (isa<MemberExpr>(E)) {
12691 if (isInitList) {
12692 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12693 false /*CheckReference*/))
12694 return;
12695 }
12696
12698 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12699 // Check for static member variables and don't warn on them.
12700 if (!isa<FieldDecl>(ME->getMemberDecl()))
12701 return;
12702 Base = ME->getBase()->IgnoreParenImpCasts();
12703 }
12704 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12705 HandleDeclRefExpr(DRE);
12706 return;
12707 }
12708
12709 Visit(E);
12710 }
12711
12712 // Reference types not handled in HandleValue are handled here since all
12713 // uses of references are bad, not just r-value uses.
12714 void VisitDeclRefExpr(DeclRefExpr *E) {
12715 if (isReferenceType)
12716 HandleDeclRefExpr(E);
12717 }
12718
12719 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12720 if (E->getCastKind() == CK_LValueToRValue) {
12721 HandleValue(E->getSubExpr());
12722 return;
12723 }
12724
12725 Inherited::VisitImplicitCastExpr(E);
12726 }
12727
12728 void VisitMemberExpr(MemberExpr *E) {
12729 if (isInitList) {
12730 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12731 return;
12732 }
12733
12734 // Don't warn on arrays since they can be treated as pointers.
12735 if (E->getType()->canDecayToPointerType()) return;
12736
12737 // Warn when a non-static method call is followed by non-static member
12738 // field accesses, which is followed by a DeclRefExpr.
12739 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12740 bool Warn = (MD && !MD->isStatic());
12741 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12742 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12743 if (!isa<FieldDecl>(ME->getMemberDecl()))
12744 Warn = false;
12745 Base = ME->getBase()->IgnoreParenImpCasts();
12746 }
12747
12748 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12749 if (Warn)
12750 HandleDeclRefExpr(DRE);
12751 return;
12752 }
12753
12754 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12755 // Visit that expression.
12756 Visit(Base);
12757 }
12758
12759 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12760 Expr *Callee = E->getCallee();
12761
12762 if (isa<UnresolvedLookupExpr>(Callee))
12763 return Inherited::VisitCXXOperatorCallExpr(E);
12764
12765 Visit(Callee);
12766 for (auto Arg: E->arguments())
12767 HandleValue(Arg->IgnoreParenImpCasts());
12768 }
12769
12770 void VisitUnaryOperator(UnaryOperator *E) {
12771 // For POD record types, addresses of its own members are well-defined.
12772 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12773 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12774 if (!isPODType)
12775 HandleValue(E->getSubExpr());
12776 return;
12777 }
12778
12779 if (E->isIncrementDecrementOp()) {
12780 HandleValue(E->getSubExpr());
12781 return;
12782 }
12783
12784 Inherited::VisitUnaryOperator(E);
12785 }
12786
12787 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12788
12789 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12790 if (E->getConstructor()->isCopyConstructor()) {
12791 Expr *ArgExpr = E->getArg(0);
12792 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12793 if (ILE->getNumInits() == 1)
12794 ArgExpr = ILE->getInit(0);
12795 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12796 if (ICE->getCastKind() == CK_NoOp)
12797 ArgExpr = ICE->getSubExpr();
12798 HandleValue(ArgExpr);
12799 return;
12800 }
12801 Inherited::VisitCXXConstructExpr(E);
12802 }
12803
12804 void VisitCallExpr(CallExpr *E) {
12805 // Treat std::move as a use.
12806 if (E->isCallToStdMove()) {
12807 HandleValue(E->getArg(0));
12808 return;
12809 }
12810
12811 Inherited::VisitCallExpr(E);
12812 }
12813
12814 void VisitBinaryOperator(BinaryOperator *E) {
12815 if (E->isCompoundAssignmentOp()) {
12816 HandleValue(E->getLHS());
12817 Visit(E->getRHS());
12818 return;
12819 }
12820
12821 Inherited::VisitBinaryOperator(E);
12822 }
12823
12824 // A custom visitor for BinaryConditionalOperator is needed because the
12825 // regular visitor would check the condition and true expression separately
12826 // but both point to the same place giving duplicate diagnostics.
12827 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12828 Visit(E->getCond());
12829 Visit(E->getFalseExpr());
12830 }
12831
12832 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12833 Decl* ReferenceDecl = DRE->getDecl();
12834 if (OrigDecl != ReferenceDecl) return;
12835 unsigned diag;
12836 if (isReferenceType) {
12837 diag = diag::warn_uninit_self_reference_in_reference_init;
12838 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12839 diag = diag::warn_static_self_reference_in_init;
12840 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12841 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12842 DRE->getDecl()->getType()->isRecordType()) {
12843 diag = diag::warn_uninit_self_reference_in_init;
12844 } else {
12845 // Local variables will be handled by the CFG analysis.
12846 return;
12847 }
12848
12849 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12850 S.PDiag(diag)
12851 << DRE->getDecl() << OrigDecl->getLocation()
12852 << DRE->getSourceRange());
12853 }
12854 };
12855
12856 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12857 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12858 bool DirectInit) {
12859 // Parameters arguments are occassionially constructed with itself,
12860 // for instance, in recursive functions. Skip them.
12861 if (isa<ParmVarDecl>(OrigDecl))
12862 return;
12863
12864 E = E->IgnoreParens();
12865
12866 // Skip checking T a = a where T is not a record or reference type.
12867 // Doing so is a way to silence uninitialized warnings.
12868 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12869 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12870 if (ICE->getCastKind() == CK_LValueToRValue)
12871 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12872 if (DRE->getDecl() == OrigDecl)
12873 return;
12874
12875 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12876 }
12877} // end anonymous namespace
12878
12879namespace {
12880 // Simple wrapper to add the name of a variable or (if no variable is
12881 // available) a DeclarationName into a diagnostic.
12882 struct VarDeclOrName {
12883 VarDecl *VDecl;
12884 DeclarationName Name;
12885
12886 friend const Sema::SemaDiagnosticBuilder &
12887 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12888 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12889 }
12890 };
12891} // end anonymous namespace
12892
12895 TypeSourceInfo *TSI,
12897 Expr *Init) {
12898 bool IsInitCapture = !VDecl;
12899 assert((!VDecl || !VDecl->isInitCapture()) &&
12900 "init captures are expected to be deduced prior to initialization");
12901
12902 VarDeclOrName VN{VDecl, Name};
12903
12905 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12906
12907 // Diagnose auto array declarations in C23, unless it's a supported extension.
12908 if (getLangOpts().C23 && Type->isArrayType() &&
12909 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
12910 Diag(Range.getBegin(), diag::err_auto_not_allowed)
12911 << (int)Deduced->getContainedAutoType()->getKeyword()
12912 << /*in array decl*/ 23 << Range;
12913 return QualType();
12914 }
12915
12916 // C++11 [dcl.spec.auto]p3
12917 if (!Init) {
12918 assert(VDecl && "no init for init capture deduction?");
12919
12920 // Except for class argument deduction, and then for an initializing
12921 // declaration only, i.e. no static at class scope or extern.
12922 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12923 VDecl->hasExternalStorage() ||
12924 VDecl->isStaticDataMember()) {
12925 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12926 << VDecl->getDeclName() << Type;
12927 return QualType();
12928 }
12929 }
12930
12931 ArrayRef<Expr*> DeduceInits;
12932 if (Init)
12933 DeduceInits = Init;
12934
12935 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12936 if (DirectInit && PL)
12937 DeduceInits = PL->exprs();
12938
12939 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12940 assert(VDecl && "non-auto type for init capture deduction?");
12943 VDecl->getLocation(), DirectInit, Init);
12944 // FIXME: Initialization should not be taking a mutable list of inits.
12945 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
12946 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12947 InitsCopy);
12948 }
12949
12950 if (DirectInit) {
12951 if (auto *IL = dyn_cast<InitListExpr>(Init))
12952 DeduceInits = IL->inits();
12953 }
12954
12955 // Deduction only works if we have exactly one source expression.
12956 if (DeduceInits.empty()) {
12957 // It isn't possible to write this directly, but it is possible to
12958 // end up in this situation with "auto x(some_pack...);"
12959 Diag(Init->getBeginLoc(), IsInitCapture
12960 ? diag::err_init_capture_no_expression
12961 : diag::err_auto_var_init_no_expression)
12962 << VN << Type << Range;
12963 return QualType();
12964 }
12965
12966 if (DeduceInits.size() > 1) {
12967 Diag(DeduceInits[1]->getBeginLoc(),
12968 IsInitCapture ? diag::err_init_capture_multiple_expressions
12969 : diag::err_auto_var_init_multiple_expressions)
12970 << VN << Type << Range;
12971 return QualType();
12972 }
12973
12974 Expr *DeduceInit = DeduceInits[0];
12975 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12976 Diag(Init->getBeginLoc(), IsInitCapture
12977 ? diag::err_init_capture_paren_braces
12978 : diag::err_auto_var_init_paren_braces)
12979 << isa<InitListExpr>(Init) << VN << Type << Range;
12980 return QualType();
12981 }
12982
12983 // Expressions default to 'id' when we're in a debugger.
12984 bool DefaultedAnyToId = false;
12985 if (getLangOpts().DebuggerCastResultToId &&
12986 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12988 if (Result.isInvalid()) {
12989 return QualType();
12990 }
12991 Init = Result.get();
12992 DefaultedAnyToId = true;
12993 }
12994
12995 // C++ [dcl.decomp]p1:
12996 // If the assignment-expression [...] has array type A and no ref-qualifier
12997 // is present, e has type cv A
12998 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13000 DeduceInit->getType()->isConstantArrayType())
13001 return Context.getQualifiedType(DeduceInit->getType(),
13002 Type.getQualifiers());
13003
13005 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13007 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13010 if (!IsInitCapture)
13011 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13012 else if (isa<InitListExpr>(Init))
13014 diag::err_init_capture_deduction_failure_from_init_list)
13015 << VN
13016 << (DeduceInit->getType().isNull() ? TSI->getType()
13017 : DeduceInit->getType())
13018 << DeduceInit->getSourceRange();
13019 else
13020 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13021 << VN << TSI->getType()
13022 << (DeduceInit->getType().isNull() ? TSI->getType()
13023 : DeduceInit->getType())
13024 << DeduceInit->getSourceRange();
13025 }
13026
13027 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13028 // 'id' instead of a specific object type prevents most of our usual
13029 // checks.
13030 // We only want to warn outside of template instantiations, though:
13031 // inside a template, the 'id' could have come from a parameter.
13032 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13033 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13035 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13036 }
13037
13038 return DeducedType;
13039}
13040
13042 Expr *Init) {
13043 assert(!Init || !Init->containsErrors());
13045 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13046 VDecl->getSourceRange(), DirectInit, Init);
13047 if (DeducedType.isNull()) {
13048 VDecl->setInvalidDecl();
13049 return true;
13050 }
13051
13052 VDecl->setType(DeducedType);
13053 assert(VDecl->isLinkageValid());
13054
13055 // In ARC, infer lifetime.
13056 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13057 VDecl->setInvalidDecl();
13058
13059 if (getLangOpts().OpenCL)
13061
13062 // If this is a redeclaration, check that the type we just deduced matches
13063 // the previously declared type.
13064 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13065 // We never need to merge the type, because we cannot form an incomplete
13066 // array of auto, nor deduce such a type.
13067 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13068 }
13069
13070 // Check the deduced type is valid for a variable declaration.
13072 return VDecl->isInvalidDecl();
13073}
13074
13077 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13078 Init = EWC->getSubExpr();
13079
13080 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13081 Init = CE->getSubExpr();
13082
13083 QualType InitType = Init->getType();
13086 "shouldn't be called if type doesn't have a non-trivial C struct");
13087 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13088 for (auto *I : ILE->inits()) {
13089 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13090 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13091 continue;
13092 SourceLocation SL = I->getExprLoc();
13094 }
13095 return;
13096 }
13097
13098 if (isa<ImplicitValueInitExpr>(Init)) {
13101 NTCUK_Init);
13102 } else {
13103 // Assume all other explicit initializers involving copying some existing
13104 // object.
13105 // TODO: ignore any explicit initializers where we can guarantee
13106 // copy-elision.
13109 }
13110}
13111
13112namespace {
13113
13114bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13115 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13116 // in the source code or implicitly by the compiler if it is in a union
13117 // defined in a system header and has non-trivial ObjC ownership
13118 // qualifications. We don't want those fields to participate in determining
13119 // whether the containing union is non-trivial.
13120 return FD->hasAttr<UnavailableAttr>();
13121}
13122
13123struct DiagNonTrivalCUnionDefaultInitializeVisitor
13124 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13125 void> {
13126 using Super =
13127 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13128 void>;
13129
13130 DiagNonTrivalCUnionDefaultInitializeVisitor(
13131 QualType OrigTy, SourceLocation OrigLoc,
13132 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13133 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13134
13135 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13136 const FieldDecl *FD, bool InNonTrivialUnion) {
13137 if (const auto *AT = S.Context.getAsArrayType(QT))
13138 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13139 InNonTrivialUnion);
13140 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13141 }
13142
13143 void visitARCStrong(QualType QT, const FieldDecl *FD,
13144 bool InNonTrivialUnion) {
13145 if (InNonTrivialUnion)
13146 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13147 << 1 << 0 << QT << FD->getName();
13148 }
13149
13150 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13151 if (InNonTrivialUnion)
13152 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13153 << 1 << 0 << QT << FD->getName();
13154 }
13155
13156 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13157 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13158 if (RD->isUnion()) {
13159 if (OrigLoc.isValid()) {
13160 bool IsUnion = false;
13161 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13162 IsUnion = OrigRD->isUnion();
13163 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13164 << 0 << OrigTy << IsUnion << UseContext;
13165 // Reset OrigLoc so that this diagnostic is emitted only once.
13166 OrigLoc = SourceLocation();
13167 }
13168 InNonTrivialUnion = true;
13169 }
13170
13171 if (InNonTrivialUnion)
13172 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13173 << 0 << 0 << QT.getUnqualifiedType() << "";
13174
13175 for (const FieldDecl *FD : RD->fields())
13176 if (!shouldIgnoreForRecordTriviality(FD))
13177 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13178 }
13179
13180 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13181
13182 // The non-trivial C union type or the struct/union type that contains a
13183 // non-trivial C union.
13184 QualType OrigTy;
13185 SourceLocation OrigLoc;
13187 Sema &S;
13188};
13189
13190struct DiagNonTrivalCUnionDestructedTypeVisitor
13191 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13192 using Super =
13194
13195 DiagNonTrivalCUnionDestructedTypeVisitor(
13196 QualType OrigTy, SourceLocation OrigLoc,
13197 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13198 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13199
13200 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13201 const FieldDecl *FD, bool InNonTrivialUnion) {
13202 if (const auto *AT = S.Context.getAsArrayType(QT))
13203 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13204 InNonTrivialUnion);
13205 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13206 }
13207
13208 void visitARCStrong(QualType QT, const FieldDecl *FD,
13209 bool InNonTrivialUnion) {
13210 if (InNonTrivialUnion)
13211 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13212 << 1 << 1 << QT << FD->getName();
13213 }
13214
13215 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13216 if (InNonTrivialUnion)
13217 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13218 << 1 << 1 << QT << FD->getName();
13219 }
13220
13221 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13222 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13223 if (RD->isUnion()) {
13224 if (OrigLoc.isValid()) {
13225 bool IsUnion = false;
13226 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13227 IsUnion = OrigRD->isUnion();
13228 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13229 << 1 << OrigTy << IsUnion << UseContext;
13230 // Reset OrigLoc so that this diagnostic is emitted only once.
13231 OrigLoc = SourceLocation();
13232 }
13233 InNonTrivialUnion = true;
13234 }
13235
13236 if (InNonTrivialUnion)
13237 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13238 << 0 << 1 << QT.getUnqualifiedType() << "";
13239
13240 for (const FieldDecl *FD : RD->fields())
13241 if (!shouldIgnoreForRecordTriviality(FD))
13242 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13243 }
13244
13245 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13246 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13247 bool InNonTrivialUnion) {}
13248
13249 // The non-trivial C union type or the struct/union type that contains a
13250 // non-trivial C union.
13251 QualType OrigTy;
13252 SourceLocation OrigLoc;
13254 Sema &S;
13255};
13256
13257struct DiagNonTrivalCUnionCopyVisitor
13258 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13260
13261 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13263 Sema &S)
13264 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13265
13266 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13267 const FieldDecl *FD, bool InNonTrivialUnion) {
13268 if (const auto *AT = S.Context.getAsArrayType(QT))
13269 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13270 InNonTrivialUnion);
13271 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13272 }
13273
13274 void visitARCStrong(QualType QT, const FieldDecl *FD,
13275 bool InNonTrivialUnion) {
13276 if (InNonTrivialUnion)
13277 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13278 << 1 << 2 << QT << FD->getName();
13279 }
13280
13281 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13282 if (InNonTrivialUnion)
13283 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13284 << 1 << 2 << QT << FD->getName();
13285 }
13286
13287 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13288 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13289 if (RD->isUnion()) {
13290 if (OrigLoc.isValid()) {
13291 bool IsUnion = false;
13292 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13293 IsUnion = OrigRD->isUnion();
13294 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13295 << 2 << OrigTy << IsUnion << UseContext;
13296 // Reset OrigLoc so that this diagnostic is emitted only once.
13297 OrigLoc = SourceLocation();
13298 }
13299 InNonTrivialUnion = true;
13300 }
13301
13302 if (InNonTrivialUnion)
13303 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13304 << 0 << 2 << QT.getUnqualifiedType() << "";
13305
13306 for (const FieldDecl *FD : RD->fields())
13307 if (!shouldIgnoreForRecordTriviality(FD))
13308 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13309 }
13310
13311 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13312 const FieldDecl *FD, bool InNonTrivialUnion) {}
13313 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13314 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13315 bool InNonTrivialUnion) {}
13316
13317 // The non-trivial C union type or the struct/union type that contains a
13318 // non-trivial C union.
13319 QualType OrigTy;
13320 SourceLocation OrigLoc;
13322 Sema &S;
13323};
13324
13325} // namespace
13326
13328 NonTrivialCUnionContext UseContext,
13329 unsigned NonTrivialKind) {
13333 "shouldn't be called if type doesn't have a non-trivial C union");
13334
13335 if ((NonTrivialKind & NTCUK_Init) &&
13337 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13338 .visit(QT, nullptr, false);
13339 if ((NonTrivialKind & NTCUK_Destruct) &&
13341 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13342 .visit(QT, nullptr, false);
13343 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13344 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13345 .visit(QT, nullptr, false);
13346}
13347
13349 // If there is no declaration, there was an error parsing it. Just ignore
13350 // the initializer.
13351 if (!RealDecl) {
13352 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13353 return;
13354 }
13355
13356 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13357 if (!Method->isInvalidDecl()) {
13358 // Pure-specifiers are handled in ActOnPureSpecifier.
13359 Diag(Method->getLocation(), diag::err_member_function_initialization)
13360 << Method->getDeclName() << Init->getSourceRange();
13361 Method->setInvalidDecl();
13362 }
13363 return;
13364 }
13365
13366 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13367 if (!VDecl) {
13368 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13369 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13370 RealDecl->setInvalidDecl();
13371 return;
13372 }
13373
13374 if (VDecl->isInvalidDecl()) {
13376 SmallVector<Expr *> SubExprs;
13377 if (Res.isUsable())
13378 SubExprs.push_back(Res.get());
13379 ExprResult Recovery =
13380 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), SubExprs);
13381 if (Expr *E = Recovery.get())
13382 VDecl->setInit(E);
13383 return;
13384 }
13385
13386 // WebAssembly tables can't be used to initialise a variable.
13387 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13388 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13389 VDecl->setInvalidDecl();
13390 return;
13391 }
13392
13393 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13394 if (VDecl->getType()->isUndeducedType()) {
13395 // Attempt typo correction early so that the type of the init expression can
13396 // be deduced based on the chosen correction if the original init contains a
13397 // TypoExpr.
13399 if (!Res.isUsable()) {
13400 // There are unresolved typos in Init, just drop them.
13401 // FIXME: improve the recovery strategy to preserve the Init.
13402 RealDecl->setInvalidDecl();
13403 return;
13404 }
13405 if (Res.get()->containsErrors()) {
13406 // Invalidate the decl as we don't know the type for recovery-expr yet.
13407 RealDecl->setInvalidDecl();
13408 VDecl->setInit(Res.get());
13409 return;
13410 }
13411 Init = Res.get();
13412
13414 return;
13415 }
13416
13417 // dllimport cannot be used on variable definitions.
13418 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13419 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13420 VDecl->setInvalidDecl();
13421 return;
13422 }
13423
13424 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13425 // the identifier has external or internal linkage, the declaration shall
13426 // have no initializer for the identifier.
13427 // C++14 [dcl.init]p5 is the same restriction for C++.
13428 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13429 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13430 VDecl->setInvalidDecl();
13431 return;
13432 }
13433
13434 if (!VDecl->getType()->isDependentType()) {
13435 // A definition must end up with a complete type, which means it must be
13436 // complete with the restriction that an array type might be completed by
13437 // the initializer; note that later code assumes this restriction.
13438 QualType BaseDeclType = VDecl->getType();
13439 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13440 BaseDeclType = Array->getElementType();
13441 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13442 diag::err_typecheck_decl_incomplete_type)) {
13443 RealDecl->setInvalidDecl();
13444 return;
13445 }
13446
13447 // The variable can not have an abstract class type.
13448 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13449 diag::err_abstract_type_in_decl,
13451 VDecl->setInvalidDecl();
13452 }
13453
13454 // C++ [module.import/6] external definitions are not permitted in header
13455 // units.
13456 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13457 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13458 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13459 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13461 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13462 VDecl->setInvalidDecl();
13463 }
13464
13465 // If adding the initializer will turn this declaration into a definition,
13466 // and we already have a definition for this variable, diagnose or otherwise
13467 // handle the situation.
13468 if (VarDecl *Def = VDecl->getDefinition())
13469 if (Def != VDecl &&
13470 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13472 checkVarDeclRedefinition(Def, VDecl))
13473 return;
13474
13475 if (getLangOpts().CPlusPlus) {
13476 // C++ [class.static.data]p4
13477 // If a static data member is of const integral or const
13478 // enumeration type, its declaration in the class definition can
13479 // specify a constant-initializer which shall be an integral
13480 // constant expression (5.19). In that case, the member can appear
13481 // in integral constant expressions. The member shall still be
13482 // defined in a namespace scope if it is used in the program and the
13483 // namespace scope definition shall not contain an initializer.
13484 //
13485 // We already performed a redefinition check above, but for static
13486 // data members we also need to check whether there was an in-class
13487 // declaration with an initializer.
13488 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13489 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13490 << VDecl->getDeclName();
13491 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13492 diag::note_previous_initializer)
13493 << 0;
13494 return;
13495 }
13496
13497 if (VDecl->hasLocalStorage())
13499
13501 VDecl->setInvalidDecl();
13502 return;
13503 }
13504 }
13505
13506 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13507 // a kernel function cannot be initialized."
13508 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13509 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13510 VDecl->setInvalidDecl();
13511 return;
13512 }
13513
13514 // The LoaderUninitialized attribute acts as a definition (of undef).
13515 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13516 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13517 VDecl->setInvalidDecl();
13518 return;
13519 }
13520
13521 // Get the decls type and save a reference for later, since
13522 // CheckInitializerTypes may change it.
13523 QualType DclT = VDecl->getType(), SavT = DclT;
13524
13525 // Expressions default to 'id' when we're in a debugger
13526 // and we are assigning it to a variable of Objective-C pointer type.
13527 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13528 Init->getType() == Context.UnknownAnyTy) {
13530 if (!Result.isUsable()) {
13531 VDecl->setInvalidDecl();
13532 return;
13533 }
13534 Init = Result.get();
13535 }
13536
13537 // Perform the initialization.
13538 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13539 bool IsParenListInit = false;
13540 if (!VDecl->isInvalidDecl()) {
13543 VDecl->getLocation(), DirectInit, Init);
13544
13545 MultiExprArg Args = Init;
13546 if (CXXDirectInit)
13547 Args = MultiExprArg(CXXDirectInit->getExprs(),
13548 CXXDirectInit->getNumExprs());
13549
13550 // Try to correct any TypoExprs in the initialization arguments.
13551 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13553 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13554 [this, Entity, Kind](Expr *E) {
13555 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13556 return Init.Failed() ? ExprError() : E;
13557 });
13558 if (!Res.isUsable()) {
13559 VDecl->setInvalidDecl();
13560 } else if (Res.get() != Args[Idx]) {
13561 Args[Idx] = Res.get();
13562 }
13563 }
13564 if (VDecl->isInvalidDecl())
13565 return;
13566
13567 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13568 /*TopLevelOfInitList=*/false,
13569 /*TreatUnavailableAsInvalid=*/false);
13570 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13571 if (!Result.isUsable()) {
13572 // If the provided initializer fails to initialize the var decl,
13573 // we attach a recovery expr for better recovery.
13574 auto RecoveryExpr =
13575 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13576 if (RecoveryExpr.get())
13577 VDecl->setInit(RecoveryExpr.get());
13578 // In general, for error recovery purposes, the initializer doesn't play
13579 // part in the valid bit of the declaration. There are a few exceptions:
13580 // 1) if the var decl has a deduced auto type, and the type cannot be
13581 // deduced by an invalid initializer;
13582 // 2) if the var decl is a decomposition decl with a non-deduced type,
13583 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13584 // Case 1) was already handled elsewhere.
13585 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13586 VDecl->setInvalidDecl();
13587 return;
13588 }
13589
13590 Init = Result.getAs<Expr>();
13591 IsParenListInit = !InitSeq.steps().empty() &&
13592 InitSeq.step_begin()->Kind ==
13594 QualType VDeclType = VDecl->getType();
13595 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
13596 !VDeclType->isDependentType() &&
13597 Context.getAsIncompleteArrayType(VDeclType) &&
13599 // Bail out if it is not possible to deduce array size from the
13600 // initializer.
13601 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13602 << VDeclType;
13603 VDecl->setInvalidDecl();
13604 return;
13605 }
13606 }
13607
13608 // Check for self-references within variable initializers.
13609 // Variables declared within a function/method body (except for references)
13610 // are handled by a dataflow analysis.
13611 // This is undefined behavior in C++, but valid in C.
13612 if (getLangOpts().CPlusPlus)
13613 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13614 VDecl->getType()->isReferenceType())
13615 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13616
13617 // If the type changed, it means we had an incomplete type that was
13618 // completed by the initializer. For example:
13619 // int ary[] = { 1, 3, 5 };
13620 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13621 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13622 VDecl->setType(DclT);
13623
13624 if (!VDecl->isInvalidDecl()) {
13625 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13626
13627 if (VDecl->hasAttr<BlocksAttr>())
13628 ObjC().checkRetainCycles(VDecl, Init);
13629
13630 // It is safe to assign a weak reference into a strong variable.
13631 // Although this code can still have problems:
13632 // id x = self.weakProp;
13633 // id y = self.weakProp;
13634 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13635 // paths through the function. This should be revisited if
13636 // -Wrepeated-use-of-weak is made flow-sensitive.
13637 if (FunctionScopeInfo *FSI = getCurFunction())
13638 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13640 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13641 Init->getBeginLoc()))
13642 FSI->markSafeWeakUse(Init);
13643 }
13644
13645 // The initialization is usually a full-expression.
13646 //
13647 // FIXME: If this is a braced initialization of an aggregate, it is not
13648 // an expression, and each individual field initializer is a separate
13649 // full-expression. For instance, in:
13650 //
13651 // struct Temp { ~Temp(); };
13652 // struct S { S(Temp); };
13653 // struct T { S a, b; } t = { Temp(), Temp() }
13654 //
13655 // we should destroy the first Temp before constructing the second.
13658 /*DiscardedValue*/ false, VDecl->isConstexpr());
13659 if (!Result.isUsable()) {
13660 VDecl->setInvalidDecl();
13661 return;
13662 }
13663 Init = Result.get();
13664
13665 // Attach the initializer to the decl.
13666 VDecl->setInit(Init);
13667
13668 if (VDecl->isLocalVarDecl()) {
13669 // Don't check the initializer if the declaration is malformed.
13670 if (VDecl->isInvalidDecl()) {
13671 // do nothing
13672
13673 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13674 // This is true even in C++ for OpenCL.
13675 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13677
13678 // Otherwise, C++ does not restrict the initializer.
13679 } else if (getLangOpts().CPlusPlus) {
13680 // do nothing
13681
13682 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13683 // static storage duration shall be constant expressions or string literals.
13684 } else if (VDecl->getStorageClass() == SC_Static) {
13686
13687 // C89 is stricter than C99 for aggregate initializers.
13688 // C89 6.5.7p3: All the expressions [...] in an initializer list
13689 // for an object that has aggregate or union type shall be
13690 // constant expressions.
13691 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13692 isa<InitListExpr>(Init)) {
13693 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13694 }
13695
13696 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13697 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13698 if (VDecl->hasLocalStorage())
13699 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13700 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13701 VDecl->getLexicalDeclContext()->isRecord()) {
13702 // This is an in-class initialization for a static data member, e.g.,
13703 //
13704 // struct S {
13705 // static const int value = 17;
13706 // };
13707
13708 // C++ [class.mem]p4:
13709 // A member-declarator can contain a constant-initializer only
13710 // if it declares a static member (9.4) of const integral or
13711 // const enumeration type, see 9.4.2.
13712 //
13713 // C++11 [class.static.data]p3:
13714 // If a non-volatile non-inline const static data member is of integral
13715 // or enumeration type, its declaration in the class definition can
13716 // specify a brace-or-equal-initializer in which every initializer-clause
13717 // that is an assignment-expression is a constant expression. A static
13718 // data member of literal type can be declared in the class definition
13719 // with the constexpr specifier; if so, its declaration shall specify a
13720 // brace-or-equal-initializer in which every initializer-clause that is
13721 // an assignment-expression is a constant expression.
13722
13723 // Do nothing on dependent types.
13724 if (DclT->isDependentType()) {
13725
13726 // Allow any 'static constexpr' members, whether or not they are of literal
13727 // type. We separately check that every constexpr variable is of literal
13728 // type.
13729 } else if (VDecl->isConstexpr()) {
13730
13731 // Require constness.
13732 } else if (!DclT.isConstQualified()) {
13733 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13734 << Init->getSourceRange();
13735 VDecl->setInvalidDecl();
13736
13737 // We allow integer constant expressions in all cases.
13738 } else if (DclT->isIntegralOrEnumerationType()) {
13739 // Check whether the expression is a constant expression.
13742 // In C++11, a non-constexpr const static data member with an
13743 // in-class initializer cannot be volatile.
13744 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13745 else if (Init->isValueDependent())
13746 ; // Nothing to check.
13747 else if (Init->isIntegerConstantExpr(Context, &Loc))
13748 ; // Ok, it's an ICE!
13749 else if (Init->getType()->isScopedEnumeralType() &&
13750 Init->isCXX11ConstantExpr(Context))
13751 ; // Ok, it is a scoped-enum constant expression.
13752 else if (Init->isEvaluatable(Context)) {
13753 // If we can constant fold the initializer through heroics, accept it,
13754 // but report this as a use of an extension for -pedantic.
13755 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13756 << Init->getSourceRange();
13757 } else {
13758 // Otherwise, this is some crazy unknown case. Report the issue at the
13759 // location provided by the isIntegerConstantExpr failed check.
13760 Diag(Loc, diag::err_in_class_initializer_non_constant)
13761 << Init->getSourceRange();
13762 VDecl->setInvalidDecl();
13763 }
13764
13765 // We allow foldable floating-point constants as an extension.
13766 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13767 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13768 // it anyway and provide a fixit to add the 'constexpr'.
13769 if (getLangOpts().CPlusPlus11) {
13770 Diag(VDecl->getLocation(),
13771 diag::ext_in_class_initializer_float_type_cxx11)
13772 << DclT << Init->getSourceRange();
13773 Diag(VDecl->getBeginLoc(),
13774 diag::note_in_class_initializer_float_type_cxx11)
13775 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13776 } else {
13777 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13778 << DclT << Init->getSourceRange();
13779
13780 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13781 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13782 << Init->getSourceRange();
13783 VDecl->setInvalidDecl();
13784 }
13785 }
13786
13787 // Suggest adding 'constexpr' in C++11 for literal types.
13788 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13789 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13790 << DclT << Init->getSourceRange()
13791 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13792 VDecl->setConstexpr(true);
13793
13794 } else {
13795 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13796 << DclT << Init->getSourceRange();
13797 VDecl->setInvalidDecl();
13798 }
13799 } else if (VDecl->isFileVarDecl()) {
13800 // In C, extern is typically used to avoid tentative definitions when
13801 // declaring variables in headers, but adding an initializer makes it a
13802 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13803 // In C++, extern is often used to give implicitly static const variables
13804 // external linkage, so don't warn in that case. If selectany is present,
13805 // this might be header code intended for C and C++ inclusion, so apply the
13806 // C++ rules.
13807 if (VDecl->getStorageClass() == SC_Extern &&
13808 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13810 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13812 Diag(VDecl->getLocation(), diag::warn_extern_init);
13813
13814 // In Microsoft C++ mode, a const variable defined in namespace scope has
13815 // external linkage by default if the variable is declared with
13816 // __declspec(dllexport).
13819 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13820 VDecl->setStorageClass(SC_Extern);
13821
13822 // C99 6.7.8p4. All file scoped initializers need to be constant.
13823 // Avoid duplicate diagnostics for constexpr variables.
13824 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13825 !VDecl->isConstexpr())
13827 }
13828
13829 QualType InitType = Init->getType();
13830 if (!InitType.isNull() &&
13834
13835 // We will represent direct-initialization similarly to copy-initialization:
13836 // int x(1); -as-> int x = 1;
13837 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13838 //
13839 // Clients that want to distinguish between the two forms, can check for
13840 // direct initializer using VarDecl::getInitStyle().
13841 // A major benefit is that clients that don't particularly care about which
13842 // exactly form was it (like the CodeGen) can handle both cases without
13843 // special case code.
13844
13845 // C++ 8.5p11:
13846 // The form of initialization (using parentheses or '=') is generally
13847 // insignificant, but does matter when the entity being initialized has a
13848 // class type.
13849 if (CXXDirectInit) {
13850 assert(DirectInit && "Call-style initializer must be direct init.");
13851 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13853 } else if (DirectInit) {
13854 // This must be list-initialization. No other way is direct-initialization.
13856 }
13857
13858 if (LangOpts.OpenMP &&
13859 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13860 VDecl->isFileVarDecl())
13861 DeclsToCheckForDeferredDiags.insert(VDecl);
13863}
13864
13866 // Our main concern here is re-establishing invariants like "a
13867 // variable's type is either dependent or complete".
13868 if (!D || D->isInvalidDecl()) return;
13869
13870 VarDecl *VD = dyn_cast<VarDecl>(D);
13871 if (!VD) return;
13872
13873 // Bindings are not usable if we can't make sense of the initializer.
13874 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13875 for (auto *BD : DD->bindings())
13876 BD->setInvalidDecl();
13877
13878 // Auto types are meaningless if we can't make sense of the initializer.
13879 if (VD->getType()->isUndeducedType()) {
13880 D->setInvalidDecl();
13881 return;
13882 }
13883
13884 QualType Ty = VD->getType();
13885 if (Ty->isDependentType()) return;
13886
13887 // Require a complete type.
13890 diag::err_typecheck_decl_incomplete_type)) {
13891 VD->setInvalidDecl();
13892 return;
13893 }
13894
13895 // Require a non-abstract type.
13896 if (RequireNonAbstractType(VD->getLocation(), Ty,
13897 diag::err_abstract_type_in_decl,
13899 VD->setInvalidDecl();
13900 return;
13901 }
13902
13903 // Don't bother complaining about constructors or destructors,
13904 // though.
13905}
13906
13908 // If there is no declaration, there was an error parsing it. Just ignore it.
13909 if (!RealDecl)
13910 return;
13911
13912 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13913 QualType Type = Var->getType();
13914
13915 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13916 if (isa<DecompositionDecl>(RealDecl)) {
13917 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13918 Var->setInvalidDecl();
13919 return;
13920 }
13921
13922 if (Type->isUndeducedType() &&
13923 DeduceVariableDeclarationType(Var, false, nullptr))
13924 return;
13925
13926 // C++11 [class.static.data]p3: A static data member can be declared with
13927 // the constexpr specifier; if so, its declaration shall specify
13928 // a brace-or-equal-initializer.
13929 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13930 // the definition of a variable [...] or the declaration of a static data
13931 // member.
13932 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13933 !Var->isThisDeclarationADemotedDefinition()) {
13934 if (Var->isStaticDataMember()) {
13935 // C++1z removes the relevant rule; the in-class declaration is always
13936 // a definition there.
13937 if (!getLangOpts().CPlusPlus17 &&
13939 Diag(Var->getLocation(),
13940 diag::err_constexpr_static_mem_var_requires_init)
13941 << Var;
13942 Var->setInvalidDecl();
13943 return;
13944 }
13945 } else {
13946 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13947 Var->setInvalidDecl();
13948 return;
13949 }
13950 }
13951
13952 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13953 // be initialized.
13954 if (!Var->isInvalidDecl() &&
13955 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13956 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13957 bool HasConstExprDefaultConstructor = false;
13958 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13959 for (auto *Ctor : RD->ctors()) {
13960 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13961 Ctor->getMethodQualifiers().getAddressSpace() ==
13963 HasConstExprDefaultConstructor = true;
13964 }
13965 }
13966 }
13967 if (!HasConstExprDefaultConstructor) {
13968 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13969 Var->setInvalidDecl();
13970 return;
13971 }
13972 }
13973
13974 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13975 if (Var->getStorageClass() == SC_Extern) {
13976 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13977 << Var;
13978 Var->setInvalidDecl();
13979 return;
13980 }
13981 if (RequireCompleteType(Var->getLocation(), Var->getType(),
13982 diag::err_typecheck_decl_incomplete_type)) {
13983 Var->setInvalidDecl();
13984 return;
13985 }
13986 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13987 if (!RD->hasTrivialDefaultConstructor()) {
13988 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13989 Var->setInvalidDecl();
13990 return;
13991 }
13992 }
13993 // The declaration is uninitialized, no need for further checks.
13994 return;
13995 }
13996
13997 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13998 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13999 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14000 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14002
14003
14004 switch (DefKind) {
14006 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14007 break;
14008
14009 // We have an out-of-line definition of a static data member
14010 // that has an in-class initializer, so we type-check this like
14011 // a declaration.
14012 //
14013 [[fallthrough]];
14014
14016 // It's only a declaration.
14017
14018 // Block scope. C99 6.7p7: If an identifier for an object is
14019 // declared with no linkage (C99 6.2.2p6), the type for the
14020 // object shall be complete.
14021 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14022 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14023 RequireCompleteType(Var->getLocation(), Type,
14024 diag::err_typecheck_decl_incomplete_type))
14025 Var->setInvalidDecl();
14026
14027 // Make sure that the type is not abstract.
14028 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14029 RequireNonAbstractType(Var->getLocation(), Type,
14030 diag::err_abstract_type_in_decl,
14032 Var->setInvalidDecl();
14033 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14034 Var->getStorageClass() == SC_PrivateExtern) {
14035 Diag(Var->getLocation(), diag::warn_private_extern);
14036 Diag(Var->getLocation(), diag::note_private_extern);
14037 }
14038
14040 !Var->isInvalidDecl())
14041 ExternalDeclarations.push_back(Var);
14042
14043 return;
14044
14046 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14047 // object that has file scope without an initializer, and without a
14048 // storage-class specifier or with the storage-class specifier "static",
14049 // constitutes a tentative definition. Note: A tentative definition with
14050 // external linkage is valid (C99 6.2.2p5).
14051 if (!Var->isInvalidDecl()) {
14052 if (const IncompleteArrayType *ArrayT
14055 Var->getLocation(), ArrayT->getElementType(),
14056 diag::err_array_incomplete_or_sizeless_type))
14057 Var->setInvalidDecl();
14058 } else if (Var->getStorageClass() == SC_Static) {
14059 // C99 6.9.2p3: If the declaration of an identifier for an object is
14060 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14061 // declared type shall not be an incomplete type.
14062 // NOTE: code such as the following
14063 // static struct s;
14064 // struct s { int a; };
14065 // is accepted by gcc. Hence here we issue a warning instead of
14066 // an error and we do not invalidate the static declaration.
14067 // NOTE: to avoid multiple warnings, only check the first declaration.
14068 if (Var->isFirstDecl())
14069 RequireCompleteType(Var->getLocation(), Type,
14070 diag::ext_typecheck_decl_incomplete_type);
14071 }
14072 }
14073
14074 // Record the tentative definition; we're done.
14075 if (!Var->isInvalidDecl())
14077 return;
14078 }
14079
14080 // Provide a specific diagnostic for uninitialized variable
14081 // definitions with incomplete array type.
14082 if (Type->isIncompleteArrayType()) {
14083 if (Var->isConstexpr())
14084 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14085 << Var;
14086 else
14087 Diag(Var->getLocation(),
14088 diag::err_typecheck_incomplete_array_needs_initializer);
14089 Var->setInvalidDecl();
14090 return;
14091 }
14092
14093 // Provide a specific diagnostic for uninitialized variable
14094 // definitions with reference type.
14095 if (Type->isReferenceType()) {
14096 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14097 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14098 return;
14099 }
14100
14101 // Do not attempt to type-check the default initializer for a
14102 // variable with dependent type.
14103 if (Type->isDependentType())
14104 return;
14105
14106 if (Var->isInvalidDecl())
14107 return;
14108
14109 if (!Var->hasAttr<AliasAttr>()) {
14110 if (RequireCompleteType(Var->getLocation(),
14112 diag::err_typecheck_decl_incomplete_type)) {
14113 Var->setInvalidDecl();
14114 return;
14115 }
14116 } else {
14117 return;
14118 }
14119
14120 // The variable can not have an abstract class type.
14121 if (RequireNonAbstractType(Var->getLocation(), Type,
14122 diag::err_abstract_type_in_decl,
14124 Var->setInvalidDecl();
14125 return;
14126 }
14127
14128 // Check for jumps past the implicit initializer. C++0x
14129 // clarifies that this applies to a "variable with automatic
14130 // storage duration", not a "local variable".
14131 // C++11 [stmt.dcl]p3
14132 // A program that jumps from a point where a variable with automatic
14133 // storage duration is not in scope to a point where it is in scope is
14134 // ill-formed unless the variable has scalar type, class type with a
14135 // trivial default constructor and a trivial destructor, a cv-qualified
14136 // version of one of these types, or an array of one of the preceding
14137 // types and is declared without an initializer.
14138 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14139 if (const RecordType *Record
14141 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14142 // Mark the function (if we're in one) for further checking even if the
14143 // looser rules of C++11 do not require such checks, so that we can
14144 // diagnose incompatibilities with C++98.
14145 if (!CXXRecord->isPOD())
14147 }
14148 }
14149 // In OpenCL, we can't initialize objects in the __local address space,
14150 // even implicitly, so don't synthesize an implicit initializer.
14151 if (getLangOpts().OpenCL &&
14152 Var->getType().getAddressSpace() == LangAS::opencl_local)
14153 return;
14154 // C++03 [dcl.init]p9:
14155 // If no initializer is specified for an object, and the
14156 // object is of (possibly cv-qualified) non-POD class type (or
14157 // array thereof), the object shall be default-initialized; if
14158 // the object is of const-qualified type, the underlying class
14159 // type shall have a user-declared default
14160 // constructor. Otherwise, if no initializer is specified for
14161 // a non- static object, the object and its subobjects, if
14162 // any, have an indeterminate initial value); if the object
14163 // or any of its subobjects are of const-qualified type, the
14164 // program is ill-formed.
14165 // C++0x [dcl.init]p11:
14166 // If no initializer is specified for an object, the object is
14167 // default-initialized; [...].
14170 = InitializationKind::CreateDefault(Var->getLocation());
14171
14172 InitializationSequence InitSeq(*this, Entity, Kind, {});
14173 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14174
14175 if (Init.get()) {
14176 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14177 // This is important for template substitution.
14178 Var->setInitStyle(VarDecl::CallInit);
14179 } else if (Init.isInvalid()) {
14180 // If default-init fails, attach a recovery-expr initializer to track
14181 // that initialization was attempted and failed.
14182 auto RecoveryExpr =
14183 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14184 if (RecoveryExpr.get())
14185 Var->setInit(RecoveryExpr.get());
14186 }
14187
14189 }
14190}
14191
14193 // If there is no declaration, there was an error parsing it. Ignore it.
14194 if (!D)
14195 return;
14196
14197 VarDecl *VD = dyn_cast<VarDecl>(D);
14198 if (!VD) {
14199 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14200 D->setInvalidDecl();
14201 return;
14202 }
14203
14204 VD->setCXXForRangeDecl(true);
14205
14206 // for-range-declaration cannot be given a storage class specifier.
14207 int Error = -1;
14208 switch (VD->getStorageClass()) {
14209 case SC_None:
14210 break;
14211 case SC_Extern:
14212 Error = 0;
14213 break;
14214 case SC_Static:
14215 Error = 1;
14216 break;
14217 case SC_PrivateExtern:
14218 Error = 2;
14219 break;
14220 case SC_Auto:
14221 Error = 3;
14222 break;
14223 case SC_Register:
14224 Error = 4;
14225 break;
14226 }
14227
14228 // for-range-declaration cannot be given a storage class specifier con't.
14229 switch (VD->getTSCSpec()) {
14230 case TSCS_thread_local:
14231 Error = 6;
14232 break;
14233 case TSCS___thread:
14234 case TSCS__Thread_local:
14235 case TSCS_unspecified:
14236 break;
14237 }
14238
14239 if (Error != -1) {
14240 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14241 << VD << Error;
14242 D->setInvalidDecl();
14243 }
14244}
14245
14247 IdentifierInfo *Ident,
14248 ParsedAttributes &Attrs) {
14249 // C++1y [stmt.iter]p1:
14250 // A range-based for statement of the form
14251 // for ( for-range-identifier : for-range-initializer ) statement
14252 // is equivalent to
14253 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14254 DeclSpec DS(Attrs.getPool().getFactory());
14255
14256 const char *PrevSpec;
14257 unsigned DiagID;
14258 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14260
14262 D.SetIdentifier(Ident, IdentLoc);
14263 D.takeAttributes(Attrs);
14264
14265 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14266 IdentLoc);
14267 Decl *Var = ActOnDeclarator(S, D);
14268 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14270 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14271 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14272 : IdentLoc);
14273}
14274
14276 if (var->isInvalidDecl()) return;
14277
14279
14280 if (getLangOpts().OpenCL) {
14281 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14282 // initialiser
14283 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14284 !var->hasInit()) {
14285 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14286 << 1 /*Init*/;
14287 var->setInvalidDecl();
14288 return;
14289 }
14290 }
14291
14292 // In Objective-C, don't allow jumps past the implicit initialization of a
14293 // local retaining variable.
14294 if (getLangOpts().ObjC &&
14295 var->hasLocalStorage()) {
14296 switch (var->getType().getObjCLifetime()) {
14300 break;
14301
14305 break;
14306 }
14307 }
14308
14309 if (var->hasLocalStorage() &&
14310 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14312
14313 // Warn about externally-visible variables being defined without a
14314 // prior declaration. We only want to do this for global
14315 // declarations, but we also specifically need to avoid doing it for
14316 // class members because the linkage of an anonymous class can
14317 // change if it's later given a typedef name.
14318 if (var->isThisDeclarationADefinition() &&
14319 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14320 var->isExternallyVisible() && var->hasLinkage() &&
14321 !var->isInline() && !var->getDescribedVarTemplate() &&
14322 var->getStorageClass() != SC_Register &&
14323 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14324 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14325 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14326 var->getLocation())) {
14327 // Find a previous declaration that's not a definition.
14328 VarDecl *prev = var->getPreviousDecl();
14329 while (prev && prev->isThisDeclarationADefinition())
14330 prev = prev->getPreviousDecl();
14331
14332 if (!prev) {
14333 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14334 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14335 << /* variable */ 0;
14336 }
14337 }
14338
14339 // Cache the result of checking for constant initialization.
14340 std::optional<bool> CacheHasConstInit;
14341 const Expr *CacheCulprit = nullptr;
14342 auto checkConstInit = [&]() mutable {
14343 if (!CacheHasConstInit)
14344 CacheHasConstInit = var->getInit()->isConstantInitializer(
14345 Context, var->getType()->isReferenceType(), &CacheCulprit);
14346 return *CacheHasConstInit;
14347 };
14348
14349 if (var->getTLSKind() == VarDecl::TLS_Static) {
14350 if (var->getType().isDestructedType()) {
14351 // GNU C++98 edits for __thread, [basic.start.term]p3:
14352 // The type of an object with thread storage duration shall not
14353 // have a non-trivial destructor.
14354 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14356 Diag(var->getLocation(), diag::note_use_thread_local);
14357 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14358 if (!checkConstInit()) {
14359 // GNU C++98 edits for __thread, [basic.start.init]p4:
14360 // An object of thread storage duration shall not require dynamic
14361 // initialization.
14362 // FIXME: Need strict checking here.
14363 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14364 << CacheCulprit->getSourceRange();
14366 Diag(var->getLocation(), diag::note_use_thread_local);
14367 }
14368 }
14369 }
14370
14371
14372 if (!var->getType()->isStructureType() && var->hasInit() &&
14373 isa<InitListExpr>(var->getInit())) {
14374 const auto *ILE = cast<InitListExpr>(var->getInit());
14375 unsigned NumInits = ILE->getNumInits();
14376 if (NumInits > 2)
14377 for (unsigned I = 0; I < NumInits; ++I) {
14378 const auto *Init = ILE->getInit(I);
14379 if (!Init)
14380 break;
14381 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14382 if (!SL)
14383 break;
14384
14385 unsigned NumConcat = SL->getNumConcatenated();
14386 // Diagnose missing comma in string array initialization.
14387 // Do not warn when all the elements in the initializer are concatenated
14388 // together. Do not warn for macros too.
14389 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14390 bool OnlyOneMissingComma = true;
14391 for (unsigned J = I + 1; J < NumInits; ++J) {
14392 const auto *Init = ILE->getInit(J);
14393 if (!Init)
14394 break;
14395 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14396 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14397 OnlyOneMissingComma = false;
14398 break;
14399 }
14400 }
14401
14402 if (OnlyOneMissingComma) {
14404 for (unsigned i = 0; i < NumConcat - 1; ++i)
14405 Hints.push_back(FixItHint::CreateInsertion(
14406 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14407
14408 Diag(SL->getStrTokenLoc(1),
14409 diag::warn_concatenated_literal_array_init)
14410 << Hints;
14411 Diag(SL->getBeginLoc(),
14412 diag::note_concatenated_string_literal_silence);
14413 }
14414 // In any case, stop now.
14415 break;
14416 }
14417 }
14418 }
14419
14420
14421 QualType type = var->getType();
14422
14423 if (var->hasAttr<BlocksAttr>())
14425
14426 Expr *Init = var->getInit();
14427 bool GlobalStorage = var->hasGlobalStorage();
14428 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14430 bool HasConstInit = true;
14431
14432 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14433 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14434 << var;
14435
14436 // Check whether the initializer is sufficiently constant.
14437 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14438 !type->isDependentType() && Init && !Init->isValueDependent() &&
14439 (GlobalStorage || var->isConstexpr() ||
14440 var->mightBeUsableInConstantExpressions(Context))) {
14441 // If this variable might have a constant initializer or might be usable in
14442 // constant expressions, check whether or not it actually is now. We can't
14443 // do this lazily, because the result might depend on things that change
14444 // later, such as which constexpr functions happen to be defined.
14446 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14447 // Prior to C++11, in contexts where a constant initializer is required,
14448 // the set of valid constant initializers is described by syntactic rules
14449 // in [expr.const]p2-6.
14450 // FIXME: Stricter checking for these rules would be useful for constinit /
14451 // -Wglobal-constructors.
14452 HasConstInit = checkConstInit();
14453
14454 // Compute and cache the constant value, and remember that we have a
14455 // constant initializer.
14456 if (HasConstInit) {
14457 (void)var->checkForConstantInitialization(Notes);
14458 Notes.clear();
14459 } else if (CacheCulprit) {
14460 Notes.emplace_back(CacheCulprit->getExprLoc(),
14461 PDiag(diag::note_invalid_subexpr_in_const_expr));
14462 Notes.back().second << CacheCulprit->getSourceRange();
14463 }
14464 } else {
14465 // Evaluate the initializer to see if it's a constant initializer.
14466 HasConstInit = var->checkForConstantInitialization(Notes);
14467 }
14468
14469 if (HasConstInit) {
14470 // FIXME: Consider replacing the initializer with a ConstantExpr.
14471 } else if (var->isConstexpr()) {
14472 SourceLocation DiagLoc = var->getLocation();
14473 // If the note doesn't add any useful information other than a source
14474 // location, fold it into the primary diagnostic.
14475 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14476 diag::note_invalid_subexpr_in_const_expr) {
14477 DiagLoc = Notes[0].first;
14478 Notes.clear();
14479 }
14480 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14481 << var << Init->getSourceRange();
14482 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14483 Diag(Notes[I].first, Notes[I].second);
14484 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14485 auto *Attr = var->getAttr<ConstInitAttr>();
14486 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14487 << Init->getSourceRange();
14488 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14489 << Attr->getRange() << Attr->isConstinit();
14490 for (auto &it : Notes)
14491 Diag(it.first, it.second);
14492 } else if (IsGlobal &&
14493 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14494 var->getLocation())) {
14495 // Warn about globals which don't have a constant initializer. Don't
14496 // warn about globals with a non-trivial destructor because we already
14497 // warned about them.
14498 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14499 if (!(RD && !RD->hasTrivialDestructor())) {
14500 // checkConstInit() here permits trivial default initialization even in
14501 // C++11 onwards, where such an initializer is not a constant initializer
14502 // but nonetheless doesn't require a global constructor.
14503 if (!checkConstInit())
14504 Diag(var->getLocation(), diag::warn_global_constructor)
14505 << Init->getSourceRange();
14506 }
14507 }
14508 }
14509
14510 // Apply section attributes and pragmas to global variables.
14511 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14513 PragmaStack<StringLiteral *> *Stack = nullptr;
14514 int SectionFlags = ASTContext::PSF_Read;
14515 bool MSVCEnv =
14516 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14517 std::optional<QualType::NonConstantStorageReason> Reason;
14518 if (HasConstInit &&
14519 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14520 Stack = &ConstSegStack;
14521 } else {
14522 SectionFlags |= ASTContext::PSF_Write;
14523 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14524 }
14525 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14526 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14527 SectionFlags |= ASTContext::PSF_Implicit;
14528 UnifySection(SA->getName(), SectionFlags, var);
14529 } else if (Stack->CurrentValue) {
14530 if (Stack != &ConstSegStack && MSVCEnv &&
14531 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14532 var->getType().isConstQualified()) {
14533 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14534 NonConstNonReferenceType) &&
14535 "This case should've already been handled elsewhere");
14536 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14537 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14539 : *Reason);
14540 }
14541 SectionFlags |= ASTContext::PSF_Implicit;
14542 auto SectionName = Stack->CurrentValue->getString();
14543 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14544 Stack->CurrentPragmaLocation,
14545 SectionAttr::Declspec_allocate));
14546 if (UnifySection(SectionName, SectionFlags, var))
14547 var->dropAttr<SectionAttr>();
14548 }
14549
14550 // Apply the init_seg attribute if this has an initializer. If the
14551 // initializer turns out to not be dynamic, we'll end up ignoring this
14552 // attribute.
14553 if (CurInitSeg && var->getInit())
14554 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14555 CurInitSegLoc));
14556 }
14557
14558 // All the following checks are C++ only.
14559 if (!getLangOpts().CPlusPlus) {
14560 // If this variable must be emitted, add it as an initializer for the
14561 // current module.
14562 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14563 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14564 return;
14565 }
14566
14567 // Require the destructor.
14568 if (!type->isDependentType())
14569 if (const RecordType *recordType = baseType->getAs<RecordType>())
14571
14572 // If this variable must be emitted, add it as an initializer for the current
14573 // module.
14574 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14575 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14576
14577 // Build the bindings if this is a structured binding declaration.
14578 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14580}
14581
14583 assert(VD->isStaticLocal());
14584
14585 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14586
14587 // Find outermost function when VD is in lambda function.
14588 while (FD && !getDLLAttr(FD) &&
14589 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14590 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14591 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14592 }
14593
14594 if (!FD)
14595 return;
14596
14597 // Static locals inherit dll attributes from their function.
14598 if (Attr *A = getDLLAttr(FD)) {
14599 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14600 NewAttr->setInherited(true);
14601 VD->addAttr(NewAttr);
14602 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14603 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14604 NewAttr->setInherited(true);
14605 VD->addAttr(NewAttr);
14606
14607 // Export this function to enforce exporting this static variable even
14608 // if it is not used in this compilation unit.
14609 if (!FD->hasAttr<DLLExportAttr>())
14610 FD->addAttr(NewAttr);
14611
14612 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14613 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14614 NewAttr->setInherited(true);
14615 VD->addAttr(NewAttr);
14616 }
14617}
14618
14620 assert(VD->getTLSKind());
14621
14622 // Perform TLS alignment check here after attributes attached to the variable
14623 // which may affect the alignment have been processed. Only perform the check
14624 // if the target has a maximum TLS alignment (zero means no constraints).
14625 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14626 // Protect the check so that it's not performed on dependent types and
14627 // dependent alignments (we can't determine the alignment in that case).
14628 if (!VD->hasDependentAlignment()) {
14629 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14630 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14631 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14633 << (unsigned)MaxAlignChars.getQuantity();
14634 }
14635 }
14636 }
14637}
14638
14640 // Note that we are no longer parsing the initializer for this declaration.
14641 ParsingInitForAutoVars.erase(ThisDecl);
14642
14643 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14644 if (!VD)
14645 return;
14646
14647 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14649 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14651 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14655 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14659 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14663 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14666 }
14667
14668 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14669 for (auto *BD : DD->bindings()) {
14671 }
14672 }
14673
14674 CheckInvalidBuiltinCountedByRef(VD->getInit(), InitializerKind);
14675
14676 checkAttributesAfterMerging(*this, *VD);
14677
14678 if (VD->isStaticLocal())
14680
14681 if (VD->getTLSKind())
14683
14684 // Perform check for initializers of device-side global variables.
14685 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14686 // 7.5). We must also apply the same checks to all __shared__
14687 // variables whether they are local or not. CUDA also allows
14688 // constant initializers for __constant__ and __device__ variables.
14689 if (getLangOpts().CUDA)
14691
14692 // Grab the dllimport or dllexport attribute off of the VarDecl.
14693 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14694
14695 // Imported static data members cannot be defined out-of-line.
14696 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14697 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14699 // We allow definitions of dllimport class template static data members
14700 // with a warning.
14702 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14703 bool IsClassTemplateMember =
14704 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14705 Context->getDescribedClassTemplate();
14706
14707 Diag(VD->getLocation(),
14708 IsClassTemplateMember
14709 ? diag::warn_attribute_dllimport_static_field_definition
14710 : diag::err_attribute_dllimport_static_field_definition);
14711 Diag(IA->getLocation(), diag::note_attribute);
14712 if (!IsClassTemplateMember)
14713 VD->setInvalidDecl();
14714 }
14715 }
14716
14717 // dllimport/dllexport variables cannot be thread local, their TLS index
14718 // isn't exported with the variable.
14719 if (DLLAttr && VD->getTLSKind()) {
14720 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14721 if (F && getDLLAttr(F)) {
14722 assert(VD->isStaticLocal());
14723 // But if this is a static local in a dlimport/dllexport function, the
14724 // function will never be inlined, which means the var would never be
14725 // imported, so having it marked import/export is safe.
14726 } else {
14727 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14728 << DLLAttr;
14729 VD->setInvalidDecl();
14730 }
14731 }
14732
14733 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14734 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14735 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14736 << Attr;
14737 VD->dropAttr<UsedAttr>();
14738 }
14739 }
14740 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14741 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14742 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14743 << Attr;
14744 VD->dropAttr<RetainAttr>();
14745 }
14746 }
14747
14748 const DeclContext *DC = VD->getDeclContext();
14749 // If there's a #pragma GCC visibility in scope, and this isn't a class
14750 // member, set the visibility of this variable.
14753
14754 // FIXME: Warn on unused var template partial specializations.
14755 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14757
14758 // Now we have parsed the initializer and can update the table of magic
14759 // tag values.
14760 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14762 return;
14763
14764 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14765 const Expr *MagicValueExpr = VD->getInit();
14766 if (!MagicValueExpr) {
14767 continue;
14768 }
14769 std::optional<llvm::APSInt> MagicValueInt;
14770 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14771 Diag(I->getRange().getBegin(),
14772 diag::err_type_tag_for_datatype_not_ice)
14773 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14774 continue;
14775 }
14776 if (MagicValueInt->getActiveBits() > 64) {
14777 Diag(I->getRange().getBegin(),
14778 diag::err_type_tag_for_datatype_too_large)
14779 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14780 continue;
14781 }
14782 uint64_t MagicValue = MagicValueInt->getZExtValue();
14783 RegisterTypeTagForDatatype(I->getArgumentKind(),
14784 MagicValue,
14785 I->getMatchingCType(),
14786 I->getLayoutCompatible(),
14787 I->getMustBeNull());
14788 }
14789}
14790
14792 auto *VD = dyn_cast<VarDecl>(DD);
14793 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14794}
14795
14797 ArrayRef<Decl *> Group) {
14799
14800 if (DS.isTypeSpecOwned())
14801 Decls.push_back(DS.getRepAsDecl());
14802
14803 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14804 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14805 bool DiagnosedMultipleDecomps = false;
14806 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14807 bool DiagnosedNonDeducedAuto = false;
14808
14809 for (Decl *D : Group) {
14810 if (!D)
14811 continue;
14812 // Check if the Decl has been declared in '#pragma omp declare target'
14813 // directive and has static storage duration.
14814 if (auto *VD = dyn_cast<VarDecl>(D);
14815 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14816 VD->hasGlobalStorage())
14818 // For declarators, there are some additional syntactic-ish checks we need
14819 // to perform.
14820 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14821 if (!FirstDeclaratorInGroup)
14822 FirstDeclaratorInGroup = DD;
14823 if (!FirstDecompDeclaratorInGroup)
14824 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14825 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14826 !hasDeducedAuto(DD))
14827 FirstNonDeducedAutoInGroup = DD;
14828
14829 if (FirstDeclaratorInGroup != DD) {
14830 // A decomposition declaration cannot be combined with any other
14831 // declaration in the same group.
14832 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14833 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14834 diag::err_decomp_decl_not_alone)
14835 << FirstDeclaratorInGroup->getSourceRange()
14836 << DD->getSourceRange();
14837 DiagnosedMultipleDecomps = true;
14838 }
14839
14840 // A declarator that uses 'auto' in any way other than to declare a
14841 // variable with a deduced type cannot be combined with any other
14842 // declarator in the same group.
14843 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14844 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14845 diag::err_auto_non_deduced_not_alone)
14846 << FirstNonDeducedAutoInGroup->getType()
14848 << FirstDeclaratorInGroup->getSourceRange()
14849 << DD->getSourceRange();
14850 DiagnosedNonDeducedAuto = true;
14851 }
14852 }
14853 }
14854
14855 Decls.push_back(D);
14856 }
14857
14859 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14860 handleTagNumbering(Tag, S);
14861 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14863 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14864 }
14865 }
14866
14867 return BuildDeclaratorGroup(Decls);
14868}
14869
14872 // C++14 [dcl.spec.auto]p7: (DR1347)
14873 // If the type that replaces the placeholder type is not the same in each
14874 // deduction, the program is ill-formed.
14875 if (Group.size() > 1) {
14876 QualType Deduced;
14877 VarDecl *DeducedDecl = nullptr;
14878 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14879 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14880 if (!D || D->isInvalidDecl())
14881 break;
14882 DeducedType *DT = D->getType()->getContainedDeducedType();
14883 if (!DT || DT->getDeducedType().isNull())
14884 continue;
14885 if (Deduced.isNull()) {
14886 Deduced = DT->getDeducedType();
14887 DeducedDecl = D;
14888 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14889 auto *AT = dyn_cast<AutoType>(DT);
14890 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14891 diag::err_auto_different_deductions)
14892 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14893 << DeducedDecl->getDeclName() << DT->getDeducedType()
14894 << D->getDeclName();
14895 if (DeducedDecl->hasInit())
14896 Dia << DeducedDecl->getInit()->getSourceRange();
14897 if (D->getInit())
14898 Dia << D->getInit()->getSourceRange();
14899 D->setInvalidDecl();
14900 break;
14901 }
14902 }
14903 }
14904
14906
14907 return DeclGroupPtrTy::make(
14908 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14909}
14910
14913}
14914
14916 // Don't parse the comment if Doxygen diagnostics are ignored.
14917 if (Group.empty() || !Group[0])
14918 return;
14919
14920 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14921 Group[0]->getLocation()) &&
14922 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14923 Group[0]->getLocation()))
14924 return;
14925
14926 if (Group.size() >= 2) {
14927 // This is a decl group. Normally it will contain only declarations
14928 // produced from declarator list. But in case we have any definitions or
14929 // additional declaration references:
14930 // 'typedef struct S {} S;'
14931 // 'typedef struct S *S;'
14932 // 'struct S *pS;'
14933 // FinalizeDeclaratorGroup adds these as separate declarations.
14934 Decl *MaybeTagDecl = Group[0];
14935 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14936 Group = Group.slice(1);
14937 }
14938 }
14939
14940 // FIMXE: We assume every Decl in the group is in the same file.
14941 // This is false when preprocessor constructs the group from decls in
14942 // different files (e. g. macros or #include).
14944}
14945
14947 // Check that there are no default arguments inside the type of this
14948 // parameter.
14949 if (getLangOpts().CPlusPlus)
14951
14952 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14953 if (D.getCXXScopeSpec().isSet()) {
14954 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14955 << D.getCXXScopeSpec().getRange();
14956 }
14957
14958 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14959 // simple identifier except [...irrelevant cases...].
14960 switch (D.getName().getKind()) {
14962 break;
14963
14971 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14973 break;
14974
14977 // GetNameForDeclarator would not produce a useful name in this case.
14978 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14979 break;
14980 }
14981}
14982
14984 SourceLocation ExplicitThisLoc) {
14985 if (!ExplicitThisLoc.isValid())
14986 return;
14987 assert(S.getLangOpts().CPlusPlus &&
14988 "explicit parameter in non-cplusplus mode");
14989 if (!S.getLangOpts().CPlusPlus23)
14990 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
14991 << P->getSourceRange();
14992
14993 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
14994 // parameter pack.
14995 if (P->isParameterPack()) {
14996 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
14997 << P->getSourceRange();
14998 return;
14999 }
15000 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15001 if (LambdaScopeInfo *LSI = S.getCurLambda())
15002 LSI->ExplicitObjectParameter = P;
15003}
15004
15006 SourceLocation ExplicitThisLoc) {
15007 const DeclSpec &DS = D.getDeclSpec();
15008
15009 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15010 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15011 // except for the special case of a single unnamed parameter of type void
15012 // with no storage class specifier, no type qualifier, and no following
15013 // ellipsis terminator.
15014 // Clang applies the C2y rules for 'register void' in all C language modes,
15015 // same as GCC, because it's questionable what that could possibly mean.
15016
15017 // C++03 [dcl.stc]p2 also permits 'auto'.
15018 StorageClass SC = SC_None;
15020 SC = SC_Register;
15021 // In C++11, the 'register' storage class specifier is deprecated.
15022 // In C++17, it is not allowed, but we tolerate it as an extension.
15023 if (getLangOpts().CPlusPlus11) {
15025 ? diag::ext_register_storage_class
15026 : diag::warn_deprecated_register)
15028 } else if (!getLangOpts().CPlusPlus &&
15030 D.getNumTypeObjects() == 0) {
15032 diag::err_invalid_storage_class_in_func_decl)
15034 D.getMutableDeclSpec().ClearStorageClassSpecs();
15035 }
15036 } else if (getLangOpts().CPlusPlus &&
15038 SC = SC_Auto;
15041 diag::err_invalid_storage_class_in_func_decl);
15042 D.getMutableDeclSpec().ClearStorageClassSpecs();
15043 }
15044
15046 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15048 if (DS.isInlineSpecified())
15049 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15050 << getLangOpts().CPlusPlus17;
15051 if (DS.hasConstexprSpecifier())
15052 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15053 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15054
15056
15058
15060 QualType parmDeclType = TInfo->getType();
15061
15062 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15063 const IdentifierInfo *II = D.getIdentifier();
15064 if (II) {
15065 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15066 RedeclarationKind::ForVisibleRedeclaration);
15067 LookupName(R, S);
15068 if (!R.empty()) {
15069 NamedDecl *PrevDecl = *R.begin();
15070 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15071 // Maybe we will complain about the shadowed template parameter.
15072 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15073 // Just pretend that we didn't see the previous declaration.
15074 PrevDecl = nullptr;
15075 }
15076 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15077 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15078 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15079 // Recover by removing the name
15080 II = nullptr;
15081 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15082 D.setInvalidType(true);
15083 }
15084 }
15085 }
15086
15087 // Temporarily put parameter variables in the translation unit, not
15088 // the enclosing context. This prevents them from accidentally
15089 // looking like class members in C++.
15090 ParmVarDecl *New =
15092 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15093
15094 if (D.isInvalidType())
15095 New->setInvalidDecl();
15096
15097 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15098
15099 assert(S->isFunctionPrototypeScope());
15100 assert(S->getFunctionPrototypeDepth() >= 1);
15101 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15102 S->getNextFunctionPrototypeIndex());
15103
15104 // Add the parameter declaration into this scope.
15105 S->AddDecl(New);
15106 if (II)
15107 IdResolver.AddDecl(New);
15108
15109 ProcessDeclAttributes(S, New, D);
15110
15111 if (D.getDeclSpec().isModulePrivateSpecified())
15112 Diag(New->getLocation(), diag::err_module_private_local)
15113 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15114 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15115
15116 if (New->hasAttr<BlocksAttr>()) {
15117 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15118 }
15119
15120 if (getLangOpts().OpenCL)
15122
15123 return New;
15124}
15125
15128 QualType T) {
15129 /* FIXME: setting StartLoc == Loc.
15130 Would it be worth to modify callers so as to provide proper source
15131 location for the unnamed parameters, embedding the parameter's type? */
15132 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15134 SC_None, nullptr);
15135 Param->setImplicit();
15136 return Param;
15137}
15138
15140 // Don't diagnose unused-parameter errors in template instantiations; we
15141 // will already have done so in the template itself.
15143 return;
15144
15145 for (const ParmVarDecl *Parameter : Parameters) {
15146 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15147 !Parameter->hasAttr<UnusedAttr>() &&
15148 !Parameter->getIdentifier()->isPlaceholder()) {
15149 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15150 << Parameter->getDeclName();
15151 }
15152 }
15153}
15154
15156 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15157 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15158 return;
15159
15160 // Warn if the return value is pass-by-value and larger than the specified
15161 // threshold.
15162 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15163 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15164 if (Size > LangOpts.NumLargeByValueCopy)
15165 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15166 }
15167
15168 // Warn if any parameter is pass-by-value and larger than the specified
15169 // threshold.
15170 for (const ParmVarDecl *Parameter : Parameters) {
15171 QualType T = Parameter->getType();
15172 if (T->isDependentType() || !T.isPODType(Context))
15173 continue;
15174 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15175 if (Size > LangOpts.NumLargeByValueCopy)
15176 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15177 << Parameter << Size;
15178 }
15179}
15180
15182 SourceLocation NameLoc,
15183 const IdentifierInfo *Name, QualType T,
15184 TypeSourceInfo *TSInfo, StorageClass SC) {
15185 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15186 if (getLangOpts().ObjCAutoRefCount &&
15187 T.getObjCLifetime() == Qualifiers::OCL_None &&
15188 T->isObjCLifetimeType()) {
15189
15190 Qualifiers::ObjCLifetime lifetime;
15191
15192 // Special cases for arrays:
15193 // - if it's const, use __unsafe_unretained
15194 // - otherwise, it's an error
15195 if (T->isArrayType()) {
15196 if (!T.isConstQualified()) {
15200 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15201 else
15202 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15203 << TSInfo->getTypeLoc().getSourceRange();
15204 }
15206 } else {
15207 lifetime = T->getObjCARCImplicitLifetime();
15208 }
15209 T = Context.getLifetimeQualifiedType(T, lifetime);
15210 }
15211
15212 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15214 TSInfo, SC, nullptr);
15215
15216 // Make a note if we created a new pack in the scope of a lambda, so that
15217 // we know that references to that pack must also be expanded within the
15218 // lambda scope.
15219 if (New->isParameterPack())
15220 if (auto *CSI = getEnclosingLambdaOrBlock())
15221 CSI->LocalPacks.push_back(New);
15222
15227
15228 // Parameter declarators cannot be interface types. All ObjC objects are
15229 // passed by reference.
15230 if (T->isObjCObjectType()) {
15231 SourceLocation TypeEndLoc =
15233 Diag(NameLoc,
15234 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15235 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15237 New->setType(T);
15238 }
15239
15240 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15241 // duration shall not be qualified by an address-space qualifier."
15242 // Since all parameters have automatic store duration, they can not have
15243 // an address space.
15244 if (T.getAddressSpace() != LangAS::Default &&
15245 // OpenCL allows function arguments declared to be an array of a type
15246 // to be qualified with an address space.
15247 !(getLangOpts().OpenCL &&
15248 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15249 // WebAssembly allows reference types as parameters. Funcref in particular
15250 // lives in a different address space.
15251 !(T->isFunctionPointerType() &&
15252 T.getAddressSpace() == LangAS::wasm_funcref)) {
15253 Diag(NameLoc, diag::err_arg_with_address_space);
15254 New->setInvalidDecl();
15255 }
15256
15257 // PPC MMA non-pointer types are not allowed as function argument types.
15258 if (Context.getTargetInfo().getTriple().isPPC64() &&
15259 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15260 New->setInvalidDecl();
15261 }
15262
15263 return New;
15264}
15265
15267 SourceLocation LocAfterDecls) {
15268 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15269
15270 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15271 // in the declaration list shall have at least one declarator, those
15272 // declarators shall only declare identifiers from the identifier list, and
15273 // every identifier in the identifier list shall be declared.
15274 //
15275 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15276 // identifiers it names shall be declared in the declaration list."
15277 //
15278 // This is why we only diagnose in C99 and later. Note, the other conditions
15279 // listed are checked elsewhere.
15280 if (!FTI.hasPrototype) {
15281 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15282 --i;
15283 if (FTI.Params[i].Param == nullptr) {
15284 if (getLangOpts().C99) {
15285 SmallString<256> Code;
15286 llvm::raw_svector_ostream(Code)
15287 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15288 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15289 << FTI.Params[i].Ident
15290 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15291 }
15292
15293 // Implicitly declare the argument as type 'int' for lack of a better
15294 // type.
15295 AttributeFactory attrs;
15296 DeclSpec DS(attrs);
15297 const char* PrevSpec; // unused
15298 unsigned DiagID; // unused
15299 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15300 DiagID, Context.getPrintingPolicy());
15301 // Use the identifier location for the type source range.
15302 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15303 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15306 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15307 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15308 }
15309 }
15310 }
15311}
15312
15313Decl *
15315 MultiTemplateParamsArg TemplateParameterLists,
15316 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15317 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15318 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15319 Scope *ParentScope = FnBodyScope->getParent();
15320
15321 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15322 // we define a non-templated function definition, we will create a declaration
15323 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15324 // The base function declaration will have the equivalent of an `omp declare
15325 // variant` annotation which specifies the mangled definition as a
15326 // specialization function under the OpenMP context defined as part of the
15327 // `omp begin declare variant`.
15329 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15331 ParentScope, D, TemplateParameterLists, Bases);
15332
15333 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15334 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15335 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15336
15337 if (!Bases.empty())
15339 Bases);
15340
15341 return Dcl;
15342}
15343
15346}
15347
15349 const FunctionDecl *&PossiblePrototype) {
15350 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15351 Prev = Prev->getPreviousDecl()) {
15352 // Ignore any declarations that occur in function or method
15353 // scope, because they aren't visible from the header.
15354 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15355 continue;
15356
15357 PossiblePrototype = Prev;
15358 return Prev->getType()->isFunctionProtoType();
15359 }
15360 return false;
15361}
15362
15363static bool
15365 const FunctionDecl *&PossiblePrototype) {
15366 // Don't warn about invalid declarations.
15367 if (FD->isInvalidDecl())
15368 return false;
15369
15370 // Or declarations that aren't global.
15371 if (!FD->isGlobal())
15372 return false;
15373
15374 // Don't warn about C++ member functions.
15375 if (isa<CXXMethodDecl>(FD))
15376 return false;
15377
15378 // Don't warn about 'main'.
15379 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15380 if (IdentifierInfo *II = FD->getIdentifier())
15381 if (II->isStr("main") || II->isStr("efi_main"))
15382 return false;
15383
15384 if (FD->isMSVCRTEntryPoint())
15385 return false;
15386
15387 // Don't warn about inline functions.
15388 if (FD->isInlined())
15389 return false;
15390
15391 // Don't warn about function templates.
15393 return false;
15394
15395 // Don't warn about function template specializations.
15397 return false;
15398
15399 // Don't warn for OpenCL kernels.
15400 if (FD->hasAttr<OpenCLKernelAttr>())
15401 return false;
15402
15403 // Don't warn on explicitly deleted functions.
15404 if (FD->isDeleted())
15405 return false;
15406
15407 // Don't warn on implicitly local functions (such as having local-typed
15408 // parameters).
15409 if (!FD->isExternallyVisible())
15410 return false;
15411
15412 // If we were able to find a potential prototype, don't warn.
15413 if (FindPossiblePrototype(FD, PossiblePrototype))
15414 return false;
15415
15416 return true;
15417}
15418
15419void
15421 const FunctionDecl *EffectiveDefinition,
15422 SkipBodyInfo *SkipBody) {
15423 const FunctionDecl *Definition = EffectiveDefinition;
15424 if (!Definition &&
15425 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15426 return;
15427
15428 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15429 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15430 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15431 // A merged copy of the same function, instantiated as a member of
15432 // the same class, is OK.
15433 if (declaresSameEntity(OrigFD, OrigDef) &&
15434 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15435 cast<Decl>(FD->getLexicalDeclContext())))
15436 return;
15437 }
15438 }
15439 }
15440
15442 return;
15443
15444 // Don't emit an error when this is redefinition of a typo-corrected
15445 // definition.
15447 return;
15448
15449 // If we don't have a visible definition of the function, and it's inline or
15450 // a template, skip the new definition.
15451 if (SkipBody && !hasVisibleDefinition(Definition) &&
15452 (Definition->getFormalLinkage() == Linkage::Internal ||
15453 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15454 Definition->getNumTemplateParameterLists())) {
15455 SkipBody->ShouldSkip = true;
15456 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15457 if (auto *TD = Definition->getDescribedFunctionTemplate())
15460 return;
15461 }
15462
15463 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15464 Definition->getStorageClass() == SC_Extern)
15465 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15466 << FD << getLangOpts().CPlusPlus;
15467 else
15468 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15469
15470 Diag(Definition->getLocation(), diag::note_previous_definition);
15471 FD->setInvalidDecl();
15472}
15473
15475 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15476
15478 LSI->CallOperator = CallOperator;
15479 LSI->Lambda = LambdaClass;
15480 LSI->ReturnType = CallOperator->getReturnType();
15481 // When this function is called in situation where the context of the call
15482 // operator is not entered, we set AfterParameterList to false, so that
15483 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15484 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
15485 // where we would set the CurContext to the lambda operator before
15486 // substituting into it. In this case the flag needs to be true such that
15487 // tryCaptureVariable can correctly handle potential captures thereof.
15488 LSI->AfterParameterList = CurContext == CallOperator;
15489
15490 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
15491 // used at the point of dealing with potential captures.
15492 //
15493 // We don't use LambdaClass->isGenericLambda() because this value doesn't
15494 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
15495 // associated. (Technically, we could recover that list from their
15496 // instantiation patterns, but for now, the GLTemplateParameterList seems
15497 // unnecessary in these cases.)
15498 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
15499 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
15500 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15501
15502 if (LCD == LCD_None)
15504 else if (LCD == LCD_ByCopy)
15506 else if (LCD == LCD_ByRef)
15508 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15509
15511 LSI->Mutable = !CallOperator->isConst();
15512 if (CallOperator->isExplicitObjectMemberFunction())
15513 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15514
15515 // Add the captures to the LSI so they can be noted as already
15516 // captured within tryCaptureVar.
15517 auto I = LambdaClass->field_begin();
15518 for (const auto &C : LambdaClass->captures()) {
15519 if (C.capturesVariable()) {
15520 ValueDecl *VD = C.getCapturedVar();
15521 if (VD->isInitCapture())
15523 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15524 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15525 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15526 /*EllipsisLoc*/C.isPackExpansion()
15527 ? C.getEllipsisLoc() : SourceLocation(),
15528 I->getType(), /*Invalid*/false);
15529
15530 } else if (C.capturesThis()) {
15531 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15532 C.getCaptureKind() == LCK_StarThis);
15533 } else {
15534 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15535 I->getType());
15536 }
15537 ++I;
15538 }
15539 return LSI;
15540}
15541
15543 SkipBodyInfo *SkipBody,
15544 FnBodyKind BodyKind) {
15545 if (!D) {
15546 // Parsing the function declaration failed in some way. Push on a fake scope
15547 // anyway so we can try to parse the function body.
15550 return D;
15551 }
15552
15553 FunctionDecl *FD = nullptr;
15554
15555 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15556 FD = FunTmpl->getTemplatedDecl();
15557 else
15558 FD = cast<FunctionDecl>(D);
15559
15560 // Do not push if it is a lambda because one is already pushed when building
15561 // the lambda in ActOnStartOfLambdaDefinition().
15562 if (!isLambdaCallOperator(FD))
15563 // [expr.const]/p14.1
15564 // An expression or conversion is in an immediate function context if it is
15565 // potentially evaluated and either: its innermost enclosing non-block scope
15566 // is a function parameter scope of an immediate function.
15569 : ExprEvalContexts.back().Context);
15570
15571 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15572 // context is nested in an immediate function context, so smaller contexts
15573 // that appear inside immediate functions (like variable initializers) are
15574 // considered to be inside an immediate function context even though by
15575 // themselves they are not immediate function contexts. But when a new
15576 // function is entered, we need to reset this tracking, since the entered
15577 // function might be not an immediate function.
15578 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15579 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15580 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15581
15582 // Check for defining attributes before the check for redefinition.
15583 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15584 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15585 FD->dropAttr<AliasAttr>();
15586 FD->setInvalidDecl();
15587 }
15588 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15589 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15590 FD->dropAttr<IFuncAttr>();
15591 FD->setInvalidDecl();
15592 }
15593 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15594 if (Context.getTargetInfo().getTriple().isAArch64() &&
15595 !Context.getTargetInfo().hasFeature("fmv") &&
15596 !Attr->isDefaultVersion()) {
15597 // If function multi versioning disabled skip parsing function body
15598 // defined with non-default target_version attribute
15599 if (SkipBody)
15600 SkipBody->ShouldSkip = true;
15601 return nullptr;
15602 }
15603 }
15604
15605 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15606 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15607 Ctor->isDefaultConstructor() &&
15609 // If this is an MS ABI dllexport default constructor, instantiate any
15610 // default arguments.
15612 }
15613 }
15614
15615 // See if this is a redefinition. If 'will have body' (or similar) is already
15616 // set, then these checks were already performed when it was set.
15617 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15619 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15620
15621 // If we're skipping the body, we're done. Don't enter the scope.
15622 if (SkipBody && SkipBody->ShouldSkip)
15623 return D;
15624 }
15625
15626 // Mark this function as "will have a body eventually". This lets users to
15627 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15628 // this function.
15629 FD->setWillHaveBody();
15630
15631 // If we are instantiating a generic lambda call operator, push
15632 // a LambdaScopeInfo onto the function stack. But use the information
15633 // that's already been calculated (ActOnLambdaExpr) to prime the current
15634 // LambdaScopeInfo.
15635 // When the template operator is being specialized, the LambdaScopeInfo,
15636 // has to be properly restored so that tryCaptureVariable doesn't try
15637 // and capture any new variables. In addition when calculating potential
15638 // captures during transformation of nested lambdas, it is necessary to
15639 // have the LSI properly restored.
15641 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15642 // instantiated, explicitly specialized.
15645 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15646 FD->setInvalidDecl();
15648 } else {
15649 assert(inTemplateInstantiation() &&
15650 "There should be an active template instantiation on the stack "
15651 "when instantiating a generic lambda!");
15652 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15653 }
15654 } else {
15655 // Enter a new function scope
15657 }
15658
15659 // Builtin functions cannot be defined.
15660 if (unsigned BuiltinID = FD->getBuiltinID()) {
15663 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15664 FD->setInvalidDecl();
15665 }
15666 }
15667
15668 // The return type of a function definition must be complete (C99 6.9.1p3).
15669 // C++23 [dcl.fct.def.general]/p2
15670 // The type of [...] the return for a function definition
15671 // shall not be a (possibly cv-qualified) class type that is incomplete
15672 // or abstract within the function body unless the function is deleted.
15673 QualType ResultType = FD->getReturnType();
15674 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15675 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15676 (RequireCompleteType(FD->getLocation(), ResultType,
15677 diag::err_func_def_incomplete_result) ||
15679 diag::err_abstract_type_in_decl,
15681 FD->setInvalidDecl();
15682
15683 if (FnBodyScope)
15684 PushDeclContext(FnBodyScope, FD);
15685
15686 // Check the validity of our function parameters
15687 if (BodyKind != FnBodyKind::Delete)
15689 /*CheckParameterNames=*/true);
15690
15691 // Add non-parameter declarations already in the function to the current
15692 // scope.
15693 if (FnBodyScope) {
15694 for (Decl *NPD : FD->decls()) {
15695 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15696 if (!NonParmDecl)
15697 continue;
15698 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15699 "parameters should not be in newly created FD yet");
15700
15701 // If the decl has a name, make it accessible in the current scope.
15702 if (NonParmDecl->getDeclName())
15703 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15704
15705 // Similarly, dive into enums and fish their constants out, making them
15706 // accessible in this scope.
15707 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15708 for (auto *EI : ED->enumerators())
15709 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15710 }
15711 }
15712 }
15713
15714 // Introduce our parameters into the function scope
15715 for (auto *Param : FD->parameters()) {
15716 Param->setOwningFunction(FD);
15717
15718 // If this has an identifier, add it to the scope stack.
15719 if (Param->getIdentifier() && FnBodyScope) {
15720 CheckShadow(FnBodyScope, Param);
15721
15722 PushOnScopeChains(Param, FnBodyScope);
15723 }
15724 }
15725
15726 // C++ [module.import/6] external definitions are not permitted in header
15727 // units. Deleted and Defaulted functions are implicitly inline (but the
15728 // inline state is not set at this point, so check the BodyKind explicitly).
15729 // FIXME: Consider an alternate location for the test where the inlined()
15730 // state is complete.
15731 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15732 !FD->isInvalidDecl() && !FD->isInlined() &&
15733 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15734 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15735 !FD->isTemplateInstantiation()) {
15736 assert(FD->isThisDeclarationADefinition());
15737 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15738 FD->setInvalidDecl();
15739 }
15740
15741 // Ensure that the function's exception specification is instantiated.
15742 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15744
15745 // dllimport cannot be applied to non-inline function definitions.
15746 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15747 !FD->isTemplateInstantiation()) {
15748 assert(!FD->hasAttr<DLLExportAttr>());
15749 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15750 FD->setInvalidDecl();
15751 return D;
15752 }
15753
15754 // Some function attributes (like OptimizeNoneAttr) need actions before
15755 // parsing body started.
15757
15758 // We want to attach documentation to original Decl (which might be
15759 // a function template).
15761 if (getCurLexicalContext()->isObjCContainer() &&
15762 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15763 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15764 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15765
15767
15768 return D;
15769}
15770
15772 if (!FD || FD->isInvalidDecl())
15773 return;
15774 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
15775 FD = TD->getTemplatedDecl();
15776 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
15780 FpPragmaStack.CurrentValue =
15782 }
15783}
15784
15786 ReturnStmt **Returns = Scope->Returns.data();
15787
15788 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15789 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15790 if (!NRVOCandidate->isNRVOVariable())
15791 Returns[I]->setNRVOCandidate(nullptr);
15792 }
15793 }
15794}
15795
15797 // We can't delay parsing the body of a constexpr function template (yet).
15798 if (D.getDeclSpec().hasConstexprSpecifier())
15799 return false;
15800
15801 // We can't delay parsing the body of a function template with a deduced
15802 // return type (yet).
15803 if (D.getDeclSpec().hasAutoTypeSpec()) {
15804 // If the placeholder introduces a non-deduced trailing return type,
15805 // we can still delay parsing it.
15806 if (D.getNumTypeObjects()) {
15807 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15808 if (Outer.Kind == DeclaratorChunk::Function &&
15809 Outer.Fun.hasTrailingReturnType()) {
15810 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15811 return Ty.isNull() || !Ty->isUndeducedType();
15812 }
15813 }
15814 return false;
15815 }
15816
15817 return true;
15818}
15819
15821 // We cannot skip the body of a function (or function template) which is
15822 // constexpr, since we may need to evaluate its body in order to parse the
15823 // rest of the file.
15824 // We cannot skip the body of a function with an undeduced return type,
15825 // because any callers of that function need to know the type.
15826 if (const FunctionDecl *FD = D->getAsFunction()) {
15827 if (FD->isConstexpr())
15828 return false;
15829 // We can't simply call Type::isUndeducedType here, because inside template
15830 // auto can be deduced to a dependent type, which is not considered
15831 // "undeduced".
15832 if (FD->getReturnType()->getContainedDeducedType())
15833 return false;
15834 }
15836}
15837
15839 if (!Decl)
15840 return nullptr;
15841 if (FunctionDecl *FD = Decl->getAsFunction())
15842 FD->setHasSkippedBody();
15843 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15844 MD->setHasSkippedBody();
15845 return Decl;
15846}
15847
15849 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
15850}
15851
15852/// RAII object that pops an ExpressionEvaluationContext when exiting a function
15853/// body.
15855public:
15856 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15858 if (!IsLambda)
15860 }
15861
15862private:
15863 Sema &S;
15864 bool IsLambda = false;
15865};
15866
15868 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15869
15870 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15871 if (auto It = EscapeInfo.find(BD); It != EscapeInfo.end())
15872 return It->second;
15873
15874 bool R = false;
15875 const BlockDecl *CurBD = BD;
15876
15877 do {
15878 R = !CurBD->doesNotEscape();
15879 if (R)
15880 break;
15881 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15882 } while (CurBD);
15883
15884 return EscapeInfo[BD] = R;
15885 };
15886
15887 // If the location where 'self' is implicitly retained is inside a escaping
15888 // block, emit a diagnostic.
15889 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15891 if (IsOrNestedInEscapingBlock(P.second))
15892 S.Diag(P.first, diag::warn_implicitly_retains_self)
15893 << FixItHint::CreateInsertion(P.first, "self->");
15894}
15895
15896static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
15897 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
15898 FD->getDeclName().isIdentifier() && FD->getName() == Name;
15899}
15900
15902 return methodHasName(FD, "get_return_object");
15903}
15904
15906 return FD->isStatic() &&
15907 methodHasName(FD, "get_return_object_on_allocation_failure");
15908}
15909
15912 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15913 return;
15914 // Allow some_promise_type::get_return_object().
15916 return;
15917 if (!FD->hasAttr<CoroWrapperAttr>())
15918 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
15919}
15920
15922 bool IsInstantiation) {
15924 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15925
15926 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15927 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15928
15930 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15931
15932 // If we skip function body, we can't tell if a function is a coroutine.
15933 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
15934 if (FSI->isCoroutine())
15936 else
15938 }
15939
15940 // Diagnose invalid SYCL kernel entry point function declarations.
15941 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
15942 SYCLKernelEntryPointAttr *SKEPAttr =
15943 FD->getAttr<SYCLKernelEntryPointAttr>();
15944 if (FD->isDefaulted()) {
15945 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15946 << /*defaulted function*/ 3;
15947 SKEPAttr->setInvalidAttr();
15948 } else if (FD->isDeleted()) {
15949 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15950 << /*deleted function*/ 2;
15951 SKEPAttr->setInvalidAttr();
15952 } else if (FSI->isCoroutine()) {
15953 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15954 << /*coroutine*/ 7;
15955 SKEPAttr->setInvalidAttr();
15956 }
15957 }
15958
15959 {
15960 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15961 // one is already popped when finishing the lambda in BuildLambdaExpr().
15962 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15963 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15964 if (FD) {
15965 // If this is called by Parser::ParseFunctionDefinition() after marking
15966 // the declaration as deleted, and if the deleted-function-body contains
15967 // a message (C++26), then a DefaultedOrDeletedInfo will have already been
15968 // added to store that message; do not overwrite it in that case.
15969 //
15970 // Since this would always set the body to 'nullptr' in that case anyway,
15971 // which is already done when the function decl is initially created,
15972 // always skipping this irrespective of whether there is a delete message
15973 // should not be a problem.
15974 if (!FD->isDeletedAsWritten())
15975 FD->setBody(Body);
15976 FD->setWillHaveBody(false);
15978
15979 if (getLangOpts().CPlusPlus14) {
15980 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15981 FD->getReturnType()->isUndeducedType()) {
15982 // For a function with a deduced result type to return void,
15983 // the result type as written must be 'auto' or 'decltype(auto)',
15984 // possibly cv-qualified or constrained, but not ref-qualified.
15985 if (!FD->getReturnType()->getAs<AutoType>()) {
15986 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15987 << FD->getReturnType();
15988 FD->setInvalidDecl();
15989 } else {
15990 // Falling off the end of the function is the same as 'return;'.
15991 Expr *Dummy = nullptr;
15993 FD, dcl->getLocation(), Dummy,
15994 FD->getReturnType()->getAs<AutoType>()))
15995 FD->setInvalidDecl();
15996 }
15997 }
15998 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
15999 // In C++11, we don't use 'auto' deduction rules for lambda call
16000 // operators because we don't support return type deduction.
16001 auto *LSI = getCurLambda();
16002 if (LSI->HasImplicitReturnType) {
16004
16005 // C++11 [expr.prim.lambda]p4:
16006 // [...] if there are no return statements in the compound-statement
16007 // [the deduced type is] the type void
16008 QualType RetType =
16009 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16010
16011 // Update the return type to the deduced type.
16012 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16013 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16014 Proto->getExtProtoInfo()));
16015 }
16016 }
16017
16018 // If the function implicitly returns zero (like 'main') or is naked,
16019 // don't complain about missing return statements.
16020 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
16022
16023 // MSVC permits the use of pure specifier (=0) on function definition,
16024 // defined at class scope, warn about this non-standard construct.
16025 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16026 !FD->isOutOfLine())
16027 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16028
16029 if (!FD->isInvalidDecl()) {
16030 // Don't diagnose unused parameters of defaulted, deleted or naked
16031 // functions.
16032 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16033 !FD->hasAttr<NakedAttr>())
16036 FD->getReturnType(), FD);
16037
16038 // If this is a structor, we need a vtable.
16039 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16040 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16041 else if (CXXDestructorDecl *Destructor =
16042 dyn_cast<CXXDestructorDecl>(FD))
16043 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16044
16045 // Try to apply the named return value optimization. We have to check
16046 // if we can do this here because lambdas keep return statements around
16047 // to deduce an implicit return type.
16048 if (FD->getReturnType()->isRecordType() &&
16050 computeNRVO(Body, FSI);
16051 }
16052
16053 // GNU warning -Wmissing-prototypes:
16054 // Warn if a global function is defined without a previous
16055 // prototype declaration. This warning is issued even if the
16056 // definition itself provides a prototype. The aim is to detect
16057 // global functions that fail to be declared in header files.
16058 const FunctionDecl *PossiblePrototype = nullptr;
16059 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16060 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16061
16062 if (PossiblePrototype) {
16063 // We found a declaration that is not a prototype,
16064 // but that could be a zero-parameter prototype
16065 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16066 TypeLoc TL = TI->getTypeLoc();
16068 Diag(PossiblePrototype->getLocation(),
16069 diag::note_declaration_not_a_prototype)
16070 << (FD->getNumParams() != 0)
16072 FTL.getRParenLoc(), "void")
16073 : FixItHint{});
16074 }
16075 } else {
16076 // Returns true if the token beginning at this Loc is `const`.
16077 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16078 const LangOptions &LangOpts) {
16079 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
16080 if (LocInfo.first.isInvalid())
16081 return false;
16082
16083 bool Invalid = false;
16084 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16085 if (Invalid)
16086 return false;
16087
16088 if (LocInfo.second > Buffer.size())
16089 return false;
16090
16091 const char *LexStart = Buffer.data() + LocInfo.second;
16092 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16093
16094 return StartTok.consume_front("const") &&
16095 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16096 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16097 };
16098
16099 auto findBeginLoc = [&]() {
16100 // If the return type has `const` qualifier, we want to insert
16101 // `static` before `const` (and not before the typename).
16102 if ((FD->getReturnType()->isAnyPointerType() &&
16105 // But only do this if we can determine where the `const` is.
16106
16107 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16108 getLangOpts()))
16109
16110 return FD->getBeginLoc();
16111 }
16112 return FD->getTypeSpecStartLoc();
16113 };
16115 diag::note_static_for_internal_linkage)
16116 << /* function */ 1
16117 << (FD->getStorageClass() == SC_None
16118 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16119 : FixItHint{});
16120 }
16121 }
16122
16123 // We might not have found a prototype because we didn't wish to warn on
16124 // the lack of a missing prototype. Try again without the checks for
16125 // whether we want to warn on the missing prototype.
16126 if (!PossiblePrototype)
16127 (void)FindPossiblePrototype(FD, PossiblePrototype);
16128
16129 // If the function being defined does not have a prototype, then we may
16130 // need to diagnose it as changing behavior in C23 because we now know
16131 // whether the function accepts arguments or not. This only handles the
16132 // case where the definition has no prototype but does have parameters
16133 // and either there is no previous potential prototype, or the previous
16134 // potential prototype also has no actual prototype. This handles cases
16135 // like:
16136 // void f(); void f(a) int a; {}
16137 // void g(a) int a; {}
16138 // See MergeFunctionDecl() for other cases of the behavior change
16139 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16140 // type without a prototype.
16141 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16142 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16143 !PossiblePrototype->isImplicit()))) {
16144 // The function definition has parameters, so this will change behavior
16145 // in C23. If there is a possible prototype, it comes before the
16146 // function definition.
16147 // FIXME: The declaration may have already been diagnosed as being
16148 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16149 // there's no way to test for the "changes behavior" condition in
16150 // SemaType.cpp when forming the declaration's function type. So, we do
16151 // this awkward dance instead.
16152 //
16153 // If we have a possible prototype and it declares a function with a
16154 // prototype, we don't want to diagnose it; if we have a possible
16155 // prototype and it has no prototype, it may have already been
16156 // diagnosed in SemaType.cpp as deprecated depending on whether
16157 // -Wstrict-prototypes is enabled. If we already warned about it being
16158 // deprecated, add a note that it also changes behavior. If we didn't
16159 // warn about it being deprecated (because the diagnostic is not
16160 // enabled), warn now that it is deprecated and changes behavior.
16161
16162 // This K&R C function definition definitely changes behavior in C23,
16163 // so diagnose it.
16164 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16165 << /*definition*/ 1 << /* not supported in C23 */ 0;
16166
16167 // If we have a possible prototype for the function which is a user-
16168 // visible declaration, we already tested that it has no prototype.
16169 // This will change behavior in C23. This gets a warning rather than a
16170 // note because it's the same behavior-changing problem as with the
16171 // definition.
16172 if (PossiblePrototype)
16173 Diag(PossiblePrototype->getLocation(),
16174 diag::warn_non_prototype_changes_behavior)
16175 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16176 << /*definition*/ 1;
16177 }
16178
16179 // Warn on CPUDispatch with an actual body.
16180 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16181 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16182 if (!CmpndBody->body_empty())
16183 Diag(CmpndBody->body_front()->getBeginLoc(),
16184 diag::warn_dispatch_body_ignored);
16185
16186 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16187 const CXXMethodDecl *KeyFunction;
16188 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16189 MD->isVirtual() &&
16190 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16191 MD == KeyFunction->getCanonicalDecl()) {
16192 // Update the key-function state if necessary for this ABI.
16193 if (FD->isInlined() &&
16196
16197 // If the newly-chosen key function is already defined, then we
16198 // need to mark the vtable as used retroactively.
16199 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16200 const FunctionDecl *Definition;
16201 if (KeyFunction && KeyFunction->isDefined(Definition))
16202 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16203 } else {
16204 // We just defined they key function; mark the vtable as used.
16205 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16206 }
16207 }
16208 }
16209
16210 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16211 "Function parsing confused");
16212 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16213 assert(MD == getCurMethodDecl() && "Method parsing confused");
16214 MD->setBody(Body);
16215 if (!MD->isInvalidDecl()) {
16217 MD->getReturnType(), MD);
16218
16219 if (Body)
16220 computeNRVO(Body, FSI);
16221 }
16222 if (FSI->ObjCShouldCallSuper) {
16223 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16224 << MD->getSelector().getAsString();
16225 FSI->ObjCShouldCallSuper = false;
16226 }
16228 const ObjCMethodDecl *InitMethod = nullptr;
16229 bool isDesignated =
16230 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16231 assert(isDesignated && InitMethod);
16232 (void)isDesignated;
16233
16234 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16235 auto IFace = MD->getClassInterface();
16236 if (!IFace)
16237 return false;
16238 auto SuperD = IFace->getSuperClass();
16239 if (!SuperD)
16240 return false;
16241 return SuperD->getIdentifier() ==
16242 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16243 };
16244 // Don't issue this warning for unavailable inits or direct subclasses
16245 // of NSObject.
16246 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16247 Diag(MD->getLocation(),
16248 diag::warn_objc_designated_init_missing_super_call);
16249 Diag(InitMethod->getLocation(),
16250 diag::note_objc_designated_init_marked_here);
16251 }
16253 }
16254 if (FSI->ObjCWarnForNoInitDelegation) {
16255 // Don't issue this warning for unavailable inits.
16256 if (!MD->isUnavailable())
16257 Diag(MD->getLocation(),
16258 diag::warn_objc_secondary_init_missing_init_call);
16259 FSI->ObjCWarnForNoInitDelegation = false;
16260 }
16261
16263 } else {
16264 // Parsing the function declaration failed in some way. Pop the fake scope
16265 // we pushed on.
16266 PopFunctionScopeInfo(ActivePolicy, dcl);
16267 return nullptr;
16268 }
16269
16270 if (Body && FSI->HasPotentialAvailabilityViolations)
16272
16273 assert(!FSI->ObjCShouldCallSuper &&
16274 "This should only be set for ObjC methods, which should have been "
16275 "handled in the block above.");
16276
16277 // Verify and clean out per-function state.
16278 if (Body && (!FD || !FD->isDefaulted())) {
16279 // C++ constructors that have function-try-blocks can't have return
16280 // statements in the handlers of that block. (C++ [except.handle]p14)
16281 // Verify this.
16282 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16283 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16284
16285 // Verify that gotos and switch cases don't jump into scopes illegally.
16288
16289 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16290 if (!Destructor->getParent()->isDependentType())
16292
16294 Destructor->getParent());
16295 }
16296
16297 // If any errors have occurred, clear out any temporaries that may have
16298 // been leftover. This ensures that these temporaries won't be picked up
16299 // for deletion in some later function.
16302 getDiagnostics().getSuppressAllDiagnostics()) {
16304 }
16305 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16306 // Since the body is valid, issue any analysis-based warnings that are
16307 // enabled.
16308 ActivePolicy = &WP;
16309 }
16310
16311 if (!IsInstantiation && FD &&
16312 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16313 !FD->isInvalidDecl() &&
16315 FD->setInvalidDecl();
16316
16317 if (FD && FD->hasAttr<NakedAttr>()) {
16318 for (const Stmt *S : Body->children()) {
16319 // Allow local register variables without initializer as they don't
16320 // require prologue.
16321 bool RegisterVariables = false;
16322 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16323 for (const auto *Decl : DS->decls()) {
16324 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16325 RegisterVariables =
16326 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16327 if (!RegisterVariables)
16328 break;
16329 }
16330 }
16331 }
16332 if (RegisterVariables)
16333 continue;
16334 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16335 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16336 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16337 FD->setInvalidDecl();
16338 break;
16339 }
16340 }
16341 }
16342
16343 assert(ExprCleanupObjects.size() ==
16344 ExprEvalContexts.back().NumCleanupObjects &&
16345 "Leftover temporaries in function");
16346 assert(!Cleanup.exprNeedsCleanups() &&
16347 "Unaccounted cleanups in function");
16348 assert(MaybeODRUseExprs.empty() &&
16349 "Leftover expressions for odr-use checking");
16350 }
16351 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16352 // the declaration context below. Otherwise, we're unable to transform
16353 // 'this' expressions when transforming immediate context functions.
16354
16355 if (!IsInstantiation)
16357
16358 PopFunctionScopeInfo(ActivePolicy, dcl);
16359 // If any errors have occurred, clear out any temporaries that may have
16360 // been leftover. This ensures that these temporaries won't be picked up for
16361 // deletion in some later function.
16364 }
16365
16366 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16367 !LangOpts.OMPTargetTriples.empty())) ||
16368 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16369 auto ES = getEmissionStatus(FD);
16372 DeclsToCheckForDeferredDiags.insert(FD);
16373 }
16374
16375 if (FD && !FD->isDeleted())
16376 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16377
16378 return dcl;
16379}
16380
16381/// When we finish delayed parsing of an attribute, we must attach it to the
16382/// relevant Decl.
16384 ParsedAttributes &Attrs) {
16385 // Always attach attributes to the underlying decl.
16386 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16387 D = TD->getTemplatedDecl();
16388 ProcessDeclAttributeList(S, D, Attrs);
16390
16391 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16392 if (Method->isStatic())
16394}
16395
16397 IdentifierInfo &II, Scope *S) {
16398 // It is not valid to implicitly define a function in C23.
16400 "Implicit function declarations aren't allowed in this language mode");
16401
16402 // Find the scope in which the identifier is injected and the corresponding
16403 // DeclContext.
16404 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16405 // In that case, we inject the declaration into the translation unit scope
16406 // instead.
16407 Scope *BlockScope = S;
16408 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16409 BlockScope = BlockScope->getParent();
16410
16411 // Loop until we find a DeclContext that is either a function/method or the
16412 // translation unit, which are the only two valid places to implicitly define
16413 // a function. This avoids accidentally defining the function within a tag
16414 // declaration, for example.
16415 Scope *ContextScope = BlockScope;
16416 while (!ContextScope->getEntity() ||
16417 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16418 !ContextScope->getEntity()->isTranslationUnit()))
16419 ContextScope = ContextScope->getParent();
16420 ContextRAII SavedContext(*this, ContextScope->getEntity());
16421
16422 // Before we produce a declaration for an implicitly defined
16423 // function, see whether there was a locally-scoped declaration of
16424 // this name as a function or variable. If so, use that
16425 // (non-visible) declaration, and complain about it.
16426 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16427 if (ExternCPrev) {
16428 // We still need to inject the function into the enclosing block scope so
16429 // that later (non-call) uses can see it.
16430 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16431
16432 // C89 footnote 38:
16433 // If in fact it is not defined as having type "function returning int",
16434 // the behavior is undefined.
16435 if (!isa<FunctionDecl>(ExternCPrev) ||
16437 cast<FunctionDecl>(ExternCPrev)->getType(),
16439 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16440 << ExternCPrev << !getLangOpts().C99;
16441 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16442 return ExternCPrev;
16443 }
16444 }
16445
16446 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16447 unsigned diag_id;
16448 if (II.getName().starts_with("__builtin_"))
16449 diag_id = diag::warn_builtin_unknown;
16450 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16451 else if (getLangOpts().C99)
16452 diag_id = diag::ext_implicit_function_decl_c99;
16453 else
16454 diag_id = diag::warn_implicit_function_decl;
16455
16456 TypoCorrection Corrected;
16457 // Because typo correction is expensive, only do it if the implicit
16458 // function declaration is going to be treated as an error.
16459 //
16460 // Perform the correction before issuing the main diagnostic, as some
16461 // consumers use typo-correction callbacks to enhance the main diagnostic.
16462 if (S && !ExternCPrev &&
16466 S, nullptr, CCC, CTK_NonError);
16467 }
16468
16469 Diag(Loc, diag_id) << &II;
16470 if (Corrected) {
16471 // If the correction is going to suggest an implicitly defined function,
16472 // skip the correction as not being a particularly good idea.
16473 bool Diagnose = true;
16474 if (const auto *D = Corrected.getCorrectionDecl())
16475 Diagnose = !D->isImplicit();
16476 if (Diagnose)
16477 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16478 /*ErrorRecovery*/ false);
16479 }
16480
16481 // If we found a prior declaration of this function, don't bother building
16482 // another one. We've already pushed that one into scope, so there's nothing
16483 // more to do.
16484 if (ExternCPrev)
16485 return ExternCPrev;
16486
16487 // Set a Declarator for the implicit definition: int foo();
16488 const char *Dummy;
16489 AttributeFactory attrFactory;
16490 DeclSpec DS(attrFactory);
16491 unsigned DiagID;
16492 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16494 (void)Error; // Silence warning.
16495 assert(!Error && "Error setting up implicit decl!");
16496 SourceLocation NoLoc;
16498 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16499 /*IsAmbiguous=*/false,
16500 /*LParenLoc=*/NoLoc,
16501 /*Params=*/nullptr,
16502 /*NumParams=*/0,
16503 /*EllipsisLoc=*/NoLoc,
16504 /*RParenLoc=*/NoLoc,
16505 /*RefQualifierIsLvalueRef=*/true,
16506 /*RefQualifierLoc=*/NoLoc,
16507 /*MutableLoc=*/NoLoc, EST_None,
16508 /*ESpecRange=*/SourceRange(),
16509 /*Exceptions=*/nullptr,
16510 /*ExceptionRanges=*/nullptr,
16511 /*NumExceptions=*/0,
16512 /*NoexceptExpr=*/nullptr,
16513 /*ExceptionSpecTokens=*/nullptr,
16514 /*DeclsInPrototype=*/{}, Loc, Loc,
16515 D),
16516 std::move(DS.getAttributes()), SourceLocation());
16517 D.SetIdentifier(&II, Loc);
16518
16519 // Insert this function into the enclosing block scope.
16520 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16521 FD->setImplicit();
16522
16524
16525 return FD;
16526}
16527
16529 FunctionDecl *FD) {
16530 if (FD->isInvalidDecl())
16531 return;
16532
16533 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16534 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16535 return;
16536
16537 std::optional<unsigned> AlignmentParam;
16538 bool IsNothrow = false;
16539 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16540 return;
16541
16542 // C++2a [basic.stc.dynamic.allocation]p4:
16543 // An allocation function that has a non-throwing exception specification
16544 // indicates failure by returning a null pointer value. Any other allocation
16545 // function never returns a null pointer value and indicates failure only by
16546 // throwing an exception [...]
16547 //
16548 // However, -fcheck-new invalidates this possible assumption, so don't add
16549 // NonNull when that is enabled.
16550 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16551 !getLangOpts().CheckNew)
16552 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16553
16554 // C++2a [basic.stc.dynamic.allocation]p2:
16555 // An allocation function attempts to allocate the requested amount of
16556 // storage. [...] If the request succeeds, the value returned by a
16557 // replaceable allocation function is a [...] pointer value p0 different
16558 // from any previously returned value p1 [...]
16559 //
16560 // However, this particular information is being added in codegen,
16561 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16562
16563 // C++2a [basic.stc.dynamic.allocation]p2:
16564 // An allocation function attempts to allocate the requested amount of
16565 // storage. If it is successful, it returns the address of the start of a
16566 // block of storage whose length in bytes is at least as large as the
16567 // requested size.
16568 if (!FD->hasAttr<AllocSizeAttr>()) {
16569 FD->addAttr(AllocSizeAttr::CreateImplicit(
16570 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16571 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16572 }
16573
16574 // C++2a [basic.stc.dynamic.allocation]p3:
16575 // For an allocation function [...], the pointer returned on a successful
16576 // call shall represent the address of storage that is aligned as follows:
16577 // (3.1) If the allocation function takes an argument of type
16578 // std​::​align_­val_­t, the storage will have the alignment
16579 // specified by the value of this argument.
16580 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16581 FD->addAttr(AllocAlignAttr::CreateImplicit(
16582 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16583 }
16584
16585 // FIXME:
16586 // C++2a [basic.stc.dynamic.allocation]p3:
16587 // For an allocation function [...], the pointer returned on a successful
16588 // call shall represent the address of storage that is aligned as follows:
16589 // (3.2) Otherwise, if the allocation function is named operator new[],
16590 // the storage is aligned for any object that does not have
16591 // new-extended alignment ([basic.align]) and is no larger than the
16592 // requested size.
16593 // (3.3) Otherwise, the storage is aligned for any object that does not
16594 // have new-extended alignment and is of the requested size.
16595}
16596
16598 if (FD->isInvalidDecl())
16599 return;
16600
16601 // If this is a built-in function, map its builtin attributes to
16602 // actual attributes.
16603 if (unsigned BuiltinID = FD->getBuiltinID()) {
16604 // Handle printf-formatting attributes.
16605 unsigned FormatIdx;
16606 bool HasVAListArg;
16607 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16608 if (!FD->hasAttr<FormatAttr>()) {
16609 const char *fmt = "printf";
16610 unsigned int NumParams = FD->getNumParams();
16611 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16612 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16613 fmt = "NSString";
16614 FD->addAttr(FormatAttr::CreateImplicit(Context,
16615 &Context.Idents.get(fmt),
16616 FormatIdx+1,
16617 HasVAListArg ? 0 : FormatIdx+2,
16618 FD->getLocation()));
16619 }
16620 }
16621 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16622 HasVAListArg)) {
16623 if (!FD->hasAttr<FormatAttr>())
16624 FD->addAttr(FormatAttr::CreateImplicit(Context,
16625 &Context.Idents.get("scanf"),
16626 FormatIdx+1,
16627 HasVAListArg ? 0 : FormatIdx+2,
16628 FD->getLocation()));
16629 }
16630
16631 // Handle automatically recognized callbacks.
16632 SmallVector<int, 4> Encoding;
16633 if (!FD->hasAttr<CallbackAttr>() &&
16634 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16635 FD->addAttr(CallbackAttr::CreateImplicit(
16636 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16637
16638 // Mark const if we don't care about errno and/or floating point exceptions
16639 // that are the only thing preventing the function from being const. This
16640 // allows IRgen to use LLVM intrinsics for such functions.
16641 bool NoExceptions =
16643 bool ConstWithoutErrnoAndExceptions =
16645 bool ConstWithoutExceptions =
16647 if (!FD->hasAttr<ConstAttr>() &&
16648 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16649 (!ConstWithoutErrnoAndExceptions ||
16650 (!getLangOpts().MathErrno && NoExceptions)) &&
16651 (!ConstWithoutExceptions || NoExceptions))
16652 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16653
16654 // We make "fma" on GNU or Windows const because we know it does not set
16655 // errno in those environments even though it could set errno based on the
16656 // C standard.
16657 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16658 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16659 !FD->hasAttr<ConstAttr>()) {
16660 switch (BuiltinID) {
16661 case Builtin::BI__builtin_fma:
16662 case Builtin::BI__builtin_fmaf:
16663 case Builtin::BI__builtin_fmal:
16664 case Builtin::BIfma:
16665 case Builtin::BIfmaf:
16666 case Builtin::BIfmal:
16667 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16668 break;
16669 default:
16670 break;
16671 }
16672 }
16673
16674 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16675 !FD->hasAttr<ReturnsTwiceAttr>())
16676 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16677 FD->getLocation()));
16678 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16679 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16680 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16681 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16682 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16683 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16684 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16685 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16686 // Add the appropriate attribute, depending on the CUDA compilation mode
16687 // and which target the builtin belongs to. For example, during host
16688 // compilation, aux builtins are __device__, while the rest are __host__.
16689 if (getLangOpts().CUDAIsDevice !=
16691 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16692 else
16693 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16694 }
16695
16696 // Add known guaranteed alignment for allocation functions.
16697 switch (BuiltinID) {
16698 case Builtin::BImemalign:
16699 case Builtin::BIaligned_alloc:
16700 if (!FD->hasAttr<AllocAlignAttr>())
16701 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16702 FD->getLocation()));
16703 break;
16704 default:
16705 break;
16706 }
16707
16708 // Add allocsize attribute for allocation functions.
16709 switch (BuiltinID) {
16710 case Builtin::BIcalloc:
16711 FD->addAttr(AllocSizeAttr::CreateImplicit(
16712 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16713 break;
16714 case Builtin::BImemalign:
16715 case Builtin::BIaligned_alloc:
16716 case Builtin::BIrealloc:
16717 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16718 ParamIdx(), FD->getLocation()));
16719 break;
16720 case Builtin::BImalloc:
16721 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16722 ParamIdx(), FD->getLocation()));
16723 break;
16724 default:
16725 break;
16726 }
16727 }
16728
16733
16734 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16735 // throw, add an implicit nothrow attribute to any extern "C" function we come
16736 // across.
16737 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16738 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16739 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16740 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16741 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16742 }
16743
16744 IdentifierInfo *Name = FD->getIdentifier();
16745 if (!Name)
16746 return;
16748 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16749 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16751 // Okay: this could be a libc/libm/Objective-C function we know
16752 // about.
16753 } else
16754 return;
16755
16756 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16757 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16758 // target-specific builtins, perhaps?
16759 if (!FD->hasAttr<FormatAttr>())
16760 FD->addAttr(FormatAttr::CreateImplicit(Context,
16761 &Context.Idents.get("printf"), 2,
16762 Name->isStr("vasprintf") ? 0 : 3,
16763 FD->getLocation()));
16764 }
16765
16766 if (Name->isStr("__CFStringMakeConstantString")) {
16767 // We already have a __builtin___CFStringMakeConstantString,
16768 // but builds that use -fno-constant-cfstrings don't go through that.
16769 if (!FD->hasAttr<FormatArgAttr>())
16770 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16771 FD->getLocation()));
16772 }
16773}
16774
16776 TypeSourceInfo *TInfo) {
16777 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16778 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16779
16780 if (!TInfo) {
16781 assert(D.isInvalidType() && "no declarator info for valid type");
16783 }
16784
16785 // Scope manipulation handled by caller.
16786 TypedefDecl *NewTD =
16788 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16789
16790 // Bail out immediately if we have an invalid declaration.
16791 if (D.isInvalidType()) {
16792 NewTD->setInvalidDecl();
16793 return NewTD;
16794 }
16795
16796 if (D.getDeclSpec().isModulePrivateSpecified()) {
16798 Diag(NewTD->getLocation(), diag::err_module_private_local)
16799 << 2 << NewTD
16800 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16802 D.getDeclSpec().getModulePrivateSpecLoc());
16803 else
16804 NewTD->setModulePrivate();
16805 }
16806
16807 // C++ [dcl.typedef]p8:
16808 // If the typedef declaration defines an unnamed class (or
16809 // enum), the first typedef-name declared by the declaration
16810 // to be that class type (or enum type) is used to denote the
16811 // class type (or enum type) for linkage purposes only.
16812 // We need to check whether the type was declared in the declaration.
16813 switch (D.getDeclSpec().getTypeSpecType()) {
16814 case TST_enum:
16815 case TST_struct:
16816 case TST_interface:
16817 case TST_union:
16818 case TST_class: {
16819 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16820 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16821 break;
16822 }
16823
16824 default:
16825 break;
16826 }
16827
16828 return NewTD;
16829}
16830
16832 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16833 QualType T = TI->getType();
16834
16835 if (T->isDependentType())
16836 return false;
16837
16838 // This doesn't use 'isIntegralType' despite the error message mentioning
16839 // integral type because isIntegralType would also allow enum types in C.
16840 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16841 if (BT->isInteger())
16842 return false;
16843
16844 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16845 << T << T->isBitIntType();
16846}
16847
16849 QualType EnumUnderlyingTy, bool IsFixed,
16850 const EnumDecl *Prev) {
16851 if (IsScoped != Prev->isScoped()) {
16852 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16853 << Prev->isScoped();
16854 Diag(Prev->getLocation(), diag::note_previous_declaration);
16855 return true;
16856 }
16857
16858 if (IsFixed && Prev->isFixed()) {
16859 if (!EnumUnderlyingTy->isDependentType() &&
16860 !Prev->getIntegerType()->isDependentType() &&
16861 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16862 Prev->getIntegerType())) {
16863 // TODO: Highlight the underlying type of the redeclaration.
16864 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16865 << EnumUnderlyingTy << Prev->getIntegerType();
16866 Diag(Prev->getLocation(), diag::note_previous_declaration)
16867 << Prev->getIntegerTypeRange();
16868 return true;
16869 }
16870 } else if (IsFixed != Prev->isFixed()) {
16871 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16872 << Prev->isFixed();
16873 Diag(Prev->getLocation(), diag::note_previous_declaration);
16874 return true;
16875 }
16876
16877 return false;
16878}
16879
16880/// Get diagnostic %select index for tag kind for
16881/// redeclaration diagnostic message.
16882/// WARNING: Indexes apply to particular diagnostics only!
16883///
16884/// \returns diagnostic %select index.
16886 switch (Tag) {
16888 return 0;
16890 return 1;
16891 case TagTypeKind::Class:
16892 return 2;
16893 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16894 }
16895}
16896
16897/// Determine if tag kind is a class-key compatible with
16898/// class for redeclaration (class, struct, or __interface).
16899///
16900/// \returns true iff the tag kind is compatible.
16902{
16903 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
16905}
16906
16908 TagTypeKind TTK) {
16909 if (isa<TypedefDecl>(PrevDecl))
16910 return NTK_Typedef;
16911 else if (isa<TypeAliasDecl>(PrevDecl))
16912 return NTK_TypeAlias;
16913 else if (isa<ClassTemplateDecl>(PrevDecl))
16914 return NTK_Template;
16915 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16916 return NTK_TypeAliasTemplate;
16917 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16919 switch (TTK) {
16922 case TagTypeKind::Class:
16923 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16924 case TagTypeKind::Union:
16925 return NTK_NonUnion;
16926 case TagTypeKind::Enum:
16927 return NTK_NonEnum;
16928 }
16929 llvm_unreachable("invalid TTK");
16930}
16931
16933 TagTypeKind NewTag, bool isDefinition,
16934 SourceLocation NewTagLoc,
16935 const IdentifierInfo *Name) {
16936 // C++ [dcl.type.elab]p3:
16937 // The class-key or enum keyword present in the
16938 // elaborated-type-specifier shall agree in kind with the
16939 // declaration to which the name in the elaborated-type-specifier
16940 // refers. This rule also applies to the form of
16941 // elaborated-type-specifier that declares a class-name or
16942 // friend class since it can be construed as referring to the
16943 // definition of the class. Thus, in any
16944 // elaborated-type-specifier, the enum keyword shall be used to
16945 // refer to an enumeration (7.2), the union class-key shall be
16946 // used to refer to a union (clause 9), and either the class or
16947 // struct class-key shall be used to refer to a class (clause 9)
16948 // declared using the class or struct class-key.
16949 TagTypeKind OldTag = Previous->getTagKind();
16950 if (OldTag != NewTag &&
16952 return false;
16953
16954 // Tags are compatible, but we might still want to warn on mismatched tags.
16955 // Non-class tags can't be mismatched at this point.
16957 return true;
16958
16959 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16960 // by our warning analysis. We don't want to warn about mismatches with (eg)
16961 // declarations in system headers that are designed to be specialized, but if
16962 // a user asks us to warn, we should warn if their code contains mismatched
16963 // declarations.
16964 auto IsIgnoredLoc = [&](SourceLocation Loc) {
16965 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16966 Loc);
16967 };
16968 if (IsIgnoredLoc(NewTagLoc))
16969 return true;
16970
16971 auto IsIgnored = [&](const TagDecl *Tag) {
16972 return IsIgnoredLoc(Tag->getLocation());
16973 };
16974 while (IsIgnored(Previous)) {
16975 Previous = Previous->getPreviousDecl();
16976 if (!Previous)
16977 return true;
16978 OldTag = Previous->getTagKind();
16979 }
16980
16981 bool isTemplate = false;
16982 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16983 isTemplate = Record->getDescribedClassTemplate();
16984
16986 if (OldTag != NewTag) {
16987 // In a template instantiation, do not offer fix-its for tag mismatches
16988 // since they usually mess up the template instead of fixing the problem.
16989 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16991 << getRedeclDiagFromTagKind(OldTag);
16992 // FIXME: Note previous location?
16993 }
16994 return true;
16995 }
16996
16997 if (isDefinition) {
16998 // On definitions, check all previous tags and issue a fix-it for each
16999 // one that doesn't match the current tag.
17000 if (Previous->getDefinition()) {
17001 // Don't suggest fix-its for redefinitions.
17002 return true;
17003 }
17004
17005 bool previousMismatch = false;
17006 for (const TagDecl *I : Previous->redecls()) {
17007 if (I->getTagKind() != NewTag) {
17008 // Ignore previous declarations for which the warning was disabled.
17009 if (IsIgnored(I))
17010 continue;
17011
17012 if (!previousMismatch) {
17013 previousMismatch = true;
17014 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17016 << getRedeclDiagFromTagKind(I->getTagKind());
17017 }
17018 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17020 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17022 }
17023 }
17024 return true;
17025 }
17026
17027 // Identify the prevailing tag kind: this is the kind of the definition (if
17028 // there is a non-ignored definition), or otherwise the kind of the prior
17029 // (non-ignored) declaration.
17030 const TagDecl *PrevDef = Previous->getDefinition();
17031 if (PrevDef && IsIgnored(PrevDef))
17032 PrevDef = nullptr;
17033 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17034 if (Redecl->getTagKind() != NewTag) {
17035 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17037 << getRedeclDiagFromTagKind(OldTag);
17038 Diag(Redecl->getLocation(), diag::note_previous_use);
17039
17040 // If there is a previous definition, suggest a fix-it.
17041 if (PrevDef) {
17042 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17046 }
17047 }
17048
17049 return true;
17050}
17051
17052/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17053/// from an outer enclosing namespace or file scope inside a friend declaration.
17054/// This should provide the commented out code in the following snippet:
17055/// namespace N {
17056/// struct X;
17057/// namespace M {
17058/// struct Y { friend struct /*N::*/ X; };
17059/// }
17060/// }
17062 SourceLocation NameLoc) {
17063 // While the decl is in a namespace, do repeated lookup of that name and see
17064 // if we get the same namespace back. If we do not, continue until
17065 // translation unit scope, at which point we have a fully qualified NNS.
17068 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17069 // This tag should be declared in a namespace, which can only be enclosed by
17070 // other namespaces. Bail if there's an anonymous namespace in the chain.
17071 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17072 if (!Namespace || Namespace->isAnonymousNamespace())
17073 return FixItHint();
17074 IdentifierInfo *II = Namespace->getIdentifier();
17075 Namespaces.push_back(II);
17076 NamedDecl *Lookup = SemaRef.LookupSingleName(
17077 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17078 if (Lookup == Namespace)
17079 break;
17080 }
17081
17082 // Once we have all the namespaces, reverse them to go outermost first, and
17083 // build an NNS.
17084 SmallString<64> Insertion;
17085 llvm::raw_svector_ostream OS(Insertion);
17086 if (DC->isTranslationUnit())
17087 OS << "::";
17088 std::reverse(Namespaces.begin(), Namespaces.end());
17089 for (auto *II : Namespaces)
17090 OS << II->getName() << "::";
17091 return FixItHint::CreateInsertion(NameLoc, Insertion);
17092}
17093
17094/// Determine whether a tag originally declared in context \p OldDC can
17095/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17096/// found a declaration in \p OldDC as a previous decl, perhaps through a
17097/// using-declaration).
17099 DeclContext *NewDC) {
17100 OldDC = OldDC->getRedeclContext();
17101 NewDC = NewDC->getRedeclContext();
17102
17103 if (OldDC->Equals(NewDC))
17104 return true;
17105
17106 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17107 // encloses the other).
17108 if (S.getLangOpts().MSVCCompat &&
17109 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17110 return true;
17111
17112 return false;
17113}
17114
17116Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17117 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17118 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17119 SourceLocation ModulePrivateLoc,
17120 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17121 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17122 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17123 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17124 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17125 // If this is not a definition, it must have a name.
17126 IdentifierInfo *OrigName = Name;
17127 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17128 "Nameless record must be a definition!");
17129 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17130
17131 OwnedDecl = false;
17133 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17134
17135 // FIXME: Check member specializations more carefully.
17136 bool isMemberSpecialization = false;
17137 bool Invalid = false;
17138
17139 // We only need to do this matching if we have template parameters
17140 // or a scope specifier, which also conveniently avoids this work
17141 // for non-C++ cases.
17142 if (TemplateParameterLists.size() > 0 ||
17143 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17144 TemplateParameterList *TemplateParams =
17146 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17147 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17148
17149 // C++23 [dcl.type.elab] p2:
17150 // If an elaborated-type-specifier is the sole constituent of a
17151 // declaration, the declaration is ill-formed unless it is an explicit
17152 // specialization, an explicit instantiation or it has one of the
17153 // following forms: [...]
17154 // C++23 [dcl.enum] p1:
17155 // If the enum-head-name of an opaque-enum-declaration contains a
17156 // nested-name-specifier, the declaration shall be an explicit
17157 // specialization.
17158 //
17159 // FIXME: Class template partial specializations can be forward declared
17160 // per CWG2213, but the resolution failed to allow qualified forward
17161 // declarations. This is almost certainly unintentional, so we allow them.
17162 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17163 !isMemberSpecialization)
17164 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17166
17167 if (TemplateParams) {
17168 if (Kind == TagTypeKind::Enum) {
17169 Diag(KWLoc, diag::err_enum_template);
17170 return true;
17171 }
17172
17173 if (TemplateParams->size() > 0) {
17174 // This is a declaration or definition of a class template (which may
17175 // be a member of another template).
17176
17177 if (Invalid)
17178 return true;
17179
17180 OwnedDecl = false;
17182 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17183 AS, ModulePrivateLoc,
17184 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17185 TemplateParameterLists.data(), SkipBody);
17186 return Result.get();
17187 } else {
17188 // The "template<>" header is extraneous.
17189 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17190 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17191 isMemberSpecialization = true;
17192 }
17193 }
17194
17195 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17196 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17197 return true;
17198 }
17199
17200 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17201 // C++23 [dcl.type.elab]p4:
17202 // If an elaborated-type-specifier appears with the friend specifier as
17203 // an entire member-declaration, the member-declaration shall have one
17204 // of the following forms:
17205 // friend class-key nested-name-specifier(opt) identifier ;
17206 // friend class-key simple-template-id ;
17207 // friend class-key nested-name-specifier template(opt)
17208 // simple-template-id ;
17209 //
17210 // Since enum is not a class-key, so declarations like "friend enum E;"
17211 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17212 // invalid, most implementations accept so we issue a pedantic warning.
17213 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17214 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17215 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17216 Diag(KWLoc, diag::note_enum_friend)
17217 << (ScopedEnum + ScopedEnumUsesClassTag);
17218 }
17219
17220 // Figure out the underlying type if this a enum declaration. We need to do
17221 // this early, because it's needed to detect if this is an incompatible
17222 // redeclaration.
17223 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17224 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17225
17226 if (Kind == TagTypeKind::Enum) {
17227 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17228 // No underlying type explicitly specified, or we failed to parse the
17229 // type, default to int.
17230 EnumUnderlying = Context.IntTy.getTypePtr();
17231 } else if (UnderlyingType.get()) {
17232 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17233 // integral type; any cv-qualification is ignored.
17234 TypeSourceInfo *TI = nullptr;
17235 GetTypeFromParser(UnderlyingType.get(), &TI);
17236 EnumUnderlying = TI;
17237
17239 // Recover by falling back to int.
17240 EnumUnderlying = Context.IntTy.getTypePtr();
17241
17244 EnumUnderlying = Context.IntTy.getTypePtr();
17245
17246 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17247 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17248 // of 'int'. However, if this is an unfixed forward declaration, don't set
17249 // the underlying type unless the user enables -fms-compatibility. This
17250 // makes unfixed forward declared enums incomplete and is more conforming.
17251 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17252 EnumUnderlying = Context.IntTy.getTypePtr();
17253 }
17254 }
17255
17256 DeclContext *SearchDC = CurContext;
17257 DeclContext *DC = CurContext;
17258 bool isStdBadAlloc = false;
17259 bool isStdAlignValT = false;
17260
17262 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17263 Redecl = RedeclarationKind::NotForRedeclaration;
17264
17265 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17266 /// implemented asks for structural equivalence checking, the returned decl
17267 /// here is passed back to the parser, allowing the tag body to be parsed.
17268 auto createTagFromNewDecl = [&]() -> TagDecl * {
17269 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17270 // If there is an identifier, use the location of the identifier as the
17271 // location of the decl, otherwise use the location of the struct/union
17272 // keyword.
17273 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17274 TagDecl *New = nullptr;
17275
17276 if (Kind == TagTypeKind::Enum) {
17277 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17278 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17279 // If this is an undefined enum, bail.
17280 if (TUK != TagUseKind::Definition && !Invalid)
17281 return nullptr;
17282 if (EnumUnderlying) {
17283 EnumDecl *ED = cast<EnumDecl>(New);
17284 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17286 else
17287 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17288 QualType EnumTy = ED->getIntegerType();
17291 : EnumTy);
17292 }
17293 } else { // struct/union
17294 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17295 nullptr);
17296 }
17297
17298 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17299 // Add alignment attributes if necessary; these attributes are checked
17300 // when the ASTContext lays out the structure.
17301 //
17302 // It is important for implementing the correct semantics that this
17303 // happen here (in ActOnTag). The #pragma pack stack is
17304 // maintained as a result of parser callbacks which can occur at
17305 // many points during the parsing of a struct declaration (because
17306 // the #pragma tokens are effectively skipped over during the
17307 // parsing of the struct).
17308 if (TUK == TagUseKind::Definition &&
17309 (!SkipBody || !SkipBody->ShouldSkip)) {
17312 }
17313 }
17315 return New;
17316 };
17317
17318 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17319 if (Name && SS.isNotEmpty()) {
17320 // We have a nested-name tag ('struct foo::bar').
17321
17322 // Check for invalid 'foo::'.
17323 if (SS.isInvalid()) {
17324 Name = nullptr;
17325 goto CreateNewDecl;
17326 }
17327
17328 // If this is a friend or a reference to a class in a dependent
17329 // context, don't try to make a decl for it.
17330 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17331 DC = computeDeclContext(SS, false);
17332 if (!DC) {
17333 IsDependent = true;
17334 return true;
17335 }
17336 } else {
17337 DC = computeDeclContext(SS, true);
17338 if (!DC) {
17339 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17340 << SS.getRange();
17341 return true;
17342 }
17343 }
17344
17345 if (RequireCompleteDeclContext(SS, DC))
17346 return true;
17347
17348 SearchDC = DC;
17349 // Look-up name inside 'foo::'.
17351
17352 if (Previous.isAmbiguous())
17353 return true;
17354
17355 if (Previous.empty()) {
17356 // Name lookup did not find anything. However, if the
17357 // nested-name-specifier refers to the current instantiation,
17358 // and that current instantiation has any dependent base
17359 // classes, we might find something at instantiation time: treat
17360 // this as a dependent elaborated-type-specifier.
17361 // But this only makes any sense for reference-like lookups.
17362 if (Previous.wasNotFoundInCurrentInstantiation() &&
17363 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17364 IsDependent = true;
17365 return true;
17366 }
17367
17368 // A tag 'foo::bar' must already exist.
17369 Diag(NameLoc, diag::err_not_tag_in_scope)
17370 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17371 Name = nullptr;
17372 Invalid = true;
17373 goto CreateNewDecl;
17374 }
17375 } else if (Name) {
17376 // C++14 [class.mem]p14:
17377 // If T is the name of a class, then each of the following shall have a
17378 // name different from T:
17379 // -- every member of class T that is itself a type
17380 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17381 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17382 return true;
17383
17384 // If this is a named struct, check to see if there was a previous forward
17385 // declaration or definition.
17386 // FIXME: We're looking into outer scopes here, even when we
17387 // shouldn't be. Doing so can result in ambiguities that we
17388 // shouldn't be diagnosing.
17389 LookupName(Previous, S);
17390
17391 // When declaring or defining a tag, ignore ambiguities introduced
17392 // by types using'ed into this scope.
17393 if (Previous.isAmbiguous() &&
17395 LookupResult::Filter F = Previous.makeFilter();
17396 while (F.hasNext()) {
17397 NamedDecl *ND = F.next();
17398 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17399 SearchDC->getRedeclContext()))
17400 F.erase();
17401 }
17402 F.done();
17403 }
17404
17405 // C++11 [namespace.memdef]p3:
17406 // If the name in a friend declaration is neither qualified nor
17407 // a template-id and the declaration is a function or an
17408 // elaborated-type-specifier, the lookup to determine whether
17409 // the entity has been previously declared shall not consider
17410 // any scopes outside the innermost enclosing namespace.
17411 //
17412 // MSVC doesn't implement the above rule for types, so a friend tag
17413 // declaration may be a redeclaration of a type declared in an enclosing
17414 // scope. They do implement this rule for friend functions.
17415 //
17416 // Does it matter that this should be by scope instead of by
17417 // semantic context?
17418 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17419 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17420 LookupResult::Filter F = Previous.makeFilter();
17421 bool FriendSawTagOutsideEnclosingNamespace = false;
17422 while (F.hasNext()) {
17423 NamedDecl *ND = F.next();
17425 if (DC->isFileContext() &&
17426 !EnclosingNS->Encloses(ND->getDeclContext())) {
17427 if (getLangOpts().MSVCCompat)
17428 FriendSawTagOutsideEnclosingNamespace = true;
17429 else
17430 F.erase();
17431 }
17432 }
17433 F.done();
17434
17435 // Diagnose this MSVC extension in the easy case where lookup would have
17436 // unambiguously found something outside the enclosing namespace.
17437 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17438 NamedDecl *ND = Previous.getFoundDecl();
17439 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17440 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17441 }
17442 }
17443
17444 // Note: there used to be some attempt at recovery here.
17445 if (Previous.isAmbiguous())
17446 return true;
17447
17448 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17449 // FIXME: This makes sure that we ignore the contexts associated
17450 // with C structs, unions, and enums when looking for a matching
17451 // tag declaration or definition. See the similar lookup tweak
17452 // in Sema::LookupName; is there a better way to deal with this?
17453 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17454 SearchDC = SearchDC->getParent();
17455 } else if (getLangOpts().CPlusPlus) {
17456 // Inside ObjCContainer want to keep it as a lexical decl context but go
17457 // past it (most often to TranslationUnit) to find the semantic decl
17458 // context.
17459 while (isa<ObjCContainerDecl>(SearchDC))
17460 SearchDC = SearchDC->getParent();
17461 }
17462 } else if (getLangOpts().CPlusPlus) {
17463 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17464 // TagDecl the same way as we skip it for named TagDecl.
17465 while (isa<ObjCContainerDecl>(SearchDC))
17466 SearchDC = SearchDC->getParent();
17467 }
17468
17469 if (Previous.isSingleResult() &&
17470 Previous.getFoundDecl()->isTemplateParameter()) {
17471 // Maybe we will complain about the shadowed template parameter.
17472 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17473 // Just pretend that we didn't see the previous declaration.
17474 Previous.clear();
17475 }
17476
17477 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17478 DC->Equals(getStdNamespace())) {
17479 if (Name->isStr("bad_alloc")) {
17480 // This is a declaration of or a reference to "std::bad_alloc".
17481 isStdBadAlloc = true;
17482
17483 // If std::bad_alloc has been implicitly declared (but made invisible to
17484 // name lookup), fill in this implicit declaration as the previous
17485 // declaration, so that the declarations get chained appropriately.
17486 if (Previous.empty() && StdBadAlloc)
17487 Previous.addDecl(getStdBadAlloc());
17488 } else if (Name->isStr("align_val_t")) {
17489 isStdAlignValT = true;
17490 if (Previous.empty() && StdAlignValT)
17491 Previous.addDecl(getStdAlignValT());
17492 }
17493 }
17494
17495 // If we didn't find a previous declaration, and this is a reference
17496 // (or friend reference), move to the correct scope. In C++, we
17497 // also need to do a redeclaration lookup there, just in case
17498 // there's a shadow friend decl.
17499 if (Name && Previous.empty() &&
17500 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17501 IsTemplateParamOrArg)) {
17502 if (Invalid) goto CreateNewDecl;
17503 assert(SS.isEmpty());
17504
17505 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17506 // C++ [basic.scope.pdecl]p5:
17507 // -- for an elaborated-type-specifier of the form
17508 //
17509 // class-key identifier
17510 //
17511 // if the elaborated-type-specifier is used in the
17512 // decl-specifier-seq or parameter-declaration-clause of a
17513 // function defined in namespace scope, the identifier is
17514 // declared as a class-name in the namespace that contains
17515 // the declaration; otherwise, except as a friend
17516 // declaration, the identifier is declared in the smallest
17517 // non-class, non-function-prototype scope that contains the
17518 // declaration.
17519 //
17520 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17521 // C structs and unions.
17522 //
17523 // It is an error in C++ to declare (rather than define) an enum
17524 // type, including via an elaborated type specifier. We'll
17525 // diagnose that later; for now, declare the enum in the same
17526 // scope as we would have picked for any other tag type.
17527 //
17528 // GNU C also supports this behavior as part of its incomplete
17529 // enum types extension, while GNU C++ does not.
17530 //
17531 // Find the context where we'll be declaring the tag.
17532 // FIXME: We would like to maintain the current DeclContext as the
17533 // lexical context,
17534 SearchDC = getTagInjectionContext(SearchDC);
17535
17536 // Find the scope where we'll be declaring the tag.
17538 } else {
17539 assert(TUK == TagUseKind::Friend);
17540 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17541
17542 // C++ [namespace.memdef]p3:
17543 // If a friend declaration in a non-local class first declares a
17544 // class or function, the friend class or function is a member of
17545 // the innermost enclosing namespace.
17546 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17547 : SearchDC->getEnclosingNamespaceContext();
17548 }
17549
17550 // In C++, we need to do a redeclaration lookup to properly
17551 // diagnose some problems.
17552 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17553 // hidden declaration so that we don't get ambiguity errors when using a
17554 // type declared by an elaborated-type-specifier. In C that is not correct
17555 // and we should instead merge compatible types found by lookup.
17556 if (getLangOpts().CPlusPlus) {
17557 // FIXME: This can perform qualified lookups into function contexts,
17558 // which are meaningless.
17559 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17560 LookupQualifiedName(Previous, SearchDC);
17561 } else {
17562 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17563 LookupName(Previous, S);
17564 }
17565 }
17566
17567 // If we have a known previous declaration to use, then use it.
17568 if (Previous.empty() && SkipBody && SkipBody->Previous)
17569 Previous.addDecl(SkipBody->Previous);
17570
17571 if (!Previous.empty()) {
17572 NamedDecl *PrevDecl = Previous.getFoundDecl();
17573 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17574
17575 // It's okay to have a tag decl in the same scope as a typedef
17576 // which hides a tag decl in the same scope. Finding this
17577 // with a redeclaration lookup can only actually happen in C++.
17578 //
17579 // This is also okay for elaborated-type-specifiers, which is
17580 // technically forbidden by the current standard but which is
17581 // okay according to the likely resolution of an open issue;
17582 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17583 if (getLangOpts().CPlusPlus) {
17584 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17585 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17586 TagDecl *Tag = TT->getDecl();
17587 if (Tag->getDeclName() == Name &&
17588 Tag->getDeclContext()->getRedeclContext()
17589 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17590 PrevDecl = Tag;
17591 Previous.clear();
17592 Previous.addDecl(Tag);
17593 Previous.resolveKind();
17594 }
17595 }
17596 }
17597 }
17598
17599 // If this is a redeclaration of a using shadow declaration, it must
17600 // declare a tag in the same context. In MSVC mode, we allow a
17601 // redefinition if either context is within the other.
17602 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17603 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17604 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
17605 TUK != TagUseKind::Friend &&
17606 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17607 !(OldTag && isAcceptableTagRedeclContext(
17608 *this, OldTag->getDeclContext(), SearchDC))) {
17609 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17610 Diag(Shadow->getTargetDecl()->getLocation(),
17611 diag::note_using_decl_target);
17612 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17613 << 0;
17614 // Recover by ignoring the old declaration.
17615 Previous.clear();
17616 goto CreateNewDecl;
17617 }
17618 }
17619
17620 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17621 // If this is a use of a previous tag, or if the tag is already declared
17622 // in the same scope (so that the definition/declaration completes or
17623 // rementions the tag), reuse the decl.
17624 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17625 isDeclInScope(DirectPrevDecl, SearchDC, S,
17626 SS.isNotEmpty() || isMemberSpecialization)) {
17627 // Make sure that this wasn't declared as an enum and now used as a
17628 // struct or something similar.
17629 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17630 TUK == TagUseKind::Definition, KWLoc,
17631 Name)) {
17632 bool SafeToContinue =
17633 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17634 Kind != TagTypeKind::Enum);
17635 if (SafeToContinue)
17636 Diag(KWLoc, diag::err_use_with_wrong_tag)
17637 << Name
17639 PrevTagDecl->getKindName());
17640 else
17641 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17642 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17643
17644 if (SafeToContinue)
17645 Kind = PrevTagDecl->getTagKind();
17646 else {
17647 // Recover by making this an anonymous redefinition.
17648 Name = nullptr;
17649 Previous.clear();
17650 Invalid = true;
17651 }
17652 }
17653
17654 if (Kind == TagTypeKind::Enum &&
17655 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17656 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17657 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
17658 return PrevTagDecl;
17659
17660 QualType EnumUnderlyingTy;
17661 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17662 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17663 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17664 EnumUnderlyingTy = QualType(T, 0);
17665
17666 // All conflicts with previous declarations are recovered by
17667 // returning the previous declaration, unless this is a definition,
17668 // in which case we want the caller to bail out.
17669 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17670 ScopedEnum, EnumUnderlyingTy,
17671 IsFixed, PrevEnum))
17672 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
17673 }
17674
17675 // C++11 [class.mem]p1:
17676 // A member shall not be declared twice in the member-specification,
17677 // except that a nested class or member class template can be declared
17678 // and then later defined.
17679 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
17680 S->isDeclScope(PrevDecl)) {
17681 Diag(NameLoc, diag::ext_member_redeclared);
17682 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17683 }
17684
17685 if (!Invalid) {
17686 // If this is a use, just return the declaration we found, unless
17687 // we have attributes.
17688 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17689 if (!Attrs.empty()) {
17690 // FIXME: Diagnose these attributes. For now, we create a new
17691 // declaration to hold them.
17692 } else if (TUK == TagUseKind::Reference &&
17693 (PrevTagDecl->getFriendObjectKind() ==
17695 PrevDecl->getOwningModule() != getCurrentModule()) &&
17696 SS.isEmpty()) {
17697 // This declaration is a reference to an existing entity, but
17698 // has different visibility from that entity: it either makes
17699 // a friend visible or it makes a type visible in a new module.
17700 // In either case, create a new declaration. We only do this if
17701 // the declaration would have meant the same thing if no prior
17702 // declaration were found, that is, if it was found in the same
17703 // scope where we would have injected a declaration.
17704 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17705 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17706 return PrevTagDecl;
17707 // This is in the injected scope, create a new declaration in
17708 // that scope.
17710 } else {
17711 return PrevTagDecl;
17712 }
17713 }
17714
17715 // Diagnose attempts to redefine a tag.
17716 if (TUK == TagUseKind::Definition) {
17717 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17718 // If we're defining a specialization and the previous definition
17719 // is from an implicit instantiation, don't emit an error
17720 // here; we'll catch this in the general case below.
17721 bool IsExplicitSpecializationAfterInstantiation = false;
17722 if (isMemberSpecialization) {
17723 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17724 IsExplicitSpecializationAfterInstantiation =
17725 RD->getTemplateSpecializationKind() !=
17727 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17728 IsExplicitSpecializationAfterInstantiation =
17729 ED->getTemplateSpecializationKind() !=
17731 }
17732
17733 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17734 // not keep more that one definition around (merge them). However,
17735 // ensure the decl passes the structural compatibility check in
17736 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17737 NamedDecl *Hidden = nullptr;
17738 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17739 // There is a definition of this tag, but it is not visible. We
17740 // explicitly make use of C++'s one definition rule here, and
17741 // assume that this definition is identical to the hidden one
17742 // we already have. Make the existing definition visible and
17743 // use it in place of this one.
17744 if (!getLangOpts().CPlusPlus) {
17745 // Postpone making the old definition visible until after we
17746 // complete parsing the new one and do the structural
17747 // comparison.
17748 SkipBody->CheckSameAsPrevious = true;
17749 SkipBody->New = createTagFromNewDecl();
17750 SkipBody->Previous = Def;
17751 return Def;
17752 } else {
17753 SkipBody->ShouldSkip = true;
17754 SkipBody->Previous = Def;
17756 // Carry on and handle it like a normal definition. We'll
17757 // skip starting the definition later.
17758 }
17759 } else if (!IsExplicitSpecializationAfterInstantiation) {
17760 // A redeclaration in function prototype scope in C isn't
17761 // visible elsewhere, so merely issue a warning.
17762 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17763 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17764 else
17765 Diag(NameLoc, diag::err_redefinition) << Name;
17767 NameLoc.isValid() ? NameLoc : KWLoc);
17768 // If this is a redefinition, recover by making this
17769 // struct be anonymous, which will make any later
17770 // references get the previous definition.
17771 Name = nullptr;
17772 Previous.clear();
17773 Invalid = true;
17774 }
17775 } else {
17776 // If the type is currently being defined, complain
17777 // about a nested redefinition.
17778 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17779 if (TD->isBeingDefined()) {
17780 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17781 Diag(PrevTagDecl->getLocation(),
17782 diag::note_previous_definition);
17783 Name = nullptr;
17784 Previous.clear();
17785 Invalid = true;
17786 }
17787 }
17788
17789 // Okay, this is definition of a previously declared or referenced
17790 // tag. We're going to create a new Decl for it.
17791 }
17792
17793 // Okay, we're going to make a redeclaration. If this is some kind
17794 // of reference, make sure we build the redeclaration in the same DC
17795 // as the original, and ignore the current access specifier.
17796 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17797 SearchDC = PrevTagDecl->getDeclContext();
17798 AS = AS_none;
17799 }
17800 }
17801 // If we get here we have (another) forward declaration or we
17802 // have a definition. Just create a new decl.
17803
17804 } else {
17805 // If we get here, this is a definition of a new tag type in a nested
17806 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17807 // new decl/type. We set PrevDecl to NULL so that the entities
17808 // have distinct types.
17809 Previous.clear();
17810 }
17811 // If we get here, we're going to create a new Decl. If PrevDecl
17812 // is non-NULL, it's a definition of the tag declared by
17813 // PrevDecl. If it's NULL, we have a new definition.
17814
17815 // Otherwise, PrevDecl is not a tag, but was found with tag
17816 // lookup. This is only actually possible in C++, where a few
17817 // things like templates still live in the tag namespace.
17818 } else {
17819 // Use a better diagnostic if an elaborated-type-specifier
17820 // found the wrong kind of type on the first
17821 // (non-redeclaration) lookup.
17822 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
17823 !Previous.isForRedeclaration()) {
17824 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17825 Diag(NameLoc, diag::err_tag_reference_non_tag)
17826 << PrevDecl << NTK << llvm::to_underlying(Kind);
17827 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17828 Invalid = true;
17829
17830 // Otherwise, only diagnose if the declaration is in scope.
17831 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17832 SS.isNotEmpty() || isMemberSpecialization)) {
17833 // do nothing
17834
17835 // Diagnose implicit declarations introduced by elaborated types.
17836 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17837 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17838 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17839 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17840 Invalid = true;
17841
17842 // Otherwise it's a declaration. Call out a particularly common
17843 // case here.
17844 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17845 unsigned Kind = 0;
17846 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17847 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17848 << Name << Kind << TND->getUnderlyingType();
17849 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17850 Invalid = true;
17851
17852 // Otherwise, diagnose.
17853 } else {
17854 // The tag name clashes with something else in the target scope,
17855 // issue an error and recover by making this tag be anonymous.
17856 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17857 notePreviousDefinition(PrevDecl, NameLoc);
17858 Name = nullptr;
17859 Invalid = true;
17860 }
17861
17862 // The existing declaration isn't relevant to us; we're in a
17863 // new scope, so clear out the previous declaration.
17864 Previous.clear();
17865 }
17866 }
17867
17868CreateNewDecl:
17869
17870 TagDecl *PrevDecl = nullptr;
17871 if (Previous.isSingleResult())
17872 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17873
17874 // If there is an identifier, use the location of the identifier as the
17875 // location of the decl, otherwise use the location of the struct/union
17876 // keyword.
17877 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17878
17879 // Otherwise, create a new declaration. If there is a previous
17880 // declaration of the same entity, the two will be linked via
17881 // PrevDecl.
17882 TagDecl *New;
17883
17884 if (Kind == TagTypeKind::Enum) {
17885 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17886 // enum X { A, B, C } D; D should chain to X.
17887 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17888 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17889 ScopedEnumUsesClassTag, IsFixed);
17890
17891 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17892 StdAlignValT = cast<EnumDecl>(New);
17893
17894 // If this is an undefined enum, warn.
17895 if (TUK != TagUseKind::Definition && !Invalid) {
17896 TagDecl *Def;
17897 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17898 // C++0x: 7.2p2: opaque-enum-declaration.
17899 // Conflicts are diagnosed above. Do nothing.
17900 }
17901 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17902 Diag(Loc, diag::ext_forward_ref_enum_def)
17903 << New;
17904 Diag(Def->getLocation(), diag::note_previous_definition);
17905 } else {
17906 unsigned DiagID = diag::ext_forward_ref_enum;
17907 if (getLangOpts().MSVCCompat)
17908 DiagID = diag::ext_ms_forward_ref_enum;
17909 else if (getLangOpts().CPlusPlus)
17910 DiagID = diag::err_forward_ref_enum;
17911 Diag(Loc, DiagID);
17912 }
17913 }
17914
17915 if (EnumUnderlying) {
17916 EnumDecl *ED = cast<EnumDecl>(New);
17917 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17919 else
17920 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17921 QualType EnumTy = ED->getIntegerType();
17924 : EnumTy);
17925 assert(ED->isComplete() && "enum with type should be complete");
17926 }
17927 } else {
17928 // struct/union/class
17929
17930 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17931 // struct X { int A; } D; D should chain to X.
17932 if (getLangOpts().CPlusPlus) {
17933 // FIXME: Look for a way to use RecordDecl for simple structs.
17934 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17935 cast_or_null<CXXRecordDecl>(PrevDecl));
17936
17937 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17938 StdBadAlloc = cast<CXXRecordDecl>(New);
17939 } else
17940 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17941 cast_or_null<RecordDecl>(PrevDecl));
17942 }
17943
17944 // Only C23 and later allow defining new types in 'offsetof()'.
17945 if (OOK != OOK_Outside && TUK == TagUseKind::Definition &&
17947 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17948 << (OOK == OOK_Macro) << New->getSourceRange();
17949
17950 // C++11 [dcl.type]p3:
17951 // A type-specifier-seq shall not define a class or enumeration [...].
17952 if (!Invalid && getLangOpts().CPlusPlus &&
17953 (IsTypeSpecifier || IsTemplateParamOrArg) &&
17954 TUK == TagUseKind::Definition) {
17955 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17956 << Context.getTagDeclType(New);
17957 Invalid = true;
17958 }
17959
17961 DC->getDeclKind() == Decl::Enum) {
17962 Diag(New->getLocation(), diag::err_type_defined_in_enum)
17963 << Context.getTagDeclType(New);
17964 Invalid = true;
17965 }
17966
17967 // Maybe add qualifier info.
17968 if (SS.isNotEmpty()) {
17969 if (SS.isSet()) {
17970 // If this is either a declaration or a definition, check the
17971 // nested-name-specifier against the current context.
17972 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
17973 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17974 /*TemplateId=*/nullptr,
17975 isMemberSpecialization))
17976 Invalid = true;
17977
17979 if (TemplateParameterLists.size() > 0) {
17980 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17981 }
17982 }
17983 else
17984 Invalid = true;
17985 }
17986
17987 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17988 // Add alignment attributes if necessary; these attributes are checked when
17989 // the ASTContext lays out the structure.
17990 //
17991 // It is important for implementing the correct semantics that this
17992 // happen here (in ActOnTag). The #pragma pack stack is
17993 // maintained as a result of parser callbacks which can occur at
17994 // many points during the parsing of a struct declaration (because
17995 // the #pragma tokens are effectively skipped over during the
17996 // parsing of the struct).
17997 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18000 }
18001 }
18002
18003 if (ModulePrivateLoc.isValid()) {
18004 if (isMemberSpecialization)
18005 Diag(New->getLocation(), diag::err_module_private_specialization)
18006 << 2
18007 << FixItHint::CreateRemoval(ModulePrivateLoc);
18008 // __module_private__ does not apply to local classes. However, we only
18009 // diagnose this as an error when the declaration specifiers are
18010 // freestanding. Here, we just ignore the __module_private__.
18011 else if (!SearchDC->isFunctionOrMethod())
18012 New->setModulePrivate();
18013 }
18014
18015 // If this is a specialization of a member class (of a class template),
18016 // check the specialization.
18017 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18018 Invalid = true;
18019
18020 // If we're declaring or defining a tag in function prototype scope in C,
18021 // note that this type can only be used within the function and add it to
18022 // the list of decls to inject into the function definition scope.
18023 if ((Name || Kind == TagTypeKind::Enum) &&
18024 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18025 if (getLangOpts().CPlusPlus) {
18026 // C++ [dcl.fct]p6:
18027 // Types shall not be defined in return or parameter types.
18028 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18029 Diag(Loc, diag::err_type_defined_in_param_type)
18030 << Name;
18031 Invalid = true;
18032 }
18033 if (TUK == TagUseKind::Declaration)
18034 Invalid = true;
18035 } else if (!PrevDecl) {
18036 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
18037 }
18038 }
18039
18040 if (Invalid)
18041 New->setInvalidDecl();
18042
18043 // Set the lexical context. If the tag has a C++ scope specifier, the
18044 // lexical context will be different from the semantic context.
18046
18047 // Mark this as a friend decl if applicable.
18048 // In Microsoft mode, a friend declaration also acts as a forward
18049 // declaration so we always pass true to setObjectOfFriendDecl to make
18050 // the tag name visible.
18051 if (TUK == TagUseKind::Friend)
18052 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18053
18054 // Set the access specifier.
18055 if (!Invalid && SearchDC->isRecord())
18056 SetMemberAccessSpecifier(New, PrevDecl, AS);
18057
18058 if (PrevDecl)
18059 CheckRedeclarationInModule(New, PrevDecl);
18060
18061 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
18062 New->startDefinition();
18063
18064 ProcessDeclAttributeList(S, New, Attrs);
18065 AddPragmaAttributes(S, New);
18066
18067 // If this has an identifier, add it to the scope stack.
18068 if (TUK == TagUseKind::Friend) {
18069 // We might be replacing an existing declaration in the lookup tables;
18070 // if so, borrow its access specifier.
18071 if (PrevDecl)
18072 New->setAccess(PrevDecl->getAccess());
18073
18075 DC->makeDeclVisibleInContext(New);
18076 if (Name) // can be null along some error paths
18077 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18078 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18079 } else if (Name) {
18080 S = getNonFieldDeclScope(S);
18081 PushOnScopeChains(New, S, true);
18082 } else {
18083 CurContext->addDecl(New);
18084 }
18085
18086 // If this is the C FILE type, notify the AST context.
18087 if (IdentifierInfo *II = New->getIdentifier())
18088 if (!New->isInvalidDecl() &&
18090 II->isStr("FILE"))
18091 Context.setFILEDecl(New);
18092
18093 if (PrevDecl)
18094 mergeDeclAttributes(New, PrevDecl);
18095
18096 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18099 }
18100
18101 // If there's a #pragma GCC visibility in scope, set the visibility of this
18102 // record.
18104
18105 if (isMemberSpecialization && !New->isInvalidDecl())
18107
18108 OwnedDecl = true;
18109 // In C++, don't return an invalid declaration. We can't recover well from
18110 // the cases where we make the type anonymous.
18111 if (Invalid && getLangOpts().CPlusPlus) {
18112 if (New->isBeingDefined())
18113 if (auto RD = dyn_cast<RecordDecl>(New))
18114 RD->completeDefinition();
18115 return true;
18116 } else if (SkipBody && SkipBody->ShouldSkip) {
18117 return SkipBody->Previous;
18118 } else {
18119 return New;
18120 }
18121}
18122
18125 TagDecl *Tag = cast<TagDecl>(TagD);
18126
18127 // Enter the tag context.
18128 PushDeclContext(S, Tag);
18129
18131
18132 // If there's a #pragma GCC visibility in scope, set the visibility of this
18133 // record.
18135}
18136
18138 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18139 return false;
18140
18141 // Make the previous decl visible.
18143 return true;
18144}
18145
18147 SourceLocation FinalLoc,
18148 bool IsFinalSpelledSealed,
18149 bool IsAbstract,
18150 SourceLocation LBraceLoc) {
18152 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18153
18154 FieldCollector->StartClass();
18155
18156 if (!Record->getIdentifier())
18157 return;
18158
18159 if (IsAbstract)
18160 Record->markAbstract();
18161
18162 if (FinalLoc.isValid()) {
18163 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18164 IsFinalSpelledSealed
18165 ? FinalAttr::Keyword_sealed
18166 : FinalAttr::Keyword_final));
18167 }
18168 // C++ [class]p2:
18169 // [...] The class-name is also inserted into the scope of the
18170 // class itself; this is known as the injected-class-name. For
18171 // purposes of access checking, the injected-class-name is treated
18172 // as if it were a public member name.
18173 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18174 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18175 Record->getLocation(), Record->getIdentifier(),
18176 /*PrevDecl=*/nullptr,
18177 /*DelayTypeCreation=*/true);
18178 Context.getTypeDeclType(InjectedClassName, Record);
18179 InjectedClassName->setImplicit();
18180 InjectedClassName->setAccess(AS_public);
18181 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18182 InjectedClassName->setDescribedClassTemplate(Template);
18183 PushOnScopeChains(InjectedClassName, S);
18184 assert(InjectedClassName->isInjectedClassName() &&
18185 "Broken injected-class-name");
18186}
18187
18189 SourceRange BraceRange) {
18191 TagDecl *Tag = cast<TagDecl>(TagD);
18192 Tag->setBraceRange(BraceRange);
18193
18194 // Make sure we "complete" the definition even it is invalid.
18195 if (Tag->isBeingDefined()) {
18196 assert(Tag->isInvalidDecl() && "We should already have completed it");
18197 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18198 RD->completeDefinition();
18199 }
18200
18201 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18202 FieldCollector->FinishClass();
18203 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18204 auto *Def = RD->getDefinition();
18205 assert(Def && "The record is expected to have a completed definition");
18206 unsigned NumInitMethods = 0;
18207 for (auto *Method : Def->methods()) {
18208 if (!Method->getIdentifier())
18209 continue;
18210 if (Method->getName() == "__init")
18211 NumInitMethods++;
18212 }
18213 if (NumInitMethods > 1 || !Def->hasInitMethod())
18214 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18215 }
18216
18217 // If we're defining a dynamic class in a module interface unit, we always
18218 // need to produce the vtable for it, even if the vtable is not used in the
18219 // current TU.
18220 //
18221 // The case where the current class is not dynamic is handled in
18222 // MarkVTableUsed.
18223 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18224 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18225 }
18226
18227 // Exit this scope of this tag's definition.
18229
18230 if (getCurLexicalContext()->isObjCContainer() &&
18231 Tag->getDeclContext()->isFileContext())
18232 Tag->setTopLevelDeclInObjCContainer();
18233
18234 // Notify the consumer that we've defined a tag.
18235 if (!Tag->isInvalidDecl())
18237
18238 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18239 // from XLs and instead matches the XL #pragma pack(1) behavior.
18240 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18241 AlignPackStack.hasValue()) {
18242 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18243 // Only diagnose #pragma align(packed).
18244 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18245 return;
18246 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18247 if (!RD)
18248 return;
18249 // Only warn if there is at least 1 bitfield member.
18250 if (llvm::any_of(RD->fields(),
18251 [](const FieldDecl *FD) { return FD->isBitField(); }))
18252 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18253 }
18254}
18255
18258 TagDecl *Tag = cast<TagDecl>(TagD);
18259 Tag->setInvalidDecl();
18260
18261 // Make sure we "complete" the definition even it is invalid.
18262 if (Tag->isBeingDefined()) {
18263 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18264 RD->completeDefinition();
18265 }
18266
18267 // We're undoing ActOnTagStartDefinition here, not
18268 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18269 // the FieldCollector.
18270
18272}
18273
18274// Note that FieldName may be null for anonymous bitfields.
18276 const IdentifierInfo *FieldName,
18277 QualType FieldTy, bool IsMsStruct,
18278 Expr *BitWidth) {
18279 assert(BitWidth);
18280 if (BitWidth->containsErrors())
18281 return ExprError();
18282
18283 // C99 6.7.2.1p4 - verify the field type.
18284 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18285 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18286 // Handle incomplete and sizeless types with a specific error.
18287 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18288 diag::err_field_incomplete_or_sizeless))
18289 return ExprError();
18290 if (FieldName)
18291 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18292 << FieldName << FieldTy << BitWidth->getSourceRange();
18293 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18294 << FieldTy << BitWidth->getSourceRange();
18295 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18297 return ExprError();
18298
18299 // If the bit-width is type- or value-dependent, don't try to check
18300 // it now.
18301 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18302 return BitWidth;
18303
18304 llvm::APSInt Value;
18306 if (ICE.isInvalid())
18307 return ICE;
18308 BitWidth = ICE.get();
18309
18310 // Zero-width bitfield is ok for anonymous field.
18311 if (Value == 0 && FieldName)
18312 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18313 << FieldName << BitWidth->getSourceRange();
18314
18315 if (Value.isSigned() && Value.isNegative()) {
18316 if (FieldName)
18317 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18318 << FieldName << toString(Value, 10);
18319 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18320 << toString(Value, 10);
18321 }
18322
18323 // The size of the bit-field must not exceed our maximum permitted object
18324 // size.
18325 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18326 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18327 << !FieldName << FieldName << toString(Value, 10);
18328 }
18329
18330 if (!FieldTy->isDependentType()) {
18331 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18332 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18333 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18334
18335 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18336 // ABI.
18337 bool CStdConstraintViolation =
18338 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18339 bool MSBitfieldViolation =
18340 Value.ugt(TypeStorageSize) &&
18341 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18342 if (CStdConstraintViolation || MSBitfieldViolation) {
18343 unsigned DiagWidth =
18344 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18345 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18346 << (bool)FieldName << FieldName << toString(Value, 10)
18347 << !CStdConstraintViolation << DiagWidth;
18348 }
18349
18350 // Warn on types where the user might conceivably expect to get all
18351 // specified bits as value bits: that's all integral types other than
18352 // 'bool'.
18353 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18354 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18355 << FieldName << toString(Value, 10)
18356 << (unsigned)TypeWidth;
18357 }
18358 }
18359
18360 if (isa<ConstantExpr>(BitWidth))
18361 return BitWidth;
18362 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
18363}
18364
18366 Declarator &D, Expr *BitfieldWidth) {
18367 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18368 D, BitfieldWidth,
18369 /*InitStyle=*/ICIS_NoInit, AS_public);
18370 return Res;
18371}
18372
18374 SourceLocation DeclStart,
18375 Declarator &D, Expr *BitWidth,
18376 InClassInitStyle InitStyle,
18377 AccessSpecifier AS) {
18378 if (D.isDecompositionDeclarator()) {
18379 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18380 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18381 << Decomp.getSourceRange();
18382 return nullptr;
18383 }
18384
18385 const IdentifierInfo *II = D.getIdentifier();
18386 SourceLocation Loc = DeclStart;
18387 if (II) Loc = D.getIdentifierLoc();
18388
18390 QualType T = TInfo->getType();
18391 if (getLangOpts().CPlusPlus) {
18393
18394 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18396 D.setInvalidType();
18397 T = Context.IntTy;
18399 }
18400 }
18401
18402 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18403
18404 if (D.getDeclSpec().isInlineSpecified())
18405 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18406 << getLangOpts().CPlusPlus17;
18407 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18408 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18409 diag::err_invalid_thread)
18411
18412 // Check to see if this name was declared as a member previously
18413 NamedDecl *PrevDecl = nullptr;
18415 RedeclarationKind::ForVisibleRedeclaration);
18416 LookupName(Previous, S);
18417 switch (Previous.getResultKind()) {
18420 PrevDecl = Previous.getAsSingle<NamedDecl>();
18421 break;
18422
18424 PrevDecl = Previous.getRepresentativeDecl();
18425 break;
18426
18430 break;
18431 }
18432 Previous.suppressDiagnostics();
18433
18434 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18435 // Maybe we will complain about the shadowed template parameter.
18436 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18437 // Just pretend that we didn't see the previous declaration.
18438 PrevDecl = nullptr;
18439 }
18440
18441 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18442 PrevDecl = nullptr;
18443
18444 bool Mutable
18445 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18446 SourceLocation TSSL = D.getBeginLoc();
18447 FieldDecl *NewFD
18448 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18449 TSSL, AS, PrevDecl, &D);
18450
18451 if (NewFD->isInvalidDecl())
18452 Record->setInvalidDecl();
18453
18454 if (D.getDeclSpec().isModulePrivateSpecified())
18455 NewFD->setModulePrivate();
18456
18457 if (NewFD->isInvalidDecl() && PrevDecl) {
18458 // Don't introduce NewFD into scope; there's already something
18459 // with the same name in the same scope.
18460 } else if (II) {
18461 PushOnScopeChains(NewFD, S);
18462 } else
18463 Record->addDecl(NewFD);
18464
18465 return NewFD;
18466}
18467
18469 TypeSourceInfo *TInfo,
18471 bool Mutable, Expr *BitWidth,
18472 InClassInitStyle InitStyle,
18473 SourceLocation TSSL,
18474 AccessSpecifier AS, NamedDecl *PrevDecl,
18475 Declarator *D) {
18476 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18477 bool InvalidDecl = false;
18478 if (D) InvalidDecl = D->isInvalidType();
18479
18480 // If we receive a broken type, recover by assuming 'int' and
18481 // marking this declaration as invalid.
18482 if (T.isNull() || T->containsErrors()) {
18483 InvalidDecl = true;
18484 T = Context.IntTy;
18485 }
18486
18488 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18489 bool isIncomplete =
18490 LangOpts.HLSL // HLSL allows sizeless builtin types
18491 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
18493 diag::err_field_incomplete_or_sizeless);
18494 if (isIncomplete) {
18495 // Fields of incomplete type force their record to be invalid.
18496 Record->setInvalidDecl();
18497 InvalidDecl = true;
18498 } else {
18499 NamedDecl *Def;
18500 EltTy->isIncompleteType(&Def);
18501 if (Def && Def->isInvalidDecl()) {
18502 Record->setInvalidDecl();
18503 InvalidDecl = true;
18504 }
18505 }
18506 }
18507
18508 // TR 18037 does not allow fields to be declared with address space
18509 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18511 Diag(Loc, diag::err_field_with_address_space);
18512 Record->setInvalidDecl();
18513 InvalidDecl = true;
18514 }
18515
18516 if (LangOpts.OpenCL) {
18517 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18518 // used as structure or union field: image, sampler, event or block types.
18519 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18520 T->isBlockPointerType()) {
18521 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18522 Record->setInvalidDecl();
18523 InvalidDecl = true;
18524 }
18525 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18526 // is enabled.
18527 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18528 "__cl_clang_bitfields", LangOpts)) {
18529 Diag(Loc, diag::err_opencl_bitfields);
18530 InvalidDecl = true;
18531 }
18532 }
18533
18534 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18535 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18536 T.hasQualifiers()) {
18537 InvalidDecl = true;
18538 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18539 }
18540
18541 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18542 // than a variably modified type.
18543 if (!InvalidDecl && T->isVariablyModifiedType()) {
18545 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18546 InvalidDecl = true;
18547 }
18548
18549 // Fields can not have abstract class types
18550 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18551 diag::err_abstract_type_in_decl,
18553 InvalidDecl = true;
18554
18555 if (InvalidDecl)
18556 BitWidth = nullptr;
18557 // If this is declared as a bit-field, check the bit-field.
18558 if (BitWidth) {
18559 BitWidth =
18560 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18561 if (!BitWidth) {
18562 InvalidDecl = true;
18563 BitWidth = nullptr;
18564 }
18565 }
18566
18567 // Check that 'mutable' is consistent with the type of the declaration.
18568 if (!InvalidDecl && Mutable) {
18569 unsigned DiagID = 0;
18570 if (T->isReferenceType())
18571 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18572 : diag::err_mutable_reference;
18573 else if (T.isConstQualified())
18574 DiagID = diag::err_mutable_const;
18575
18576 if (DiagID) {
18577 SourceLocation ErrLoc = Loc;
18578 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18579 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18580 Diag(ErrLoc, DiagID);
18581 if (DiagID != diag::ext_mutable_reference) {
18582 Mutable = false;
18583 InvalidDecl = true;
18584 }
18585 }
18586 }
18587
18588 // C++11 [class.union]p8 (DR1460):
18589 // At most one variant member of a union may have a
18590 // brace-or-equal-initializer.
18591 if (InitStyle != ICIS_NoInit)
18592 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18593
18594 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18595 BitWidth, Mutable, InitStyle);
18596 if (InvalidDecl)
18597 NewFD->setInvalidDecl();
18598
18599 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18600 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18601 Diag(Loc, diag::err_duplicate_member) << II;
18602 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18603 NewFD->setInvalidDecl();
18604 }
18605
18606 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18607 if (Record->isUnion()) {
18608 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18609 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18610 if (RDecl->getDefinition()) {
18611 // C++ [class.union]p1: An object of a class with a non-trivial
18612 // constructor, a non-trivial copy constructor, a non-trivial
18613 // destructor, or a non-trivial copy assignment operator
18614 // cannot be a member of a union, nor can an array of such
18615 // objects.
18616 if (CheckNontrivialField(NewFD))
18617 NewFD->setInvalidDecl();
18618 }
18619 }
18620
18621 // C++ [class.union]p1: If a union contains a member of reference type,
18622 // the program is ill-formed, except when compiling with MSVC extensions
18623 // enabled.
18624 if (EltTy->isReferenceType()) {
18625 const bool HaveMSExt =
18626 getLangOpts().MicrosoftExt &&
18628
18629 Diag(NewFD->getLocation(),
18630 HaveMSExt ? diag::ext_union_member_of_reference_type
18631 : diag::err_union_member_of_reference_type)
18632 << NewFD->getDeclName() << EltTy;
18633 if (!HaveMSExt)
18634 NewFD->setInvalidDecl();
18635 }
18636 }
18637 }
18638
18639 // FIXME: We need to pass in the attributes given an AST
18640 // representation, not a parser representation.
18641 if (D) {
18642 // FIXME: The current scope is almost... but not entirely... correct here.
18644
18645 if (NewFD->hasAttrs())
18647 }
18648
18649 // In auto-retain/release, infer strong retension for fields of
18650 // retainable type.
18651 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
18652 NewFD->setInvalidDecl();
18653
18654 if (T.isObjCGCWeak())
18655 Diag(Loc, diag::warn_attribute_weak_on_field);
18656
18657 // PPC MMA non-pointer types are not allowed as field types.
18658 if (Context.getTargetInfo().getTriple().isPPC64() &&
18659 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
18660 NewFD->setInvalidDecl();
18661
18662 NewFD->setAccess(AS);
18663 return NewFD;
18664}
18665
18667 assert(FD);
18668 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18669
18670 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18671 return false;
18672
18674 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18675 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18676 if (RDecl->getDefinition()) {
18677 // We check for copy constructors before constructors
18678 // because otherwise we'll never get complaints about
18679 // copy constructors.
18680
18682 // We're required to check for any non-trivial constructors. Since the
18683 // implicit default constructor is suppressed if there are any
18684 // user-declared constructors, we just need to check that there is a
18685 // trivial default constructor and a trivial copy constructor. (We don't
18686 // worry about move constructors here, since this is a C++98 check.)
18687 if (RDecl->hasNonTrivialCopyConstructor())
18689 else if (!RDecl->hasTrivialDefaultConstructor())
18691 else if (RDecl->hasNonTrivialCopyAssignment())
18693 else if (RDecl->hasNonTrivialDestructor())
18695
18696 if (member != CXXSpecialMemberKind::Invalid) {
18697 if (!getLangOpts().CPlusPlus11 &&
18698 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18699 // Objective-C++ ARC: it is an error to have a non-trivial field of
18700 // a union. However, system headers in Objective-C programs
18701 // occasionally have Objective-C lifetime objects within unions,
18702 // and rather than cause the program to fail, we make those
18703 // members unavailable.
18705 if (getSourceManager().isInSystemHeader(Loc)) {
18706 if (!FD->hasAttr<UnavailableAttr>())
18707 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18708 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18709 return false;
18710 }
18711 }
18712
18713 Diag(
18714 FD->getLocation(),
18716 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
18717 : diag::err_illegal_union_or_anon_struct_member)
18718 << FD->getParent()->isUnion() << FD->getDeclName()
18719 << llvm::to_underlying(member);
18720 DiagnoseNontrivial(RDecl, member);
18721 return !getLangOpts().CPlusPlus11;
18722 }
18723 }
18724 }
18725
18726 return false;
18727}
18728
18730 SmallVectorImpl<Decl *> &AllIvarDecls) {
18731 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18732 return;
18733
18734 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18735 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18736
18737 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
18738 return;
18739 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18740 if (!ID) {
18741 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18742 if (!CD->IsClassExtension())
18743 return;
18744 }
18745 // No need to add this to end of @implementation.
18746 else
18747 return;
18748 }
18749 // All conditions are met. Add a new bitfield to the tail end of ivars.
18750 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18751 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18752 Expr *BitWidth =
18753 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
18754
18755 Ivar = ObjCIvarDecl::Create(
18756 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
18758 ObjCIvarDecl::Private, BitWidth, true);
18759 AllIvarDecls.push_back(Ivar);
18760}
18761
18762/// [class.dtor]p4:
18763/// At the end of the definition of a class, overload resolution is
18764/// performed among the prospective destructors declared in that class with
18765/// an empty argument list to select the destructor for the class, also
18766/// known as the selected destructor.
18767///
18768/// We do the overload resolution here, then mark the selected constructor in the AST.
18769/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18771 if (!Record->hasUserDeclaredDestructor()) {
18772 return;
18773 }
18774
18775 SourceLocation Loc = Record->getLocation();
18777
18778 for (auto *Decl : Record->decls()) {
18779 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18780 if (DD->isInvalidDecl())
18781 continue;
18782 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18783 OCS);
18784 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18785 }
18786 }
18787
18788 if (OCS.empty()) {
18789 return;
18790 }
18792 unsigned Msg = 0;
18793 OverloadCandidateDisplayKind DisplayKind;
18794
18795 switch (OCS.BestViableFunction(S, Loc, Best)) {
18796 case OR_Success:
18797 case OR_Deleted:
18798 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18799 break;
18800
18801 case OR_Ambiguous:
18802 Msg = diag::err_ambiguous_destructor;
18803 DisplayKind = OCD_AmbiguousCandidates;
18804 break;
18805
18807 Msg = diag::err_no_viable_destructor;
18808 DisplayKind = OCD_AllCandidates;
18809 break;
18810 }
18811
18812 if (Msg) {
18813 // OpenCL have got their own thing going with destructors. It's slightly broken,
18814 // but we allow it.
18815 if (!S.LangOpts.OpenCL) {
18816 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18817 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18818 Record->setInvalidDecl();
18819 }
18820 // It's a bit hacky: At this point we've raised an error but we want the
18821 // rest of the compiler to continue somehow working. However almost
18822 // everything we'll try to do with the class will depend on there being a
18823 // destructor. So let's pretend the first one is selected and hope for the
18824 // best.
18825 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18826 }
18827}
18828
18829/// [class.mem.special]p5
18830/// Two special member functions are of the same kind if:
18831/// - they are both default constructors,
18832/// - they are both copy or move constructors with the same first parameter
18833/// type, or
18834/// - they are both copy or move assignment operators with the same first
18835/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18837 CXXMethodDecl *M1,
18838 CXXMethodDecl *M2,
18840 // We don't want to compare templates to non-templates: See
18841 // https://github.com/llvm/llvm-project/issues/59206
18843 return bool(M1->getDescribedFunctionTemplate()) ==
18845 // FIXME: better resolve CWG
18846 // https://cplusplus.github.io/CWG/issues/2787.html
18847 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18848 M2->getNonObjectParameter(0)->getType()))
18849 return false;
18852 return false;
18853
18854 return true;
18855}
18856
18857/// [class.mem.special]p6:
18858/// An eligible special member function is a special member function for which:
18859/// - the function is not deleted,
18860/// - the associated constraints, if any, are satisfied, and
18861/// - no special member function of the same kind whose associated constraints
18862/// [CWG2595], if any, are satisfied is more constrained.
18866 SmallVector<bool, 4> SatisfactionStatus;
18867
18868 for (CXXMethodDecl *Method : Methods) {
18869 const Expr *Constraints = Method->getTrailingRequiresClause();
18870 if (!Constraints)
18871 SatisfactionStatus.push_back(true);
18872 else {
18873 ConstraintSatisfaction Satisfaction;
18874 if (S.CheckFunctionConstraints(Method, Satisfaction))
18875 SatisfactionStatus.push_back(false);
18876 else
18877 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18878 }
18879 }
18880
18881 for (size_t i = 0; i < Methods.size(); i++) {
18882 if (!SatisfactionStatus[i])
18883 continue;
18884 CXXMethodDecl *Method = Methods[i];
18885 CXXMethodDecl *OrigMethod = Method;
18886 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18887 OrigMethod = cast<CXXMethodDecl>(MF);
18888
18889 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18890 bool AnotherMethodIsMoreConstrained = false;
18891 for (size_t j = 0; j < Methods.size(); j++) {
18892 if (i == j || !SatisfactionStatus[j])
18893 continue;
18894 CXXMethodDecl *OtherMethod = Methods[j];
18895 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18896 OtherMethod = cast<CXXMethodDecl>(MF);
18897
18898 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18899 CSM))
18900 continue;
18901
18902 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18903 if (!OtherConstraints)
18904 continue;
18905 if (!Constraints) {
18906 AnotherMethodIsMoreConstrained = true;
18907 break;
18908 }
18909 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18910 {Constraints},
18911 AnotherMethodIsMoreConstrained)) {
18912 // There was an error with the constraints comparison. Exit the loop
18913 // and don't consider this function eligible.
18914 AnotherMethodIsMoreConstrained = true;
18915 }
18916 if (AnotherMethodIsMoreConstrained)
18917 break;
18918 }
18919 // FIXME: Do not consider deleted methods as eligible after implementing
18920 // DR1734 and DR1496.
18921 if (!AnotherMethodIsMoreConstrained) {
18922 Method->setIneligibleOrNotSelected(false);
18923 Record->addedEligibleSpecialMemberFunction(Method,
18924 1 << llvm::to_underlying(CSM));
18925 }
18926 }
18927}
18928
18931 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18932 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18933 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18934 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18935 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18936
18937 for (auto *Decl : Record->decls()) {
18938 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18939 if (!MD) {
18940 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18941 if (FTD)
18942 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18943 }
18944 if (!MD)
18945 continue;
18946 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18947 if (CD->isInvalidDecl())
18948 continue;
18949 if (CD->isDefaultConstructor())
18950 DefaultConstructors.push_back(MD);
18951 else if (CD->isCopyConstructor())
18952 CopyConstructors.push_back(MD);
18953 else if (CD->isMoveConstructor())
18954 MoveConstructors.push_back(MD);
18955 } else if (MD->isCopyAssignmentOperator()) {
18956 CopyAssignmentOperators.push_back(MD);
18957 } else if (MD->isMoveAssignmentOperator()) {
18958 MoveAssignmentOperators.push_back(MD);
18959 }
18960 }
18961
18962 SetEligibleMethods(S, Record, DefaultConstructors,
18964 SetEligibleMethods(S, Record, CopyConstructors,
18966 SetEligibleMethods(S, Record, MoveConstructors,
18968 SetEligibleMethods(S, Record, CopyAssignmentOperators,
18970 SetEligibleMethods(S, Record, MoveAssignmentOperators,
18972}
18973
18974void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18975 ArrayRef<Decl *> Fields, SourceLocation LBrac,
18976 SourceLocation RBrac,
18977 const ParsedAttributesView &Attrs) {
18978 assert(EnclosingDecl && "missing record or interface decl");
18979
18980 // If this is an Objective-C @implementation or category and we have
18981 // new fields here we should reset the layout of the interface since
18982 // it will now change.
18983 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
18984 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18985 switch (DC->getKind()) {
18986 default: break;
18987 case Decl::ObjCCategory:
18988 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18989 break;
18990 case Decl::ObjCImplementation:
18991 Context.
18992 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18993 break;
18994 }
18995 }
18996
18997 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18998 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18999
19000 // Start counting up the number of named members; make sure to include
19001 // members of anonymous structs and unions in the total.
19002 unsigned NumNamedMembers = 0;
19003 if (Record) {
19004 for (const auto *I : Record->decls()) {
19005 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19006 if (IFD->getDeclName())
19007 ++NumNamedMembers;
19008 }
19009 }
19010
19011 // Verify that all the fields are okay.
19013
19014 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19015 i != end; ++i) {
19016 FieldDecl *FD = cast<FieldDecl>(*i);
19017
19018 // Get the type for the field.
19019 const Type *FDTy = FD->getType().getTypePtr();
19020
19021 if (!FD->isAnonymousStructOrUnion()) {
19022 // Remember all fields written by the user.
19023 RecFields.push_back(FD);
19024 }
19025
19026 // If the field is already invalid for some reason, don't emit more
19027 // diagnostics about it.
19028 if (FD->isInvalidDecl()) {
19029 EnclosingDecl->setInvalidDecl();
19030 continue;
19031 }
19032
19033 // C99 6.7.2.1p2:
19034 // A structure or union shall not contain a member with
19035 // incomplete or function type (hence, a structure shall not
19036 // contain an instance of itself, but may contain a pointer to
19037 // an instance of itself), except that the last member of a
19038 // structure with more than one named member may have incomplete
19039 // array type; such a structure (and any union containing,
19040 // possibly recursively, a member that is such a structure)
19041 // shall not be a member of a structure or an element of an
19042 // array.
19043 bool IsLastField = (i + 1 == Fields.end());
19044 if (FDTy->isFunctionType()) {
19045 // Field declared as a function.
19046 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19047 << FD->getDeclName();
19048 FD->setInvalidDecl();
19049 EnclosingDecl->setInvalidDecl();
19050 continue;
19051 } else if (FDTy->isIncompleteArrayType() &&
19052 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19053 if (Record) {
19054 // Flexible array member.
19055 // Microsoft and g++ is more permissive regarding flexible array.
19056 // It will accept flexible array in union and also
19057 // as the sole element of a struct/class.
19058 unsigned DiagID = 0;
19059 if (!Record->isUnion() && !IsLastField) {
19060 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19061 << FD->getDeclName() << FD->getType()
19062 << llvm::to_underlying(Record->getTagKind());
19063 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19064 FD->setInvalidDecl();
19065 EnclosingDecl->setInvalidDecl();
19066 continue;
19067 } else if (Record->isUnion())
19068 DiagID = getLangOpts().MicrosoftExt
19069 ? diag::ext_flexible_array_union_ms
19070 : diag::ext_flexible_array_union_gnu;
19071 else if (NumNamedMembers < 1)
19072 DiagID = getLangOpts().MicrosoftExt
19073 ? diag::ext_flexible_array_empty_aggregate_ms
19074 : diag::ext_flexible_array_empty_aggregate_gnu;
19075
19076 if (DiagID)
19077 Diag(FD->getLocation(), DiagID)
19078 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19079 // While the layout of types that contain virtual bases is not specified
19080 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19081 // virtual bases after the derived members. This would make a flexible
19082 // array member declared at the end of an object not adjacent to the end
19083 // of the type.
19084 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19085 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19086 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19087 if (!getLangOpts().C99)
19088 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19089 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19090
19091 // If the element type has a non-trivial destructor, we would not
19092 // implicitly destroy the elements, so disallow it for now.
19093 //
19094 // FIXME: GCC allows this. We should probably either implicitly delete
19095 // the destructor of the containing class, or just allow this.
19096 QualType BaseElem = Context.getBaseElementType(FD->getType());
19097 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19098 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19099 << FD->getDeclName() << FD->getType();
19100 FD->setInvalidDecl();
19101 EnclosingDecl->setInvalidDecl();
19102 continue;
19103 }
19104 // Okay, we have a legal flexible array member at the end of the struct.
19105 Record->setHasFlexibleArrayMember(true);
19106 } else {
19107 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19108 // unless they are followed by another ivar. That check is done
19109 // elsewhere, after synthesized ivars are known.
19110 }
19111 } else if (!FDTy->isDependentType() &&
19112 (LangOpts.HLSL // HLSL allows sizeless builtin types
19114 diag::err_incomplete_type)
19116 FD->getLocation(), FD->getType(),
19117 diag::err_field_incomplete_or_sizeless))) {
19118 // Incomplete type
19119 FD->setInvalidDecl();
19120 EnclosingDecl->setInvalidDecl();
19121 continue;
19122 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19123 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19124 // A type which contains a flexible array member is considered to be a
19125 // flexible array member.
19126 Record->setHasFlexibleArrayMember(true);
19127 if (!Record->isUnion()) {
19128 // If this is a struct/class and this is not the last element, reject
19129 // it. Note that GCC supports variable sized arrays in the middle of
19130 // structures.
19131 if (!IsLastField)
19132 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19133 << FD->getDeclName() << FD->getType();
19134 else {
19135 // We support flexible arrays at the end of structs in
19136 // other structs as an extension.
19137 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19138 << FD->getDeclName();
19139 }
19140 }
19141 }
19142 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19144 diag::err_abstract_type_in_decl,
19146 // Ivars can not have abstract class types
19147 FD->setInvalidDecl();
19148 }
19149 if (Record && FDTTy->getDecl()->hasObjectMember())
19150 Record->setHasObjectMember(true);
19151 if (Record && FDTTy->getDecl()->hasVolatileMember())
19152 Record->setHasVolatileMember(true);
19153 } else if (FDTy->isObjCObjectType()) {
19154 /// A field cannot be an Objective-c object
19155 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19158 FD->setType(T);
19159 } else if (Record && Record->isUnion() &&
19161 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19162 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19165 // For backward compatibility, fields of C unions declared in system
19166 // headers that have non-trivial ObjC ownership qualifications are marked
19167 // as unavailable unless the qualifier is explicit and __strong. This can
19168 // break ABI compatibility between programs compiled with ARC and MRR, but
19169 // is a better option than rejecting programs using those unions under
19170 // ARC.
19171 FD->addAttr(UnavailableAttr::CreateImplicit(
19172 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19173 FD->getLocation()));
19174 } else if (getLangOpts().ObjC &&
19175 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19176 !Record->hasObjectMember()) {
19177 if (FD->getType()->isObjCObjectPointerType() ||
19178 FD->getType().isObjCGCStrong())
19179 Record->setHasObjectMember(true);
19180 else if (Context.getAsArrayType(FD->getType())) {
19181 QualType BaseType = Context.getBaseElementType(FD->getType());
19182 if (BaseType->isRecordType() &&
19183 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19184 Record->setHasObjectMember(true);
19185 else if (BaseType->isObjCObjectPointerType() ||
19186 BaseType.isObjCGCStrong())
19187 Record->setHasObjectMember(true);
19188 }
19189 }
19190
19191 if (Record && !getLangOpts().CPlusPlus &&
19192 !shouldIgnoreForRecordTriviality(FD)) {
19193 QualType FT = FD->getType();
19195 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19197 Record->isUnion())
19198 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19199 }
19202 Record->setNonTrivialToPrimitiveCopy(true);
19203 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19204 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19205 }
19206 if (FT.isDestructedType()) {
19207 Record->setNonTrivialToPrimitiveDestroy(true);
19208 Record->setParamDestroyedInCallee(true);
19209 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19210 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19211 }
19212
19213 if (const auto *RT = FT->getAs<RecordType>()) {
19214 if (RT->getDecl()->getArgPassingRestrictions() ==
19216 Record->setArgPassingRestrictions(
19219 Record->setArgPassingRestrictions(
19221 }
19222
19223 if (Record && FD->getType().isVolatileQualified())
19224 Record->setHasVolatileMember(true);
19225 // Keep track of the number of named members.
19226 if (FD->getIdentifier())
19227 ++NumNamedMembers;
19228 }
19229
19230 // Okay, we successfully defined 'Record'.
19231 if (Record) {
19232 bool Completed = false;
19233 if (S) {
19234 Scope *Parent = S->getParent();
19235 if (Parent && Parent->isTypeAliasScope() &&
19236 Parent->isTemplateParamScope())
19237 Record->setInvalidDecl();
19238 }
19239
19240 if (CXXRecord) {
19241 if (!CXXRecord->isInvalidDecl()) {
19242 // Set access bits correctly on the directly-declared conversions.
19244 I = CXXRecord->conversion_begin(),
19245 E = CXXRecord->conversion_end(); I != E; ++I)
19246 I.setAccess((*I)->getAccess());
19247 }
19248
19249 // Add any implicitly-declared members to this class.
19251
19252 if (!CXXRecord->isDependentType()) {
19253 if (!CXXRecord->isInvalidDecl()) {
19254 // If we have virtual base classes, we may end up finding multiple
19255 // final overriders for a given virtual function. Check for this
19256 // problem now.
19257 if (CXXRecord->getNumVBases()) {
19258 CXXFinalOverriderMap FinalOverriders;
19259 CXXRecord->getFinalOverriders(FinalOverriders);
19260
19261 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19262 MEnd = FinalOverriders.end();
19263 M != MEnd; ++M) {
19264 for (OverridingMethods::iterator SO = M->second.begin(),
19265 SOEnd = M->second.end();
19266 SO != SOEnd; ++SO) {
19267 assert(SO->second.size() > 0 &&
19268 "Virtual function without overriding functions?");
19269 if (SO->second.size() == 1)
19270 continue;
19271
19272 // C++ [class.virtual]p2:
19273 // In a derived class, if a virtual member function of a base
19274 // class subobject has more than one final overrider the
19275 // program is ill-formed.
19276 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19277 << (const NamedDecl *)M->first << Record;
19278 Diag(M->first->getLocation(),
19279 diag::note_overridden_virtual_function);
19281 OM = SO->second.begin(),
19282 OMEnd = SO->second.end();
19283 OM != OMEnd; ++OM)
19284 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19285 << (const NamedDecl *)M->first << OM->Method->getParent();
19286
19287 Record->setInvalidDecl();
19288 }
19289 }
19290 CXXRecord->completeDefinition(&FinalOverriders);
19291 Completed = true;
19292 }
19293 }
19294 ComputeSelectedDestructor(*this, CXXRecord);
19296 }
19297 }
19298
19299 if (!Completed)
19300 Record->completeDefinition();
19301
19302 // Handle attributes before checking the layout.
19304
19305 // Check to see if a FieldDecl is a pointer to a function.
19306 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19307 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19308 if (!FD) {
19309 // Check whether this is a forward declaration that was inserted by
19310 // Clang. This happens when a non-forward declared / defined type is
19311 // used, e.g.:
19312 //
19313 // struct foo {
19314 // struct bar *(*f)();
19315 // struct bar *(*g)();
19316 // };
19317 //
19318 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19319 // incomplete definition.
19320 if (const auto *TD = dyn_cast<TagDecl>(D))
19321 return !TD->isCompleteDefinition();
19322 return false;
19323 }
19324 QualType FieldType = FD->getType().getDesugaredType(Context);
19325 if (isa<PointerType>(FieldType)) {
19326 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19327 return PointeeType.getDesugaredType(Context)->isFunctionType();
19328 }
19329 return false;
19330 };
19331
19332 // Maybe randomize the record's decls. We automatically randomize a record
19333 // of function pointers, unless it has the "no_randomize_layout" attribute.
19334 if (!getLangOpts().CPlusPlus &&
19335 (Record->hasAttr<RandomizeLayoutAttr>() ||
19336 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19337 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19338 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19339 !Record->isRandomized()) {
19340 SmallVector<Decl *, 32> NewDeclOrdering;
19342 NewDeclOrdering))
19343 Record->reorderDecls(NewDeclOrdering);
19344 }
19345
19346 // We may have deferred checking for a deleted destructor. Check now.
19347 if (CXXRecord) {
19348 auto *Dtor = CXXRecord->getDestructor();
19349 if (Dtor && Dtor->isImplicit() &&
19351 CXXRecord->setImplicitDestructorIsDeleted();
19352 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19353 }
19354 }
19355
19356 if (Record->hasAttrs()) {
19358
19359 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19360 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19361 IA->getRange(), IA->getBestCase(),
19362 IA->getInheritanceModel());
19363 }
19364
19365 // Check if the structure/union declaration is a type that can have zero
19366 // size in C. For C this is a language extension, for C++ it may cause
19367 // compatibility problems.
19368 bool CheckForZeroSize;
19369 if (!getLangOpts().CPlusPlus) {
19370 CheckForZeroSize = true;
19371 } else {
19372 // For C++ filter out types that cannot be referenced in C code.
19373 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19374 CheckForZeroSize =
19375 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19376 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19377 CXXRecord->isCLike();
19378 }
19379 if (CheckForZeroSize) {
19380 bool ZeroSize = true;
19381 bool IsEmpty = true;
19382 unsigned NonBitFields = 0;
19383 for (RecordDecl::field_iterator I = Record->field_begin(),
19384 E = Record->field_end();
19385 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19386 IsEmpty = false;
19387 if (I->isUnnamedBitField()) {
19388 if (!I->isZeroLengthBitField())
19389 ZeroSize = false;
19390 } else {
19391 ++NonBitFields;
19392 QualType FieldType = I->getType();
19393 if (FieldType->isIncompleteType() ||
19394 !Context.getTypeSizeInChars(FieldType).isZero())
19395 ZeroSize = false;
19396 }
19397 }
19398
19399 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19400 // allowed in C++, but warn if its declaration is inside
19401 // extern "C" block.
19402 if (ZeroSize) {
19403 Diag(RecLoc, getLangOpts().CPlusPlus ?
19404 diag::warn_zero_size_struct_union_in_extern_c :
19405 diag::warn_zero_size_struct_union_compat)
19406 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19407 }
19408
19409 // Structs without named members are extension in C (C99 6.7.2.1p7),
19410 // but are accepted by GCC. In C2y, this became implementation-defined
19411 // (C2y 6.7.3.2p10).
19412 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
19413 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
19414 : diag::ext_no_named_members_in_struct_union)
19415 << Record->isUnion();
19416 }
19417 }
19418 } else {
19419 ObjCIvarDecl **ClsFields =
19420 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19421 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19422 ID->setEndOfDefinitionLoc(RBrac);
19423 // Add ivar's to class's DeclContext.
19424 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19425 ClsFields[i]->setLexicalDeclContext(ID);
19426 ID->addDecl(ClsFields[i]);
19427 }
19428 // Must enforce the rule that ivars in the base classes may not be
19429 // duplicates.
19430 if (ID->getSuperClass())
19431 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19432 } else if (ObjCImplementationDecl *IMPDecl =
19433 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19434 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19435 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19436 // Ivar declared in @implementation never belongs to the implementation.
19437 // Only it is in implementation's lexical context.
19438 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19439 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
19440 RBrac);
19441 IMPDecl->setIvarLBraceLoc(LBrac);
19442 IMPDecl->setIvarRBraceLoc(RBrac);
19443 } else if (ObjCCategoryDecl *CDecl =
19444 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19445 // case of ivars in class extension; all other cases have been
19446 // reported as errors elsewhere.
19447 // FIXME. Class extension does not have a LocEnd field.
19448 // CDecl->setLocEnd(RBrac);
19449 // Add ivar's to class extension's DeclContext.
19450 // Diagnose redeclaration of private ivars.
19451 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19452 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19453 if (IDecl) {
19454 if (const ObjCIvarDecl *ClsIvar =
19455 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19456 Diag(ClsFields[i]->getLocation(),
19457 diag::err_duplicate_ivar_declaration);
19458 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19459 continue;
19460 }
19461 for (const auto *Ext : IDecl->known_extensions()) {
19462 if (const ObjCIvarDecl *ClsExtIvar
19463 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19464 Diag(ClsFields[i]->getLocation(),
19465 diag::err_duplicate_ivar_declaration);
19466 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19467 continue;
19468 }
19469 }
19470 }
19471 ClsFields[i]->setLexicalDeclContext(CDecl);
19472 CDecl->addDecl(ClsFields[i]);
19473 }
19474 CDecl->setIvarLBraceLoc(LBrac);
19475 CDecl->setIvarRBraceLoc(RBrac);
19476 }
19477 }
19479}
19480
19481/// Determine whether the given integral value is representable within
19482/// the given type T.
19484 llvm::APSInt &Value,
19485 QualType T) {
19486 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19487 "Integral type required!");
19488 unsigned BitWidth = Context.getIntWidth(T);
19489
19490 if (Value.isUnsigned() || Value.isNonNegative()) {
19492 --BitWidth;
19493 return Value.getActiveBits() <= BitWidth;
19494 }
19495 return Value.getSignificantBits() <= BitWidth;
19496}
19497
19498// Given an integral type, return the next larger integral type
19499// (or a NULL type of no such type exists).
19501 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19502 // enum checking below.
19503 assert((T->isIntegralType(Context) ||
19504 T->isEnumeralType()) && "Integral type required!");
19505 const unsigned NumTypes = 4;
19506 QualType SignedIntegralTypes[NumTypes] = {
19507 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19508 };
19509 QualType UnsignedIntegralTypes[NumTypes] = {
19510 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19511 Context.UnsignedLongLongTy
19512 };
19513
19514 unsigned BitWidth = Context.getTypeSize(T);
19515 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19516 : UnsignedIntegralTypes;
19517 for (unsigned I = 0; I != NumTypes; ++I)
19518 if (Context.getTypeSize(Types[I]) > BitWidth)
19519 return Types[I];
19520
19521 return QualType();
19522}
19523
19525 EnumConstantDecl *LastEnumConst,
19526 SourceLocation IdLoc,
19528 Expr *Val) {
19529 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19530 llvm::APSInt EnumVal(IntWidth);
19531 QualType EltTy;
19532
19534 Val = nullptr;
19535
19536 if (Val)
19537 Val = DefaultLvalueConversion(Val).get();
19538
19539 if (Val) {
19540 if (Enum->isDependentType() || Val->isTypeDependent() ||
19541 Val->containsErrors())
19542 EltTy = Context.DependentTy;
19543 else {
19544 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19545 // underlying type, but do allow it in all other contexts.
19546 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19547 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19548 // constant-expression in the enumerator-definition shall be a converted
19549 // constant expression of the underlying type.
19550 EltTy = Enum->getIntegerType();
19551 ExprResult Converted =
19552 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19554 if (Converted.isInvalid())
19555 Val = nullptr;
19556 else
19557 Val = Converted.get();
19558 } else if (!Val->isValueDependent() &&
19559 !(Val =
19561 .get())) {
19562 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19563 } else {
19564 if (Enum->isComplete()) {
19565 EltTy = Enum->getIntegerType();
19566
19567 // In Obj-C and Microsoft mode, require the enumeration value to be
19568 // representable in the underlying type of the enumeration. In C++11,
19569 // we perform a non-narrowing conversion as part of converted constant
19570 // expression checking.
19571 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19573 .getTriple()
19574 .isWindowsMSVCEnvironment()) {
19575 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19576 } else {
19577 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19578 }
19579 }
19580
19581 // Cast to the underlying type.
19582 Val = ImpCastExprToType(Val, EltTy,
19583 EltTy->isBooleanType() ? CK_IntegralToBoolean
19584 : CK_IntegralCast)
19585 .get();
19586 } else if (getLangOpts().CPlusPlus) {
19587 // C++11 [dcl.enum]p5:
19588 // If the underlying type is not fixed, the type of each enumerator
19589 // is the type of its initializing value:
19590 // - If an initializer is specified for an enumerator, the
19591 // initializing value has the same type as the expression.
19592 EltTy = Val->getType();
19593 } else {
19594 // C99 6.7.2.2p2:
19595 // The expression that defines the value of an enumeration constant
19596 // shall be an integer constant expression that has a value
19597 // representable as an int.
19598
19599 // Complain if the value is not representable in an int.
19601 Diag(IdLoc, getLangOpts().C23
19602 ? diag::warn_c17_compat_enum_value_not_int
19603 : diag::ext_c23_enum_value_not_int)
19604 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
19605 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19606 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19607 // Force the type of the expression to 'int'.
19608 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19609 }
19610 EltTy = Val->getType();
19611 }
19612 }
19613 }
19614 }
19615
19616 if (!Val) {
19617 if (Enum->isDependentType())
19618 EltTy = Context.DependentTy;
19619 else if (!LastEnumConst) {
19620 // C++0x [dcl.enum]p5:
19621 // If the underlying type is not fixed, the type of each enumerator
19622 // is the type of its initializing value:
19623 // - If no initializer is specified for the first enumerator, the
19624 // initializing value has an unspecified integral type.
19625 //
19626 // GCC uses 'int' for its unspecified integral type, as does
19627 // C99 6.7.2.2p3.
19628 if (Enum->isFixed()) {
19629 EltTy = Enum->getIntegerType();
19630 }
19631 else {
19632 EltTy = Context.IntTy;
19633 }
19634 } else {
19635 // Assign the last value + 1.
19636 EnumVal = LastEnumConst->getInitVal();
19637 ++EnumVal;
19638 EltTy = LastEnumConst->getType();
19639
19640 // Check for overflow on increment.
19641 if (EnumVal < LastEnumConst->getInitVal()) {
19642 // C++0x [dcl.enum]p5:
19643 // If the underlying type is not fixed, the type of each enumerator
19644 // is the type of its initializing value:
19645 //
19646 // - Otherwise the type of the initializing value is the same as
19647 // the type of the initializing value of the preceding enumerator
19648 // unless the incremented value is not representable in that type,
19649 // in which case the type is an unspecified integral type
19650 // sufficient to contain the incremented value. If no such type
19651 // exists, the program is ill-formed.
19653 if (T.isNull() || Enum->isFixed()) {
19654 // There is no integral type larger enough to represent this
19655 // value. Complain, then allow the value to wrap around.
19656 EnumVal = LastEnumConst->getInitVal();
19657 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19658 ++EnumVal;
19659 if (Enum->isFixed())
19660 // When the underlying type is fixed, this is ill-formed.
19661 Diag(IdLoc, diag::err_enumerator_wrapped)
19662 << toString(EnumVal, 10)
19663 << EltTy;
19664 else
19665 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19666 << toString(EnumVal, 10);
19667 } else {
19668 EltTy = T;
19669 }
19670
19671 // Retrieve the last enumerator's value, extent that type to the
19672 // type that is supposed to be large enough to represent the incremented
19673 // value, then increment.
19674 EnumVal = LastEnumConst->getInitVal();
19675 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19676 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19677 ++EnumVal;
19678
19679 // If we're not in C++, diagnose the overflow of enumerator values,
19680 // which in C99 means that the enumerator value is not representable in
19681 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
19682 // are representable in some larger integral type and we allow it in
19683 // older language modes as an extension.
19684 // Exclude fixed enumerators since they are diagnosed with an error for
19685 // this case.
19686 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
19687 Diag(IdLoc, getLangOpts().C23
19688 ? diag::warn_c17_compat_enum_value_not_int
19689 : diag::ext_c23_enum_value_not_int)
19690 << 1 << toString(EnumVal, 10) << 1;
19691 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
19692 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19693 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19694 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
19695 : diag::ext_c23_enum_value_not_int)
19696 << 1 << toString(EnumVal, 10) << 1;
19697 }
19698 }
19699 }
19700
19701 if (!EltTy->isDependentType()) {
19702 // Make the enumerator value match the signedness and size of the
19703 // enumerator's type.
19704 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19705 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19706 }
19707
19708 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19709 Val, EnumVal);
19710}
19711
19713 SourceLocation IILoc) {
19714 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19716 return SkipBodyInfo();
19717
19718 // We have an anonymous enum definition. Look up the first enumerator to
19719 // determine if we should merge the definition with an existing one and
19720 // skip the body.
19721 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19723 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19724 if (!PrevECD)
19725 return SkipBodyInfo();
19726
19727 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19728 NamedDecl *Hidden;
19729 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19731 Skip.Previous = Hidden;
19732 return Skip;
19733 }
19734
19735 return SkipBodyInfo();
19736}
19737
19738Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19740 const ParsedAttributesView &Attrs,
19741 SourceLocation EqualLoc, Expr *Val) {
19742 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19743 EnumConstantDecl *LastEnumConst =
19744 cast_or_null<EnumConstantDecl>(lastEnumConst);
19745
19746 // The scope passed in may not be a decl scope. Zip up the scope tree until
19747 // we find one that is.
19748 S = getNonFieldDeclScope(S);
19749
19750 // Verify that there isn't already something declared with this name in this
19751 // scope.
19752 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
19753 RedeclarationKind::ForVisibleRedeclaration);
19754 LookupName(R, S);
19755 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19756
19757 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19758 // Maybe we will complain about the shadowed template parameter.
19759 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19760 // Just pretend that we didn't see the previous declaration.
19761 PrevDecl = nullptr;
19762 }
19763
19764 // C++ [class.mem]p15:
19765 // If T is the name of a class, then each of the following shall have a name
19766 // different from T:
19767 // - every enumerator of every member of class T that is an unscoped
19768 // enumerated type
19769 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19771 DeclarationNameInfo(Id, IdLoc));
19772
19773 EnumConstantDecl *New =
19774 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19775 if (!New)
19776 return nullptr;
19777
19778 if (PrevDecl) {
19779 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19780 // Check for other kinds of shadowing not already handled.
19781 CheckShadow(New, PrevDecl, R);
19782 }
19783
19784 // When in C++, we may get a TagDecl with the same name; in this case the
19785 // enum constant will 'hide' the tag.
19786 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19787 "Received TagDecl when not in C++!");
19788 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19789 if (isa<EnumConstantDecl>(PrevDecl))
19790 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19791 else
19792 Diag(IdLoc, diag::err_redefinition) << Id;
19793 notePreviousDefinition(PrevDecl, IdLoc);
19794 return nullptr;
19795 }
19796 }
19797
19798 // Process attributes.
19799 ProcessDeclAttributeList(S, New, Attrs);
19800 AddPragmaAttributes(S, New);
19801 ProcessAPINotes(New);
19802
19803 // Register this decl in the current scope stack.
19804 New->setAccess(TheEnumDecl->getAccess());
19805 PushOnScopeChains(New, S);
19806
19808
19809 return New;
19810}
19811
19812// Returns true when the enum initial expression does not trigger the
19813// duplicate enum warning. A few common cases are exempted as follows:
19814// Element2 = Element1
19815// Element2 = Element1 + 1
19816// Element2 = Element1 - 1
19817// Where Element2 and Element1 are from the same enum.
19819 Expr *InitExpr = ECD->getInitExpr();
19820 if (!InitExpr)
19821 return true;
19822 InitExpr = InitExpr->IgnoreImpCasts();
19823
19824 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19825 if (!BO->isAdditiveOp())
19826 return true;
19827 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19828 if (!IL)
19829 return true;
19830 if (IL->getValue() != 1)
19831 return true;
19832
19833 InitExpr = BO->getLHS();
19834 }
19835
19836 // This checks if the elements are from the same enum.
19837 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19838 if (!DRE)
19839 return true;
19840
19841 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19842 if (!EnumConstant)
19843 return true;
19844
19845 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19846 Enum)
19847 return true;
19848
19849 return false;
19850}
19851
19852// Emits a warning when an element is implicitly set a value that
19853// a previous element has already been set to.
19856 // Avoid anonymous enums
19857 if (!Enum->getIdentifier())
19858 return;
19859
19860 // Only check for small enums.
19861 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19862 return;
19863
19864 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19865 return;
19866
19867 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19868 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19869
19870 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19871
19872 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19873 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19874
19875 // Use int64_t as a key to avoid needing special handling for map keys.
19876 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19877 llvm::APSInt Val = D->getInitVal();
19878 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19879 };
19880
19881 DuplicatesVector DupVector;
19882 ValueToVectorMap EnumMap;
19883
19884 // Populate the EnumMap with all values represented by enum constants without
19885 // an initializer.
19886 for (auto *Element : Elements) {
19887 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19888
19889 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19890 // this constant. Skip this enum since it may be ill-formed.
19891 if (!ECD) {
19892 return;
19893 }
19894
19895 // Constants with initializers are handled in the next loop.
19896 if (ECD->getInitExpr())
19897 continue;
19898
19899 // Duplicate values are handled in the next loop.
19900 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19901 }
19902
19903 if (EnumMap.size() == 0)
19904 return;
19905
19906 // Create vectors for any values that has duplicates.
19907 for (auto *Element : Elements) {
19908 // The last loop returned if any constant was null.
19909 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19910 if (!ValidDuplicateEnum(ECD, Enum))
19911 continue;
19912
19913 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19914 if (Iter == EnumMap.end())
19915 continue;
19916
19917 DeclOrVector& Entry = Iter->second;
19918 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19919 // Ensure constants are different.
19920 if (D == ECD)
19921 continue;
19922
19923 // Create new vector and push values onto it.
19924 auto Vec = std::make_unique<ECDVector>();
19925 Vec->push_back(D);
19926 Vec->push_back(ECD);
19927
19928 // Update entry to point to the duplicates vector.
19929 Entry = Vec.get();
19930
19931 // Store the vector somewhere we can consult later for quick emission of
19932 // diagnostics.
19933 DupVector.emplace_back(std::move(Vec));
19934 continue;
19935 }
19936
19937 ECDVector *Vec = cast<ECDVector *>(Entry);
19938 // Make sure constants are not added more than once.
19939 if (*Vec->begin() == ECD)
19940 continue;
19941
19942 Vec->push_back(ECD);
19943 }
19944
19945 // Emit diagnostics.
19946 for (const auto &Vec : DupVector) {
19947 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19948
19949 // Emit warning for one enum constant.
19950 auto *FirstECD = Vec->front();
19951 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19952 << FirstECD << toString(FirstECD->getInitVal(), 10)
19953 << FirstECD->getSourceRange();
19954
19955 // Emit one note for each of the remaining enum constants with
19956 // the same value.
19957 for (auto *ECD : llvm::drop_begin(*Vec))
19958 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19959 << ECD << toString(ECD->getInitVal(), 10)
19960 << ECD->getSourceRange();
19961 }
19962}
19963
19964bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19965 bool AllowMask) const {
19966 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19967 assert(ED->isCompleteDefinition() && "expected enum definition");
19968
19969 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19970 llvm::APInt &FlagBits = R.first->second;
19971
19972 if (R.second) {
19973 for (auto *E : ED->enumerators()) {
19974 const auto &EVal = E->getInitVal();
19975 // Only single-bit enumerators introduce new flag values.
19976 if (EVal.isPowerOf2())
19977 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19978 }
19979 }
19980
19981 // A value is in a flag enum if either its bits are a subset of the enum's
19982 // flag bits (the first condition) or we are allowing masks and the same is
19983 // true of its complement (the second condition). When masks are allowed, we
19984 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19985 //
19986 // While it's true that any value could be used as a mask, the assumption is
19987 // that a mask will have all of the insignificant bits set. Anything else is
19988 // likely a logic error.
19989 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19990 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
19991}
19992
19994 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19995 const ParsedAttributesView &Attrs) {
19996 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19998
19999 ProcessDeclAttributeList(S, Enum, Attrs);
20001
20002 if (Enum->isDependentType()) {
20003 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20004 EnumConstantDecl *ECD =
20005 cast_or_null<EnumConstantDecl>(Elements[i]);
20006 if (!ECD) continue;
20007
20008 ECD->setType(EnumType);
20009 }
20010
20011 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20012 return;
20013 }
20014
20015 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20016 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
20017 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
20018
20019 // Verify that all the values are okay, compute the size of the values, and
20020 // reverse the list.
20021 unsigned NumNegativeBits = 0;
20022 unsigned NumPositiveBits = 0;
20023 bool MembersRepresentableByInt = true;
20024
20025 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20026 EnumConstantDecl *ECD =
20027 cast_or_null<EnumConstantDecl>(Elements[i]);
20028 if (!ECD) continue; // Already issued a diagnostic.
20029
20030 llvm::APSInt InitVal = ECD->getInitVal();
20031
20032 // Keep track of the size of positive and negative values.
20033 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20034 // If the enumerator is zero that should still be counted as a positive
20035 // bit since we need a bit to store the value zero.
20036 unsigned ActiveBits = InitVal.getActiveBits();
20037 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
20038 } else {
20039 NumNegativeBits =
20040 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
20041 }
20042 MembersRepresentableByInt &=
20044 }
20045
20046 // If we have an empty set of enumerators we still need one bit.
20047 // From [dcl.enum]p8
20048 // If the enumerator-list is empty, the values of the enumeration are as if
20049 // the enumeration had a single enumerator with value 0
20050 if (!NumPositiveBits && !NumNegativeBits)
20051 NumPositiveBits = 1;
20052
20053 // Figure out the type that should be used for this enum.
20054 QualType BestType;
20055 unsigned BestWidth;
20056
20057 // C++0x N3000 [conv.prom]p3:
20058 // An rvalue of an unscoped enumeration type whose underlying
20059 // type is not fixed can be converted to an rvalue of the first
20060 // of the following types that can represent all the values of
20061 // the enumeration: int, unsigned int, long int, unsigned long
20062 // int, long long int, or unsigned long long int.
20063 // C99 6.4.4.3p2:
20064 // An identifier declared as an enumeration constant has type int.
20065 // The C99 rule is modified by C23.
20066 QualType BestPromotionType;
20067
20068 bool Packed = Enum->hasAttr<PackedAttr>();
20069 // -fshort-enums is the equivalent to specifying the packed attribute on all
20070 // enum definitions.
20071 if (LangOpts.ShortEnums)
20072 Packed = true;
20073
20074 // If the enum already has a type because it is fixed or dictated by the
20075 // target, promote that type instead of analyzing the enumerators.
20076 if (Enum->isComplete()) {
20077 BestType = Enum->getIntegerType();
20078 if (Context.isPromotableIntegerType(BestType))
20079 BestPromotionType = Context.getPromotedIntegerType(BestType);
20080 else
20081 BestPromotionType = BestType;
20082
20083 BestWidth = Context.getIntWidth(BestType);
20084 }
20085 else if (NumNegativeBits) {
20086 // If there is a negative value, figure out the smallest integer type (of
20087 // int/long/longlong) that fits.
20088 // If it's packed, check also if it fits a char or a short.
20089 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
20090 BestType = Context.SignedCharTy;
20091 BestWidth = CharWidth;
20092 } else if (Packed && NumNegativeBits <= ShortWidth &&
20093 NumPositiveBits < ShortWidth) {
20094 BestType = Context.ShortTy;
20095 BestWidth = ShortWidth;
20096 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
20097 BestType = Context.IntTy;
20098 BestWidth = IntWidth;
20099 } else {
20100 BestWidth = Context.getTargetInfo().getLongWidth();
20101
20102 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
20103 BestType = Context.LongTy;
20104 } else {
20105 BestWidth = Context.getTargetInfo().getLongLongWidth();
20106
20107 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
20108 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20109 BestType = Context.LongLongTy;
20110 }
20111 }
20112 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
20113 } else {
20114 // If there is no negative value, figure out the smallest type that fits
20115 // all of the enumerator values.
20116 // If it's packed, check also if it fits a char or a short.
20117 if (Packed && NumPositiveBits <= CharWidth) {
20118 BestType = Context.UnsignedCharTy;
20119 BestPromotionType = Context.IntTy;
20120 BestWidth = CharWidth;
20121 } else if (Packed && NumPositiveBits <= ShortWidth) {
20122 BestType = Context.UnsignedShortTy;
20123 BestPromotionType = Context.IntTy;
20124 BestWidth = ShortWidth;
20125 } else if (NumPositiveBits <= IntWidth) {
20126 BestType = Context.UnsignedIntTy;
20127 BestWidth = IntWidth;
20128 BestPromotionType
20129 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20131 } else if (NumPositiveBits <=
20132 (BestWidth = Context.getTargetInfo().getLongWidth())) {
20133 BestType = Context.UnsignedLongTy;
20134 BestPromotionType
20135 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20137 } else {
20138 BestWidth = Context.getTargetInfo().getLongLongWidth();
20139 if (NumPositiveBits > BestWidth) {
20140 // This can happen with bit-precise integer types, but those are not
20141 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
20142 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
20143 // a 128-bit integer, we should consider doing the same.
20144 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20145 }
20146 BestType = Context.UnsignedLongLongTy;
20147 BestPromotionType
20148 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20150 }
20151 }
20152
20153 // Loop over all of the enumerator constants, changing their types to match
20154 // the type of the enum if needed.
20155 for (auto *D : Elements) {
20156 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20157 if (!ECD) continue; // Already issued a diagnostic.
20158
20159 // C99 says the enumerators have int type, but we allow, as an
20160 // extension, the enumerators to be larger than int size. If each
20161 // enumerator value fits in an int, type it as an int, otherwise type it the
20162 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20163 // that X has type 'int', not 'unsigned'.
20164
20165 // Determine whether the value fits into an int.
20166 llvm::APSInt InitVal = ECD->getInitVal();
20167
20168 // If it fits into an integer type, force it. Otherwise force it to match
20169 // the enum decl type.
20170 QualType NewTy;
20171 unsigned NewWidth;
20172 bool NewSign;
20173 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20174 MembersRepresentableByInt) {
20175 // C23 6.7.3.3.3p15:
20176 // The enumeration member type for an enumerated type without fixed
20177 // underlying type upon completion is:
20178 // - int if all the values of the enumeration are representable as an
20179 // int; or,
20180 // - the enumerated type
20181 NewTy = Context.IntTy;
20182 NewWidth = IntWidth;
20183 NewSign = true;
20184 } else if (ECD->getType() == BestType) {
20185 // Already the right type!
20186 if (getLangOpts().CPlusPlus)
20187 // C++ [dcl.enum]p4: Following the closing brace of an
20188 // enum-specifier, each enumerator has the type of its
20189 // enumeration.
20190 ECD->setType(EnumType);
20191 continue;
20192 } else {
20193 NewTy = BestType;
20194 NewWidth = BestWidth;
20195 NewSign = BestType->isSignedIntegerOrEnumerationType();
20196 }
20197
20198 // Adjust the APSInt value.
20199 InitVal = InitVal.extOrTrunc(NewWidth);
20200 InitVal.setIsSigned(NewSign);
20201 ECD->setInitVal(Context, InitVal);
20202
20203 // Adjust the Expr initializer and type.
20204 if (ECD->getInitExpr() &&
20205 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20206 ECD->setInitExpr(ImplicitCastExpr::Create(
20207 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20208 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20209 if (getLangOpts().CPlusPlus)
20210 // C++ [dcl.enum]p4: Following the closing brace of an
20211 // enum-specifier, each enumerator has the type of its
20212 // enumeration.
20213 ECD->setType(EnumType);
20214 else
20215 ECD->setType(NewTy);
20216 }
20217
20218 Enum->completeDefinition(BestType, BestPromotionType,
20219 NumPositiveBits, NumNegativeBits);
20220
20221 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20222
20223 if (Enum->isClosedFlag()) {
20224 for (Decl *D : Elements) {
20225 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20226 if (!ECD) continue; // Already issued a diagnostic.
20227
20228 llvm::APSInt InitVal = ECD->getInitVal();
20229 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20230 !IsValueInFlagEnum(Enum, InitVal, true))
20231 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20232 << ECD << Enum;
20233 }
20234 }
20235
20236 // Now that the enum type is defined, ensure it's not been underaligned.
20237 if (Enum->hasAttrs())
20239}
20240
20242 SourceLocation StartLoc,
20243 SourceLocation EndLoc) {
20244 StringLiteral *AsmString = cast<StringLiteral>(expr);
20245
20247 AsmString, StartLoc,
20248 EndLoc);
20249 CurContext->addDecl(New);
20250 return New;
20251}
20252
20254 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20255 CurContext->addDecl(New);
20256 PushDeclContext(S, New);
20258 PushCompoundScope(false);
20259 return New;
20260}
20261
20263 D->setStmt(Statement);
20267}
20268
20270 IdentifierInfo* AliasName,
20271 SourceLocation PragmaLoc,
20272 SourceLocation NameLoc,
20273 SourceLocation AliasNameLoc) {
20274 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20276 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20278 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20279 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20280
20281 // If a declaration that:
20282 // 1) declares a function or a variable
20283 // 2) has external linkage
20284 // already exists, add a label attribute to it.
20285 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20286 if (isDeclExternC(PrevDecl))
20287 PrevDecl->addAttr(Attr);
20288 else
20289 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20290 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20291 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20292 } else
20293 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20294}
20295
20297 SourceLocation PragmaLoc,
20298 SourceLocation NameLoc) {
20299 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20300
20301 if (PrevDecl) {
20302 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20303 } else {
20304 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20305 }
20306}
20307
20309 IdentifierInfo* AliasName,
20310 SourceLocation PragmaLoc,
20311 SourceLocation NameLoc,
20312 SourceLocation AliasNameLoc) {
20313 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20315 WeakInfo W = WeakInfo(Name, NameLoc);
20316
20317 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20318 if (!PrevDecl->hasAttr<AliasAttr>())
20319 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20321 } else {
20322 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20323 }
20324}
20325
20327 bool Final) {
20328 assert(FD && "Expected non-null FunctionDecl");
20329
20330 // SYCL functions can be template, so we check if they have appropriate
20331 // attribute prior to checking if it is a template.
20332 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20334
20335 // Templates are emitted when they're instantiated.
20336 if (FD->isDependentContext())
20338
20339 // Check whether this function is an externally visible definition.
20340 auto IsEmittedForExternalSymbol = [this, FD]() {
20341 // We have to check the GVA linkage of the function's *definition* -- if we
20342 // only have a declaration, we don't know whether or not the function will
20343 // be emitted, because (say) the definition could include "inline".
20344 const FunctionDecl *Def = FD->getDefinition();
20345
20346 // We can't compute linkage when we skip function bodies.
20347 return Def && !Def->hasSkippedBody() &&
20349 getASTContext().GetGVALinkageForFunction(Def));
20350 };
20351
20352 if (LangOpts.OpenMPIsTargetDevice) {
20353 // In OpenMP device mode we will not emit host only functions, or functions
20354 // we don't need due to their linkage.
20355 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20356 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20357 // DevTy may be changed later by
20358 // #pragma omp declare target to(*) device_type(*).
20359 // Therefore DevTy having no value does not imply host. The emission status
20360 // will be checked again at the end of compilation unit with Final = true.
20361 if (DevTy)
20362 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20364 // If we have an explicit value for the device type, or we are in a target
20365 // declare context, we need to emit all extern and used symbols.
20366 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20367 if (IsEmittedForExternalSymbol())
20369 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20370 // we'll omit it.
20371 if (Final)
20373 } else if (LangOpts.OpenMP > 45) {
20374 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20375 // function. In 5.0, no_host was introduced which might cause a function to
20376 // be omitted.
20377 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20378 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20379 if (DevTy)
20380 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20382 }
20383
20384 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20386
20387 if (LangOpts.CUDA) {
20388 // When compiling for device, host functions are never emitted. Similarly,
20389 // when compiling for host, device and global functions are never emitted.
20390 // (Technically, we do emit a host-side stub for global functions, but this
20391 // doesn't count for our purposes here.)
20393 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20395 if (!LangOpts.CUDAIsDevice &&
20398
20399 if (IsEmittedForExternalSymbol())
20401 }
20402
20403 // Otherwise, the function is known-emitted if it's in our set of
20404 // known-emitted functions.
20406}
20407
20409 // Host-side references to a __global__ function refer to the stub, so the
20410 // function itself is never emitted and therefore should not be marked.
20411 // If we have host fn calls kernel fn calls host+device, the HD function
20412 // does not get instantiated on the host. We model this by omitting at the
20413 // call to the kernel from the callgraph. This ensures that, when compiling
20414 // for host, only HD functions actually called from the host get marked as
20415 // known-emitted.
20416 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20418}
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:84
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
const Decl * D
enum clang::sema::@1724::IndirectLocalPathEntry::EntryKind Kind
IndirectLocalPath & Path
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:2218
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Iter
Definition: HTMLLogger.cpp:153
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:57
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:1134
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:15867
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6834
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:15364
static bool isMainVar(DeclarationName Name, VarDecl *VD)
Definition: SemaDecl.cpp:7434
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:11402
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:3326
static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6925
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:3491
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:798
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:6532
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:1473
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:6570
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:2272
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:9221
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:3438
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2786
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
Definition: SemaDecl.cpp:8202
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:9567
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
Definition: SemaDecl.cpp:3244
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
Definition: SemaDecl.cpp:8578
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
Definition: SemaDecl.cpp:11804
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:2675
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:4451
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
Definition: SemaDecl.cpp:11898
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15348
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
Definition: SemaDecl.cpp:11522
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:2039
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
Definition: SemaDecl.cpp:14983
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:564
static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6960
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
Definition: SemaDecl.cpp:11411
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:7175
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:19483
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:19854
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
Definition: SemaDecl.cpp:4998
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:2918
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
Definition: SemaDecl.cpp:16901
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:3473
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7012
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:5934
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:4865
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:9257
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:9750
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
Definition: SemaDecl.cpp:15896
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:3380
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:8547
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2644
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
Definition: SemaDecl.cpp:9439
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
Definition: SemaDecl.cpp:3043
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:8227
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:17061
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:5285
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:8464
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
Definition: SemaDecl.cpp:1915
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
Definition: SemaDecl.cpp:9761
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:5361
OpenCLParamType
Definition: SemaDecl.cpp:9430
@ InvalidAddrSpacePtrKernelParam
Definition: SemaDecl.cpp:9434
@ ValidKernelParam
Definition: SemaDecl.cpp:9431
@ InvalidKernelParam
Definition: SemaDecl.cpp:9435
@ RecordKernelParam
Definition: SemaDecl.cpp:9436
@ PtrKernelParam
Definition: SemaDecl.cpp:9433
@ PtrPtrKernelParam
Definition: SemaDecl.cpp:9432
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:6043
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:18836
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:584
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:18770
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:7220
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:5445
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11331
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:9741
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
Definition: SemaDecl.cpp:3287
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:3417
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:16885
static void checkInheritableAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6933
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
Definition: SemaDecl.cpp:2166
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:4348
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:9064
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
Definition: SemaDecl.cpp:5969
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:18863
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:813
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
Definition: SemaDecl.cpp:7247
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:8191
@ SDK_StructuredBinding
Definition: SemaDecl.cpp:8198
@ SDK_Field
Definition: SemaDecl.cpp:8195
@ SDK_Global
Definition: SemaDecl.cpp:8193
@ SDK_Local
Definition: SemaDecl.cpp:8192
@ SDK_Typedef
Definition: SemaDecl.cpp:8196
@ SDK_StaticMember
Definition: SemaDecl.cpp:8194
@ SDK_Using
Definition: SemaDecl.cpp:8197
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4811
static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
Definition: SemaDecl.cpp:7406
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:3401
static void checkWeakAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6881
static void checkSelectAnyAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6913
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:9461
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:5459
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
Definition: SemaDecl.cpp:12475
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
Definition: SemaDecl.cpp:7298
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
Definition: SemaDecl.cpp:1784
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
Definition: SemaDecl.cpp:18929
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11144
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
Definition: SemaDecl.cpp:1773
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2892
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:6454
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:14791
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
Definition: SemaDecl.cpp:7394
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:5916
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1826
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
Definition: SemaDecl.cpp:11085
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
Definition: SemaDecl.cpp:6795
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:5424
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:11553
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:8218
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:11377
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:7026
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11162
static void checkAliasAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6900
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:2399
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:19818
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:19500
static void checkWeakRefAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6891
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:7206
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2663
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
Definition: SemaDecl.cpp:10992
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Definition: SemaDecl.cpp:11426
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1800
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:17098
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 for SYCL constructs.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to Wasm.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
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
#define bool
Definition: amdgpuintrin.h:20
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
Definition: SemaDecl.cpp:15854
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:15856
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
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:188
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
SourceManager & getSourceManager()
Definition: ASTContext.h:741
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2915
QualType getParenType(QualType NamedType) const
CanQualType LongTy
Definition: ASTContext.h:1169
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
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:684
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2218
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
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:1998
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2716
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
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:2108
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:2024
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:2086
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:2921
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:1188
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:1703
IdentifierTable & Idents
Definition: ASTContext.h:680
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
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:834
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:530
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:2206
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:2120
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
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:3014
CanQualType CharTy
Definition: ASTContext.h:1162
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
CanQualType IntTy
Definition: ASTContext.h:1169
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:2289
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType SignedCharTy
Definition: ASTContext.h:1169
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:733
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:2196
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2763
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:2482
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:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1170
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:1681
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1533
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:2918
CanQualType ShortTy
Definition: ASTContext.h:1169
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:2011
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:799
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:2312
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:2096
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:1169
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:2384
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2390
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2387
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2396
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2393
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:2513
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:3357
Wrapper for source info for arrays.
Definition: TypeLoc.h:1592
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1594
Expr * getSizeExpr() const
Definition: TypeLoc.h:1614
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1622
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1602
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
QualType getElementType() const
Definition: Type.h:3589
Attr - This represents one attribute.
Definition: Attr.h:43
attr::Kind getKind() const
Definition: Attr.h:89
bool isInherited() const
Definition: Attr.h:98
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition: Attr.h:103
SourceLocation getLocation() const
Definition: Attr.h:96
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:637
AttributeFactory & getFactory() const
Definition: ParsedAttr.h:733
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:6132
QualType getModifiedType() const
Definition: Type.h:6162
bool isCallingConv() const
Definition: Type.cpp:4206
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6561
AutoTypeKeyword getKeyword() const
Definition: Type.h:6592
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4324
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
A binding in a decomposition declaration.
Definition: DeclCXX.h:4130
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4488
bool doesNotEscape() const
Definition: Decl.h:4639
This class is used for builtin types like 'int'.
Definition: Type.h:3034
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:219
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:263
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:223
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:138
bool isImmediate(unsigned ID) const
Returns true if this is an immediate (consteval) function.
Definition: Builtins.h:285
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:248
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:203
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:112
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition: Builtins.h:168
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:214
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:183
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:161
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:209
bool isConstWithoutExceptions(unsigned ID) const
Definition: Builtins.h:252
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache",...
Definition: Builtins.h:175
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition: Builtins.h:117
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:128
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition: Builtins.h:123
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:2553
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:2815
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2885
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:3004
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, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2250
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
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:2949
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:2078
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:2549
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2603
bool isVirtual() const
Definition: DeclCXX.h:2133
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2668
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2582
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:2368
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2239
bool isConst() const
Definition: DeclCXX.h:2130
bool isStatic() const
Definition: DeclCXX.cpp:2280
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2560
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2174
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:1346
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1252
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:1378
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1563
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:1388
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:131
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:2024
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:1109
bool hasDefinition() const
Definition: DeclCXX.h:572
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1991
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1071
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1995
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1300
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:123
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:149
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:129
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
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:4262
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
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:205
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:245
bool isZeroSize() const
Return true if the size is zero.
Definition: Type.h:3685
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3671
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:349
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:1368
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2218
bool isFileContext() const
Definition: DeclBase.h:2160
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2045
bool isObjCContainer() const
Definition: DeclBase.h:2128
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1400
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
bool isClosure() const
Definition: DeclBase.h:2122
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2105
bool isNamespace() const
Definition: DeclBase.h:2178
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
bool isTranslationUnit() const
Definition: DeclBase.h:2165
bool isRecord() const
Definition: DeclBase.h:2169
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1990
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1687
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1768
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1637
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2008
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1424
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2349
bool isFunctionOrMethod() const
Definition: DeclBase.h:2141
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1285
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1385
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1404
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2082
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1415
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:550
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:645
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:860
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 TST TST_void
Definition: DeclSpec.h:279
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:558
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:1050
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1065
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:314
bool isInStdNamespace() const
Definition: DeclBase.cpp:422
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:438
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1215
bool isFromGlobalModule() const
Whether this declaration comes from global module.
Definition: DeclBase.cpp:1160
T * getAttr() const
Definition: DeclBase.h:576
bool hasAttrs() const
Definition: DeclBase.h:521
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:520
void addAttr(Attr *A)
Definition: DeclBase.cpp:1010
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:523
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:764
bool isInNamedModule() const
Whether this declaration comes from a named module.
Definition: DeclBase.cpp:1164
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1140
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:151
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:635
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:882
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1208
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1206
@ FOK_Declared
A friend of a previously-declared entity.
Definition: DeclBase.h:1207
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:281
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1109
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:574
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:835
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:246
void dropAttrs()
Definition: DeclBase.cpp:1003
@ 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:1169
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2766
bool isInvalidDecl() const
Definition: DeclBase.h:591
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1158
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:505
SourceLocation getLocation() const
Definition: DeclBase.h:442
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:822
void setImplicit(bool I=true)
Definition: DeclBase.h:597
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:611
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:549
DeclContext * getDeclContext()
Definition: DeclBase.h:451
attr_range attrs() const
Definition: DeclBase.h:538
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
void dropAttr()
Definition: DeclBase.h:559
AttrVec & getAttrs()
Definition: DeclBase.h:527
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:355
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:907
bool hasAttr() const
Definition: DeclBase.h:580
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1224
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:359
Kind getKind() const
Definition: DeclBase.h:445
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:430
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:735
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:792
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:777
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2039
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2079
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1977
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:822
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:769
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1989
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:810
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2023
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:4189
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3450
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:6527
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:6548
bool isDeduced() const
Definition: Type.h:6549
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2454
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2434
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2443
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:939
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:954
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2354
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2368
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3291
llvm::APSInt getInitVal() const
Definition: Decl.h:3311
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5478
const Expr * getInitExpr() const
Definition: Decl.h:3309
Represents an enum.
Definition: Decl.h:3861
enumerator_range enumerators() const
Definition: Decl.h:3994
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4066
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:4030
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:4033
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4080
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4877
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4922
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4075
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4897
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:4016
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4021
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6103
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
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:3097
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:3093
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3077
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:276
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:978
void applyChanges(FPOptionsOverride FPO)
Definition: LangOptions.h:1091
bool isFPConstrained() const
Definition: LangOptions.h:906
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
Definition: LangOptions.h:1085
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3136
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4570
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
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:4555
bool isZeroLengthBitField() 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:4613
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5610
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
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:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
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:101
Represents a function declaration or definition.
Definition: Decl.h:1935
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2565
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2404
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4064
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3609
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4057
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4052
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3262
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2249
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2577
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2556
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3883
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3638
param_iterator param_end()
Definition: Decl.h:2662
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2796
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2571
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3582
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2317
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2305
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3494
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4172
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2376
void setWillHaveBody(bool V=true)
Definition: Decl.h:2562
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2371
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4182
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3623
param_iterator param_begin()
Definition: Decl.h:2661
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2698
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3096
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2468
FunctionEffectsRef getFunctionEffects() const
Definition: Decl.h:3009
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3320
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4116
@ TK_MemberSpecialization
Definition: Decl.h:1947
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2763
bool isStatic() const
Definition: Decl.h:2804
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4382
void setTrivial(bool IT)
Definition: Decl.h:2306
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4003
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
bool isDeletedAsWritten() const
Definition: Decl.h:2472
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition: Decl.h:2393
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2288
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3498
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2292
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2356
bool isImmediateEscalating() const
Definition: Decl.cpp:3275
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2284
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2555
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2217
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3313
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2791
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:3372
bool param_empty() const
Definition: Decl.h:2660
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:2124
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3187
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2153
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3578
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2349
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4405
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2808
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:3997
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3989
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2401
void setDefaulted(bool D=true)
Definition: Decl.h:2314
bool isConsteval() const
Definition: Decl.h:2410
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:2737
void setBody(Stmt *B)
Definition: Decl.cpp:3255
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3512
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3133
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition: Decl.h:2387
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4024
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3702
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2146
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3163
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2363
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:3210
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2774
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3564
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2561
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:5044
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5373
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4908
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5107
unsigned getNumParams() const
Definition: Type.h:5360
QualType getParamType(unsigned i) const
Definition: Type.h:5362
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:5566
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5393
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5484
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5371
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5367
ArrayRef< QualType > param_types() const
Definition: Type.h:5516
Declaration of a template function.
Definition: DeclTemplate.h:959
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:541
Wrapper for source info for functions.
Definition: TypeLoc.h:1459
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4432
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4547
CallingConv getCC() const
Definition: Type.h:4494
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4513
unsigned getRegParm() const
Definition: Type.h:4487
bool getNoCallerSavedRegs() const
Definition: Type.h:4483
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4506
bool getHasRegParm() const
Definition: Type.h:4485
bool getNoReturn() const
Definition: Type.h:4480
bool getProducesResult() const
Definition: Type.h:4481
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:4527
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:4541
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4660
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3537
unsigned getRegParmType() const
Definition: Type.h:4651
CallingConv getCallConv() const
Definition: Type.h:4659
QualType getReturnType() const
Definition: Type.h:4648
bool getCmseNSCallAttr() const
Definition: Type.h:4658
@ SME_PStateSMEnabledMask
Definition: Type.h:4587
@ SME_PStateSMCompatibleMask
Definition: Type.h:4588
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:3724
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2089
Represents a C array with an unspecified size.
Definition: Type.h:3764
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3335
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5506
void setInherited(bool I)
Definition: Attr.h:155
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2524
Describes an C or C++ initializer list.
Definition: Expr.h:5088
child_range children()
Definition: Expr.h:5280
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:7579
@ 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:980
Represents the declaration of a label.
Definition: Decl.h:503
bool isResolvedMSAsmLabel() const
Definition: Decl.h:538
LabelStmt * getStmt() const
Definition: Decl.h:527
bool isMSAsmLabel() const
Definition: Decl.h:537
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:289
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:672
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:816
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:721
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:534
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:591
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
Definition: LangOptions.h:727
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:573
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:1357
Represents a linkage specification.
Definition: DeclCXX.h:2957
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:3034
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:3236
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
Describes a module or submodule.
Definition: Module.h:115
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:121
Module * Parent
The parent of this module.
Definition: Module.h:164
bool isPrivateModule() const
Definition: Module.h:220
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition: Module.h:619
bool isModuleImplementation() const
Is this a module implementation.
Definition: Module.h:635
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:624
bool isImplicitGlobalModule() const
Definition: Module.h:216
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:240
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:195
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:693
@ ClassId_NSObject
Definition: NSAPI.h:30
This represents a decl that may have a name.
Definition: Decl.h:253
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:466
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
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:280
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:458
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:408
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
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:699
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1919
bool isExternallyVisible() const
Definition: Decl.h:412
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:376
Represent a C++ namespace.
Definition: Decl.h:551
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:602
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:79
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:1831
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:941
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:255
Expr ** getExprs()
Definition: Expr.h:5905
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5894
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1234
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1247
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1230
Sugar for parentheses used when specifying types.
Definition: Type.h:3172
Represents a parameter to a function.
Definition: Decl.h:1725
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1785
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1789
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
QualType getOriginalType() const
Definition: Decl.cpp:2931
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:2922
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:836
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:916
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:956
AttributePool & getPool() const
Definition: ParsedAttr.h:963
PipeType - OpenCL20.
Definition: Type.h:7785
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1313
Wrapper for source info for pointers.
Definition: TypeLoc.h:1332
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1338
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
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:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8020
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:8014
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:8083
@ DK_nontrivial_c_struct
Definition: Type.h:1524
PrimitiveDefaultInitializeKind
Definition: Type.h:1452
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2867
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:102
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1209
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1291
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
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:2915
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7936
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8062
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:8077
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7976
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getCanonicalType() const
Definition: Type.h:7988
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8030
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition: Type.cpp:2899
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1428
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8009
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
bool isCanonical() const
Definition: Type.h:7993
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1304
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1437
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2641
NonConstantStorageReason
Definition: Type.h:1013
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: Type.h:1482
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: Type.h:1487
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:8071
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7876
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7883
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4420
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
bool hasConst() const
Definition: Type.h:450
void removeConst()
Definition: Type.h:452
void addConst()
Definition: Type.h:453
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
bool empty() const
Definition: Type.h:640
Represents a struct/union/class.
Definition: Decl.h:4162
bool hasObjectMember() const
Definition: Decl.h:4222
field_range fields() const
Definition: Decl.h:4368
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5040
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5060
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5106
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4353
field_iterator field_begin() const
Definition: Decl.cpp:5094
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
RecordDecl * getDecl() const
Definition: Type.h:6087
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:7258
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:864
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
redecl_iterator redecls_end() const
Definition: Redeclarable.h:302
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4995
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:222
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3046
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:3094
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:382
void RemoveDecl(Decl *D)
Definition: Scope.h:354
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:385
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:582
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:271
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
void CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition: SemaARM.cpp:1334
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:656
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
Definition: SemaCUDA.cpp:1068
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
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:738
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
Definition: SemaCUDA.cpp:1003
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition: SemaCUDA.cpp:803
void CheckEntryPoint(FunctionDecl *FD)
Definition: SemaHLSL.cpp:365
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition: SemaHLSL.cpp:265
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition: SemaHLSL.cpp:332
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition: SemaHLSL.cpp:299
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition: SemaHLSL.cpp:279
void ActOnVariableDeclarator(VarDecl *VD)
Definition: SemaHLSL.cpp:2488
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:591
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:1372
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition: SemaSYCL.cpp:251
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:1507
Mode getAlignMode() const
Definition: Sema.h:1509
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:985
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:997
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition: Sema.h:3254
static NameClassification VarTemplate(TemplateName Name)
Definition: Sema.h:3264
static NameClassification Unknown()
Definition: Sema.h:3234
static NameClassification OverloadSet(ExprResult E)
Definition: Sema.h:3238
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition: Sema.h:3282
static NameClassification FunctionTemplate(TemplateName Name)
Definition: Sema.h:3270
static NameClassification NonType(NamedDecl *D)
Definition: Sema.h:3244
static NameClassification Concept(TemplateName Name)
Definition: Sema.h:3276
static NameClassification UndeclaredNonType()
Definition: Sema.h:3250
static NameClassification TypeTemplate(TemplateName Name)
Definition: Sema.h:3258
static NameClassification Error()
Definition: Sema.h:3232
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12086
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12116
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:14246
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:11018
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6395
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition: Sema.h:3102
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6689
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12643
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition: Sema.cpp:2388
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:732
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:2471
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
Definition: SemaType.cpp:9133
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:6609
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:9788
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:1561
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:15139
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:7844
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:5835
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:8986
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8990
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:9009
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:9025
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:9022
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8998
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:8993
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6625
void ActOnPopScope(SourceLocation Loc, Scope *S)
Definition: SemaDecl.cpp:2182
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5318
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15838
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12893
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:36
NonTrivialCUnionContext
Definition: Sema.h:3624
@ NTCUC_CopyInit
Definition: Sema.h:3634
@ NTCUC_AutoVar
Definition: Sema.h:3632
@ NTCUC_DefaultInitializedObject
Definition: Sema.h:3630
@ NTCUC_FunctionReturn
Definition: Sema.h:3628
@ NTCUC_FunctionParam
Definition: Sema.h:3626
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:3531
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:6102
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
Definition: SemaLookup.cpp:995
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:18256
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
Definition: SemaDecl.cpp:7442
SemaOpenMP & OpenMP()
Definition: Sema.h:1126
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:6087
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:867
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:18188
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition: Sema.h:4325
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:3084
PragmaClangSection PragmaClangRodataSection
Definition: Sema.h:1433
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:16396
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:6032
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:15005
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:1190
SemaCUDA & CUDA()
Definition: Sema.h:1071
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:17394
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:1457
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
Definition: SemaAttr.cpp:272
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:2292
Preprocessor & getPreprocessor() const
Definition: Sema.h:531
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6840
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1664
PragmaStack< StringLiteral * > CodeSegStack
Definition: Sema.h:1658
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:1268
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:6230
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:17152
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:4817
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:12307
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:16597
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:2101
@ 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:18275
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:18373
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:14619
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:1433
SemaSYCL & SYCL()
Definition: Sema.h:1151
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15474
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:1570
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3409
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:643
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:1659
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:20241
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15126
ASTContext & Context
Definition: Sema.h:909
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14639
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5794
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:529
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20262
void * SkippedDefinitionContext
Definition: Sema.h:3949
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:916
SemaObjC & ObjC()
Definition: Sema.h:1111
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
Definition: SemaDecl.cpp:5323
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4927
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:72
@ AllowFold
Definition: Sema.h:7245
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1499
PragmaStack< bool > StrictGuardStackCheckStack
Definition: Sema.h:1661
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:3092
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:2333
ASTContext & getASTContext() const
Definition: Sema.h:532
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:15910
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:1715
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:17827
PragmaStack< StringLiteral * > ConstSegStack
Definition: Sema.h:1657
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:692
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:667
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3101
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:4774
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9486
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20408
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:817
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:5476
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1575
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:16932
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:9051
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:11789
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:7962
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:792
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:4364
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2180
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:1249
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:4164
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:16831
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition: Sema.h:527
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:82
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2198
void PopCompoundScope()
Definition: Sema.cpp:2330
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:19712
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition: Sema.h:13915
@ UPPC_EnumeratorValue
The enumerator value.
Definition: Sema.h:13918
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13930
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:13924
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13903
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:13942
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition: Sema.h:13927
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:13906
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition: Sema.h:13909
const LangOptions & getLangOpts() const
Definition: Sema.h:525
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:1697
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:::lifetimebound]] attr for std:: functions and methods.
Definition: SemaAttr.cpp:219
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition: Sema.h:3109
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1390
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:6585
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:6619
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1600
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:908
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:8251
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:1980
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
const LangOptions & LangOpts
Definition: Sema.h:907
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2406
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition: Sema.h:14996
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15314
SemaHLSL & HLSL()
Definition: Sema.h:1076
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1832
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11924
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:18468
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:1434
SemaRISCV & RISCV()
Definition: Sema.h:1141
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition: Sema.h:15160
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:3717
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:20066
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:1156
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:1312
PragmaStack< AlignPackInfo > AlignPackStack
Definition: Sema.h:1646
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:15796
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6480
PragmaStack< StringLiteral * > BSSSegStack
Definition: Sema.h:1656
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition: Sema.h:736
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:9582
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:8166
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:862
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:16907
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1377
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8398
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:12494
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:19738
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:940
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2325
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:14871
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Definition: SemaDecl.cpp:2289
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:2264
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:20296
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:18666
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6477
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1324
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:18146
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:9783
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:8926
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:3189
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:14990
StringLiteral * CurInitSeg
Last section used with #pragma init_seg.
Definition: Sema.h:1696
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20326
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:9588
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:8946
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:15420
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:18137
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15344
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1044
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:14911
SemaOpenCL & OpenCL()
Definition: Sema.h:1121
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5799
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:15181
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 ...
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:8439
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1291
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4719
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
Definition: SemaDecl.cpp:15771
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition: Sema.h:3106
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9241
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:15820
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:11030
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:3842
@ NTK_Typedef
Definition: Sema.h:3847
@ NTK_NonUnion
Definition: Sema.h:3845
@ NTK_TypeAlias
Definition: Sema.h:3848
@ NTK_NonClass
Definition: Sema.h:3844
@ NTK_NonEnum
Definition: Sema.h:3846
@ NTK_NonStruct
Definition: Sema.h:3843
@ NTK_TemplateTemplateArgument
Definition: Sema.h:3851
@ NTK_TypeAliasTemplate
Definition: Sema.h:3850
@ NTK_Template
Definition: Sema.h:3849
SourceManager & getSourceManager() const
Definition: Sema.h:530
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:3059
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:4289
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:19993
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:1342
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:11205
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:18123
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:1435
@ NTCUK_Destruct
Definition: Sema.h:3654
@ NTCUK_Init
Definition: Sema.h:3653
@ NTCUK_Copy
Definition: Sema.h:3655
PragmaClangSection PragmaClangDataSection
Definition: Sema.h:1432
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20252
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15848
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:13865
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:1230
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:20269
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:6287
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:20253
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8274
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:9383
@ CTK_ErrorRecovery
Definition: Sema.h:9384
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14275
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14796
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2346
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:4480
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:6054
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:594
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
@ CCEK_Enumerator
Enumerator value with fixed underlying type.
Definition: Sema.h:10000
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
Definition: SemaDecl.cpp:18729
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3095
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:1895
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition: Sema.h:3080
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:19524
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12529
ASTConsumer & Consumer
Definition: Sema.h:910
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4227
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:9787
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:9779
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:9783
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:6484
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2052
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:945
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1686
@ 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:16528
@ 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:4043
@ AMK_None
Don't merge availability attributes at all.
Definition: Sema.h:4045
@ AMK_Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition: Sema.h:4051
@ AMK_ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition: Sema.h:4054
@ AMK_OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition: Sema.h:4057
@ AMK_Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition: Sema.h:4048
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14915
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5704
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14582
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:17116
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:4797
SemaPPC & PPC()
Definition: Sema.h:1131
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:76
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9119
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:15266
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:872
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1338
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20901
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18974
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:1291
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:11054
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:3099
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17904
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7917
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1310
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:912
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:5752
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15905
DiagnosticsEngine & Diags
Definition: Sema.h:911
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:526
FPOptions CurFPFeatures
Definition: Sema.h:905
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15901
NamespaceDecl * getStdNamespace() const
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:6642
PragmaStack< StringLiteral * > DataSegStack
Definition: Sema.h:1655
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:693
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7265
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:14946
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11283
@ TPC_ClassTemplateMember
Definition: Sema.h:11281
@ TPC_FunctionTemplate
Definition: Sema.h:11280
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11284
@ TPC_VarTemplate
Definition: Sema.h:11279
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:6726
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:16383
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2070
void PopDeclContext()
Definition: SemaDecl.cpp:1317
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:6066
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:1581
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:8879
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:13907
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:13075
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:1566
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:16775
OffsetOfKind
Definition: Sema.h:3866
@ OOK_Outside
Definition: Sema.h:3868
@ OOK_Macro
Definition: Sema.h:3873
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13348
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:18365
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:4325
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:14192
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:284
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:3074
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1963
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:21168
PragmaClangSection PragmaClangBSSSection
Definition: Sema.h:1431
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6061
@ AbstractVariableType
Definition: Sema.h:5759
@ AbstractReturnType
Definition: Sema.h:5757
@ AbstractFieldType
Definition: Sema.h:5760
@ AbstractIvarType
Definition: Sema.h:5761
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:1705
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:7966
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:1239
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:8180
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:20308
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:8610
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:1324
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:13041
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:2437
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2751
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:3055
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
Definition: SemaAttr.cpp:1275
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:15785
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:13327
SemaWasm & Wasm()
Definition: Sema.h:1166
IdentifierResolver IdResolver
Definition: Sema.h:3003
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:19964
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2337
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:683
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:15155
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:7925
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:3375
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6048
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:16848
SemaARM & ARM()
Definition: Sema.h:1051
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:317
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:8268
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:1266
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
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:294
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:333
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
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:3578
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3853
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3701
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3676
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3662
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3681
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4762
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4753
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4745
bool isUnion() const
Definition: Decl.h:3784
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4808
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4845
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3802
TagKind getTagKind() const
Definition: Decl.h:3773
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:220
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1540
unsigned getShortWidth() const
getShortWidth/Align - Return the size of 'signed short' and 'unsigned short' for this target,...
Definition: TargetInfo.h:514
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:519
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
Definition: TargetInfo.h:1826
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:529
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1583
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1591
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1530
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1399
unsigned getCharWidth() const
Definition: TargetInfo.h:509
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:565
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:524
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
Definition: TargetInfo.h:1504
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1300
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1493
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:656
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:399
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:207
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6666
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4340
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:4451
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5625
Represents a declaration of a type.
Definition: Decl.h:3384
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3410
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:1256
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:749
SourceLocation getTemplateKeywordLoc() const
Get the SourceLocation of the template keyword (if any).
Definition: TypeLoc.cpp:756
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:2715
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7907
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:7918
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6929
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3178
The base class of the type hierarchy.
Definition: Type.h:1828
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:2511
bool isStructureType() const
Definition: Type.cpp:662
bool isDecltypeType() const
Definition: Type.h:8388
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isDependentSizedArrayType() const
Definition: Type.h:8283
bool isBlockPointerType() const
Definition: Type.h:8205
bool isVoidType() const
Definition: Type.h:8515
bool isBooleanType() const
Definition: Type.h:8643
bool isFunctionReferenceType() const
Definition: Type.h:8238
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2201
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8693
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2937
bool isIncompleteArrayType() const
Definition: Type.h:8271
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8814
bool isDependentAddressSpaceType() const
Definition: Type.h:8329
bool isConstantArrayType() const
Definition: Type.h:8267
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8673
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isArrayType() const
Definition: Type.h:8263
bool isFunctionPointerType() const
Definition: Type.h:8231
bool isPointerType() const
Definition: Type.h:8191
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2517
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
bool isReferenceType() const
Definition: Type.h:8209
bool isEnumeralType() const
Definition: Type.h:8295
bool isScalarType() const
Definition: Type.h:8614
bool isVariableArrayType() const
Definition: Type.h:8275
bool isClkEventT() const
Definition: Type.h:8406
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8630
bool isImageType() const
Definition: Type.h:8418
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
bool isPipeType() const
Definition: Type.h:8425
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isBitIntType() const
Definition: Type.h:8429
bool isOpenCLSpecificType() const
Definition: Type.h:8454
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2372
bool isHalfType() const
Definition: Type.h:8519
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2045
bool isHLSLSpecificType() const
Definition: Type.h:8472
const RecordType * getAsStructureType() const
Definition: Type.cpp:754
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2501
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2700
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8686
bool isAtomicType() const
Definition: Type.h:8346
bool isFunctionProtoType() const
Definition: Type.h:2535
bool isObjCIdType() const
Definition: Type.h:8366
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isObjCObjectType() const
Definition: Type.h:8337
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5048
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8649
bool isEventT() const
Definition: Type.h:8402
bool isPointerOrReferenceType() const
Definition: Type.h:8195
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4991
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:8753
bool isFunctionType() const
Definition: Type.h:8187
bool isObjCObjectPointerType() const
Definition: Type.h:8333
bool isMemberFunctionPointerType() const
Definition: Type.h:8249
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2541
bool isFloatingType() const
Definition: Type.cpp:2283
bool isAnyPointerType() const
Definition: Type.h:8199
TypeClass getTypeClass() const
Definition: Type.h:2341
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:2050
bool isSamplerT() const
Definition: Type.h:8398
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:638
bool isNullPtrType() const
Definition: Type.h:8548
bool isRecordType() const
Definition: Type.h:8291
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4763
bool isUnionType() const
Definition: Type.cpp:704
bool isFunctionNoProtoType() const
Definition: Type.h:2534
bool isReserveIDT() const
Definition: Type.h:8414
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:1924
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1920
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3528
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5527
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3427
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3477
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:3492
QualType getUnderlyingType() const
Definition: Decl.h:3482
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3488
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5536
TypedefNameDecl * getDecl() const
Definition: Type.h:5745
QualType desugar() const
Definition: Type.cpp:3920
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:2232
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:419
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:3343
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3407
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3204
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5396
Represents a variable declaration or definition.
Definition: Decl.h:882
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2786
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2140
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1469
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1513
TLSKind getTLSKind() const
Definition: Decl.cpp:2157
bool hasInit() const
Definition: Decl.cpp:2387
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1396
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2249
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2179
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:2433
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2246
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1522
bool isCXXCondDecl() const
Definition: Decl.h:1559
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:893
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition: Decl.h:896
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:890
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2152
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1541
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1177
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2355
void setInlineSpecified()
Definition: Decl.h:1502
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1159
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2748
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1293
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1124
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1495
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1128
const Expr * getInit() const
Definition: Decl.h:1319
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1168
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1135
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2418
void setConstexpr(bool IC)
Definition: Decl.h:1516
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:905
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:908
void setInit(Expr *I)
Definition: Decl.cpp:2449
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2334
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1249
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1246
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1252
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2791
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2234
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1204
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1119
void setImplicitlyInline()
Definition: Decl.h:1507
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1420
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1536
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2682
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1213
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:2755
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition: Decl.h:1430
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2662
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:3808
Expr * getSizeExpr() const
Definition: Type.h:3827
Captures information about a #pragma weak directive.
Definition: Weak.h:25
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
bool isVariableCapture() const
Definition: ScopeInfo.h:650
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:745
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:732
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:755
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1093
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:737
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition: ScopeInfo.h:141
void addByrefBlockVar(VarDecl *VD)
Definition: ScopeInfo.h:498
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition: ScopeInfo.h:150
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition: ScopeInfo.h:167
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition: ScopeInfo.h:145
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition: ScopeInfo.h:158
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:884
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition: ScopeInfo.h:915
ParmVarDecl * ExplicitObjectParameter
Definition: ScopeInfo.h:881
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition: ScopeInfo.h:948
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:871
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:874
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:896
Provides information about an attempted template argument deduction, whose success or failure was des...
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:173
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:63
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
@ 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:30
CUDAFunctionTarget
Definition: Cuda.h:145
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:447
TagTypeKind
The kind of a tag type.
Definition: Type.h:6876
@ 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:1488
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:1098
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:34
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:423
@ 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:1914
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1274
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:365
@ 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:5784
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
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::@224 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:158
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
Extra information about a function prototype.
Definition: Type.h:5192
FunctionEffectsRef FunctionEffects
Definition: Type.h:5202
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:5212
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:58
std::vector< std::string > Features
Definition: TargetInfo.h:59
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
SourceLocation PragmaLocation
Definition: Sema.h:1428
ValueType CurrentValue
Definition: Sema.h:1631
bool CheckSameAsPrevious
Definition: Sema.h:351
NamedDecl * Previous
Definition: Sema.h:352
NamedDecl * New
Definition: Sema.h:353
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.