clang 19.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
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/SemaCUDA.h"
49#include "clang/Sema/SemaHLSL.h"
52#include "clang/Sema/Template.h"
53#include "llvm/ADT/STLForwardCompat.h"
54#include "llvm/ADT/SmallString.h"
55#include "llvm/ADT/StringExtras.h"
56#include "llvm/TargetParser/Triple.h"
57#include <algorithm>
58#include <cstring>
59#include <functional>
60#include <optional>
61#include <unordered_map>
62
63using namespace clang;
64using namespace sema;
65
67 if (OwnedType) {
68 Decl *Group[2] = { OwnedType, Ptr };
70 }
71
73}
74
75namespace {
76
77class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
78 public:
79 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
80 bool AllowTemplates = false,
81 bool AllowNonTemplates = true)
82 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
83 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
84 WantExpressionKeywords = false;
85 WantCXXNamedCasts = false;
86 WantRemainingKeywords = false;
87 }
88
89 bool ValidateCandidate(const TypoCorrection &candidate) override {
90 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
91 if (!AllowInvalidDecl && ND->isInvalidDecl())
92 return false;
93
95 return AllowTemplates;
96
97 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
98 if (!IsType)
99 return false;
100
101 if (AllowNonTemplates)
102 return true;
103
104 // An injected-class-name of a class template (specialization) is valid
105 // as a template or as a non-template.
106 if (AllowTemplates) {
107 auto *RD = dyn_cast<CXXRecordDecl>(ND);
108 if (!RD || !RD->isInjectedClassName())
109 return false;
110 RD = cast<CXXRecordDecl>(RD->getDeclContext());
111 return RD->getDescribedClassTemplate() ||
112 isa<ClassTemplateSpecializationDecl>(RD);
113 }
114
115 return false;
116 }
117
118 return !WantClassName && candidate.isKeyword();
119 }
120
121 std::unique_ptr<CorrectionCandidateCallback> clone() override {
122 return std::make_unique<TypeNameValidatorCCC>(*this);
123 }
124
125 private:
126 bool AllowInvalidDecl;
127 bool WantClassName;
128 bool AllowTemplates;
129 bool AllowNonTemplates;
130};
131
132} // end anonymous namespace
133
134namespace {
135enum class UnqualifiedTypeNameLookupResult {
136 NotFound,
137 FoundNonType,
138 FoundType
139};
140} // end anonymous namespace
141
142/// Tries to perform unqualified lookup of the type decls in bases for
143/// dependent class.
144/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
145/// type decl, \a FoundType if only type decls are found.
146static UnqualifiedTypeNameLookupResult
148 SourceLocation NameLoc,
149 const CXXRecordDecl *RD) {
150 if (!RD->hasDefinition())
151 return UnqualifiedTypeNameLookupResult::NotFound;
152 // Look for type decls in base classes.
153 UnqualifiedTypeNameLookupResult FoundTypeDecl =
154 UnqualifiedTypeNameLookupResult::NotFound;
155 for (const auto &Base : RD->bases()) {
156 const CXXRecordDecl *BaseRD = nullptr;
157 if (auto *BaseTT = Base.getType()->getAs<TagType>())
158 BaseRD = BaseTT->getAsCXXRecordDecl();
159 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
160 // Look for type decls in dependent base classes that have known primary
161 // templates.
162 if (!TST || !TST->isDependentType())
163 continue;
164 auto *TD = TST->getTemplateName().getAsTemplateDecl();
165 if (!TD)
166 continue;
167 if (auto *BasePrimaryTemplate =
168 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
169 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
170 BaseRD = BasePrimaryTemplate;
171 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
173 CTD->findPartialSpecialization(Base.getType()))
174 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
175 BaseRD = PS;
176 }
177 }
178 }
179 if (BaseRD) {
180 for (NamedDecl *ND : BaseRD->lookup(&II)) {
181 if (!isa<TypeDecl>(ND))
182 return UnqualifiedTypeNameLookupResult::FoundNonType;
183 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
184 }
185 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
186 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
187 case UnqualifiedTypeNameLookupResult::FoundNonType:
188 return UnqualifiedTypeNameLookupResult::FoundNonType;
189 case UnqualifiedTypeNameLookupResult::FoundType:
190 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
191 break;
192 case UnqualifiedTypeNameLookupResult::NotFound:
193 break;
194 }
195 }
196 }
197 }
198
199 return FoundTypeDecl;
200}
201
203 const IdentifierInfo &II,
204 SourceLocation NameLoc) {
205 // Lookup in the parent class template context, if any.
206 const CXXRecordDecl *RD = nullptr;
207 UnqualifiedTypeNameLookupResult FoundTypeDecl =
208 UnqualifiedTypeNameLookupResult::NotFound;
209 for (DeclContext *DC = S.CurContext;
210 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
211 DC = DC->getParent()) {
212 // Look for type decls in dependent base classes that have known primary
213 // templates.
214 RD = dyn_cast<CXXRecordDecl>(DC);
215 if (RD && RD->getDescribedClassTemplate())
216 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
217 }
218 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
219 return nullptr;
220
221 // We found some types in dependent base classes. Recover as if the user
222 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
223 // lookup during template instantiation.
224 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
225
226 ASTContext &Context = S.Context;
227 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
228 cast<Type>(Context.getRecordType(RD)));
229 QualType T =
231
232 CXXScopeSpec SS;
233 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
234
235 TypeLocBuilder Builder;
236 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
237 DepTL.setNameLoc(NameLoc);
239 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
240 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
241}
242
243/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
245 SourceLocation NameLoc,
246 bool WantNontrivialTypeSourceInfo = true) {
247 switch (T->getTypeClass()) {
248 case Type::DeducedTemplateSpecialization:
249 case Type::Enum:
250 case Type::InjectedClassName:
251 case Type::Record:
252 case Type::Typedef:
253 case Type::UnresolvedUsing:
254 case Type::Using:
255 break;
256 // These can never be qualified so an ElaboratedType node
257 // would carry no additional meaning.
258 case Type::ObjCInterface:
259 case Type::ObjCTypeParam:
260 case Type::TemplateTypeParm:
261 return ParsedType::make(T);
262 default:
263 llvm_unreachable("Unexpected Type Class");
264 }
265
266 if (!SS || SS->isEmpty())
268 ElaboratedTypeKeyword::None, nullptr, T, nullptr));
269
271 if (!WantNontrivialTypeSourceInfo)
272 return ParsedType::make(ElTy);
273
274 TypeLocBuilder Builder;
275 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
276 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
279 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
280}
281
282/// If the identifier refers to a type name within this scope,
283/// return the declaration of that type.
284///
285/// This routine performs ordinary name lookup of the identifier II
286/// within the given scope, with optional C++ scope specifier SS, to
287/// determine whether the name refers to a type. If so, returns an
288/// opaque pointer (actually a QualType) corresponding to that
289/// type. Otherwise, returns NULL.
291 Scope *S, CXXScopeSpec *SS, bool isClassName,
292 bool HasTrailingDot, ParsedType ObjectTypePtr,
293 bool IsCtorOrDtorName,
294 bool WantNontrivialTypeSourceInfo,
295 bool IsClassTemplateDeductionContext,
296 ImplicitTypenameContext AllowImplicitTypename,
297 IdentifierInfo **CorrectedII) {
298 // FIXME: Consider allowing this outside C++1z mode as an extension.
299 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
300 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
301 !isClassName && !HasTrailingDot;
302
303 // Determine where we will perform name lookup.
304 DeclContext *LookupCtx = nullptr;
305 if (ObjectTypePtr) {
306 QualType ObjectType = ObjectTypePtr.get();
307 if (ObjectType->isRecordType())
308 LookupCtx = computeDeclContext(ObjectType);
309 } else if (SS && SS->isNotEmpty()) {
310 LookupCtx = computeDeclContext(*SS, false);
311
312 if (!LookupCtx) {
313 if (isDependentScopeSpecifier(*SS)) {
314 // C++ [temp.res]p3:
315 // A qualified-id that refers to a type and in which the
316 // nested-name-specifier depends on a template-parameter (14.6.2)
317 // shall be prefixed by the keyword typename to indicate that the
318 // qualified-id denotes a type, forming an
319 // elaborated-type-specifier (7.1.5.3).
320 //
321 // We therefore do not perform any name lookup if the result would
322 // refer to a member of an unknown specialization.
323 // In C++2a, in several contexts a 'typename' is not required. Also
324 // allow this as an extension.
325 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
326 !isClassName && !IsCtorOrDtorName)
327 return nullptr;
328 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
329 if (IsImplicitTypename) {
330 SourceLocation QualifiedLoc = SS->getRange().getBegin();
332 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
333 else
334 Diag(QualifiedLoc, diag::ext_implicit_typename)
335 << SS->getScopeRep() << II.getName()
336 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
337 }
338
339 // We know from the grammar that this name refers to a type,
340 // so build a dependent node to describe the type.
341 if (WantNontrivialTypeSourceInfo)
342 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
343 (ImplicitTypenameContext)IsImplicitTypename)
344 .get();
345
348 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
350 SourceLocation(), QualifierLoc, II, NameLoc);
351 return ParsedType::make(T);
352 }
353
354 return nullptr;
355 }
356
357 if (!LookupCtx->isDependentContext() &&
358 RequireCompleteDeclContext(*SS, LookupCtx))
359 return nullptr;
360 }
361
362 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
363 // lookup for class-names.
364 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
366 LookupResult Result(*this, &II, NameLoc, Kind);
367 if (LookupCtx) {
368 // Perform "qualified" name lookup into the declaration context we
369 // computed, which is either the type of the base of a member access
370 // expression or the declaration context associated with a prior
371 // nested-name-specifier.
372 LookupQualifiedName(Result, LookupCtx);
373
374 if (ObjectTypePtr && Result.empty()) {
375 // C++ [basic.lookup.classref]p3:
376 // If the unqualified-id is ~type-name, the type-name is looked up
377 // in the context of the entire postfix-expression. If the type T of
378 // the object expression is of a class type C, the type-name is also
379 // looked up in the scope of class C. At least one of the lookups shall
380 // find a name that refers to (possibly cv-qualified) T.
381 LookupName(Result, S);
382 }
383 } else {
384 // Perform unqualified name lookup.
385 LookupName(Result, S);
386
387 // For unqualified lookup in a class template in MSVC mode, look into
388 // dependent base classes where the primary class template is known.
389 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
390 if (ParsedType TypeInBase =
391 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
392 return TypeInBase;
393 }
394 }
395
396 NamedDecl *IIDecl = nullptr;
397 UsingShadowDecl *FoundUsingShadow = nullptr;
398 switch (Result.getResultKind()) {
400 if (CorrectedII) {
401 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
402 AllowDeducedTemplate);
403 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
404 S, SS, CCC, CTK_ErrorRecovery);
405 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
406 TemplateTy Template;
407 bool MemberOfUnknownSpecialization;
409 TemplateName.setIdentifier(NewII, NameLoc);
411 CXXScopeSpec NewSS, *NewSSPtr = SS;
412 if (SS && NNS) {
413 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
414 NewSSPtr = &NewSS;
415 }
416 if (Correction && (NNS || NewII != &II) &&
417 // Ignore a correction to a template type as the to-be-corrected
418 // identifier is not a template (typo correction for template names
419 // is handled elsewhere).
420 !(getLangOpts().CPlusPlus && NewSSPtr &&
421 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
422 Template, MemberOfUnknownSpecialization))) {
423 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
424 isClassName, HasTrailingDot, ObjectTypePtr,
425 IsCtorOrDtorName,
426 WantNontrivialTypeSourceInfo,
427 IsClassTemplateDeductionContext);
428 if (Ty) {
429 diagnoseTypo(Correction,
430 PDiag(diag::err_unknown_type_or_class_name_suggest)
431 << Result.getLookupName() << isClassName);
432 if (SS && NNS)
433 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
434 *CorrectedII = NewII;
435 return Ty;
436 }
437 }
438 }
439 Result.suppressDiagnostics();
440 return nullptr;
442 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
444 SS->getScopeRep(), &II);
445 TypeLocBuilder TLB;
449 TL.setNameLoc(NameLoc);
451 }
452 [[fallthrough]];
455 Result.suppressDiagnostics();
456 return nullptr;
457
459 // Recover from type-hiding ambiguities by hiding the type. We'll
460 // do the lookup again when looking for an object, and we can
461 // diagnose the error then. If we don't do this, then the error
462 // about hiding the type will be immediately followed by an error
463 // that only makes sense if the identifier was treated like a type.
464 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
465 Result.suppressDiagnostics();
466 return nullptr;
467 }
468
469 // Look to see if we have a type anywhere in the list of results.
470 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
471 Res != ResEnd; ++Res) {
472 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
473 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
474 RealRes) ||
475 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
476 if (!IIDecl ||
477 // Make the selection of the recovery decl deterministic.
478 RealRes->getLocation() < IIDecl->getLocation()) {
479 IIDecl = RealRes;
480 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
481 }
482 }
483 }
484
485 if (!IIDecl) {
486 // None of the entities we found is a type, so there is no way
487 // to even assume that the result is a type. In this case, don't
488 // complain about the ambiguity. The parser will either try to
489 // perform this lookup again (e.g., as an object name), which
490 // will produce the ambiguity, or will complain that it expected
491 // a type name.
492 Result.suppressDiagnostics();
493 return nullptr;
494 }
495
496 // We found a type within the ambiguous lookup; diagnose the
497 // ambiguity and then return that type. This might be the right
498 // answer, or it might not be, but it suppresses any attempt to
499 // perform the name lookup again.
500 break;
501
503 IIDecl = Result.getFoundDecl();
504 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
505 break;
506 }
507
508 assert(IIDecl && "Didn't find decl");
509
510 QualType T;
511 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
512 // C++ [class.qual]p2: A lookup that would find the injected-class-name
513 // instead names the constructors of the class, except when naming a class.
514 // This is ill-formed when we're not actually forming a ctor or dtor name.
515 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
516 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
517 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
518 FoundRD->isInjectedClassName() &&
519 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
520 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
521 << &II << /*Type*/1;
522
523 DiagnoseUseOfDecl(IIDecl, NameLoc);
524
526 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
527 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
528 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
529 if (!HasTrailingDot)
531 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
532 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
533 (void)DiagnoseUseOfDecl(UD, NameLoc);
534 // Recover with 'int'
536 } else if (AllowDeducedTemplate) {
537 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
538 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
539 TemplateName Template =
540 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
542 false);
543 // Don't wrap in a further UsingType.
544 FoundUsingShadow = nullptr;
545 }
546 }
547
548 if (T.isNull()) {
549 // If it's not plausibly a type, suppress diagnostics.
550 Result.suppressDiagnostics();
551 return nullptr;
552 }
553
554 if (FoundUsingShadow)
555 T = Context.getUsingType(FoundUsingShadow, T);
556
557 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
558}
559
560// Builds a fake NNS for the given decl context.
561static NestedNameSpecifier *
563 for (;; DC = DC->getLookupParent()) {
564 DC = DC->getPrimaryContext();
565 auto *ND = dyn_cast<NamespaceDecl>(DC);
566 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
567 return NestedNameSpecifier::Create(Context, nullptr, ND);
568 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
569 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
570 RD->getTypeForDecl());
571 else if (isa<TranslationUnitDecl>(DC))
573 }
574 llvm_unreachable("something isn't in TU scope?");
575}
576
577/// Find the parent class with dependent bases of the innermost enclosing method
578/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
579/// up allowing unqualified dependent type names at class-level, which MSVC
580/// correctly rejects.
581static const CXXRecordDecl *
583 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
584 DC = DC->getPrimaryContext();
585 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
586 if (MD->getParent()->hasAnyDependentBases())
587 return MD->getParent();
588 }
589 return nullptr;
590}
591
593 SourceLocation NameLoc,
594 bool IsTemplateTypeArg) {
595 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
596
597 NestedNameSpecifier *NNS = nullptr;
598 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
599 // If we weren't able to parse a default template argument, delay lookup
600 // until instantiation time by making a non-dependent DependentTypeName. We
601 // pretend we saw a NestedNameSpecifier referring to the current scope, and
602 // lookup is retried.
603 // FIXME: This hurts our diagnostic quality, since we get errors like "no
604 // type named 'Foo' in 'current_namespace'" when the user didn't write any
605 // name specifiers.
607 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
608 } else if (const CXXRecordDecl *RD =
610 // Build a DependentNameType that will perform lookup into RD at
611 // instantiation time.
612 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
613 RD->getTypeForDecl());
614
615 // Diagnose that this identifier was undeclared, and retry the lookup during
616 // template instantiation.
617 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
618 << RD;
619 } else {
620 // This is not a situation that we should recover from.
621 return ParsedType();
622 }
623
624 QualType T =
626
627 // Build type location information. We synthesized the qualifier, so we have
628 // to build a fake NestedNameSpecifierLoc.
629 NestedNameSpecifierLocBuilder NNSLocBuilder;
630 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
631 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
632
633 TypeLocBuilder Builder;
634 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
635 DepTL.setNameLoc(NameLoc);
637 DepTL.setQualifierLoc(QualifierLoc);
638 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
639}
640
641/// isTagName() - This method is called *for error recovery purposes only*
642/// to determine if the specified name is a valid tag name ("struct foo"). If
643/// so, this returns the TST for the tag corresponding to it (TST_enum,
644/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
645/// cases in C where the user forgot to specify the tag.
647 // Do a tag name lookup in this scope.
648 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
649 LookupName(R, S, false);
652 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
653 switch (TD->getTagKind()) {
659 return DeclSpec::TST_union;
661 return DeclSpec::TST_class;
663 return DeclSpec::TST_enum;
664 }
665 }
666
668}
669
670/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
671/// if a CXXScopeSpec's type is equal to the type of one of the base classes
672/// then downgrade the missing typename error to a warning.
673/// This is needed for MSVC compatibility; Example:
674/// @code
675/// template<class T> class A {
676/// public:
677/// typedef int TYPE;
678/// };
679/// template<class T> class B : public A<T> {
680/// public:
681/// A<T>::TYPE a; // no typename required because A<T> is a base class.
682/// };
683/// @endcode
685 if (CurContext->isRecord()) {
687 return true;
688
689 const Type *Ty = SS->getScopeRep()->getAsType();
690
691 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
692 for (const auto &Base : RD->bases())
693 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
694 return true;
695 return S->isFunctionPrototypeScope();
696 }
697 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
698}
699
701 SourceLocation IILoc,
702 Scope *S,
703 CXXScopeSpec *SS,
704 ParsedType &SuggestedType,
705 bool IsTemplateName) {
706 // Don't report typename errors for editor placeholders.
707 if (II->isEditorPlaceholder())
708 return;
709 // We don't have anything to suggest (yet).
710 SuggestedType = nullptr;
711
712 // There may have been a typo in the name of the type. Look up typo
713 // results, in case we have something that we can suggest.
714 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
715 /*AllowTemplates=*/IsTemplateName,
716 /*AllowNonTemplates=*/!IsTemplateName);
717 if (TypoCorrection Corrected =
719 CCC, CTK_ErrorRecovery)) {
720 // FIXME: Support error recovery for the template-name case.
721 bool CanRecover = !IsTemplateName;
722 if (Corrected.isKeyword()) {
723 // We corrected to a keyword.
724 diagnoseTypo(Corrected,
725 PDiag(IsTemplateName ? diag::err_no_template_suggest
726 : diag::err_unknown_typename_suggest)
727 << II);
728 II = Corrected.getCorrectionAsIdentifierInfo();
729 } else {
730 // We found a similarly-named type or interface; suggest that.
731 if (!SS || !SS->isSet()) {
732 diagnoseTypo(Corrected,
733 PDiag(IsTemplateName ? diag::err_no_template_suggest
734 : diag::err_unknown_typename_suggest)
735 << II, CanRecover);
736 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
737 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
738 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
739 II->getName().equals(CorrectedStr);
740 diagnoseTypo(Corrected,
741 PDiag(IsTemplateName
742 ? diag::err_no_member_template_suggest
743 : diag::err_unknown_nested_typename_suggest)
744 << II << DC << DroppedSpecifier << SS->getRange(),
745 CanRecover);
746 } else {
747 llvm_unreachable("could not have corrected a typo here");
748 }
749
750 if (!CanRecover)
751 return;
752
753 CXXScopeSpec tmpSS;
754 if (Corrected.getCorrectionSpecifier())
755 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
756 SourceRange(IILoc));
757 // FIXME: Support class template argument deduction here.
758 SuggestedType =
759 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
760 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
761 /*IsCtorOrDtorName=*/false,
762 /*WantNontrivialTypeSourceInfo=*/true);
763 }
764 return;
765 }
766
767 if (getLangOpts().CPlusPlus && !IsTemplateName) {
768 // See if II is a class template that the user forgot to pass arguments to.
769 UnqualifiedId Name;
770 Name.setIdentifier(II, IILoc);
771 CXXScopeSpec EmptySS;
772 TemplateTy TemplateResult;
773 bool MemberOfUnknownSpecialization;
774 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
775 Name, nullptr, true, TemplateResult,
776 MemberOfUnknownSpecialization) == TNK_Type_template) {
777 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
778 return;
779 }
780 }
781
782 // FIXME: Should we move the logic that tries to recover from a missing tag
783 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
784
785 if (!SS || (!SS->isSet() && !SS->isInvalid()))
786 Diag(IILoc, IsTemplateName ? diag::err_no_template
787 : diag::err_unknown_typename)
788 << II;
789 else if (DeclContext *DC = computeDeclContext(*SS, false))
790 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
791 : diag::err_typename_nested_not_found)
792 << II << DC << SS->getRange();
793 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
794 SuggestedType =
795 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
796 } else if (isDependentScopeSpecifier(*SS)) {
797 unsigned DiagID = diag::err_typename_missing;
798 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
799 DiagID = diag::ext_typename_missing;
800
801 Diag(SS->getRange().getBegin(), DiagID)
802 << SS->getScopeRep() << II->getName()
803 << SourceRange(SS->getRange().getBegin(), IILoc)
804 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
805 SuggestedType = ActOnTypenameType(S, SourceLocation(),
806 *SS, *II, IILoc).get();
807 } else {
808 assert(SS && SS->isInvalid() &&
809 "Invalid scope specifier has already been diagnosed");
810 }
811}
812
813/// Determine whether the given result set contains either a type name
814/// or
815static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
816 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
817 NextToken.is(tok::less);
818
819 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
820 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
821 return true;
822
823 if (CheckTemplate && isa<TemplateDecl>(*I))
824 return true;
825 }
826
827 return false;
828}
829
831 Scope *S, CXXScopeSpec &SS,
832 IdentifierInfo *&Name,
833 SourceLocation NameLoc) {
834 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
835 SemaRef.LookupParsedName(R, S, &SS);
836 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
837 StringRef FixItTagName;
838 switch (Tag->getTagKind()) {
840 FixItTagName = "class ";
841 break;
842
844 FixItTagName = "enum ";
845 break;
846
848 FixItTagName = "struct ";
849 break;
850
852 FixItTagName = "__interface ";
853 break;
854
856 FixItTagName = "union ";
857 break;
858 }
859
860 StringRef TagName = FixItTagName.drop_back();
861 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
862 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
863 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
864
865 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
866 I != IEnd; ++I)
867 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
868 << Name << TagName;
869
870 // Replace lookup results with just the tag decl.
872 SemaRef.LookupParsedName(Result, S, &SS);
873 return true;
874 }
875
876 return false;
877}
878
880 IdentifierInfo *&Name,
881 SourceLocation NameLoc,
882 const Token &NextToken,
884 DeclarationNameInfo NameInfo(Name, NameLoc);
885 ObjCMethodDecl *CurMethod = getCurMethodDecl();
886
887 assert(NextToken.isNot(tok::coloncolon) &&
888 "parse nested name specifiers before calling ClassifyName");
889 if (getLangOpts().CPlusPlus && SS.isSet() &&
890 isCurrentClassName(*Name, S, &SS)) {
891 // Per [class.qual]p2, this names the constructors of SS, not the
892 // injected-class-name. We don't have a classification for that.
893 // There's not much point caching this result, since the parser
894 // will reject it later.
896 }
897
898 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
899 LookupParsedName(Result, S, &SS, !CurMethod);
900
901 if (SS.isInvalid())
903
904 // For unqualified lookup in a class template in MSVC mode, look into
905 // dependent base classes where the primary class template is known.
906 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
907 if (ParsedType TypeInBase =
908 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
909 return TypeInBase;
910 }
911
912 // Perform lookup for Objective-C instance variables (including automatically
913 // synthesized instance variables), if we're in an Objective-C method.
914 // FIXME: This lookup really, really needs to be folded in to the normal
915 // unqualified lookup mechanism.
916 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
918 if (Ivar.isInvalid())
920 if (Ivar.isUsable())
921 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
922
923 // We defer builtin creation until after ivar lookup inside ObjC methods.
924 if (Result.empty())
926 }
927
928 bool SecondTry = false;
929 bool IsFilteredTemplateName = false;
930
931Corrected:
932 switch (Result.getResultKind()) {
934 // If an unqualified-id is followed by a '(', then we have a function
935 // call.
936 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
937 // In C++, this is an ADL-only call.
938 // FIXME: Reference?
941
942 // C90 6.3.2.2:
943 // If the expression that precedes the parenthesized argument list in a
944 // function call consists solely of an identifier, and if no
945 // declaration is visible for this identifier, the identifier is
946 // implicitly declared exactly as if, in the innermost block containing
947 // the function call, the declaration
948 //
949 // extern int identifier ();
950 //
951 // appeared.
952 //
953 // We also allow this in C99 as an extension. However, this is not
954 // allowed in all language modes as functions without prototypes may not
955 // be supported.
956 if (getLangOpts().implicitFunctionsAllowed()) {
957 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
959 }
960 }
961
962 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
963 // In C++20 onwards, this could be an ADL-only call to a function
964 // template, and we're required to assume that this is a template name.
965 //
966 // FIXME: Find a way to still do typo correction in this case.
967 TemplateName Template =
970 }
971
972 // In C, we first see whether there is a tag type by the same name, in
973 // which case it's likely that the user just forgot to write "enum",
974 // "struct", or "union".
975 if (!getLangOpts().CPlusPlus && !SecondTry &&
976 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
977 break;
978 }
979
980 // Perform typo correction to determine if there is another name that is
981 // close to this name.
982 if (!SecondTry && CCC) {
983 SecondTry = true;
984 if (TypoCorrection Corrected =
985 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
986 &SS, *CCC, CTK_ErrorRecovery)) {
987 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
988 unsigned QualifiedDiag = diag::err_no_member_suggest;
989
990 NamedDecl *FirstDecl = Corrected.getFoundDecl();
991 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
992 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
993 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
994 UnqualifiedDiag = diag::err_no_template_suggest;
995 QualifiedDiag = diag::err_no_member_template_suggest;
996 } else if (UnderlyingFirstDecl &&
997 (isa<TypeDecl>(UnderlyingFirstDecl) ||
998 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
999 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1000 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1001 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1002 }
1003
1004 if (SS.isEmpty()) {
1005 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1006 } else {// FIXME: is this even reachable? Test it.
1007 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1008 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1009 Name->getName().equals(CorrectedStr);
1010 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1011 << Name << computeDeclContext(SS, false)
1012 << DroppedSpecifier << SS.getRange());
1013 }
1014
1015 // Update the name, so that the caller has the new name.
1016 Name = Corrected.getCorrectionAsIdentifierInfo();
1017
1018 // Typo correction corrected to a keyword.
1019 if (Corrected.isKeyword())
1020 return Name;
1021
1022 // Also update the LookupResult...
1023 // FIXME: This should probably go away at some point
1024 Result.clear();
1025 Result.setLookupName(Corrected.getCorrection());
1026 if (FirstDecl)
1027 Result.addDecl(FirstDecl);
1028
1029 // If we found an Objective-C instance variable, let
1030 // LookupInObjCMethod build the appropriate expression to
1031 // reference the ivar.
1032 // FIXME: This is a gross hack.
1033 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1034 DeclResult R =
1035 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1036 if (R.isInvalid())
1038 if (R.isUsable())
1039 return NameClassification::NonType(Ivar);
1040 }
1041
1042 goto Corrected;
1043 }
1044 }
1045
1046 // We failed to correct; just fall through and let the parser deal with it.
1047 Result.suppressDiagnostics();
1049
1051 // We performed name lookup into the current instantiation, and there were
1052 // dependent bases, so we treat this result the same way as any other
1053 // dependent nested-name-specifier.
1054
1055 // C++ [temp.res]p2:
1056 // A name used in a template declaration or definition and that is
1057 // dependent on a template-parameter is assumed not to name a type
1058 // unless the applicable name lookup finds a type name or the name is
1059 // qualified by the keyword typename.
1060 //
1061 // FIXME: If the next token is '<', we might want to ask the parser to
1062 // perform some heroics to see if we actually have a
1063 // template-argument-list, which would indicate a missing 'template'
1064 // keyword here.
1066 }
1067
1071 break;
1072
1074 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1075 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1076 /*AllowDependent=*/false)) {
1077 // C++ [temp.local]p3:
1078 // A lookup that finds an injected-class-name (10.2) can result in an
1079 // ambiguity in certain cases (for example, if it is found in more than
1080 // one base class). If all of the injected-class-names that are found
1081 // refer to specializations of the same class template, and if the name
1082 // is followed by a template-argument-list, the reference refers to the
1083 // class template itself and not a specialization thereof, and is not
1084 // ambiguous.
1085 //
1086 // This filtering can make an ambiguous result into an unambiguous one,
1087 // so try again after filtering out template names.
1089 if (!Result.isAmbiguous()) {
1090 IsFilteredTemplateName = true;
1091 break;
1092 }
1093 }
1094
1095 // Diagnose the ambiguity and return an error.
1097 }
1098
1099 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1100 (IsFilteredTemplateName ||
1102 Result, /*AllowFunctionTemplates=*/true,
1103 /*AllowDependent=*/false,
1104 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1106 // C++ [temp.names]p3:
1107 // After name lookup (3.4) finds that a name is a template-name or that
1108 // an operator-function-id or a literal- operator-id refers to a set of
1109 // overloaded functions any member of which is a function template if
1110 // this is followed by a <, the < is always taken as the delimiter of a
1111 // template-argument-list and never as the less-than operator.
1112 // C++2a [temp.names]p2:
1113 // A name is also considered to refer to a template if it is an
1114 // unqualified-id followed by a < and name lookup finds either one
1115 // or more functions or finds nothing.
1116 if (!IsFilteredTemplateName)
1118
1119 bool IsFunctionTemplate;
1120 bool IsVarTemplate;
1121 TemplateName Template;
1122 if (Result.end() - Result.begin() > 1) {
1123 IsFunctionTemplate = true;
1124 Template = Context.getOverloadedTemplateName(Result.begin(),
1125 Result.end());
1126 } else if (!Result.empty()) {
1127 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1128 *Result.begin(), /*AllowFunctionTemplates=*/true,
1129 /*AllowDependent=*/false));
1130 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1131 IsVarTemplate = isa<VarTemplateDecl>(TD);
1132
1133 UsingShadowDecl *FoundUsingShadow =
1134 dyn_cast<UsingShadowDecl>(*Result.begin());
1135 assert(!FoundUsingShadow ||
1136 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1137 Template =
1138 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1139 if (SS.isNotEmpty())
1141 /*TemplateKeyword=*/false,
1142 Template);
1143 } else {
1144 // All results were non-template functions. This is a function template
1145 // name.
1146 IsFunctionTemplate = true;
1147 Template = Context.getAssumedTemplateName(NameInfo.getName());
1148 }
1149
1150 if (IsFunctionTemplate) {
1151 // Function templates always go through overload resolution, at which
1152 // point we'll perform the various checks (e.g., accessibility) we need
1153 // to based on which function we selected.
1154 Result.suppressDiagnostics();
1155
1156 return NameClassification::FunctionTemplate(Template);
1157 }
1158
1159 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1161 }
1162
1163 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1165 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1166 T = Context.getUsingType(USD, T);
1167 return buildNamedType(*this, &SS, T, NameLoc);
1168 };
1169
1170 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1171 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1172 DiagnoseUseOfDecl(Type, NameLoc);
1173 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1174 return BuildTypeFor(Type, *Result.begin());
1175 }
1176
1177 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1178 if (!Class) {
1179 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1180 if (ObjCCompatibleAliasDecl *Alias =
1181 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1182 Class = Alias->getClassInterface();
1183 }
1184
1185 if (Class) {
1186 DiagnoseUseOfDecl(Class, NameLoc);
1187
1188 if (NextToken.is(tok::period)) {
1189 // Interface. <something> is parsed as a property reference expression.
1190 // Just return "unknown" as a fall-through for now.
1191 Result.suppressDiagnostics();
1193 }
1194
1196 return ParsedType::make(T);
1197 }
1198
1199 if (isa<ConceptDecl>(FirstDecl)) {
1200 // We want to preserve the UsingShadowDecl for concepts.
1201 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1204 TemplateName(cast<TemplateDecl>(FirstDecl)));
1205 }
1206
1207 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1208 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1210 }
1211
1212 // We can have a type template here if we're classifying a template argument.
1213 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1214 !isa<VarTemplateDecl>(FirstDecl))
1216 TemplateName(cast<TemplateDecl>(FirstDecl)));
1217
1218 // Check for a tag type hidden by a non-type decl in a few cases where it
1219 // seems likely a type is wanted instead of the non-type that was found.
1220 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1221 if ((NextToken.is(tok::identifier) ||
1222 (NextIsOp &&
1223 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1224 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1225 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1226 DiagnoseUseOfDecl(Type, NameLoc);
1227 return BuildTypeFor(Type, *Result.begin());
1228 }
1229
1230 // If we already know which single declaration is referenced, just annotate
1231 // that declaration directly. Defer resolving even non-overloaded class
1232 // member accesses, as we need to defer certain access checks until we know
1233 // the context.
1234 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1235 if (Result.isSingleResult() && !ADL &&
1236 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1237 return NameClassification::NonType(Result.getRepresentativeDecl());
1238
1239 // Otherwise, this is an overload set that we will need to resolve later.
1240 Result.suppressDiagnostics();
1242 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1243 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1244 /*KnownDependent=*/false));
1245}
1246
1249 SourceLocation NameLoc) {
1250 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1251 CXXScopeSpec SS;
1252 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1253 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1254}
1255
1258 IdentifierInfo *Name,
1259 SourceLocation NameLoc,
1260 bool IsAddressOfOperand) {
1261 DeclarationNameInfo NameInfo(Name, NameLoc);
1262 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1263 NameInfo, IsAddressOfOperand,
1264 /*TemplateArgs=*/nullptr);
1265}
1266
1268 NamedDecl *Found,
1269 SourceLocation NameLoc,
1270 const Token &NextToken) {
1271 if (getCurMethodDecl() && SS.isEmpty())
1272 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1273 return BuildIvarRefExpr(S, NameLoc, Ivar);
1274
1275 // Reconstruct the lookup result.
1276 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1277 Result.addDecl(Found);
1278 Result.resolveKind();
1279
1280 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1281 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1282}
1283
1285 // For an implicit class member access, transform the result into a member
1286 // access expression if necessary.
1287 auto *ULE = cast<UnresolvedLookupExpr>(E);
1288 if ((*ULE->decls_begin())->isCXXClassMember()) {
1289 CXXScopeSpec SS;
1290 SS.Adopt(ULE->getQualifierLoc());
1291
1292 // Reconstruct the lookup result.
1293 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1295 Result.setNamingClass(ULE->getNamingClass());
1296 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1297 Result.addDecl(*I, I.getAccess());
1298 Result.resolveKind();
1300 nullptr, S);
1301 }
1302
1303 // Otherwise, this is already in the form we needed, and no further checks
1304 // are necessary.
1305 return ULE;
1306}
1307
1310 auto *TD = Name.getAsTemplateDecl();
1311 if (!TD)
1313 if (isa<ClassTemplateDecl>(TD))
1315 if (isa<FunctionTemplateDecl>(TD))
1317 if (isa<VarTemplateDecl>(TD))
1319 if (isa<TypeAliasTemplateDecl>(TD))
1321 if (isa<TemplateTemplateParmDecl>(TD))
1323 if (isa<ConceptDecl>(TD))
1326}
1327
1329 assert(DC->getLexicalParent() == CurContext &&
1330 "The next DeclContext should be lexically contained in the current one.");
1331 CurContext = DC;
1332 S->setEntity(DC);
1333}
1334
1336 assert(CurContext && "DeclContext imbalance!");
1337
1339 assert(CurContext && "Popped translation unit!");
1340}
1341
1343 Decl *D) {
1344 // Unlike PushDeclContext, the context to which we return is not necessarily
1345 // the containing DC of TD, because the new context will be some pre-existing
1346 // TagDecl definition instead of a fresh one.
1347 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1348 CurContext = cast<TagDecl>(D)->getDefinition();
1349 assert(CurContext && "skipping definition of undefined tag");
1350 // Start lookups from the parent of the current context; we don't want to look
1351 // into the pre-existing complete definition.
1352 S->setEntity(CurContext->getLookupParent());
1353 return Result;
1354}
1355
1357 CurContext = static_cast<decltype(CurContext)>(Context);
1358}
1359
1360/// EnterDeclaratorContext - Used when we must lookup names in the context
1361/// of a declarator's nested name specifier.
1362///
1364 // C++0x [basic.lookup.unqual]p13:
1365 // A name used in the definition of a static data member of class
1366 // X (after the qualified-id of the static member) is looked up as
1367 // if the name was used in a member function of X.
1368 // C++0x [basic.lookup.unqual]p14:
1369 // If a variable member of a namespace is defined outside of the
1370 // scope of its namespace then any name used in the definition of
1371 // the variable member (after the declarator-id) is looked up as
1372 // if the definition of the variable member occurred in its
1373 // namespace.
1374 // Both of these imply that we should push a scope whose context
1375 // is the semantic context of the declaration. We can't use
1376 // PushDeclContext here because that context is not necessarily
1377 // lexically contained in the current context. Fortunately,
1378 // the containing scope should have the appropriate information.
1379
1380 assert(!S->getEntity() && "scope already has entity");
1381
1382#ifndef NDEBUG
1383 Scope *Ancestor = S->getParent();
1384 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1385 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1386#endif
1387
1388 CurContext = DC;
1389 S->setEntity(DC);
1390
1391 if (S->getParent()->isTemplateParamScope()) {
1392 // Also set the corresponding entities for all immediately-enclosing
1393 // template parameter scopes.
1394 EnterTemplatedContext(S->getParent(), DC);
1395 }
1396}
1397
1399 assert(S->getEntity() == CurContext && "Context imbalance!");
1400
1401 // Switch back to the lexical context. The safety of this is
1402 // enforced by an assert in EnterDeclaratorContext.
1403 Scope *Ancestor = S->getParent();
1404 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1405 CurContext = Ancestor->getEntity();
1406
1407 // We don't need to do anything with the scope, which is going to
1408 // disappear.
1409}
1410
1412 assert(S->isTemplateParamScope() &&
1413 "expected to be initializing a template parameter scope");
1414
1415 // C++20 [temp.local]p7:
1416 // In the definition of a member of a class template that appears outside
1417 // of the class template definition, the name of a member of the class
1418 // template hides the name of a template-parameter of any enclosing class
1419 // templates (but not a template-parameter of the member if the member is a
1420 // class or function template).
1421 // C++20 [temp.local]p9:
1422 // In the definition of a class template or in the definition of a member
1423 // of such a template that appears outside of the template definition, for
1424 // each non-dependent base class (13.8.2.1), if the name of the base class
1425 // or the name of a member of the base class is the same as the name of a
1426 // template-parameter, the base class name or member name hides the
1427 // template-parameter name (6.4.10).
1428 //
1429 // This means that a template parameter scope should be searched immediately
1430 // after searching the DeclContext for which it is a template parameter
1431 // scope. For example, for
1432 // template<typename T> template<typename U> template<typename V>
1433 // void N::A<T>::B<U>::f(...)
1434 // we search V then B<U> (and base classes) then U then A<T> (and base
1435 // classes) then T then N then ::.
1436 unsigned ScopeDepth = getTemplateDepth(S);
1437 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1438 DeclContext *SearchDCAfterScope = DC;
1439 for (; DC; DC = DC->getLookupParent()) {
1440 if (const TemplateParameterList *TPL =
1441 cast<Decl>(DC)->getDescribedTemplateParams()) {
1442 unsigned DCDepth = TPL->getDepth() + 1;
1443 if (DCDepth > ScopeDepth)
1444 continue;
1445 if (ScopeDepth == DCDepth)
1446 SearchDCAfterScope = DC = DC->getLookupParent();
1447 break;
1448 }
1449 }
1450 S->setLookupEntity(SearchDCAfterScope);
1451 }
1452}
1453
1455 // We assume that the caller has already called
1456 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1457 FunctionDecl *FD = D->getAsFunction();
1458 if (!FD)
1459 return;
1460
1461 // Same implementation as PushDeclContext, but enters the context
1462 // from the lexical parent, rather than the top-level class.
1463 assert(CurContext == FD->getLexicalParent() &&
1464 "The next DeclContext should be lexically contained in the current one.");
1465 CurContext = FD;
1466 S->setEntity(CurContext);
1467
1468 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1469 ParmVarDecl *Param = FD->getParamDecl(P);
1470 // If the parameter has an identifier, then add it to the scope
1471 if (Param->getIdentifier()) {
1472 S->AddDecl(Param);
1473 IdResolver.AddDecl(Param);
1474 }
1475 }
1476}
1477
1479 // Same implementation as PopDeclContext, but returns to the lexical parent,
1480 // rather than the top-level class.
1481 assert(CurContext && "DeclContext imbalance!");
1483 assert(CurContext && "Popped translation unit!");
1484}
1485
1486/// Determine whether overloading is allowed for a new function
1487/// declaration considering prior declarations of the same name.
1488///
1489/// This routine determines whether overloading is possible, not
1490/// whether a new declaration actually overloads a previous one.
1491/// It will return true in C++ (where overloads are alway permitted)
1492/// or, as a C extension, when either the new declaration or a
1493/// previous one is declared with the 'overloadable' attribute.
1495 ASTContext &Context,
1496 const FunctionDecl *New) {
1497 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1498 return true;
1499
1500 // Multiversion function declarations are not overloads in the
1501 // usual sense of that term, but lookup will report that an
1502 // overload set was found if more than one multiversion function
1503 // declaration is present for the same name. It is therefore
1504 // inadequate to assume that some prior declaration(s) had
1505 // the overloadable attribute; checking is required. Since one
1506 // declaration is permitted to omit the attribute, it is necessary
1507 // to check at least two; hence the 'any_of' check below. Note that
1508 // the overloadable attribute is implicitly added to declarations
1509 // that were required to have it but did not.
1510 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1511 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1512 return ND->hasAttr<OverloadableAttr>();
1513 });
1514 } else if (Previous.getResultKind() == LookupResult::Found)
1515 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1516
1517 return false;
1518}
1519
1520/// Add this decl to the scope shadowed decl chains.
1521void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1522 // Move up the scope chain until we find the nearest enclosing
1523 // non-transparent context. The declaration will be introduced into this
1524 // scope.
1525 while (S->getEntity() && S->getEntity()->isTransparentContext())
1526 S = S->getParent();
1527
1528 // Add scoped declarations into their context, so that they can be
1529 // found later. Declarations without a context won't be inserted
1530 // into any context.
1531 if (AddToContext)
1532 CurContext->addDecl(D);
1533
1534 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1535 // are function-local declarations.
1536 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1537 return;
1538
1539 // Template instantiations should also not be pushed into scope.
1540 if (isa<FunctionDecl>(D) &&
1541 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1542 return;
1543
1544 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1545 S->AddDecl(D);
1546 return;
1547 }
1548 // If this replaces anything in the current scope,
1550 IEnd = IdResolver.end();
1551 for (; I != IEnd; ++I) {
1552 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1553 S->RemoveDecl(*I);
1555
1556 // Should only need to replace one decl.
1557 break;
1558 }
1559 }
1560
1561 S->AddDecl(D);
1562
1563 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1564 // Implicitly-generated labels may end up getting generated in an order that
1565 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1566 // the label at the appropriate place in the identifier chain.
1567 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1568 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1569 if (IDC == CurContext) {
1570 if (!S->isDeclScope(*I))
1571 continue;
1572 } else if (IDC->Encloses(CurContext))
1573 break;
1574 }
1575
1577 } else {
1579 }
1581}
1582
1584 bool AllowInlineNamespace) const {
1585 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1586}
1587
1589 DeclContext *TargetDC = DC->getPrimaryContext();
1590 do {
1591 if (DeclContext *ScopeDC = S->getEntity())
1592 if (ScopeDC->getPrimaryContext() == TargetDC)
1593 return S;
1594 } while ((S = S->getParent()));
1595
1596 return nullptr;
1597}
1598
1600 DeclContext*,
1601 ASTContext&);
1602
1603/// Filters out lookup results that don't fall within the given scope
1604/// as determined by isDeclInScope.
1606 bool ConsiderLinkage,
1607 bool AllowInlineNamespace) {
1609 while (F.hasNext()) {
1610 NamedDecl *D = F.next();
1611
1612 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1613 continue;
1614
1615 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1616 continue;
1617
1618 F.erase();
1619 }
1620
1621 F.done();
1622}
1623
1624/// We've determined that \p New is a redeclaration of \p Old. Check that they
1625/// have compatible owning modules.
1627 // [module.interface]p7:
1628 // A declaration is attached to a module as follows:
1629 // - If the declaration is a non-dependent friend declaration that nominates a
1630 // function with a declarator-id that is a qualified-id or template-id or that
1631 // nominates a class other than with an elaborated-type-specifier with neither
1632 // a nested-name-specifier nor a simple-template-id, it is attached to the
1633 // module to which the friend is attached ([basic.link]).
1634 if (New->getFriendObjectKind() &&
1638 return false;
1639 }
1640
1641 Module *NewM = New->getOwningModule();
1642 Module *OldM = Old->getOwningModule();
1643
1644 if (NewM && NewM->isPrivateModule())
1645 NewM = NewM->Parent;
1646 if (OldM && OldM->isPrivateModule())
1647 OldM = OldM->Parent;
1648
1649 if (NewM == OldM)
1650 return false;
1651
1652 if (NewM && OldM) {
1653 // A module implementation unit has visibility of the decls in its
1654 // implicitly imported interface.
1655 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1656 return false;
1657
1658 // Partitions are part of the module, but a partition could import another
1659 // module, so verify that the PMIs agree.
1660 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1663 return false;
1664 }
1665
1666 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1667 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1668 if (NewIsModuleInterface || OldIsModuleInterface) {
1669 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1670 // if a declaration of D [...] appears in the purview of a module, all
1671 // other such declarations shall appear in the purview of the same module
1672 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1673 << New
1674 << NewIsModuleInterface
1675 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1676 << OldIsModuleInterface
1677 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1678 Diag(Old->getLocation(), diag::note_previous_declaration);
1679 New->setInvalidDecl();
1680 return true;
1681 }
1682
1683 return false;
1684}
1685
1686// [module.interface]p6:
1687// A redeclaration of an entity X is implicitly exported if X was introduced by
1688// an exported declaration; otherwise it shall not be exported.
1690 // [module.interface]p1:
1691 // An export-declaration shall inhabit a namespace scope.
1692 //
1693 // So it is meaningless to talk about redeclaration which is not at namespace
1694 // scope.
1695 if (!New->getLexicalDeclContext()
1697 ->isFileContext() ||
1698 !Old->getLexicalDeclContext()
1700 ->isFileContext())
1701 return false;
1702
1703 bool IsNewExported = New->isInExportDeclContext();
1704 bool IsOldExported = Old->isInExportDeclContext();
1705
1706 // It should be irrevelant if both of them are not exported.
1707 if (!IsNewExported && !IsOldExported)
1708 return false;
1709
1710 if (IsOldExported)
1711 return false;
1712
1713 assert(IsNewExported);
1714
1715 auto Lk = Old->getFormalLinkage();
1716 int S = 0;
1717 if (Lk == Linkage::Internal)
1718 S = 1;
1719 else if (Lk == Linkage::Module)
1720 S = 2;
1721 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1722 Diag(Old->getLocation(), diag::note_previous_declaration);
1723 return true;
1724}
1725
1726// A wrapper function for checking the semantic restrictions of
1727// a redeclaration within a module.
1730 return true;
1731
1732 if (CheckRedeclarationExported(New, Old))
1733 return true;
1734
1735 return false;
1736}
1737
1738// Check the redefinition in C++20 Modules.
1739//
1740// [basic.def.odr]p14:
1741// For any definable item D with definitions in multiple translation units,
1742// - if D is a non-inline non-templated function or variable, or
1743// - if the definitions in different translation units do not satisfy the
1744// following requirements,
1745// the program is ill-formed; a diagnostic is required only if the definable
1746// item is attached to a named module and a prior definition is reachable at
1747// the point where a later definition occurs.
1748// - Each such definition shall not be attached to a named module
1749// ([module.unit]).
1750// - Each such definition shall consist of the same sequence of tokens, ...
1751// ...
1752//
1753// Return true if the redefinition is not allowed. Return false otherwise.
1755 const NamedDecl *Old) const {
1756 assert(getASTContext().isSameEntity(New, Old) &&
1757 "New and Old are not the same definition, we should diagnostic it "
1758 "immediately instead of checking it.");
1759 assert(const_cast<Sema *>(this)->isReachable(New) &&
1760 const_cast<Sema *>(this)->isReachable(Old) &&
1761 "We shouldn't see unreachable definitions here.");
1762
1763 Module *NewM = New->getOwningModule();
1764 Module *OldM = Old->getOwningModule();
1765
1766 // We only checks for named modules here. The header like modules is skipped.
1767 // FIXME: This is not right if we import the header like modules in the module
1768 // purview.
1769 //
1770 // For example, assuming "header.h" provides definition for `D`.
1771 // ```C++
1772 // //--- M.cppm
1773 // export module M;
1774 // import "header.h"; // or #include "header.h" but import it by clang modules
1775 // actually.
1776 //
1777 // //--- Use.cpp
1778 // import M;
1779 // import "header.h"; // or uses clang modules.
1780 // ```
1781 //
1782 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1783 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1784 // reject it. But the current implementation couldn't detect the case since we
1785 // don't record the information about the importee modules.
1786 //
1787 // But this might not be painful in practice. Since the design of C++20 Named
1788 // Modules suggests us to use headers in global module fragment instead of
1789 // module purview.
1790 if (NewM && NewM->isHeaderLikeModule())
1791 NewM = nullptr;
1792 if (OldM && OldM->isHeaderLikeModule())
1793 OldM = nullptr;
1794
1795 if (!NewM && !OldM)
1796 return true;
1797
1798 // [basic.def.odr]p14.3
1799 // Each such definition shall not be attached to a named module
1800 // ([module.unit]).
1801 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1802 return true;
1803
1804 // Then New and Old lives in the same TU if their share one same module unit.
1805 if (NewM)
1806 NewM = NewM->getTopLevelModule();
1807 if (OldM)
1808 OldM = OldM->getTopLevelModule();
1809 return OldM == NewM;
1810}
1811
1813 if (D->getDeclContext()->isFileContext())
1814 return false;
1815
1816 return isa<UsingShadowDecl>(D) ||
1817 isa<UnresolvedUsingTypenameDecl>(D) ||
1818 isa<UnresolvedUsingValueDecl>(D);
1819}
1820
1821/// Removes using shadow declarations not at class scope from the lookup
1822/// results.
1825 while (F.hasNext())
1827 F.erase();
1828
1829 F.done();
1830}
1831
1832/// Check for this common pattern:
1833/// @code
1834/// class S {
1835/// S(const S&); // DO NOT IMPLEMENT
1836/// void operator=(const S&); // DO NOT IMPLEMENT
1837/// };
1838/// @endcode
1840 // FIXME: Should check for private access too but access is set after we get
1841 // the decl here.
1843 return false;
1844
1845 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1846 return CD->isCopyConstructor();
1847 return D->isCopyAssignmentOperator();
1848}
1849
1850// We need this to handle
1851//
1852// typedef struct {
1853// void *foo() { return 0; }
1854// } A;
1855//
1856// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1857// for example. If 'A', foo will have external linkage. If we have '*A',
1858// foo will have no linkage. Since we can't know until we get to the end
1859// of the typedef, this function finds out if D might have non-external linkage.
1860// Callers should verify at the end of the TU if it D has external linkage or
1861// not.
1862bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1863 const DeclContext *DC = D->getDeclContext();
1864 while (!DC->isTranslationUnit()) {
1865 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1866 if (!RD->hasNameForLinkage())
1867 return true;
1868 }
1869 DC = DC->getParent();
1870 }
1871
1872 return !D->isExternallyVisible();
1873}
1874
1875// FIXME: This needs to be refactored; some other isInMainFile users want
1876// these semantics.
1877static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1879 return false;
1880 return S.SourceMgr.isInMainFile(Loc);
1881}
1882
1884 assert(D);
1885
1886 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1887 return false;
1888
1889 // Ignore all entities declared within templates, and out-of-line definitions
1890 // of members of class templates.
1891 if (D->getDeclContext()->isDependentContext() ||
1893 return false;
1894
1895 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1896 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1897 return false;
1898 // A non-out-of-line declaration of a member specialization was implicitly
1899 // instantiated; it's the out-of-line declaration that we're interested in.
1900 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1901 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1902 return false;
1903
1904 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1905 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1906 return false;
1907 } else {
1908 // 'static inline' functions are defined in headers; don't warn.
1909 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1910 return false;
1911 }
1912
1913 if (FD->doesThisDeclarationHaveABody() &&
1915 return false;
1916 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1917 // Constants and utility variables are defined in headers with internal
1918 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1919 // like "inline".)
1920 if (!isMainFileLoc(*this, VD->getLocation()))
1921 return false;
1922
1923 if (Context.DeclMustBeEmitted(VD))
1924 return false;
1925
1926 if (VD->isStaticDataMember() &&
1927 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1928 return false;
1929 if (VD->isStaticDataMember() &&
1930 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1931 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1932 return false;
1933
1934 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1935 return false;
1936 } else {
1937 return false;
1938 }
1939
1940 // Only warn for unused decls internal to the translation unit.
1941 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1942 // for inline functions defined in the main source file, for instance.
1943 return mightHaveNonExternalLinkage(D);
1944}
1945
1947 if (!D)
1948 return;
1949
1950 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1951 const FunctionDecl *First = FD->getFirstDecl();
1953 return; // First should already be in the vector.
1954 }
1955
1956 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1957 const VarDecl *First = VD->getFirstDecl();
1959 return; // First should already be in the vector.
1960 }
1961
1964}
1965
1966static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1967 const NamedDecl *D) {
1968 if (D->isInvalidDecl())
1969 return false;
1970
1971 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1972 // For a decomposition declaration, warn if none of the bindings are
1973 // referenced, instead of if the variable itself is referenced (which
1974 // it is, by the bindings' expressions).
1975 bool IsAllPlaceholders = true;
1976 for (const auto *BD : DD->bindings()) {
1977 if (BD->isReferenced())
1978 return false;
1979 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1980 }
1981 if (IsAllPlaceholders)
1982 return false;
1983 } else if (!D->getDeclName()) {
1984 return false;
1985 } else if (D->isReferenced() || D->isUsed()) {
1986 return false;
1987 }
1988
1989 if (D->isPlaceholderVar(LangOpts))
1990 return false;
1991
1992 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1993 D->hasAttr<CleanupAttr>())
1994 return false;
1995
1996 if (isa<LabelDecl>(D))
1997 return true;
1998
1999 // Except for labels, we only care about unused decls that are local to
2000 // functions.
2001 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2002 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2003 // For dependent types, the diagnostic is deferred.
2004 WithinFunction =
2005 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2006 if (!WithinFunction)
2007 return false;
2008
2009 if (isa<TypedefNameDecl>(D))
2010 return true;
2011
2012 // White-list anything that isn't a local variable.
2013 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2014 return false;
2015
2016 // Types of valid local variables should be complete, so this should succeed.
2017 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2018
2019 const Expr *Init = VD->getInit();
2020 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2021 Init = Cleanups->getSubExpr();
2022
2023 const auto *Ty = VD->getType().getTypePtr();
2024
2025 // Only look at the outermost level of typedef.
2026 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2027 // Allow anything marked with __attribute__((unused)).
2028 if (TT->getDecl()->hasAttr<UnusedAttr>())
2029 return false;
2030 }
2031
2032 // Warn for reference variables whose initializtion performs lifetime
2033 // extension.
2034 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2035 MTE && MTE->getExtendingDecl()) {
2036 Ty = VD->getType().getNonReferenceType().getTypePtr();
2037 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2038 }
2039
2040 // If we failed to complete the type for some reason, or if the type is
2041 // dependent, don't diagnose the variable.
2042 if (Ty->isIncompleteType() || Ty->isDependentType())
2043 return false;
2044
2045 // Look at the element type to ensure that the warning behaviour is
2046 // consistent for both scalars and arrays.
2047 Ty = Ty->getBaseElementTypeUnsafe();
2048
2049 if (const TagType *TT = Ty->getAs<TagType>()) {
2050 const TagDecl *Tag = TT->getDecl();
2051 if (Tag->hasAttr<UnusedAttr>())
2052 return false;
2053
2054 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2055 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2056 return false;
2057
2058 if (Init) {
2059 const auto *Construct =
2060 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2061 if (Construct && !Construct->isElidable()) {
2062 const CXXConstructorDecl *CD = Construct->getConstructor();
2063 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2064 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2065 return false;
2066 }
2067
2068 // Suppress the warning if we don't know how this is constructed, and
2069 // it could possibly be non-trivial constructor.
2070 if (Init->isTypeDependent()) {
2071 for (const CXXConstructorDecl *Ctor : RD->ctors())
2072 if (!Ctor->isTrivial())
2073 return false;
2074 }
2075
2076 // Suppress the warning if the constructor is unresolved because
2077 // its arguments are dependent.
2078 if (isa<CXXUnresolvedConstructExpr>(Init))
2079 return false;
2080 }
2081 }
2082 }
2083
2084 // TODO: __attribute__((unused)) templates?
2085 }
2086
2087 return true;
2088}
2089
2091 FixItHint &Hint) {
2092 if (isa<LabelDecl>(D)) {
2094 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2095 /*SkipTrailingWhitespaceAndNewline=*/false);
2096 if (AfterColon.isInvalid())
2097 return;
2099 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2100 }
2101}
2102
2105 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2106}
2107
2109 DiagReceiverTy DiagReceiver) {
2110 if (D->getTypeForDecl()->isDependentType())
2111 return;
2112
2113 for (auto *TmpD : D->decls()) {
2114 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2115 DiagnoseUnusedDecl(T, DiagReceiver);
2116 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2117 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2118 }
2119}
2120
2123 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2124}
2125
2126/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2127/// unless they are marked attr(unused).
2130 return;
2131
2132 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2133 // typedefs can be referenced later on, so the diagnostics are emitted
2134 // at end-of-translation-unit.
2136 return;
2137 }
2138
2139 FixItHint Hint;
2141
2142 unsigned DiagID;
2143 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2144 DiagID = diag::warn_unused_exception_param;
2145 else if (isa<LabelDecl>(D))
2146 DiagID = diag::warn_unused_label;
2147 else
2148 DiagID = diag::warn_unused_variable;
2149
2150 SourceLocation DiagLoc = D->getLocation();
2151 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2152}
2153
2155 DiagReceiverTy DiagReceiver) {
2156 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2157 // it's not really unused.
2158 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2159 return;
2160
2161 // In C++, `_` variables behave as if they were maybe_unused
2162 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2163 return;
2164
2165 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2166
2167 if (Ty->isReferenceType() || Ty->isDependentType())
2168 return;
2169
2170 if (const TagType *TT = Ty->getAs<TagType>()) {
2171 const TagDecl *Tag = TT->getDecl();
2172 if (Tag->hasAttr<UnusedAttr>())
2173 return;
2174 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2175 // mimic gcc's behavior.
2176 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2177 RD && !RD->hasAttr<WarnUnusedAttr>())
2178 return;
2179 }
2180
2181 // Don't warn about __block Objective-C pointer variables, as they might
2182 // be assigned in the block but not used elsewhere for the purpose of lifetime
2183 // extension.
2184 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2185 return;
2186
2187 // Don't warn about Objective-C pointer variables with precise lifetime
2188 // semantics; they can be used to ensure ARC releases the object at a known
2189 // time, which may mean assignment but no other references.
2190 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2191 return;
2192
2193 auto iter = RefsMinusAssignments.find(VD);
2194 if (iter == RefsMinusAssignments.end())
2195 return;
2196
2197 assert(iter->getSecond() >= 0 &&
2198 "Found a negative number of references to a VarDecl");
2199 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2200 // Assume the given VarDecl is "used" if its ref count stored in
2201 // `RefMinusAssignments` is positive, with one exception.
2202 //
2203 // For a C++ variable whose decl (with initializer) entirely consist the
2204 // condition expression of a if/while/for construct,
2205 // Clang creates a DeclRefExpr for the condition expression rather than a
2206 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2207 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2208 // used in the body of the if/while/for construct.
2209 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2210 if (!UnusedCXXCondDecl)
2211 return;
2212 }
2213
2214 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2215 : diag::warn_unused_but_set_variable;
2216 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2217}
2218
2220 Sema::DiagReceiverTy DiagReceiver) {
2221 // Verify that we have no forward references left. If so, there was a goto
2222 // or address of a label taken, but no definition of it. Label fwd
2223 // definitions are indicated with a null substmt which is also not a resolved
2224 // MS inline assembly label name.
2225 bool Diagnose = false;
2226 if (L->isMSAsmLabel())
2227 Diagnose = !L->isResolvedMSAsmLabel();
2228 else
2229 Diagnose = L->getStmt() == nullptr;
2230 if (Diagnose)
2231 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2232 << L);
2233}
2234
2236 S->applyNRVO();
2237
2238 if (S->decl_empty()) return;
2239 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2240 "Scope shouldn't contain decls!");
2241
2242 /// We visit the decls in non-deterministic order, but we want diagnostics
2243 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2244 /// and sort the diagnostics before emitting them, after we visited all decls.
2245 struct LocAndDiag {
2246 SourceLocation Loc;
2247 std::optional<SourceLocation> PreviousDeclLoc;
2249 };
2251 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2252 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2253 };
2254 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2255 SourceLocation PreviousDeclLoc,
2256 PartialDiagnostic PD) {
2257 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2258 };
2259
2260 for (auto *TmpD : S->decls()) {
2261 assert(TmpD && "This decl didn't get pushed??");
2262
2263 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2264 NamedDecl *D = cast<NamedDecl>(TmpD);
2265
2266 // Diagnose unused variables in this scope.
2267 if (!S->hasUnrecoverableErrorOccurred()) {
2268 DiagnoseUnusedDecl(D, addDiag);
2269 if (const auto *RD = dyn_cast<RecordDecl>(D))
2270 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2271 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2272 DiagnoseUnusedButSetDecl(VD, addDiag);
2273 RefsMinusAssignments.erase(VD);
2274 }
2275 }
2276
2277 if (!D->getDeclName()) continue;
2278
2279 // If this was a forward reference to a label, verify it was defined.
2280 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2281 CheckPoppedLabel(LD, *this, addDiag);
2282
2283 // Remove this name from our lexical scope, and warn on it if we haven't
2284 // already.
2286 auto ShadowI = ShadowingDecls.find(D);
2287 if (ShadowI != ShadowingDecls.end()) {
2288 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2289 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2290 PDiag(diag::warn_ctor_parm_shadows_field)
2291 << D << FD << FD->getParent());
2292 }
2293 ShadowingDecls.erase(ShadowI);
2294 }
2295 }
2296
2297 llvm::sort(DeclDiags,
2298 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2299 // The particular order for diagnostics is not important, as long
2300 // as the order is deterministic. Using the raw location is going
2301 // to generally be in source order unless there are macro
2302 // expansions involved.
2303 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2304 });
2305 for (const LocAndDiag &D : DeclDiags) {
2306 Diag(D.Loc, D.PD);
2307 if (D.PreviousDeclLoc)
2308 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2309 }
2310}
2311
2312/// Look for an Objective-C class in the translation unit.
2313///
2314/// \param Id The name of the Objective-C class we're looking for. If
2315/// typo-correction fixes this name, the Id will be updated
2316/// to the fixed name.
2317///
2318/// \param IdLoc The location of the name in the translation unit.
2319///
2320/// \param DoTypoCorrection If true, this routine will attempt typo correction
2321/// if there is no class with the given name.
2322///
2323/// \returns The declaration of the named Objective-C class, or NULL if the
2324/// class could not be found.
2326 SourceLocation IdLoc,
2327 bool DoTypoCorrection) {
2328 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2329 // creation from this context.
2331
2332 if (!IDecl && DoTypoCorrection) {
2333 // Perform typo correction at the given location, but only if we
2334 // find an Objective-C class name.
2336 if (TypoCorrection C =
2338 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2339 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2340 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2341 Id = IDecl->getIdentifier();
2342 }
2343 }
2344 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2345 // This routine must always return a class definition, if any.
2346 if (Def && Def->getDefinition())
2347 Def = Def->getDefinition();
2348 return Def;
2349}
2350
2351/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2352/// from S, where a non-field would be declared. This routine copes
2353/// with the difference between C and C++ scoping rules in structs and
2354/// unions. For example, the following code is well-formed in C but
2355/// ill-formed in C++:
2356/// @code
2357/// struct S6 {
2358/// enum { BAR } e;
2359/// };
2360///
2361/// void test_S6() {
2362/// struct S6 a;
2363/// a.e = BAR;
2364/// }
2365/// @endcode
2366/// For the declaration of BAR, this routine will return a different
2367/// scope. The scope S will be the scope of the unnamed enumeration
2368/// within S6. In C++, this routine will return the scope associated
2369/// with S6, because the enumeration's scope is a transparent
2370/// context but structures can contain non-field names. In C, this
2371/// routine will return the translation unit scope, since the
2372/// enumeration's scope is a transparent context and structures cannot
2373/// contain non-field names.
2375 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2376 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2377 (S->isClassScope() && !getLangOpts().CPlusPlus))
2378 S = S->getParent();
2379 return S;
2380}
2381
2382static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2384 switch (Error) {
2386 return "";
2388 return BuiltinInfo.getHeaderName(ID);
2390 return "stdio.h";
2392 return "setjmp.h";
2394 return "ucontext.h";
2395 }
2396 llvm_unreachable("unhandled error kind");
2397}
2398
2400 unsigned ID, SourceLocation Loc) {
2402
2403 if (getLangOpts().CPlusPlus) {
2405 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2406 CLinkageDecl->setImplicit();
2407 Parent->addDecl(CLinkageDecl);
2408 Parent = CLinkageDecl;
2409 }
2410
2411 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2412 /*TInfo=*/nullptr, SC_Extern,
2413 getCurFPFeatures().isFPConstrained(),
2414 false, Type->isFunctionProtoType());
2415 New->setImplicit();
2416 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2417
2418 // Create Decl objects for each parameter, adding them to the
2419 // FunctionDecl.
2420 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2422 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2424 Context, New, SourceLocation(), SourceLocation(), nullptr,
2425 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2426 parm->setScopeInfo(0, i);
2427 Params.push_back(parm);
2428 }
2429 New->setParams(Params);
2430 }
2431
2433 return New;
2434}
2435
2436/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2437/// file scope. lazily create a decl for it. ForRedeclaration is true
2438/// if we're creating this built-in in anticipation of redeclaring the
2439/// built-in.
2441 Scope *S, bool ForRedeclaration,
2442 SourceLocation Loc) {
2444
2446 QualType R = Context.GetBuiltinType(ID, Error);
2447 if (Error) {
2448 if (!ForRedeclaration)
2449 return nullptr;
2450
2451 // If we have a builtin without an associated type we should not emit a
2452 // warning when we were not able to find a type for it.
2453 if (Error == ASTContext::GE_Missing_type ||
2455 return nullptr;
2456
2457 // If we could not find a type for setjmp it is because the jmp_buf type was
2458 // not defined prior to the setjmp declaration.
2459 if (Error == ASTContext::GE_Missing_setjmp) {
2460 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2462 return nullptr;
2463 }
2464
2465 // Generally, we emit a warning that the declaration requires the
2466 // appropriate header.
2467 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2468 << getHeaderName(Context.BuiltinInfo, ID, Error)
2470 return nullptr;
2471 }
2472
2473 if (!ForRedeclaration &&
2476 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2477 : diag::ext_implicit_lib_function_decl)
2478 << Context.BuiltinInfo.getName(ID) << R;
2479 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2480 Diag(Loc, diag::note_include_header_or_declare)
2481 << Header << Context.BuiltinInfo.getName(ID);
2482 }
2483
2484 if (R.isNull())
2485 return nullptr;
2486
2487 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2489
2490 // TUScope is the translation-unit scope to insert this function into.
2491 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2492 // relate Scopes to DeclContexts, and probably eliminate CurContext
2493 // entirely, but we're not there yet.
2494 DeclContext *SavedContext = CurContext;
2495 CurContext = New->getDeclContext();
2497 CurContext = SavedContext;
2498 return New;
2499}
2500
2501/// Typedef declarations don't have linkage, but they still denote the same
2502/// entity if their types are the same.
2503/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2504/// isSameEntity.
2508 // This is only interesting when modules are enabled.
2509 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2510 return;
2511
2512 // Empty sets are uninteresting.
2513 if (Previous.empty())
2514 return;
2515
2516 LookupResult::Filter Filter = Previous.makeFilter();
2517 while (Filter.hasNext()) {
2518 NamedDecl *Old = Filter.next();
2519
2520 // Non-hidden declarations are never ignored.
2521 if (S.isVisible(Old))
2522 continue;
2523
2524 // Declarations of the same entity are not ignored, even if they have
2525 // different linkages.
2526 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2527 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2528 Decl->getUnderlyingType()))
2529 continue;
2530
2531 // If both declarations give a tag declaration a typedef name for linkage
2532 // purposes, then they declare the same entity.
2533 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2534 Decl->getAnonDeclWithTypedefName())
2535 continue;
2536 }
2537
2538 Filter.erase();
2539 }
2540
2541 Filter.done();
2542}
2543
2545 QualType OldType;
2546 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2547 OldType = OldTypedef->getUnderlyingType();
2548 else
2549 OldType = Context.getTypeDeclType(Old);
2550 QualType NewType = New->getUnderlyingType();
2551
2552 if (NewType->isVariablyModifiedType()) {
2553 // Must not redefine a typedef with a variably-modified type.
2554 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2555 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2556 << Kind << NewType;
2557 if (Old->getLocation().isValid())
2559 New->setInvalidDecl();
2560 return true;
2561 }
2562
2563 if (OldType != NewType &&
2564 !OldType->isDependentType() &&
2565 !NewType->isDependentType() &&
2566 !Context.hasSameType(OldType, NewType)) {
2567 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2568 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2569 << Kind << NewType << OldType;
2570 if (Old->getLocation().isValid())
2572 New->setInvalidDecl();
2573 return true;
2574 }
2575 return false;
2576}
2577
2578/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2579/// same name and scope as a previous declaration 'Old'. Figure out
2580/// how to resolve this situation, merging decls or emitting
2581/// diagnostics as appropriate. If there was an error, set New to be invalid.
2582///
2584 LookupResult &OldDecls) {
2585 // If the new decl is known invalid already, don't bother doing any
2586 // merging checks.
2587 if (New->isInvalidDecl()) return;
2588
2589 // Allow multiple definitions for ObjC built-in typedefs.
2590 // FIXME: Verify the underlying types are equivalent!
2591 if (getLangOpts().ObjC) {
2592 const IdentifierInfo *TypeID = New->getIdentifier();
2593 switch (TypeID->getLength()) {
2594 default: break;
2595 case 2:
2596 {
2597 if (!TypeID->isStr("id"))
2598 break;
2599 QualType T = New->getUnderlyingType();
2600 if (!T->isPointerType())
2601 break;
2602 if (!T->isVoidPointerType()) {
2603 QualType PT = T->castAs<PointerType>()->getPointeeType();
2604 if (!PT->isStructureType())
2605 break;
2606 }
2608 // Install the built-in type for 'id', ignoring the current definition.
2610 return;
2611 }
2612 case 5:
2613 if (!TypeID->isStr("Class"))
2614 break;
2616 // Install the built-in type for 'Class', ignoring the current definition.
2618 return;
2619 case 3:
2620 if (!TypeID->isStr("SEL"))
2621 break;
2623 // Install the built-in type for 'SEL', ignoring the current definition.
2625 return;
2626 }
2627 // Fall through - the typedef name was not a builtin type.
2628 }
2629
2630 // Verify the old decl was also a type.
2631 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2632 if (!Old) {
2633 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2634 << New->getDeclName();
2635
2636 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2637 if (OldD->getLocation().isValid())
2638 notePreviousDefinition(OldD, New->getLocation());
2639
2640 return New->setInvalidDecl();
2641 }
2642
2643 // If the old declaration is invalid, just give up here.
2644 if (Old->isInvalidDecl())
2645 return New->setInvalidDecl();
2646
2647 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2648 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2649 auto *NewTag = New->getAnonDeclWithTypedefName();
2650 NamedDecl *Hidden = nullptr;
2651 if (OldTag && NewTag &&
2652 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2653 !hasVisibleDefinition(OldTag, &Hidden)) {
2654 // There is a definition of this tag, but it is not visible. Use it
2655 // instead of our tag.
2656 New->setTypeForDecl(OldTD->getTypeForDecl());
2657 if (OldTD->isModed())
2658 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2659 OldTD->getUnderlyingType());
2660 else
2661 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2662
2663 // Make the old tag definition visible.
2665
2666 // If this was an unscoped enumeration, yank all of its enumerators
2667 // out of the scope.
2668 if (isa<EnumDecl>(NewTag)) {
2669 Scope *EnumScope = getNonFieldDeclScope(S);
2670 for (auto *D : NewTag->decls()) {
2671 auto *ED = cast<EnumConstantDecl>(D);
2672 assert(EnumScope->isDeclScope(ED));
2673 EnumScope->RemoveDecl(ED);
2675 ED->getLexicalDeclContext()->removeDecl(ED);
2676 }
2677 }
2678 }
2679 }
2680
2681 // If the typedef types are not identical, reject them in all languages and
2682 // with any extensions enabled.
2683 if (isIncompatibleTypedef(Old, New))
2684 return;
2685
2686 // The types match. Link up the redeclaration chain and merge attributes if
2687 // the old declaration was a typedef.
2688 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2689 New->setPreviousDecl(Typedef);
2690 mergeDeclAttributes(New, Old);
2691 }
2692
2693 if (getLangOpts().MicrosoftExt)
2694 return;
2695
2696 if (getLangOpts().CPlusPlus) {
2697 // C++ [dcl.typedef]p2:
2698 // In a given non-class scope, a typedef specifier can be used to
2699 // redefine the name of any type declared in that scope to refer
2700 // to the type to which it already refers.
2701 if (!isa<CXXRecordDecl>(CurContext))
2702 return;
2703
2704 // C++0x [dcl.typedef]p4:
2705 // In a given class scope, a typedef specifier can be used to redefine
2706 // any class-name declared in that scope that is not also a typedef-name
2707 // to refer to the type to which it already refers.
2708 //
2709 // This wording came in via DR424, which was a correction to the
2710 // wording in DR56, which accidentally banned code like:
2711 //
2712 // struct S {
2713 // typedef struct A { } A;
2714 // };
2715 //
2716 // in the C++03 standard. We implement the C++0x semantics, which
2717 // allow the above but disallow
2718 //
2719 // struct S {
2720 // typedef int I;
2721 // typedef int I;
2722 // };
2723 //
2724 // since that was the intent of DR56.
2725 if (!isa<TypedefNameDecl>(Old))
2726 return;
2727
2728 Diag(New->getLocation(), diag::err_redefinition)
2729 << New->getDeclName();
2731 return New->setInvalidDecl();
2732 }
2733
2734 // Modules always permit redefinition of typedefs, as does C11.
2735 if (getLangOpts().Modules || getLangOpts().C11)
2736 return;
2737
2738 // If we have a redefinition of a typedef in C, emit a warning. This warning
2739 // is normally mapped to an error, but can be controlled with
2740 // -Wtypedef-redefinition. If either the original or the redefinition is
2741 // in a system header, don't emit this for compatibility with GCC.
2742 if (getDiagnostics().getSuppressSystemWarnings() &&
2743 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2744 (Old->isImplicit() ||
2747 return;
2748
2749 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2750 << New->getDeclName();
2752}
2753
2754/// DeclhasAttr - returns true if decl Declaration already has the target
2755/// attribute.
2756static bool DeclHasAttr(const Decl *D, const Attr *A) {
2757 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2758 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2759 for (const auto *i : D->attrs())
2760 if (i->getKind() == A->getKind()) {
2761 if (Ann) {
2762 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2763 return true;
2764 continue;
2765 }
2766 // FIXME: Don't hardcode this check
2767 if (OA && isa<OwnershipAttr>(i))
2768 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2769 return true;
2770 }
2771
2772 return false;
2773}
2774
2776 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2777 return VD->isThisDeclarationADefinition();
2778 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2779 return TD->isCompleteDefinition() || TD->isBeingDefined();
2780 return true;
2781}
2782
2783/// Merge alignment attributes from \p Old to \p New, taking into account the
2784/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2785///
2786/// \return \c true if any attributes were added to \p New.
2787static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2788 // Look for alignas attributes on Old, and pick out whichever attribute
2789 // specifies the strictest alignment requirement.
2790 AlignedAttr *OldAlignasAttr = nullptr;
2791 AlignedAttr *OldStrictestAlignAttr = nullptr;
2792 unsigned OldAlign = 0;
2793 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2794 // FIXME: We have no way of representing inherited dependent alignments
2795 // in a case like:
2796 // template<int A, int B> struct alignas(A) X;
2797 // template<int A, int B> struct alignas(B) X {};
2798 // For now, we just ignore any alignas attributes which are not on the
2799 // definition in such a case.
2800 if (I->isAlignmentDependent())
2801 return false;
2802
2803 if (I->isAlignas())
2804 OldAlignasAttr = I;
2805
2806 unsigned Align = I->getAlignment(S.Context);
2807 if (Align > OldAlign) {
2808 OldAlign = Align;
2809 OldStrictestAlignAttr = I;
2810 }
2811 }
2812
2813 // Look for alignas attributes on New.
2814 AlignedAttr *NewAlignasAttr = nullptr;
2815 unsigned NewAlign = 0;
2816 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2817 if (I->isAlignmentDependent())
2818 return false;
2819
2820 if (I->isAlignas())
2821 NewAlignasAttr = I;
2822
2823 unsigned Align = I->getAlignment(S.Context);
2824 if (Align > NewAlign)
2825 NewAlign = Align;
2826 }
2827
2828 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2829 // Both declarations have 'alignas' attributes. We require them to match.
2830 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2831 // fall short. (If two declarations both have alignas, they must both match
2832 // every definition, and so must match each other if there is a definition.)
2833
2834 // If either declaration only contains 'alignas(0)' specifiers, then it
2835 // specifies the natural alignment for the type.
2836 if (OldAlign == 0 || NewAlign == 0) {
2837 QualType Ty;
2838 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2839 Ty = VD->getType();
2840 else
2841 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2842
2843 if (OldAlign == 0)
2844 OldAlign = S.Context.getTypeAlign(Ty);
2845 if (NewAlign == 0)
2846 NewAlign = S.Context.getTypeAlign(Ty);
2847 }
2848
2849 if (OldAlign != NewAlign) {
2850 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2853 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2854 }
2855 }
2856
2857 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2858 // C++11 [dcl.align]p6:
2859 // if any declaration of an entity has an alignment-specifier,
2860 // every defining declaration of that entity shall specify an
2861 // equivalent alignment.
2862 // C11 6.7.5/7:
2863 // If the definition of an object does not have an alignment
2864 // specifier, any other declaration of that object shall also
2865 // have no alignment specifier.
2866 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2867 << OldAlignasAttr;
2868 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2869 << OldAlignasAttr;
2870 }
2871
2872 bool AnyAdded = false;
2873
2874 // Ensure we have an attribute representing the strictest alignment.
2875 if (OldAlign > NewAlign) {
2876 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2877 Clone->setInherited(true);
2878 New->addAttr(Clone);
2879 AnyAdded = true;
2880 }
2881
2882 // Ensure we have an alignas attribute if the old declaration had one.
2883 if (OldAlignasAttr && !NewAlignasAttr &&
2884 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2885 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2886 Clone->setInherited(true);
2887 New->addAttr(Clone);
2888 AnyAdded = true;
2889 }
2890
2891 return AnyAdded;
2892}
2893
2894#define WANT_DECL_MERGE_LOGIC
2895#include "clang/Sema/AttrParsedAttrImpl.inc"
2896#undef WANT_DECL_MERGE_LOGIC
2897
2899 const InheritableAttr *Attr,
2901 // Diagnose any mutual exclusions between the attribute that we want to add
2902 // and attributes that already exist on the declaration.
2903 if (!DiagnoseMutualExclusions(S, D, Attr))
2904 return false;
2905
2906 // This function copies an attribute Attr from a previous declaration to the
2907 // new declaration D if the new declaration doesn't itself have that attribute
2908 // yet or if that attribute allows duplicates.
2909 // If you're adding a new attribute that requires logic different from
2910 // "use explicit attribute on decl if present, else use attribute from
2911 // previous decl", for example if the attribute needs to be consistent
2912 // between redeclarations, you need to call a custom merge function here.
2913 InheritableAttr *NewAttr = nullptr;
2914 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2915 NewAttr = S.mergeAvailabilityAttr(
2916 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2917 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2918 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2919 AA->getPriority());
2920 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2921 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2922 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2923 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2924 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2925 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2926 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2927 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2928 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2929 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2930 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2931 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2932 FA->getFirstArg());
2933 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2934 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2935 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2936 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2937 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2938 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2939 IA->getInheritanceModel());
2940 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2941 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2942 &S.Context.Idents.get(AA->getSpelling()));
2943 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2944 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2945 isa<CUDAGlobalAttr>(Attr))) {
2946 // CUDA target attributes are part of function signature for
2947 // overloading purposes and must not be merged.
2948 return false;
2949 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2950 NewAttr = S.mergeMinSizeAttr(D, *MA);
2951 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2952 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2953 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2954 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2955 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2956 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2957 else if (isa<AlignedAttr>(Attr))
2958 // AlignedAttrs are handled separately, because we need to handle all
2959 // such attributes on a declaration at the same time.
2960 NewAttr = nullptr;
2961 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2962 (AMK == Sema::AMK_Override ||
2965 NewAttr = nullptr;
2966 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2967 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2968 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2969 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2970 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2971 NewAttr = S.mergeImportNameAttr(D, *INA);
2972 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2973 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2974 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2975 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2976 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2977 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2978 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2979 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2980 NT->getZ());
2981 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2982 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2983 else if (isa<SuppressAttr>(Attr))
2984 // Do nothing. Each redeclaration should be suppressed separately.
2985 NewAttr = nullptr;
2986 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2987 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2988
2989 if (NewAttr) {
2990 NewAttr->setInherited(true);
2991 D->addAttr(NewAttr);
2992 if (isa<MSInheritanceAttr>(NewAttr))
2993 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2994 return true;
2995 }
2996
2997 return false;
2998}
2999
3000static const NamedDecl *getDefinition(const Decl *D) {
3001 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
3002 return TD->getDefinition();
3003 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3004 const VarDecl *Def = VD->getDefinition();
3005 if (Def)
3006 return Def;
3007 return VD->getActingDefinition();
3008 }
3009 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3010 const FunctionDecl *Def = nullptr;
3011 if (FD->isDefined(Def, true))
3012 return Def;
3013 }
3014 return nullptr;
3015}
3016
3017static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3018 for (const auto *Attribute : D->attrs())
3019 if (Attribute->getKind() == Kind)
3020 return true;
3021 return false;
3022}
3023
3024/// checkNewAttributesAfterDef - If we already have a definition, check that
3025/// there are no new attributes in this declaration.
3026static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3027 if (!New->hasAttrs())
3028 return;
3029
3030 const NamedDecl *Def = getDefinition(Old);
3031 if (!Def || Def == New)
3032 return;
3033
3034 AttrVec &NewAttributes = New->getAttrs();
3035 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3036 const Attr *NewAttribute = NewAttributes[I];
3037
3038 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3039 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3040 SkipBodyInfo SkipBody;
3041 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3042
3043 // If we're skipping this definition, drop the "alias" attribute.
3044 if (SkipBody.ShouldSkip) {
3045 NewAttributes.erase(NewAttributes.begin() + I);
3046 --E;
3047 continue;
3048 }
3049 } else {
3050 VarDecl *VD = cast<VarDecl>(New);
3051 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3053 ? diag::err_alias_after_tentative
3054 : diag::err_redefinition;
3055 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3056 if (Diag == diag::err_redefinition)
3057 S.notePreviousDefinition(Def, VD->getLocation());
3058 else
3059 S.Diag(Def->getLocation(), diag::note_previous_definition);
3060 VD->setInvalidDecl();
3061 }
3062 ++I;
3063 continue;
3064 }
3065
3066 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3067 // Tentative definitions are only interesting for the alias check above.
3068 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3069 ++I;
3070 continue;
3071 }
3072 }
3073
3074 if (hasAttribute(Def, NewAttribute->getKind())) {
3075 ++I;
3076 continue; // regular attr merging will take care of validating this.
3077 }
3078
3079 if (isa<C11NoReturnAttr>(NewAttribute)) {
3080 // C's _Noreturn is allowed to be added to a function after it is defined.
3081 ++I;
3082 continue;
3083 } else if (isa<UuidAttr>(NewAttribute)) {
3084 // msvc will allow a subsequent definition to add an uuid to a class
3085 ++I;
3086 continue;
3087 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3088 if (AA->isAlignas()) {
3089 // C++11 [dcl.align]p6:
3090 // if any declaration of an entity has an alignment-specifier,
3091 // every defining declaration of that entity shall specify an
3092 // equivalent alignment.
3093 // C11 6.7.5/7:
3094 // If the definition of an object does not have an alignment
3095 // specifier, any other declaration of that object shall also
3096 // have no alignment specifier.
3097 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3098 << AA;
3099 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3100 << AA;
3101 NewAttributes.erase(NewAttributes.begin() + I);
3102 --E;
3103 continue;
3104 }
3105 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3106 // If there is a C definition followed by a redeclaration with this
3107 // attribute then there are two different definitions. In C++, prefer the
3108 // standard diagnostics.
3109 if (!S.getLangOpts().CPlusPlus) {
3110 S.Diag(NewAttribute->getLocation(),
3111 diag::err_loader_uninitialized_redeclaration);
3112 S.Diag(Def->getLocation(), diag::note_previous_definition);
3113 NewAttributes.erase(NewAttributes.begin() + I);
3114 --E;
3115 continue;
3116 }
3117 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3118 cast<VarDecl>(New)->isInline() &&
3119 !cast<VarDecl>(New)->isInlineSpecified()) {
3120 // Don't warn about applying selectany to implicitly inline variables.
3121 // Older compilers and language modes would require the use of selectany
3122 // to make such variables inline, and it would have no effect if we
3123 // honored it.
3124 ++I;
3125 continue;
3126 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3127 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3128 // declarations after definitions.
3129 ++I;
3130 continue;
3131 }
3132
3133 S.Diag(NewAttribute->getLocation(),
3134 diag::warn_attribute_precede_definition);
3135 S.Diag(Def->getLocation(), diag::note_previous_definition);
3136 NewAttributes.erase(NewAttributes.begin() + I);
3137 --E;
3138 }
3139}
3140
3141static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3142 const ConstInitAttr *CIAttr,
3143 bool AttrBeforeInit) {
3144 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3145
3146 // Figure out a good way to write this specifier on the old declaration.
3147 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3148 // enough of the attribute list spelling information to extract that without
3149 // heroics.
3150 std::string SuitableSpelling;
3151 if (S.getLangOpts().CPlusPlus20)
3152 SuitableSpelling = std::string(
3153 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3154 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3155 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3156 InsertLoc, {tok::l_square, tok::l_square,
3157 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3158 S.PP.getIdentifierInfo("require_constant_initialization"),
3159 tok::r_square, tok::r_square}));
3160 if (SuitableSpelling.empty())
3161 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3162 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3163 S.PP.getIdentifierInfo("require_constant_initialization"),
3164 tok::r_paren, tok::r_paren}));
3165 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3166 SuitableSpelling = "constinit";
3167 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3168 SuitableSpelling = "[[clang::require_constant_initialization]]";
3169 if (SuitableSpelling.empty())
3170 SuitableSpelling = "__attribute__((require_constant_initialization))";
3171 SuitableSpelling += " ";
3172
3173 if (AttrBeforeInit) {
3174 // extern constinit int a;
3175 // int a = 0; // error (missing 'constinit'), accepted as extension
3176 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3177 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3178 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3179 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3180 } else {
3181 // int a = 0;
3182 // constinit extern int a; // error (missing 'constinit')
3183 S.Diag(CIAttr->getLocation(),
3184 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3185 : diag::warn_require_const_init_added_too_late)
3186 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3187 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3188 << CIAttr->isConstinit()
3189 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3190 }
3191}
3192
3193/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3196 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3197 UsedAttr *NewAttr = OldAttr->clone(Context);
3198 NewAttr->setInherited(true);
3199 New->addAttr(NewAttr);
3200 }
3201 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3202 RetainAttr *NewAttr = OldAttr->clone(Context);
3203 NewAttr->setInherited(true);
3204 New->addAttr(NewAttr);
3205 }
3206
3207 if (!Old->hasAttrs() && !New->hasAttrs())
3208 return;
3209
3210 // [dcl.constinit]p1:
3211 // If the [constinit] specifier is applied to any declaration of a
3212 // variable, it shall be applied to the initializing declaration.
3213 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3214 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3215 if (bool(OldConstInit) != bool(NewConstInit)) {
3216 const auto *OldVD = cast<VarDecl>(Old);
3217 auto *NewVD = cast<VarDecl>(New);
3218
3219 // Find the initializing declaration. Note that we might not have linked
3220 // the new declaration into the redeclaration chain yet.
3221 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3222 if (!InitDecl &&
3223 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3224 InitDecl = NewVD;
3225
3226 if (InitDecl == NewVD) {
3227 // This is the initializing declaration. If it would inherit 'constinit',
3228 // that's ill-formed. (Note that we do not apply this to the attribute
3229 // form).
3230 if (OldConstInit && OldConstInit->isConstinit())
3231 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3232 /*AttrBeforeInit=*/true);
3233 } else if (NewConstInit) {
3234 // This is the first time we've been told that this declaration should
3235 // have a constant initializer. If we already saw the initializing
3236 // declaration, this is too late.
3237 if (InitDecl && InitDecl != NewVD) {
3238 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3239 /*AttrBeforeInit=*/false);
3240 NewVD->dropAttr<ConstInitAttr>();
3241 }
3242 }
3243 }
3244
3245 // Attributes declared post-definition are currently ignored.
3246 checkNewAttributesAfterDef(*this, New, Old);
3247
3248 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3249 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3250 if (!OldA->isEquivalent(NewA)) {
3251 // This redeclaration changes __asm__ label.
3252 Diag(New->getLocation(), diag::err_different_asm_label);
3253 Diag(OldA->getLocation(), diag::note_previous_declaration);
3254 }
3255 } else if (Old->isUsed()) {
3256 // This redeclaration adds an __asm__ label to a declaration that has
3257 // already been ODR-used.
3258 Diag(New->getLocation(), diag::err_late_asm_label_name)
3259 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3260 }
3261 }
3262
3263 // Re-declaration cannot add abi_tag's.
3264 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3265 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3266 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3267 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3268 Diag(NewAbiTagAttr->getLocation(),
3269 diag::err_new_abi_tag_on_redeclaration)
3270 << NewTag;
3271 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3272 }
3273 }
3274 } else {
3275 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3276 Diag(Old->getLocation(), diag::note_previous_declaration);
3277 }
3278 }
3279
3280 // This redeclaration adds a section attribute.
3281 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3282 if (auto *VD = dyn_cast<VarDecl>(New)) {
3283 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3284 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3285 Diag(Old->getLocation(), diag::note_previous_declaration);
3286 }
3287 }
3288 }
3289
3290 // Redeclaration adds code-seg attribute.
3291 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3292 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3293 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3294 Diag(New->getLocation(), diag::warn_mismatched_section)
3295 << 0 /*codeseg*/;
3296 Diag(Old->getLocation(), diag::note_previous_declaration);
3297 }
3298
3299 if (!Old->hasAttrs())
3300 return;
3301
3302 bool foundAny = New->hasAttrs();
3303
3304 // Ensure that any moving of objects within the allocated map is done before
3305 // we process them.
3306 if (!foundAny) New->setAttrs(AttrVec());
3307
3308 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3309 // Ignore deprecated/unavailable/availability attributes if requested.
3311 if (isa<DeprecatedAttr>(I) ||
3312 isa<UnavailableAttr>(I) ||
3313 isa<AvailabilityAttr>(I)) {
3314 switch (AMK) {
3315 case AMK_None:
3316 continue;
3317
3318 case AMK_Redeclaration:
3319 case AMK_Override:
3322 LocalAMK = AMK;
3323 break;
3324 }
3325 }
3326
3327 // Already handled.
3328 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3329 continue;
3330
3331 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3332 foundAny = true;
3333 }
3334
3335 if (mergeAlignedAttrs(*this, New, Old))
3336 foundAny = true;
3337
3338 if (!foundAny) New->dropAttrs();
3339}
3340
3341/// mergeParamDeclAttributes - Copy attributes from the old parameter
3342/// to the new one.
3344 const ParmVarDecl *oldDecl,
3345 Sema &S) {
3346 // C++11 [dcl.attr.depend]p2:
3347 // The first declaration of a function shall specify the
3348 // carries_dependency attribute for its declarator-id if any declaration
3349 // of the function specifies the carries_dependency attribute.
3350 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3351 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3352 S.Diag(CDA->getLocation(),
3353 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3354 // Find the first declaration of the parameter.
3355 // FIXME: Should we build redeclaration chains for function parameters?
3356 const FunctionDecl *FirstFD =
3357 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3358 const ParmVarDecl *FirstVD =
3359 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3360 S.Diag(FirstVD->getLocation(),
3361 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3362 }
3363
3364 // HLSL parameter declarations for inout and out must match between
3365 // declarations. In HLSL inout and out are ambiguous at the call site, but
3366 // have different calling behavior, so you cannot overload a method based on a
3367 // difference between inout and out annotations.
3368 if (S.getLangOpts().HLSL) {
3369 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3370 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3371 // We don't need to cover the case where one declaration doesn't have an
3372 // attribute. The only possible case there is if one declaration has an `in`
3373 // attribute and the other declaration has no attribute. This case is
3374 // allowed since parameters are `in` by default.
3375 if (NDAttr && ODAttr &&
3376 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3377 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3378 << NDAttr << newDecl;
3379 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3380 << ODAttr;
3381 }
3382 }
3383
3384 if (!oldDecl->hasAttrs())
3385 return;
3386
3387 bool foundAny = newDecl->hasAttrs();
3388
3389 // Ensure that any moving of objects within the allocated map is
3390 // done before we process them.
3391 if (!foundAny) newDecl->setAttrs(AttrVec());
3392
3393 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3394 if (!DeclHasAttr(newDecl, I)) {
3395 InheritableAttr *newAttr =
3396 cast<InheritableParamAttr>(I->clone(S.Context));
3397 newAttr->setInherited(true);
3398 newDecl->addAttr(newAttr);
3399 foundAny = true;
3400 }
3401 }
3402
3403 if (!foundAny) newDecl->dropAttrs();
3404}
3405
3407 const ASTContext &Ctx) {
3408
3409 auto NoSizeInfo = [&Ctx](QualType Ty) {
3410 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3411 return true;
3412 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3413 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3414 return false;
3415 };
3416
3417 // `type[]` is equivalent to `type *` and `type[*]`.
3418 if (NoSizeInfo(Old) && NoSizeInfo(New))
3419 return true;
3420
3421 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3422 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3423 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3424 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3425 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3426 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3427 return false;
3428 return true;
3429 }
3430
3431 // Only compare size, ignore Size modifiers and CVR.
3432 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3433 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3434 Ctx.getAsConstantArrayType(New)->getSize();
3435 }
3436
3437 // Don't try to compare dependent sized array
3439 return true;
3440 }
3441
3442 return Old == New;
3443}
3444
3445static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3446 const ParmVarDecl *OldParam,
3447 Sema &S) {
3448 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3449 if (auto Newnullability = NewParam->getType()->getNullability()) {
3450 if (*Oldnullability != *Newnullability) {
3451 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3453 *Newnullability,
3455 != 0))
3457 *Oldnullability,
3459 != 0));
3460 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3461 }
3462 } else {
3463 QualType NewT = NewParam->getType();
3464 NewT = S.Context.getAttributedType(
3466 NewT, NewT);
3467 NewParam->setType(NewT);
3468 }
3469 }
3470 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3471 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3472 if (OldParamDT && NewParamDT &&
3473 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3474 QualType OldParamOT = OldParamDT->getOriginalType();
3475 QualType NewParamOT = NewParamDT->getOriginalType();
3476 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3477 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3478 << NewParam << NewParamOT;
3479 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3480 << OldParamOT;
3481 }
3482 }
3483}
3484
3485namespace {
3486
3487/// Used in MergeFunctionDecl to keep track of function parameters in
3488/// C.
3489struct GNUCompatibleParamWarning {
3490 ParmVarDecl *OldParm;
3491 ParmVarDecl *NewParm;
3492 QualType PromotedType;
3493};
3494
3495} // end anonymous namespace
3496
3497// Determine whether the previous declaration was a definition, implicit
3498// declaration, or a declaration.
3499template <typename T>
3500static std::pair<diag::kind, SourceLocation>
3501getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3502 diag::kind PrevDiag;
3503 SourceLocation OldLocation = Old->getLocation();
3504 if (Old->isThisDeclarationADefinition())
3505 PrevDiag = diag::note_previous_definition;
3506 else if (Old->isImplicit()) {
3507 PrevDiag = diag::note_previous_implicit_declaration;
3508 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3509 if (FD->getBuiltinID())
3510 PrevDiag = diag::note_previous_builtin_declaration;
3511 }
3512 if (OldLocation.isInvalid())
3513 OldLocation = New->getLocation();
3514 } else
3515 PrevDiag = diag::note_previous_declaration;
3516 return std::make_pair(PrevDiag, OldLocation);
3517}
3518
3519/// canRedefineFunction - checks if a function can be redefined. Currently,
3520/// only extern inline functions can be redefined, and even then only in
3521/// GNU89 mode.
3522static bool canRedefineFunction(const FunctionDecl *FD,
3523 const LangOptions& LangOpts) {
3524 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3525 !LangOpts.CPlusPlus &&
3526 FD->isInlineSpecified() &&
3527 FD->getStorageClass() == SC_Extern);
3528}
3529
3531 const AttributedType *AT = T->getAs<AttributedType>();
3532 while (AT && !AT->isCallingConv())
3533 AT = AT->getModifiedType()->getAs<AttributedType>();
3534 return AT;
3535}
3536
3537template <typename T>
3538static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3539 const DeclContext *DC = Old->getDeclContext();
3540 if (DC->isRecord())
3541 return false;
3542
3543 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3544 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3545 return true;
3546 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3547 return true;
3548 return false;
3549}
3550
3551template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3552static bool isExternC(VarTemplateDecl *) { return false; }
3553static bool isExternC(FunctionTemplateDecl *) { return false; }
3554
3555/// Check whether a redeclaration of an entity introduced by a
3556/// using-declaration is valid, given that we know it's not an overload
3557/// (nor a hidden tag declaration).
3558template<typename ExpectedDecl>
3560 ExpectedDecl *New) {
3561 // C++11 [basic.scope.declarative]p4:
3562 // Given a set of declarations in a single declarative region, each of
3563 // which specifies the same unqualified name,
3564 // -- they shall all refer to the same entity, or all refer to functions
3565 // and function templates; or
3566 // -- exactly one declaration shall declare a class name or enumeration
3567 // name that is not a typedef name and the other declarations shall all
3568 // refer to the same variable or enumerator, or all refer to functions
3569 // and function templates; in this case the class name or enumeration
3570 // name is hidden (3.3.10).
3571
3572 // C++11 [namespace.udecl]p14:
3573 // If a function declaration in namespace scope or block scope has the
3574 // same name and the same parameter-type-list as a function introduced
3575 // by a using-declaration, and the declarations do not declare the same
3576 // function, the program is ill-formed.
3577
3578 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3579 if (Old &&
3580 !Old->getDeclContext()->getRedeclContext()->Equals(
3581 New->getDeclContext()->getRedeclContext()) &&
3582 !(isExternC(Old) && isExternC(New)))
3583 Old = nullptr;
3584
3585 if (!Old) {
3586 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3587 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3588 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3589 return true;
3590 }
3591 return false;
3592}
3593
3595 const FunctionDecl *B) {
3596 assert(A->getNumParams() == B->getNumParams());
3597
3598 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3599 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3600 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3601 if (AttrA == AttrB)
3602 return true;
3603 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3604 AttrA->isDynamic() == AttrB->isDynamic();
3605 };
3606
3607 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3608}
3609
3610/// If necessary, adjust the semantic declaration context for a qualified
3611/// declaration to name the correct inline namespace within the qualifier.
3613 DeclaratorDecl *OldD) {
3614 // The only case where we need to update the DeclContext is when
3615 // redeclaration lookup for a qualified name finds a declaration
3616 // in an inline namespace within the context named by the qualifier:
3617 //
3618 // inline namespace N { int f(); }
3619 // int ::f(); // Sema DC needs adjusting from :: to N::.
3620 //
3621 // For unqualified declarations, the semantic context *can* change
3622 // along the redeclaration chain (for local extern declarations,
3623 // extern "C" declarations, and friend declarations in particular).
3624 if (!NewD->getQualifier())
3625 return;
3626
3627 // NewD is probably already in the right context.
3628 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3629 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3630 if (NamedDC->Equals(SemaDC))
3631 return;
3632
3633 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3634 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3635 "unexpected context for redeclaration");
3636
3637 auto *LexDC = NewD->getLexicalDeclContext();
3638 auto FixSemaDC = [=](NamedDecl *D) {
3639 if (!D)
3640 return;
3641 D->setDeclContext(SemaDC);
3642 D->setLexicalDeclContext(LexDC);
3643 };
3644
3645 FixSemaDC(NewD);
3646 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3647 FixSemaDC(FD->getDescribedFunctionTemplate());
3648 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3649 FixSemaDC(VD->getDescribedVarTemplate());
3650}
3651
3652/// MergeFunctionDecl - We just parsed a function 'New' from
3653/// declarator D which has the same name and scope as a previous
3654/// declaration 'Old'. Figure out how to resolve this situation,
3655/// merging decls or emitting diagnostics as appropriate.
3656///
3657/// In C++, New and Old must be declarations that are not
3658/// overloaded. Use IsOverload to determine whether New and Old are
3659/// overloaded, and to select the Old declaration that New should be
3660/// merged with.
3661///
3662/// Returns true if there was an error, false otherwise.
3664 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3665 // Verify the old decl was also a function.
3666 FunctionDecl *Old = OldD->getAsFunction();
3667 if (!Old) {
3668 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3669 if (New->getFriendObjectKind()) {
3670 Diag(New->getLocation(), diag::err_using_decl_friend);
3671 Diag(Shadow->getTargetDecl()->getLocation(),
3672 diag::note_using_decl_target);
3673 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3674 << 0;
3675 return true;
3676 }
3677
3678 // Check whether the two declarations might declare the same function or
3679 // function template.
3680 if (FunctionTemplateDecl *NewTemplate =
3682 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3683 NewTemplate))
3684 return true;
3685 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3686 ->getAsFunction();
3687 } else {
3688 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3689 return true;
3690 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3691 }
3692 } else {
3693 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3694 << New->getDeclName();
3695 notePreviousDefinition(OldD, New->getLocation());
3696 return true;
3697 }
3698 }
3699
3700 // If the old declaration was found in an inline namespace and the new
3701 // declaration was qualified, update the DeclContext to match.
3703
3704 // If the old declaration is invalid, just give up here.
3705 if (Old->isInvalidDecl())
3706 return true;
3707
3708 // Disallow redeclaration of some builtins.
3709 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3710 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3711 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3712 << Old << Old->getType();
3713 return true;
3714 }
3715
3716 diag::kind PrevDiag;
3717 SourceLocation OldLocation;
3718 std::tie(PrevDiag, OldLocation) =
3720
3721 // Don't complain about this if we're in GNU89 mode and the old function
3722 // is an extern inline function.
3723 // Don't complain about specializations. They are not supposed to have
3724 // storage classes.
3725 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3726 New->getStorageClass() == SC_Static &&
3727 Old->hasExternalFormalLinkage() &&
3730 if (getLangOpts().MicrosoftExt) {
3731 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3732 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3733 } else {
3734 Diag(New->getLocation(), diag::err_static_non_static) << New;
3735 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3736 return true;
3737 }
3738 }
3739
3740 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3741 if (!Old->hasAttr<InternalLinkageAttr>()) {
3742 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3743 << ILA;
3744 Diag(Old->getLocation(), diag::note_previous_declaration);
3745 New->dropAttr<InternalLinkageAttr>();
3746 }
3747
3748 if (auto *EA = New->getAttr<ErrorAttr>()) {
3749 if (!Old->hasAttr<ErrorAttr>()) {
3750 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3751 Diag(Old->getLocation(), diag::note_previous_declaration);
3752 New->dropAttr<ErrorAttr>();
3753 }
3754 }
3755
3756 if (CheckRedeclarationInModule(New, Old))
3757 return true;
3758
3759 if (!getLangOpts().CPlusPlus) {
3760 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3761 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3762 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3763 << New << OldOvl;
3764
3765 // Try our best to find a decl that actually has the overloadable
3766 // attribute for the note. In most cases (e.g. programs with only one
3767 // broken declaration/definition), this won't matter.
3768 //
3769 // FIXME: We could do this if we juggled some extra state in
3770 // OverloadableAttr, rather than just removing it.
3771 const Decl *DiagOld = Old;
3772 if (OldOvl) {
3773 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3774 const auto *A = D->getAttr<OverloadableAttr>();
3775 return A && !A->isImplicit();
3776 });
3777 // If we've implicitly added *all* of the overloadable attrs to this
3778 // chain, emitting a "previous redecl" note is pointless.
3779 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3780 }
3781
3782 if (DiagOld)
3783 Diag(DiagOld->getLocation(),
3784 diag::note_attribute_overloadable_prev_overload)
3785 << OldOvl;
3786
3787 if (OldOvl)
3788 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3789 else
3790 New->dropAttr<OverloadableAttr>();
3791 }
3792 }
3793
3794 // It is not permitted to redeclare an SME function with different SME
3795 // attributes.
3796 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3797 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3798 << New->getType() << Old->getType();
3799 Diag(OldLocation, diag::note_previous_declaration);
3800 return true;
3801 }
3802
3803 // If a function is first declared with a calling convention, but is later
3804 // declared or defined without one, all following decls assume the calling
3805 // convention of the first.
3806 //
3807 // It's OK if a function is first declared without a calling convention,
3808 // but is later declared or defined with the default calling convention.
3809 //
3810 // To test if either decl has an explicit calling convention, we look for
3811 // AttributedType sugar nodes on the type as written. If they are missing or
3812 // were canonicalized away, we assume the calling convention was implicit.
3813 //
3814 // Note also that we DO NOT return at this point, because we still have
3815 // other tests to run.
3816 QualType OldQType = Context.getCanonicalType(Old->getType());
3817 QualType NewQType = Context.getCanonicalType(New->getType());
3818 const FunctionType *OldType = cast<FunctionType>(OldQType);
3819 const FunctionType *NewType = cast<FunctionType>(NewQType);
3820 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3821 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3822 bool RequiresAdjustment = false;
3823
3824 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3826 const FunctionType *FT =
3827 First->getType().getCanonicalType()->castAs<FunctionType>();
3829 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3830 if (!NewCCExplicit) {
3831 // Inherit the CC from the previous declaration if it was specified
3832 // there but not here.
3833 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3834 RequiresAdjustment = true;
3835 } else if (Old->getBuiltinID()) {
3836 // Builtin attribute isn't propagated to the new one yet at this point,
3837 // so we check if the old one is a builtin.
3838
3839 // Calling Conventions on a Builtin aren't really useful and setting a
3840 // default calling convention and cdecl'ing some builtin redeclarations is
3841 // common, so warn and ignore the calling convention on the redeclaration.
3842 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3843 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3845 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3846 RequiresAdjustment = true;
3847 } else {
3848 // Calling conventions aren't compatible, so complain.
3849 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3850 Diag(New->getLocation(), diag::err_cconv_change)
3851 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3852 << !FirstCCExplicit
3853 << (!FirstCCExplicit ? "" :
3855
3856 // Put the note on the first decl, since it is the one that matters.
3857 Diag(First->getLocation(), diag::note_previous_declaration);
3858 return true;
3859 }
3860 }
3861
3862 // FIXME: diagnose the other way around?
3863 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3864 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3865 RequiresAdjustment = true;
3866 }
3867
3868 // Merge regparm attribute.
3869 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3870 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3871 if (NewTypeInfo.getHasRegParm()) {
3872 Diag(New->getLocation(), diag::err_regparm_mismatch)
3873 << NewType->getRegParmType()
3874 << OldType->getRegParmType();
3875 Diag(OldLocation, diag::note_previous_declaration);
3876 return true;
3877 }
3878
3879 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3880 RequiresAdjustment = true;
3881 }
3882
3883 // Merge ns_returns_retained attribute.
3884 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3885 if (NewTypeInfo.getProducesResult()) {
3886 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3887 << "'ns_returns_retained'";
3888 Diag(OldLocation, diag::note_previous_declaration);
3889 return true;
3890 }
3891
3892 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3893 RequiresAdjustment = true;
3894 }
3895
3896 if (OldTypeInfo.getNoCallerSavedRegs() !=
3897 NewTypeInfo.getNoCallerSavedRegs()) {
3898 if (NewTypeInfo.getNoCallerSavedRegs()) {
3899 AnyX86NoCallerSavedRegistersAttr *Attr =
3900 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3901 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3902 Diag(OldLocation, diag::note_previous_declaration);
3903 return true;
3904 }
3905
3906 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3907 RequiresAdjustment = true;
3908 }
3909
3910 if (RequiresAdjustment) {
3913 New->setType(QualType(AdjustedType, 0));
3914 NewQType = Context.getCanonicalType(New->getType());
3915 }
3916
3917 // If this redeclaration makes the function inline, we may need to add it to
3918 // UndefinedButUsed.
3919 if (!Old->isInlined() && New->isInlined() &&
3920 !New->hasAttr<GNUInlineAttr>() &&
3921 !getLangOpts().GNUInline &&
3922 Old->isUsed(false) &&
3923 !Old->isDefined() && !New->isThisDeclarationADefinition())
3924 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3925 SourceLocation()));
3926
3927 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3928 // about it.
3929 if (New->hasAttr<GNUInlineAttr>() &&
3930 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3931 UndefinedButUsed.erase(Old->getCanonicalDecl());
3932 }
3933
3934 // If pass_object_size params don't match up perfectly, this isn't a valid
3935 // redeclaration.
3936 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3938 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3939 << New->getDeclName();
3940 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3941 return true;
3942 }
3943
3944 if (getLangOpts().CPlusPlus) {
3945 OldQType = Context.getCanonicalType(Old->getType());
3946 NewQType = Context.getCanonicalType(New->getType());
3947
3948 // Go back to the type source info to compare the declared return types,
3949 // per C++1y [dcl.type.auto]p13:
3950 // Redeclarations or specializations of a function or function template
3951 // with a declared return type that uses a placeholder type shall also
3952 // use that placeholder, not a deduced type.
3953 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3954 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3955 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3956 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3957 OldDeclaredReturnType)) {
3958 QualType ResQT;
3959 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3960 OldDeclaredReturnType->isObjCObjectPointerType())
3961 // FIXME: This does the wrong thing for a deduced return type.
3962 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3963 if (ResQT.isNull()) {
3964 if (New->isCXXClassMember() && New->isOutOfLine())
3965 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3966 << New << New->getReturnTypeSourceRange();
3967 else
3968 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3969 << New->getReturnTypeSourceRange();
3970 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3971 << Old->getReturnTypeSourceRange();
3972 return true;
3973 }
3974 else
3975 NewQType = ResQT;
3976 }
3977
3978 QualType OldReturnType = OldType->getReturnType();
3979 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3980 if (OldReturnType != NewReturnType) {
3981 // If this function has a deduced return type and has already been
3982 // defined, copy the deduced value from the old declaration.
3983 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3984 if (OldAT && OldAT->isDeduced()) {
3985 QualType DT = OldAT->getDeducedType();
3986 if (DT.isNull()) {
3988 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3989 } else {
3990 New->setType(SubstAutoType(New->getType(), DT));
3991 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3992 }
3993 }
3994 }
3995
3996 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3997 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3998 if (OldMethod && NewMethod) {
3999 // Preserve triviality.
4000 NewMethod->setTrivial(OldMethod->isTrivial());
4001
4002 // MSVC allows explicit template specialization at class scope:
4003 // 2 CXXMethodDecls referring to the same function will be injected.
4004 // We don't want a redeclaration error.
4005 bool IsClassScopeExplicitSpecialization =
4006 OldMethod->isFunctionTemplateSpecialization() &&
4008 bool isFriend = NewMethod->getFriendObjectKind();
4009
4010 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4011 !IsClassScopeExplicitSpecialization) {
4012 // -- Member function declarations with the same name and the
4013 // same parameter types cannot be overloaded if any of them
4014 // is a static member function declaration.
4015 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4016 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4017 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4018 return true;
4019 }
4020
4021 // C++ [class.mem]p1:
4022 // [...] A member shall not be declared twice in the
4023 // member-specification, except that a nested class or member
4024 // class template can be declared and then later defined.
4025 if (!inTemplateInstantiation()) {
4026 unsigned NewDiag;
4027 if (isa<CXXConstructorDecl>(OldMethod))
4028 NewDiag = diag::err_constructor_redeclared;
4029 else if (isa<CXXDestructorDecl>(NewMethod))
4030 NewDiag = diag::err_destructor_redeclared;
4031 else if (isa<CXXConversionDecl>(NewMethod))
4032 NewDiag = diag::err_conv_function_redeclared;
4033 else
4034 NewDiag = diag::err_member_redeclared;
4035
4036 Diag(New->getLocation(), NewDiag);
4037 } else {
4038 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4039 << New << New->getType();
4040 }
4041 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4042 return true;
4043
4044 // Complain if this is an explicit declaration of a special
4045 // member that was initially declared implicitly.
4046 //
4047 // As an exception, it's okay to befriend such methods in order
4048 // to permit the implicit constructor/destructor/operator calls.
4049 } else if (OldMethod->isImplicit()) {
4050 if (isFriend) {
4051 NewMethod->setImplicit();
4052 } else {
4053 Diag(NewMethod->getLocation(),
4054 diag::err_definition_of_implicitly_declared_member)
4055 << New << llvm::to_underlying(getSpecialMember(OldMethod));
4056 return true;
4057 }
4058 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4059 Diag(NewMethod->getLocation(),
4060 diag::err_definition_of_explicitly_defaulted_member)
4061 << llvm::to_underlying(getSpecialMember(OldMethod));
4062 return true;
4063 }
4064 }
4065
4066 // C++1z [over.load]p2
4067 // Certain function declarations cannot be overloaded:
4068 // -- Function declarations that differ only in the return type,
4069 // the exception specification, or both cannot be overloaded.
4070
4071 // Check the exception specifications match. This may recompute the type of
4072 // both Old and New if it resolved exception specifications, so grab the
4073 // types again after this. Because this updates the type, we do this before
4074 // any of the other checks below, which may update the "de facto" NewQType
4075 // but do not necessarily update the type of New.
4076 if (CheckEquivalentExceptionSpec(Old, New))
4077 return true;
4078
4079 // C++11 [dcl.attr.noreturn]p1:
4080 // The first declaration of a function shall specify the noreturn
4081 // attribute if any declaration of that function specifies the noreturn
4082 // attribute.
4083 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4084 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4085 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4086 << NRA;
4087 Diag(Old->getLocation(), diag::note_previous_declaration);
4088 }
4089
4090 // C++11 [dcl.attr.depend]p2:
4091 // The first declaration of a function shall specify the
4092 // carries_dependency attribute for its declarator-id if any declaration
4093 // of the function specifies the carries_dependency attribute.
4094 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4095 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4096 Diag(CDA->getLocation(),
4097 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4098 Diag(Old->getFirstDecl()->getLocation(),
4099 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4100 }
4101
4102 // (C++98 8.3.5p3):
4103 // All declarations for a function shall agree exactly in both the
4104 // return type and the parameter-type-list.
4105 // We also want to respect all the extended bits except noreturn.
4106
4107 // noreturn should now match unless the old type info didn't have it.
4108 QualType OldQTypeForComparison = OldQType;
4109 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4110 auto *OldType = OldQType->castAs<FunctionProtoType>();
4111 const FunctionType *OldTypeForComparison
4112 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4113 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4114 assert(OldQTypeForComparison.isCanonical());
4115 }
4116
4117 if (haveIncompatibleLanguageLinkages(Old, New)) {
4118 // As a special case, retain the language linkage from previous
4119 // declarations of a friend function as an extension.
4120 //
4121 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4122 // and is useful because there's otherwise no way to specify language
4123 // linkage within class scope.
4124 //
4125 // Check cautiously as the friend object kind isn't yet complete.
4126 if (New->getFriendObjectKind() != Decl::FOK_None) {
4127 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4128 Diag(OldLocation, PrevDiag);
4129 } else {
4130 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4131 Diag(OldLocation, PrevDiag);
4132 return true;
4133 }
4134 }
4135
4136 // If the function types are compatible, merge the declarations. Ignore the
4137 // exception specifier because it was already checked above in
4138 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4139 // about incompatible types under -fms-compatibility.
4140 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4141 NewQType))
4142 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4143
4144 // If the types are imprecise (due to dependent constructs in friends or
4145 // local extern declarations), it's OK if they differ. We'll check again
4146 // during instantiation.
4147 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4148 return false;
4149
4150 // Fall through for conflicting redeclarations and redefinitions.
4151 }
4152
4153 // C: Function types need to be compatible, not identical. This handles
4154 // duplicate function decls like "void f(int); void f(enum X);" properly.
4155 if (!getLangOpts().CPlusPlus) {
4156 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4157 // type is specified by a function definition that contains a (possibly
4158 // empty) identifier list, both shall agree in the number of parameters
4159 // and the type of each parameter shall be compatible with the type that
4160 // results from the application of default argument promotions to the
4161 // type of the corresponding identifier. ...
4162 // This cannot be handled by ASTContext::typesAreCompatible() because that
4163 // doesn't know whether the function type is for a definition or not when
4164 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4165 // we need to cover here is that the number of arguments agree as the
4166 // default argument promotion rules were already checked by
4167 // ASTContext::typesAreCompatible().
4168 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4169 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4170 if (Old->hasInheritedPrototype())
4171 Old = Old->getCanonicalDecl();
4172 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4173 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4174 return true;
4175 }
4176
4177 // If we are merging two functions where only one of them has a prototype,
4178 // we may have enough information to decide to issue a diagnostic that the
4179 // function without a protoype will change behavior in C23. This handles
4180 // cases like:
4181 // void i(); void i(int j);
4182 // void i(int j); void i();
4183 // void i(); void i(int j) {}
4184 // See ActOnFinishFunctionBody() for other cases of the behavior change
4185 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4186 // type without a prototype.
4187 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4188 !New->isImplicit() && !Old->isImplicit()) {
4189 const FunctionDecl *WithProto, *WithoutProto;
4190 if (New->hasWrittenPrototype()) {
4191 WithProto = New;
4192 WithoutProto = Old;
4193 } else {
4194 WithProto = Old;
4195 WithoutProto = New;
4196 }
4197
4198 if (WithProto->getNumParams() != 0) {
4199 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4200 // The one without the prototype will be changing behavior in C23, so
4201 // warn about that one so long as it's a user-visible declaration.
4202 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4203 if (WithoutProto == New)
4204 IsWithoutProtoADef = NewDeclIsDefn;
4205 else
4206 IsWithProtoADef = NewDeclIsDefn;
4207 Diag(WithoutProto->getLocation(),
4208 diag::warn_non_prototype_changes_behavior)
4209 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4210 << (WithoutProto == Old) << IsWithProtoADef;
4211
4212 // The reason the one without the prototype will be changing behavior
4213 // is because of the one with the prototype, so note that so long as
4214 // it's a user-visible declaration. There is one exception to this:
4215 // when the new declaration is a definition without a prototype, the
4216 // old declaration with a prototype is not the cause of the issue,
4217 // and that does not need to be noted because the one with a
4218 // prototype will not change behavior in C23.
4219 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4220 !IsWithoutProtoADef)
4221 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4222 }
4223 }
4224 }
4225
4226 if (Context.typesAreCompatible(OldQType, NewQType)) {
4227 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4228 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4229 const FunctionProtoType *OldProto = nullptr;
4230 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4231 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4232 // The old declaration provided a function prototype, but the
4233 // new declaration does not. Merge in the prototype.
4234 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4235 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4236 OldProto->getParamTypes(),
4237 OldProto->getExtProtoInfo());
4238 New->setType(NewQType);
4240
4241 // Synthesize parameters with the same types.
4243 for (const auto &ParamType : OldProto->param_types()) {
4245 Context, New, SourceLocation(), SourceLocation(), nullptr,
4246 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4247 Param->setScopeInfo(0, Params.size());
4248 Param->setImplicit();
4249 Params.push_back(Param);
4250 }
4251
4252 New->setParams(Params);
4253 }
4254
4255 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4256 }
4257 }
4258
4259 // Check if the function types are compatible when pointer size address
4260 // spaces are ignored.
4261 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4262 return false;
4263
4264 // GNU C permits a K&R definition to follow a prototype declaration
4265 // if the declared types of the parameters in the K&R definition
4266 // match the types in the prototype declaration, even when the
4267 // promoted types of the parameters from the K&R definition differ
4268 // from the types in the prototype. GCC then keeps the types from
4269 // the prototype.
4270 //
4271 // If a variadic prototype is followed by a non-variadic K&R definition,
4272 // the K&R definition becomes variadic. This is sort of an edge case, but
4273 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4274 // C99 6.9.1p8.
4275 if (!getLangOpts().CPlusPlus &&
4276 Old->hasPrototype() && !New->hasPrototype() &&
4277 New->getType()->getAs<FunctionProtoType>() &&
4278 Old->getNumParams() == New->getNumParams()) {
4281 const FunctionProtoType *OldProto
4282 = Old->getType()->getAs<FunctionProtoType>();
4283 const FunctionProtoType *NewProto
4284 = New->getType()->getAs<FunctionProtoType>();
4285
4286 // Determine whether this is the GNU C extension.
4287 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4288 NewProto->getReturnType());
4289 bool LooseCompatible = !MergedReturn.isNull();
4290 for (unsigned Idx = 0, End = Old->getNumParams();
4291 LooseCompatible && Idx != End; ++Idx) {
4292 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4293 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4294 if (Context.typesAreCompatible(OldParm->getType(),
4295 NewProto->getParamType(Idx))) {
4296 ArgTypes.push_back(NewParm->getType());
4297 } else if (Context.typesAreCompatible(OldParm->getType(),
4298 NewParm->getType(),
4299 /*CompareUnqualified=*/true)) {
4300 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4301 NewProto->getParamType(Idx) };
4302 Warnings.push_back(Warn);
4303 ArgTypes.push_back(NewParm->getType());
4304 } else
4305 LooseCompatible = false;
4306 }
4307
4308 if (LooseCompatible) {
4309 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4310 Diag(Warnings[Warn].NewParm->getLocation(),
4311 diag::ext_param_promoted_not_compatible_with_prototype)
4312 << Warnings[Warn].PromotedType
4313 << Warnings[Warn].OldParm->getType();
4314 if (Warnings[Warn].OldParm->getLocation().isValid())
4315 Diag(Warnings[Warn].OldParm->getLocation(),
4316 diag::note_previous_declaration);
4317 }
4318
4319 if (MergeTypeWithOld)
4320 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4321 OldProto->getExtProtoInfo()));
4322 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4323 }
4324
4325 // Fall through to diagnose conflicting types.
4326 }
4327
4328 // A function that has already been declared has been redeclared or
4329 // defined with a different type; show an appropriate diagnostic.
4330
4331 // If the previous declaration was an implicitly-generated builtin
4332 // declaration, then at the very least we should use a specialized note.
4333 unsigned BuiltinID;
4334 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4335 // If it's actually a library-defined builtin function like 'malloc'
4336 // or 'printf', just warn about the incompatible redeclaration.
4338 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4339 Diag(OldLocation, diag::note_previous_builtin_declaration)
4340 << Old << Old->getType();
4341 return false;
4342 }
4343
4344 PrevDiag = diag::note_previous_builtin_declaration;
4345 }
4346
4347 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4348 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4349 return true;
4350}
4351
4352/// Completes the merge of two function declarations that are
4353/// known to be compatible.
4354///
4355/// This routine handles the merging of attributes and other
4356/// properties of function declarations from the old declaration to
4357/// the new declaration, once we know that New is in fact a
4358/// redeclaration of Old.
4359///
4360/// \returns false
4362 Scope *S, bool MergeTypeWithOld) {
4363 // Merge the attributes
4364 mergeDeclAttributes(New, Old);
4365
4366 // Merge "pure" flag.
4367 if (Old->isPureVirtual())
4368 New->setIsPureVirtual();
4369
4370 // Merge "used" flag.
4371 if (Old->getMostRecentDecl()->isUsed(false))
4372 New->setIsUsed();
4373
4374 // Merge attributes from the parameters. These can mismatch with K&R
4375 // declarations.
4376 if (New->getNumParams() == Old->getNumParams())
4377 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4378 ParmVarDecl *NewParam = New->getParamDecl(i);
4379 ParmVarDecl *OldParam = Old->getParamDecl(i);
4380 mergeParamDeclAttributes(NewParam, OldParam, *this);
4381 mergeParamDeclTypes(NewParam, OldParam, *this);
4382 }
4383
4384 if (getLangOpts().CPlusPlus)
4385 return MergeCXXFunctionDecl(New, Old, S);
4386
4387 // Merge the function types so the we get the composite types for the return
4388 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4389 // was visible.
4390 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4391 if (!Merged.isNull() && MergeTypeWithOld)
4392 New->setType(Merged);
4393
4394 return false;
4395}
4396
4398 ObjCMethodDecl *oldMethod) {
4399 // Merge the attributes, including deprecated/unavailable
4400 AvailabilityMergeKind MergeKind =
4401 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4404 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4405 : AMK_Override;
4406
4407 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4408
4409 // Merge attributes from the parameters.
4411 oe = oldMethod->param_end();
4413 ni = newMethod->param_begin(), ne = newMethod->param_end();
4414 ni != ne && oi != oe; ++ni, ++oi)
4415 mergeParamDeclAttributes(*ni, *oi, *this);
4416
4417 CheckObjCMethodOverride(newMethod, oldMethod);
4418}
4419
4421 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4422
4424 ? diag::err_redefinition_different_type
4425 : diag::err_redeclaration_different_type)
4426 << New->getDeclName() << New->getType() << Old->getType();
4427
4428 diag::kind PrevDiag;
4429 SourceLocation OldLocation;
4430 std::tie(PrevDiag, OldLocation)
4432 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4433 New->setInvalidDecl();
4434}
4435
4436/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4437/// scope as a previous declaration 'Old'. Figure out how to merge their types,
4438/// emitting diagnostics as appropriate.
4439///
4440/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4441/// to here in AddInitializerToDecl. We can't check them before the initializer
4442/// is attached.
4444 bool MergeTypeWithOld) {
4445 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4446 return;
4447
4448 QualType MergedT;
4449 if (getLangOpts().CPlusPlus) {
4450 if (New->getType()->isUndeducedType()) {
4451 // We don't know what the new type is until the initializer is attached.
4452 return;
4453 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4454 // These could still be something that needs exception specs checked.
4455 return MergeVarDeclExceptionSpecs(New, Old);
4456 }
4457 // C++ [basic.link]p10:
4458 // [...] the types specified by all declarations referring to a given
4459 // object or function shall be identical, except that declarations for an
4460 // array object can specify array types that differ by the presence or
4461 // absence of a major array bound (8.3.4).
4462 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4463 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4464 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4465
4466 // We are merging a variable declaration New into Old. If it has an array
4467 // bound, and that bound differs from Old's bound, we should diagnose the
4468 // mismatch.
4469 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4470 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4471 PrevVD = PrevVD->getPreviousDecl()) {
4472 QualType PrevVDTy = PrevVD->getType();
4473 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4474 continue;
4475
4476 if (!Context.hasSameType(New->getType(), PrevVDTy))
4477 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4478 }
4479 }
4480
4481 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4482 if (Context.hasSameType(OldArray->getElementType(),
4483 NewArray->getElementType()))
4484 MergedT = New->getType();
4485 }
4486 // FIXME: Check visibility. New is hidden but has a complete type. If New
4487 // has no array bound, it should not inherit one from Old, if Old is not
4488 // visible.
4489 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4490 if (Context.hasSameType(OldArray->getElementType(),
4491 NewArray->getElementType()))
4492 MergedT = Old->getType();
4493 }
4494 }
4495 else if (New->getType()->isObjCObjectPointerType() &&
4496 Old->getType()->isObjCObjectPointerType()) {
4497 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4498 Old->getType());
4499 }
4500 } else {
4501 // C 6.2.7p2:
4502 // All declarations that refer to the same object or function shall have
4503 // compatible type.
4504 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4505 }
4506 if (MergedT.isNull()) {
4507 // It's OK if we couldn't merge types if either type is dependent, for a
4508 // block-scope variable. In other cases (static data members of class
4509 // templates, variable templates, ...), we require the types to be
4510 // equivalent.
4511 // FIXME: The C++ standard doesn't say anything about this.
4512 if ((New->getType()->isDependentType() ||
4513 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4514 // If the old type was dependent, we can't merge with it, so the new type
4515 // becomes dependent for now. We'll reproduce the original type when we
4516 // instantiate the TypeSourceInfo for the variable.
4517 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4519 return;
4520 }
4521 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4522 }
4523
4524 // Don't actually update the type on the new declaration if the old
4525 // declaration was an extern declaration in a different scope.
4526 if (MergeTypeWithOld)
4527 New->setType(MergedT);
4528}
4529
4530static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4532 // C11 6.2.7p4:
4533 // For an identifier with internal or external linkage declared
4534 // in a scope in which a prior declaration of that identifier is
4535 // visible, if the prior declaration specifies internal or
4536 // external linkage, the type of the identifier at the later
4537 // declaration becomes the composite type.
4538 //
4539 // If the variable isn't visible, we do not merge with its type.
4540 if (Previous.isShadowed())
4541 return false;
4542
4543 if (S.getLangOpts().CPlusPlus) {
4544 // C++11 [dcl.array]p3:
4545 // If there is a preceding declaration of the entity in the same
4546 // scope in which the bound was specified, an omitted array bound
4547 // is taken to be the same as in that earlier declaration.
4548 return NewVD->isPreviousDeclInSameBlockScope() ||
4551 } else {
4552 // If the old declaration was function-local, don't merge with its
4553 // type unless we're in the same function.
4554 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4555 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4556 }
4557}
4558
4559/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4560/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4561/// situation, merging decls or emitting diagnostics as appropriate.
4562///
4563/// Tentative definition rules (C99 6.9.2p2) are checked by
4564/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4565/// definitions here, since the initializer hasn't been attached.
4566///
4568 // If the new decl is already invalid, don't do any other checking.
4569 if (New->isInvalidDecl())
4570 return;
4571
4572 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4573 return;
4574
4575 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4576
4577 // Verify the old decl was also a variable or variable template.
4578 VarDecl *Old = nullptr;
4579 VarTemplateDecl *OldTemplate = nullptr;
4580 if (Previous.isSingleResult()) {
4581 if (NewTemplate) {
4582 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4583 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4584
4585 if (auto *Shadow =
4586 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4587 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4588 return New->setInvalidDecl();
4589 } else {
4590 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4591
4592 if (auto *Shadow =
4593 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4594 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4595 return New->setInvalidDecl();
4596 }
4597 }
4598 if (!Old) {
4599 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4600 << New->getDeclName();
4601 notePreviousDefinition(Previous.getRepresentativeDecl(),
4602 New->getLocation());
4603 return New->setInvalidDecl();
4604 }
4605
4606 // If the old declaration was found in an inline namespace and the new
4607 // declaration was qualified, update the DeclContext to match.
4609
4610 // Ensure the template parameters are compatible.
4611 if (NewTemplate &&
4613 OldTemplate->getTemplateParameters(),
4614 /*Complain=*/true, TPL_TemplateMatch))
4615 return New->setInvalidDecl();
4616
4617 // C++ [class.mem]p1:
4618 // A member shall not be declared twice in the member-specification [...]
4619 //
4620 // Here, we need only consider static data members.
4621 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4622 Diag(New->getLocation(), diag::err_duplicate_member)
4623 << New->getIdentifier();
4624 Diag(Old->getLocation(), diag::note_previous_declaration);
4625 New->setInvalidDecl();
4626 }
4627
4628 mergeDeclAttributes(New, Old);
4629 // Warn if an already-declared variable is made a weak_import in a subsequent
4630 // declaration
4631 if (New->hasAttr<WeakImportAttr>() &&
4632 Old->getStorageClass() == SC_None &&
4633 !Old->hasAttr<WeakImportAttr>()) {
4634 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4635 Diag(Old->getLocation(), diag::note_previous_declaration);
4636 // Remove weak_import attribute on new declaration.
4637 New->dropAttr<WeakImportAttr>();
4638 }
4639
4640 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4641 if (!Old->hasAttr<InternalLinkageAttr>()) {
4642 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4643 << ILA;
4644 Diag(Old->getLocation(), diag::note_previous_declaration);
4645 New->dropAttr<InternalLinkageAttr>();
4646 }
4647
4648 // Merge the types.
4649 VarDecl *MostRecent = Old->getMostRecentDecl();
4650 if (MostRecent != Old) {
4651 MergeVarDeclTypes(New, MostRecent,
4652 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4653 if (New->isInvalidDecl())
4654 return;
4655 }
4656
4657 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4658 if (New->isInvalidDecl())
4659 return;
4660
4661 diag::kind PrevDiag;
4662 SourceLocation OldLocation;
4663 std::tie(PrevDiag, OldLocation) =
4665
4666 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4667 if (New->getStorageClass() == SC_Static &&
4668 !New->isStaticDataMember() &&
4669 Old->hasExternalFormalLinkage()) {
4670 if (getLangOpts().MicrosoftExt) {
4671 Diag(New->getLocation(), diag::ext_static_non_static)
4672 << New->getDeclName();
4673 Diag(OldLocation, PrevDiag);
4674 } else {
4675 Diag(New->getLocation(), diag::err_static_non_static)
4676 << New->getDeclName();
4677 Diag(OldLocation, PrevDiag);
4678 return New->setInvalidDecl();
4679 }
4680 }
4681 // C99 6.2.2p4:
4682 // For an identifier declared with the storage-class specifier
4683 // extern in a scope in which a prior declaration of that
4684 // identifier is visible,23) if the prior declaration specifies
4685 // internal or external linkage, the linkage of the identifier at
4686 // the later declaration is the same as the linkage specified at
4687 // the prior declaration. If no prior declaration is visible, or
4688 // if the prior declaration specifies no linkage, then the
4689 // identifier has external linkage.
4690 if (New->hasExternalStorage() && Old->hasLinkage())
4691 /* Okay */;
4692 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4693 !New->isStaticDataMember() &&
4695 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4696 Diag(OldLocation, PrevDiag);
4697 return New->setInvalidDecl();
4698 }
4699
4700 // Check if extern is followed by non-extern and vice-versa.
4701 if (New->hasExternalStorage() &&
4702 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4703 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4704 Diag(OldLocation, PrevDiag);
4705 return New->setInvalidDecl();
4706 }
4707 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4708 !New->hasExternalStorage()) {
4709 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4710 Diag(OldLocation, PrevDiag);
4711 return New->setInvalidDecl();
4712 }
4713
4714 if (CheckRedeclarationInModule(New, Old))
4715 return;
4716
4717 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4718
4719 // FIXME: The test for external storage here seems wrong? We still
4720 // need to check for mismatches.
4721 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4722 // Don't complain about out-of-line definitions of static members.
4723 !(Old->getLexicalDeclContext()->isRecord() &&
4724 !New->getLexicalDeclContext()->isRecord())) {
4725 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4726 Diag(OldLocation, PrevDiag);
4727 return New->setInvalidDecl();
4728 }
4729
4730 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4731 if (VarDecl *Def = Old->getDefinition()) {
4732 // C++1z [dcl.fcn.spec]p4:
4733 // If the definition of a variable appears in a translation unit before
4734 // its first declaration as inline, the program is ill-formed.
4735 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4736 Diag(Def->getLocation(), diag::note_previous_definition);
4737 }
4738 }
4739
4740 // If this redeclaration makes the variable inline, we may need to add it to
4741 // UndefinedButUsed.
4742 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4744 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4745 SourceLocation()));
4746
4747 if (New->getTLSKind() != Old->getTLSKind()) {
4748 if (!Old->getTLSKind()) {
4749 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4750 Diag(OldLocation, PrevDiag);
4751 } else if (!New->getTLSKind()) {
4752 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4753 Diag(OldLocation, PrevDiag);
4754 } else {
4755 // Do not allow redeclaration to change the variable between requiring
4756 // static and dynamic initialization.
4757 // FIXME: GCC allows this, but uses the TLS keyword on the first
4758 // declaration to determine the kind. Do we need to be compatible here?
4759 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4760 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4761 Diag(OldLocation, PrevDiag);
4762 }
4763 }
4764
4765 // C++ doesn't have tentative definitions, so go right ahead and check here.
4766 if (getLangOpts().CPlusPlus) {
4767 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4768 Old->getCanonicalDecl()->isConstexpr()) {
4769 // This definition won't be a definition any more once it's been merged.
4770 Diag(New->getLocation(),
4771 diag::warn_deprecated_redundant_constexpr_static_def);
4773 VarDecl *Def = Old->getDefinition();
4774 if (Def && checkVarDeclRedefinition(Def, New))
4775 return;
4776 }
4777 }
4778
4779 if (haveIncompatibleLanguageLinkages(Old, New)) {
4780 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4781 Diag(OldLocation, PrevDiag);
4782 New->setInvalidDecl();
4783 return;
4784 }
4785
4786 // Merge "used" flag.
4787 if (Old->getMostRecentDecl()->isUsed(false))
4788 New->setIsUsed();
4789
4790 // Keep a chain of previous declarations.
4791 New->setPreviousDecl(Old);
4792 if (NewTemplate)
4793 NewTemplate->setPreviousDecl(OldTemplate);
4794
4795 // Inherit access appropriately.
4796 New->setAccess(Old->getAccess());
4797 if (NewTemplate)
4798 NewTemplate->setAccess(New->getAccess());
4799
4800 if (Old->isInline())
4801 New->setImplicitlyInline();
4802}
4803
4805 SourceManager &SrcMgr = getSourceManager();
4806 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4807 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4808 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4809 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4810 auto &HSI = PP.getHeaderSearchInfo();
4811 StringRef HdrFilename =
4812 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4813
4814 auto noteFromModuleOrInclude = [&](Module *Mod,
4815 SourceLocation IncLoc) -> bool {
4816 // Redefinition errors with modules are common with non modular mapped
4817 // headers, example: a non-modular header H in module A that also gets
4818 // included directly in a TU. Pointing twice to the same header/definition
4819 // is confusing, try to get better diagnostics when modules is on.
4820 if (IncLoc.isValid()) {
4821 if (Mod) {
4822 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4823 << HdrFilename.str() << Mod->getFullModuleName();
4824 if (!Mod->DefinitionLoc.isInvalid())
4825 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4826 << Mod->getFullModuleName();
4827 } else {
4828 Diag(IncLoc, diag::note_redefinition_include_same_file)
4829 << HdrFilename.str();
4830 }
4831 return true;
4832 }
4833
4834 return false;
4835 };
4836
4837 // Is it the same file and same offset? Provide more information on why
4838 // this leads to a redefinition error.
4839 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4840 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4841 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4842 bool EmittedDiag =
4843 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4844 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4845
4846 // If the header has no guards, emit a note suggesting one.
4847 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4848 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4849
4850 if (EmittedDiag)
4851 return;
4852 }
4853
4854 // Redefinition coming from different files or couldn't do better above.
4855 if (Old->getLocation().isValid())
4856 Diag(Old->getLocation(), diag::note_previous_definition);
4857}
4858
4859/// We've just determined that \p Old and \p New both appear to be definitions
4860/// of the same variable. Either diagnose or fix the problem.
4862 if (!hasVisibleDefinition(Old) &&
4863 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4864 isa<VarTemplateSpecializationDecl>(New) ||
4867 // The previous definition is hidden, and multiple definitions are
4868 // permitted (in separate TUs). Demote this to a declaration.
4870
4871 // Make the canonical definition visible.
4872 if (auto *OldTD = Old->getDescribedVarTemplate())
4875 return false;
4876 } else {
4877 Diag(New->getLocation(), diag::err_redefinition) << New;
4879 New->setInvalidDecl();
4880 return true;
4881 }
4882}
4883
4884/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4885/// no declarator (e.g. "struct foo;") is parsed.
4887 DeclSpec &DS,
4888 const ParsedAttributesView &DeclAttrs,
4889 RecordDecl *&AnonRecord) {
4891 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4892}
4893
4894// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4895// disambiguate entities defined in different scopes.
4896// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4897// compatibility.
4898// We will pick our mangling number depending on which version of MSVC is being
4899// targeted.
4900static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4902 ? S->getMSCurManglingNumber()
4903 : S->getMSLastManglingNumber();
4904}
4905
4906void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4907 if (!Context.getLangOpts().CPlusPlus)
4908 return;
4909
4910 if (isa<CXXRecordDecl>(Tag->getParent())) {
4911 // If this tag is the direct child of a class, number it if
4912 // it is anonymous.
4913 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4914 return;
4918 Tag, MCtx.getManglingNumber(
4919 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4920 return;
4921 }
4922
4923 // If this tag isn't a direct child of a class, number it if it is local.
4925 Decl *ManglingContextDecl;
4926 std::tie(MCtx, ManglingContextDecl) =
4928 if (MCtx) {
4930 Tag, MCtx->getManglingNumber(
4931 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4932 }
4933}
4934
4935namespace {
4936struct NonCLikeKind {
4937 enum {
4938 None,
4939 BaseClass,
4940 DefaultMemberInit,
4941 Lambda,
4942 Friend,
4943 OtherMember,
4944 Invalid,
4945 } Kind = None;
4946 SourceRange Range;
4947
4948 explicit operator bool() { return Kind != None; }
4949};
4950}
4951
4952/// Determine whether a class is C-like, according to the rules of C++
4953/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4954static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4955 if (RD->isInvalidDecl())
4956 return {NonCLikeKind::Invalid, {}};
4957
4958 // C++ [dcl.typedef]p9: [P1766R1]
4959 // An unnamed class with a typedef name for linkage purposes shall not
4960 //
4961 // -- have any base classes
4962 if (RD->getNumBases())
4963 return {NonCLikeKind::BaseClass,
4965 RD->bases_end()[-1].getEndLoc())};
4966 bool Invalid = false;
4967 for (Decl *D : RD->decls()) {
4968 // Don't complain about things we already diagnosed.
4969 if (D->isInvalidDecl()) {
4970 Invalid = true;
4971 continue;
4972 }
4973
4974 // -- have any [...] default member initializers
4975 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4976 if (FD->hasInClassInitializer()) {
4977 auto *Init = FD->getInClassInitializer();
4978 return {NonCLikeKind::DefaultMemberInit,
4979 Init ? Init->getSourceRange() : D->getSourceRange()};
4980 }
4981 continue;
4982 }
4983
4984 // FIXME: We don't allow friend declarations. This violates the wording of
4985 // P1766, but not the intent.
4986 if (isa<FriendDecl>(D))
4987 return {NonCLikeKind::Friend, D->getSourceRange()};
4988
4989 // -- declare any members other than non-static data members, member
4990 // enumerations, or member classes,
4991 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4992 isa<EnumDecl>(D))
4993 continue;
4994 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4995 if (!MemberRD) {
4996 if (D->isImplicit())
4997 continue;
4998 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4999 }
5000
5001 // -- contain a lambda-expression,
5002 if (MemberRD->isLambda())
5003 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5004
5005 // and all member classes shall also satisfy these requirements
5006 // (recursively).
5007 if (MemberRD->isThisDeclarationADefinition()) {
5008 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5009 return Kind;
5010 }
5011 }
5012
5013 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5014}
5015
5017 TypedefNameDecl *NewTD) {
5018 if (TagFromDeclSpec->isInvalidDecl())
5019 return;
5020
5021 // Do nothing if the tag already has a name for linkage purposes.
5022 if (TagFromDeclSpec->hasNameForLinkage())
5023 return;
5024
5025 // A well-formed anonymous tag must always be a TUK_Definition.
5026 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5027
5028 // The type must match the tag exactly; no qualifiers allowed.
5030 Context.getTagDeclType(TagFromDeclSpec))) {
5031 if (getLangOpts().CPlusPlus)
5032 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5033 return;
5034 }
5035
5036 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5037 // An unnamed class with a typedef name for linkage purposes shall [be
5038 // C-like].
5039 //
5040 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5041 // shouldn't happen, but there are constructs that the language rule doesn't
5042 // disallow for which we can't reasonably avoid computing linkage early.
5043 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5044 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5045 : NonCLikeKind();
5046 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5047 if (NonCLike || ChangesLinkage) {
5048 if (NonCLike.Kind == NonCLikeKind::Invalid)
5049 return;
5050
5051 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5052 if (ChangesLinkage) {
5053 // If the linkage changes, we can't accept this as an extension.
5054 if (NonCLike.Kind == NonCLikeKind::None)
5055 DiagID = diag::err_typedef_changes_linkage;
5056 else
5057 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5058 }
5059
5060 SourceLocation FixitLoc =
5061 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5062 llvm::SmallString<40> TextToInsert;
5063 TextToInsert += ' ';
5064 TextToInsert += NewTD->getIdentifier()->getName();
5065
5066 Diag(FixitLoc, DiagID)
5067 << isa<TypeAliasDecl>(NewTD)
5068 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5069 if (NonCLike.Kind != NonCLikeKind::None) {
5070 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5071 << NonCLike.Kind - 1 << NonCLike.Range;
5072 }
5073 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5074 << NewTD << isa<TypeAliasDecl>(NewTD);
5075
5076 if (ChangesLinkage)
5077 return;
5078 }
5079
5080 // Otherwise, set this as the anon-decl typedef for the tag.
5081 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5082}
5083
5084static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5086 switch (T) {
5088 return 0;
5090 return 1;
5092 return 2;
5094 return 3;
5095 case DeclSpec::TST_enum:
5096 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5097 if (ED->isScopedUsingClassTag())
5098 return 5;
5099 if (ED->isScoped())
5100 return 6;
5101 }
5102 return 4;
5103 default:
5104 llvm_unreachable("unexpected type specifier");
5105 }
5106}
5107/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5108/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5109/// parameters to cope with template friend declarations.
5111 DeclSpec &DS,
5112 const ParsedAttributesView &DeclAttrs,
5113 MultiTemplateParamsArg TemplateParams,
5114 bool IsExplicitInstantiation,
5115 RecordDecl *&AnonRecord) {
5116 Decl *TagD = nullptr;
5117 TagDecl *Tag = nullptr;
5123 TagD = DS.getRepAsDecl();
5124
5125 if (!TagD) // We probably had an error
5126 return nullptr;
5127
5128 // Note that the above type specs guarantee that the
5129 // type rep is a Decl, whereas in many of the others
5130 // it's a Type.
5131 if (isa<TagDecl>(TagD))
5132 Tag = cast<TagDecl>(TagD);
5133 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5134 Tag = CTD->getTemplatedDecl();
5135 }
5136
5137 if (Tag) {
5138 handleTagNumbering(Tag, S);
5139 Tag->setFreeStanding();
5140 if (Tag->isInvalidDecl())
5141 return Tag;
5142 }
5143
5144 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5145 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5146 // or incomplete types shall not be restrict-qualified."
5147 if (TypeQuals & DeclSpec::TQ_restrict)
5149 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5150 << DS.getSourceRange();
5151 }
5152
5153 if (DS.isInlineSpecified())
5154 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5155 << getLangOpts().CPlusPlus17;
5156
5157 if (DS.hasConstexprSpecifier()) {
5158 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5159 // and definitions of functions and variables.
5160 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5161 // the declaration of a function or function template
5162 if (Tag)
5163 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5165 << static_cast<int>(DS.getConstexprSpecifier());
5166 else if (getLangOpts().C23)
5167 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5168 else
5169 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5170 << static_cast<int>(DS.getConstexprSpecifier());
5171 // Don't emit warnings after this error.
5172 return TagD;
5173 }
5174
5176
5177 if (DS.isFriendSpecified()) {
5178 // If we're dealing with a decl but not a TagDecl, assume that
5179 // whatever routines created it handled the friendship aspect.
5180 if (TagD && !Tag)
5181 return nullptr;
5182 return ActOnFriendTypeDecl(S, DS, TemplateParams);
5183 }
5184
5185 // Track whether this decl-specifier declares anything.
5186 bool DeclaresAnything = true;
5187
5188 // Handle anonymous struct definitions.
5189 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5190 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5192 if (getLangOpts().CPlusPlus ||
5193 Record->getDeclContext()->isRecord()) {
5194 // If CurContext is a DeclContext that can contain statements,
5195 // RecursiveASTVisitor won't visit the decls that
5196 // BuildAnonymousStructOrUnion() will put into CurContext.
5197 // Also store them here so that they can be part of the
5198 // DeclStmt that gets created in this case.
5199 // FIXME: Also return the IndirectFieldDecls created by
5200 // BuildAnonymousStructOr union, for the same reason?
5202 AnonRecord = Record;
5203 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5205 }
5206
5207 DeclaresAnything = false;
5208 }
5209 }
5210
5211 // C11 6.7.2.1p2:
5212 // A struct-declaration that does not declare an anonymous structure or
5213 // anonymous union shall contain a struct-declarator-list.
5214 //
5215 // This rule also existed in C89 and C99; the grammar for struct-declaration
5216 // did not permit a struct-declaration without a struct-declarator-list.
5219 // Check for Microsoft C extension: anonymous struct/union member.
5220 // Handle 2 kinds of anonymous struct/union:
5221 // struct STRUCT;
5222 // union UNION;
5223 // and
5224 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5225 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5226 if ((Tag && Tag->getDeclName()) ||
5228 RecordDecl *Record = nullptr;
5229 if (Tag)
5230 Record = dyn_cast<RecordDecl>(Tag);
5231 else if (const RecordType *RT =
5233 Record = RT->getDecl();
5234 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5235 Record = UT->getDecl();
5236
5237 if (Record && getLangOpts().MicrosoftExt) {
5238 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5239 << Record->isUnion() << DS.getSourceRange();
5241 }
5242
5243 DeclaresAnything = false;
5244 }
5245 }
5246
5247 // Skip all the checks below if we have a type error.
5249 (TagD && TagD->isInvalidDecl()))
5250 return TagD;
5251
5252 if (getLangOpts().CPlusPlus &&
5254 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5255 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5256 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5257 DeclaresAnything = false;
5258
5259 if (!DS.isMissingDeclaratorOk()) {
5260 // Customize diagnostic for a typedef missing a name.
5262 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5263 << DS.getSourceRange();
5264 else
5265 DeclaresAnything = false;
5266 }
5267
5268 if (DS.isModulePrivateSpecified() &&
5269 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5270 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5271 << llvm::to_underlying(Tag->getTagKind())
5273
5275
5276 // C 6.7/2:
5277 // A declaration [...] shall declare at least a declarator [...], a tag,
5278 // or the members of an enumeration.
5279 // C++ [dcl.dcl]p3:
5280 // [If there are no declarators], and except for the declaration of an
5281 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5282 // names into the program, or shall redeclare a name introduced by a
5283 // previous declaration.
5284 if (!DeclaresAnything) {
5285 // In C, we allow this as a (popular) extension / bug. Don't bother
5286 // producing further diagnostics for redundant qualifiers after this.
5287 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5288 ? diag::err_no_declarators
5289 : diag::ext_no_declarators)
5290 << DS.getSourceRange();
5291 return TagD;
5292 }
5293
5294 // C++ [dcl.stc]p1:
5295 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5296 // init-declarator-list of the declaration shall not be empty.
5297 // C++ [dcl.fct.spec]p1:
5298 // If a cv-qualifier appears in a decl-specifier-seq, the
5299 // init-declarator-list of the declaration shall not be empty.
5300 //
5301 // Spurious qualifiers here appear to be valid in C.
5302 unsigned DiagID = diag::warn_standalone_specifier;
5303 if (getLangOpts().CPlusPlus)
5304 DiagID = diag::ext_standalone_specifier;
5305
5306 // Note that a linkage-specification sets a storage class, but
5307 // 'extern "C" struct foo;' is actually valid and not theoretically
5308 // useless.
5309 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5310 if (SCS == DeclSpec::SCS_mutable)
5311 // Since mutable is not a viable storage class specifier in C, there is
5312 // no reason to treat it as an extension. Instead, diagnose as an error.
5313 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5314 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5315 Diag(DS.getStorageClassSpecLoc(), DiagID)
5317 }
5318
5322 if (DS.getTypeQualifiers()) {
5324 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5326 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5327 // Restrict is covered above.
5329 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5331 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5332 }
5333
5334 // Warn about ignored type attributes, for example:
5335 // __attribute__((aligned)) struct A;
5336 // Attributes should be placed after tag to apply to type declaration.
5337 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5338 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5339 if (TypeSpecType == DeclSpec::TST_class ||
5340 TypeSpecType == DeclSpec::TST_struct ||
5341 TypeSpecType == DeclSpec::TST_interface ||
5342 TypeSpecType == DeclSpec::TST_union ||
5343 TypeSpecType == DeclSpec::TST_enum) {
5344
5345 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5346 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5347 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5348 DiagnosticId = diag::warn_attribute_ignored;
5349 else if (AL.isRegularKeywordAttribute())
5350 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5351 else
5352 DiagnosticId = diag::warn_declspec_attribute_ignored;
5353 Diag(AL.getLoc(), DiagnosticId)
5354 << AL << GetDiagnosticTypeSpecifierID(DS);
5355 };
5356
5357 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5358 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5359 }
5360 }
5361
5362 return TagD;
5363}
5364
5365/// We are trying to inject an anonymous member into the given scope;
5366/// check if there's an existing declaration that can't be overloaded.
5367///
5368/// \return true if this is a forbidden redeclaration
5369static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5370 DeclContext *Owner,
5371 DeclarationName Name,
5372 SourceLocation NameLoc, bool IsUnion,
5373 StorageClass SC) {
5374 LookupResult R(SemaRef, Name, NameLoc,
5377 RedeclarationKind::ForVisibleRedeclaration);
5378 if (!SemaRef.LookupName(R, S)) return false;
5379
5380 // Pick a representative declaration.
5382 assert(PrevDecl && "Expected a non-null Decl");
5383
5384 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5385 return false;
5386
5387 if (SC == StorageClass::SC_None &&
5388 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5389 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5390 if (!Owner->isRecord())
5391 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5392 return false;
5393 }
5394
5395 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5396 << IsUnion << Name;
5397 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5398
5399 return true;
5400}
5401
5403 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5405}
5406
5407/// Emit diagnostic warnings for placeholder members.
5408/// We can only do that after the class is fully constructed,
5409/// as anonymous union/structs can insert placeholders
5410/// in their parent scope (which might be a Record).
5412 if (!getLangOpts().CPlusPlus)
5413 return;
5414
5415 // This function can be parsed before we have validated the
5416 // structure as an anonymous struct
5417 if (Record->isAnonymousStructOrUnion())
5418 return;
5419
5420 const NamedDecl *First = 0;
5421 for (const Decl *D : Record->decls()) {
5422 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5423 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5424 continue;
5425 if (!First)
5426 First = ND;
5427 else
5429 }
5430}
5431
5432/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5433/// anonymous struct or union AnonRecord into the owning context Owner
5434/// and scope S. This routine will be invoked just after we realize
5435/// that an unnamed union or struct is actually an anonymous union or
5436/// struct, e.g.,
5437///
5438/// @code
5439/// union {
5440/// int i;
5441/// float f;
5442/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5443/// // f into the surrounding scope.x
5444/// @endcode
5445///
5446/// This routine is recursive, injecting the names of nested anonymous
5447/// structs/unions into the owning context and scope as well.
5448static bool
5450 RecordDecl *AnonRecord, AccessSpecifier AS,
5451 StorageClass SC,
5452 SmallVectorImpl<NamedDecl *> &Chaining) {
5453 bool Invalid = false;
5454
5455 // Look every FieldDecl and IndirectFieldDecl with a name.
5456 for (auto *D : AnonRecord->decls()) {
5457 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5458 cast<NamedDecl>(D)->getDeclName()) {
5459 ValueDecl *VD = cast<ValueDecl>(D);
5460 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5461 VD->getLocation(), AnonRecord->isUnion(),
5462 SC)) {
5463 // C++ [class.union]p2:
5464 // The names of the members of an anonymous union shall be
5465 // distinct from the names of any other entity in the
5466 // scope in which the anonymous union is declared.
5467 Invalid = true;
5468 } else {
5469 // C++ [class.union]p2:
5470 // For the purpose of name lookup, after the anonymous union
5471 // definition, the members of the anonymous union are
5472 // considered to have been defined in the scope in which the
5473 // anonymous union is declared.
5474 unsigned OldChainingSize = Chaining.size();
5475 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5476 Chaining.append(IF->chain_begin(), IF->chain_end());
5477 else
5478 Chaining.push_back(VD);
5479
5480 assert(Chaining.size() >= 2);
5481 NamedDecl **NamedChain =
5482 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5483 for (unsigned i = 0; i < Chaining.size(); i++)
5484 NamedChain[i] = Chaining[i];
5485
5487 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5488 VD->getType(), {NamedChain, Chaining.size()});
5489
5490 for (const auto *Attr : VD->attrs())
5491 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5492
5493 IndirectField->setAccess(AS);
5494 IndirectField->setImplicit();
5495 SemaRef.PushOnScopeChains(IndirectField, S);
5496
5497 // That includes picking up the appropriate access specifier.
5498 if (AS != AS_none) IndirectField->setAccess(AS);
5499
5500 Chaining.resize(OldChainingSize);
5501 }
5502 }
5503 }
5504
5505 return Invalid;
5506}
5507
5508/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5509/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5510/// illegal input values are mapped to SC_None.
5511static StorageClass
5513 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5514 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5515 "Parser allowed 'typedef' as storage class VarDecl.");
5516 switch (StorageClassSpec) {
5519 if (DS.isExternInLinkageSpec())
5520 return SC_None;
5521 return SC_Extern;
5522 case DeclSpec::SCS_static: return SC_Static;
5523 case DeclSpec::SCS_auto: return SC_Auto;
5526 // Illegal SCSs map to None: error reporting is up to the caller.
5527 case DeclSpec::SCS_mutable: // Fall through.
5528 case DeclSpec::SCS_typedef: return SC_None;
5529 }
5530 llvm_unreachable("unknown storage class specifier");
5531}
5532
5534 assert(Record->hasInClassInitializer());
5535
5536 for (const auto *I : Record->decls()) {
5537 const auto *FD = dyn_cast<FieldDecl>(I);
5538 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5539 FD = IFD->getAnonField();
5540 if (FD && FD->hasInClassInitializer())
5541 return FD->getLocation();
5542 }
5543
5544 llvm_unreachable("couldn't find in-class initializer");
5545}
5546
5548 SourceLocation DefaultInitLoc) {
5549 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5550 return;
5551
5552 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5553 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5554}
5555
5557 CXXRecordDecl *AnonUnion) {
5558 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5559 return;
5560
5562}
5563
5564/// BuildAnonymousStructOrUnion - Handle the declaration of an
5565/// anonymous structure or union. Anonymous unions are a C++ feature
5566/// (C++ [class.union]) and a C11 feature; anonymous structures
5567/// are a C11 feature and GNU C++ extension.
5569 AccessSpecifier AS,
5571 const PrintingPolicy &Policy) {
5572 DeclContext *Owner = Record->getDeclContext();
5573
5574 // Diagnose whether this anonymous struct/union is an extension.
5575 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5576 Diag(Record->getLocation(), diag::ext_anonymous_union);
5577 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5578 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5579 else if (!Record->isUnion() && !getLangOpts().C11)
5580 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5581
5582 // C and C++ require different kinds of checks for anonymous
5583 // structs/unions.
5584 bool Invalid = false;
5585 if (getLangOpts().CPlusPlus) {
5586 const char *PrevSpec = nullptr;
5587 if (Record->isUnion()) {
5588 // C++ [class.union]p6:
5589 // C++17 [class.union.anon]p2:
5590 // Anonymous unions declared in a named namespace or in the
5591 // global namespace shall be declared static.
5592 unsigned DiagID;
5593 DeclContext *OwnerScope = Owner->getRedeclContext();
5595 (OwnerScope->isTranslationUnit() ||
5596 (OwnerScope->isNamespace() &&
5597 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5598 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5599 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5600
5601 // Recover by adding 'static'.
5603 PrevSpec, DiagID, Policy);
5604 }
5605 // C++ [class.union]p6:
5606 // A storage class is not allowed in a declaration of an
5607 // anonymous union in a class scope.
5609 isa<RecordDecl>(Owner)) {
5611 diag::err_anonymous_union_with_storage_spec)
5613
5614 // Recover by removing the storage specifier.
5617 PrevSpec, DiagID, Context.getPrintingPolicy());
5618 }
5619 }
5620
5621 // Ignore const/volatile/restrict qualifiers.
5622 if (DS.getTypeQualifiers()) {
5624 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5625 << Record->isUnion() << "const"
5629 diag::ext_anonymous_struct_union_qualified)
5630 << Record->isUnion() << "volatile"
5634 diag::ext_anonymous_struct_union_qualified)
5635 << Record->isUnion() << "restrict"
5639 diag::ext_anonymous_struct_union_qualified)
5640 << Record->isUnion() << "_Atomic"
5644 diag::ext_anonymous_struct_union_qualified)
5645 << Record->isUnion() << "__unaligned"
5647
5649 }
5650
5651 // C++ [class.union]p2:
5652 // The member-specification of an anonymous union shall only
5653 // define non-static data members. [Note: nested types and
5654 // functions cannot be declared within an anonymous union. ]
5655 for (auto *Mem : Record->decls()) {
5656 // Ignore invalid declarations; we already diagnosed them.
5657 if (Mem->isInvalidDecl())
5658 continue;
5659
5660 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5661 // C++ [class.union]p3:
5662 // An anonymous union shall not have private or protected
5663 // members (clause 11).
5664 assert(FD->getAccess() != AS_none);
5665 if (FD->getAccess() != AS_public) {
5666 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5667 << Record->isUnion() << (FD->getAccess() == AS_protected);
5668 Invalid = true;
5669 }
5670
5671 // C++ [class.union]p1
5672 // An object of a class with a non-trivial constructor, a non-trivial
5673 // copy constructor, a non-trivial destructor, or a non-trivial copy
5674 // assignment operator cannot be a member of a union, nor can an
5675 // array of such objects.
5676 if (CheckNontrivialField(FD))
5677 Invalid = true;
5678 } else if (Mem->isImplicit()) {
5679 // Any implicit members are fine.
5680 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5681 // This is a type that showed up in an
5682 // elaborated-type-specifier inside the anonymous struct or
5683 // union, but which actually declares a type outside of the
5684 // anonymous struct or union. It's okay.
5685 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5686 if (!MemRecord->isAnonymousStructOrUnion() &&
5687 MemRecord->getDeclName()) {
5688 // Visual C++ allows type definition in anonymous struct or union.
5689 if (getLangOpts().MicrosoftExt)
5690 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5691 << Record->isUnion();
5692 else {
5693 // This is a nested type declaration.
5694 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5695 << Record->isUnion();
5696 Invalid = true;
5697 }
5698 } else {
5699 // This is an anonymous type definition within another anonymous type.
5700 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5701 // not part of standard C++.
5702 Diag(MemRecord->getLocation(),
5703 diag::ext_anonymous_record_with_anonymous_type)
5704 << Record->isUnion();
5705 }
5706 } else if (isa<AccessSpecDecl>(Mem)) {
5707 // Any access specifier is fine.
5708 } else if (isa<StaticAssertDecl>(Mem)) {
5709 // In C++1z, static_assert declarations are also fine.
5710 } else {
5711 // We have something that isn't a non-static data
5712 // member. Complain about it.
5713 unsigned DK = diag::err_anonymous_record_bad_member;
5714 if (isa<TypeDecl>(Mem))
5715 DK = diag::err_anonymous_record_with_type;
5716 else if (isa<FunctionDecl>(Mem))
5717 DK = diag::err_anonymous_record_with_function;
5718 else if (isa<VarDecl>(Mem))
5719 DK = diag::err_anonymous_record_with_static;
5720
5721 // Visual C++ allows type definition in anonymous struct or union.
5722 if (getLangOpts().MicrosoftExt &&
5723 DK == diag::err_anonymous_record_with_type)
5724 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5725 << Record->isUnion();
5726 else {
5727 Diag(Mem->getLocation(), DK) << Record->isUnion();
5728 Invalid = true;
5729 }
5730 }
5731 }
5732
5733 // C++11 [class.union]p8 (DR1460):
5734 // At most one variant member of a union may have a
5735 // brace-or-equal-initializer.
5736 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5737 Owner->isRecord())
5738 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5739 cast<CXXRecordDecl>(Record));
5740 }
5741
5742 if (!Record->isUnion() && !Owner->isRecord()) {
5743 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5744 << getLangOpts().CPlusPlus;
5745 Invalid = true;
5746 }
5747
5748 // C++ [dcl.dcl]p3:
5749 // [If there are no declarators], and except for the declaration of an
5750 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5751 // names into the program
5752 // C++ [class.mem]p2:
5753 // each such member-declaration shall either declare at least one member
5754 // name of the class or declare at least one unnamed bit-field
5755 //
5756 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5757 if (getLangOpts().CPlusPlus && Record->field_empty())
5758 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5759
5760 // Mock up a declarator.
5764 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5765
5766 // Create a declaration for this anonymous struct/union.
5767 NamedDecl *Anon = nullptr;
5768 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5769 Anon = FieldDecl::Create(
5770 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5771 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5772 /*BitWidth=*/nullptr, /*Mutable=*/false,
5773 /*InitStyle=*/ICIS_NoInit);
5774 Anon->setAccess(AS);
5775 ProcessDeclAttributes(S, Anon, Dc);
5776
5777 if (getLangOpts().CPlusPlus)
5778 FieldCollector->Add(cast<FieldDecl>(Anon));
5779 } else {
5780 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5781 if (SCSpec == DeclSpec::SCS_mutable) {
5782 // mutable can only appear on non-static class members, so it's always
5783 // an error here
5784 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5785 Invalid = true;
5786 SC = SC_None;
5787 }
5788
5789 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5790 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5791 Context.getTypeDeclType(Record), TInfo, SC);
5792 ProcessDeclAttributes(S, Anon, Dc);
5793
5794 // Default-initialize the implicit variable. This initialization will be
5795 // trivial in almost all cases, except if a union member has an in-class
5796 // initializer:
5797 // union { int n = 0; };
5799 }
5800 Anon->setImplicit();
5801
5802 // Mark this as an anonymous struct/union type.
5803 Record->setAnonymousStructOrUnion(true);
5804
5805 // Add the anonymous struct/union object to the current
5806 // context. We'll be referencing this object when we refer to one of
5807 // its members.
5808 Owner->addDecl(Anon);
5809
5810 // Inject the members of the anonymous struct/union into the owning
5811 // context and into the identifier resolver chain for name lookup
5812 // purposes.
5814 Chain.push_back(Anon);
5815
5816 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5817 Chain))
5818 Invalid = true;
5819
5820 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5821 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5823 Decl *ManglingContextDecl;
5824 std::tie(MCtx, ManglingContextDecl) =
5825 getCurrentMangleNumberContext(NewVD->getDeclContext());
5826 if (MCtx) {
5828 NewVD, MCtx->getManglingNumber(
5829 NewVD, getMSManglingNumber(getLangOpts(), S)));
5831 }
5832 }
5833 }
5834
5835 if (Invalid)
5836 Anon->setInvalidDecl();
5837
5838 return Anon;
5839}
5840
5841/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5842/// Microsoft C anonymous structure.
5843/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5844/// Example:
5845///
5846/// struct A { int a; };
5847/// struct B { struct A; int b; };
5848///
5849/// void foo() {
5850/// B var;
5851/// var.a = 3;
5852/// }
5853///
5855 RecordDecl *Record) {
5856 assert(Record && "expected a record!");
5857
5858 // Mock up a declarator.
5861 assert(TInfo && "couldn't build declarator info for anonymous struct");
5862
5863 auto *ParentDecl = cast<RecordDecl>(CurContext);
5865
5866 // Create a declaration for this anonymous struct.
5867 NamedDecl *Anon =
5868 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5869 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5870 /*BitWidth=*/nullptr, /*Mutable=*/false,
5871 /*InitStyle=*/ICIS_NoInit);
5872 Anon->setImplicit();
5873
5874 // Add the anonymous struct object to the current context.
5875 CurContext->addDecl(Anon);
5876
5877 // Inject the members of the anonymous struct into the current
5878 // context and into the identifier resolver chain for name lookup
5879 // purposes.
5881 Chain.push_back(Anon);
5882
5883 RecordDecl *RecordDef = Record->getDefinition();
5884 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5885 diag::err_field_incomplete_or_sizeless) ||
5887 *this, S, CurContext, RecordDef, AS_none,
5889 Anon->setInvalidDecl();
5890 ParentDecl->setInvalidDecl();
5891 }
5892
5893 return Anon;
5894}
5895
5896/// GetNameForDeclarator - Determine the full declaration name for the
5897/// given Declarator.
5900}
5901
5902/// Retrieves the declaration name from a parsed unqualified-id.
5905 DeclarationNameInfo NameInfo;
5906 NameInfo.setLoc(Name.StartLocation);
5907
5908 switch (Name.getKind()) {
5909
5912 NameInfo.setName(Name.Identifier);
5913 return NameInfo;
5914
5916 // C++ [temp.deduct.guide]p3:
5917 // The simple-template-id shall name a class template specialization.
5918 // The template-name shall be the same identifier as the template-name
5919 // of the simple-template-id.
5920 // These together intend to imply that the template-name shall name a
5921 // class template.
5922 // FIXME: template<typename T> struct X {};
5923 // template<typename T> using Y = X<T>;
5924 // Y(int) -> Y<int>;
5925 // satisfies these rules but does not name a class template.
5926 TemplateName TN = Name.TemplateName.get().get();
5927 auto *Template = TN.getAsTemplateDecl();
5928 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5929 Diag(Name.StartLocation,
5930 diag::err_deduction_guide_name_not_class_template)
5932 if (Template)
5933 NoteTemplateLocation(*Template);
5934 return DeclarationNameInfo();
5935 }
5936
5937 NameInfo.setName(
5939 return NameInfo;
5940 }
5941
5944 Name.OperatorFunctionId.Operator));
5946 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5947 return NameInfo;
5948
5951 Name.Identifier));
5952 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5953 return NameInfo;
5954
5956 TypeSourceInfo *TInfo;
5957 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5958 if (Ty.isNull())
5959 return DeclarationNameInfo();
5962 NameInfo.setNamedTypeInfo(TInfo);
5963 return NameInfo;
5964 }
5965
5967 TypeSourceInfo *TInfo;
5968 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5969 if (Ty.isNull())
5970 return DeclarationNameInfo();
5973 NameInfo.setNamedTypeInfo(TInfo);
5974 return NameInfo;
5975 }
5976
5978 // In well-formed code, we can only have a constructor
5979 // template-id that refers to the current context, so go there
5980 // to find the actual type being constructed.
5981 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5982 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5983 return DeclarationNameInfo();
5984
5985 // Determine the type of the class being constructed.
5986 QualType CurClassType = Context.getTypeDeclType(CurClass);
5987
5988 // FIXME: Check two things: that the template-id names the same type as
5989 // CurClassType, and that the template-id does not occur when the name
5990 // was qualified.
5991
5993 Context.getCanonicalType(CurClassType)));
5994 // FIXME: should we retrieve TypeSourceInfo?
5995 NameInfo.setNamedTypeInfo(nullptr);
5996 return NameInfo;
5997 }
5998
6000 TypeSourceInfo *TInfo;
6001 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6002 if (Ty.isNull())
6003 return DeclarationNameInfo();
6006 NameInfo.setNamedTypeInfo(TInfo);
6007 return NameInfo;
6008 }
6009
6011 TemplateName TName = Name.TemplateId->Template.get();
6012 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6013 return Context.getNameForTemplate(TName, TNameLoc);
6014 }
6015
6016 } // switch (Name.getKind())
6017
6018 llvm_unreachable("Unknown name kind");
6019}
6020
6022 do {
6023 if (Ty->isPointerType() || Ty->isReferenceType())
6024 Ty = Ty->getPointeeType();
6025 else if (Ty->isArrayType())
6027 else
6028 return Ty.withoutLocalFastQualifiers();
6029 } while (true);
6030}
6031
6032/// hasSimilarParameters - Determine whether the C++ functions Declaration
6033/// and Definition have "nearly" matching parameters. This heuristic is
6034/// used to improve diagnostics in the case where an out-of-line function
6035/// definition doesn't match any declaration within the class or namespace.
6036/// Also sets Params to the list of indices to the parameters that differ
6037/// between the declaration and the definition. If hasSimilarParameters
6038/// returns true and Params is empty, then all of the parameters match.
6042 SmallVectorImpl<unsigned> &Params) {
6043 Params.clear();
6044 if (Declaration->param_size() != Definition->param_size())
6045 return false;
6046 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6047 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6048 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6049
6050 // The parameter types are identical
6051 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6052 continue;
6053
6054 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6055 QualType DefParamBaseTy = getCoreType(DefParamTy);
6056 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6057 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6058
6059 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6060 (DeclTyName && DeclTyName == DefTyName))
6061 Params.push_back(Idx);
6062 else // The two parameters aren't even close
6063 return false;
6064 }
6065
6066 return true;
6067}
6068
6069/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6070/// declarator needs to be rebuilt in the current instantiation.
6071/// Any bits of declarator which appear before the name are valid for
6072/// consideration here. That's specifically the type in the decl spec
6073/// and the base type in any member-pointer chunks.
6075 DeclarationName Name) {
6076 // The types we specifically need to rebuild are:
6077 // - typenames, typeofs, and decltypes
6078 // - types which will become injected class names
6079 // Of course, we also need to rebuild any type referencing such a
6080 // type. It's safest to just say "dependent", but we call out a
6081 // few cases here.
6082
6083 DeclSpec &DS = D.getMutableDeclSpec();
6084 switch (DS.getTypeSpecType()) {
6088#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6089#include "clang/Basic/TransformTypeTraits.def"
6090 case DeclSpec::TST_atomic: {
6091 // Grab the type from the parser.
6092 TypeSourceInfo *TSI = nullptr;
6093 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6094 if (T.isNull() || !T->isInstantiationDependentType()) break;
6095
6096 // Make sure there's a type source info. This isn't really much
6097 // of a waste; most dependent types should have type source info
6098 // attached already.
6099 if (!TSI)
6101
6102 // Rebuild the type in the current instantiation.
6104 if (!TSI) return true;
6105
6106 // Store the new type back in the decl spec.
6107 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6108 DS.UpdateTypeRep(LocType);
6109 break;
6110 }
6111
6115 Expr *E = DS.getRepAsExpr();
6117 if (Result.isInvalid()) return true;
6118 DS.UpdateExprRep(Result.get());
6119 break;
6120 }
6121
6122 default:
6123 // Nothing to do for these decl specs.
6124 break;
6125 }
6126
6127 // It doesn't matter what order we do this in.
6128 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6129 DeclaratorChunk &Chunk = D.getTypeObject(I);
6130
6131 // The only type information in the declarator which can come
6132 // before the declaration name is the base type of a member
6133 // pointer.
6135 continue;
6136
6137 // Rebuild the scope specifier in-place.
6138 CXXScopeSpec &SS = Chunk.Mem.Scope();
6140 return true;
6141 }
6142
6143 return false;
6144}
6145
6146/// Returns true if the declaration is declared in a system header or from a
6147/// system macro.
6148static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6149 return SM.isInSystemHeader(D->getLocation()) ||
6150 SM.isInSystemMacro(D->getLocation());
6151}
6152
6154 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6155 // of system decl.
6156 if (D->getPreviousDecl() || D->isImplicit())
6157 return;
6161 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6162 << D << static_cast<int>(Status);
6163 }
6164}
6165
6168
6169 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6170 // declaration only if the `bind_to_declaration` extension is set.
6172 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6173 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6174 llvm::omp::TraitProperty::
6175 implementation_extension_bind_to_declaration))
6177 S, D, MultiTemplateParamsArg(), Bases);
6178
6180
6182 Dcl && Dcl->getDeclContext()->isFileContext())
6184
6185 if (!Bases.empty())
6187 Bases);
6188
6189 return Dcl;
6190}
6191
6192/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6193/// If T is the name of a class, then each of the following shall have a
6194/// name different from T:
6195/// - every static data member of class T;
6196/// - every member function of class T
6197/// - every member of class T that is itself a type;
6198/// \returns true if the declaration name violates these rules.
6200 DeclarationNameInfo NameInfo) {
6201 DeclarationName Name = NameInfo.getName();
6202
6203 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6204 while (Record && Record->isAnonymousStructOrUnion())
6205 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6206 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6207 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6208 return true;
6209 }
6210
6211 return false;
6212}
6213
6214/// Diagnose a declaration whose declarator-id has the given
6215/// nested-name-specifier.
6216///
6217/// \param SS The nested-name-specifier of the declarator-id.
6218///
6219/// \param DC The declaration context to which the nested-name-specifier
6220/// resolves.
6221///
6222/// \param Name The name of the entity being declared.
6223///
6224/// \param Loc The location of the name of the entity being declared.
6225///
6226/// \param IsMemberSpecialization Whether we are declaring a member
6227/// specialization.
6228///
6229/// \param TemplateId The template-id, if any.
6230///
6231/// \returns true if we cannot safely recover from this error, false otherwise.
6233 DeclarationName Name,
6234 SourceLocation Loc,
6235 TemplateIdAnnotation *TemplateId,
6236 bool IsMemberSpecialization) {
6237 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6238 "without nested-name-specifier");
6239 DeclContext *Cur = CurContext;
6240 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6241 Cur = Cur->getParent();
6242
6243 // If the user provided a superfluous scope specifier that refers back to the
6244 // class in which the entity is already declared, diagnose and ignore it.
6245 //
6246 // class X {
6247 // void X::f();
6248 // };
6249 //
6250 // Note, it was once ill-formed to give redundant qualification in all
6251 // contexts, but that rule was removed by DR482.
6252 if (Cur->Equals(DC)) {
6253 if (Cur->isRecord()) {
6254 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6255 : diag::err_member_extra_qualification)
6256 << Name << FixItHint::CreateRemoval(SS.getRange());
6257 SS.clear();
6258 } else {
6259 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6260 }
6261 return false;
6262 }
6263
6264 // Check whether the qualifying scope encloses the scope of the original
6265 // declaration. For a template-id, we perform the checks in
6266 // CheckTemplateSpecializationScope.
6267 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6268 if (Cur->isRecord())
6269 Diag(Loc, diag::err_member_qualification)
6270 << Name << SS.getRange();
6271 else if (isa<TranslationUnitDecl>(DC))
6272 Diag(Loc, diag::err_invalid_declarator_global_scope)
6273 << Name << SS.getRange();
6274 else if (isa<FunctionDecl>(Cur))
6275 Diag(Loc, diag::err_invalid_declarator_in_function)
6276 << Name << SS.getRange();
6277 else if (isa<BlockDecl>(Cur))
6278 Diag(Loc, diag::err_invalid_declarator_in_block)
6279 << Name << SS.getRange();
6280 else if (isa<ExportDecl>(Cur)) {
6281 if (!isa<NamespaceDecl>(DC))
6282 Diag(Loc, diag::err_export_non_namespace_scope_name)
6283 << Name << SS.getRange();
6284 else
6285 // The cases that DC is not NamespaceDecl should be handled in
6286 // CheckRedeclarationExported.
6287 return false;
6288 } else
6289 Diag(Loc, diag::err_invalid_declarator_scope)
6290 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6291
6292 return true;
6293 }
6294
6295 if (Cur->isRecord()) {
6296 // Cannot qualify members within a class.
6297 Diag(Loc, diag::err_member_qualification)
6298 << Name << SS.getRange();
6299 SS.clear();
6300
6301 // C++ constructors and destructors with incorrect scopes can break
6302 // our AST invariants by having the wrong underlying types. If
6303 // that's the case, then drop this declaration entirely.
6304 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6305 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6306 !Context.hasSameType(Name.getCXXNameType(),
6307 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6308 return true;
6309
6310 return false;
6311 }
6312
6313 // C++23 [temp.names]p5:
6314 // The keyword template shall not appear immediately after a declarative
6315 // nested-name-specifier.
6316 //
6317 // First check the template-id (if any), and then check each component of the
6318 // nested-name-specifier in reverse order.
6319 //
6320 // FIXME: nested-name-specifiers in friend declarations are declarative,
6321 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6322 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6323 Diag(Loc, diag::ext_template_after_declarative_nns)
6325
6327 do {
6328 if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6330 Diag(Loc, diag::ext_template_after_declarative_nns)
6332 SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6333
6334 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6335 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6336 // C++23 [expr.prim.id.qual]p3:
6337 // [...] If a nested-name-specifier N is declarative and has a
6338 // simple-template-id with a template argument list A that involves a
6339 // template parameter, let T be the template nominated by N without A.
6340 // T shall be a class template.
6341 if (TST->isDependentType() && TST->isTypeAlias())
6342 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6343 << SpecLoc.getLocalSourceRange();
6344 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6345 // C++23 [expr.prim.id.qual]p2:
6346 // [...] A declarative nested-name-specifier shall not have a
6347 // computed-type-specifier.
6348 //
6349 // CWG2858 changed this from 'decltype-specifier' to
6350 // 'computed-type-specifier'.
6351 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6352 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6353 }
6354 }
6355 } while ((SpecLoc = SpecLoc.getPrefix()));
6356
6357 return false;
6358}
6359
6361 MultiTemplateParamsArg TemplateParamLists) {
6362 // TODO: consider using NameInfo for diagnostic.
6364 DeclarationName Name = NameInfo.getName();
6365
6366 // All of these full declarators require an identifier. If it doesn't have
6367 // one, the ParsedFreeStandingDeclSpec action should be used.
6368 if (D.isDecompositionDeclarator()) {
6369 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6370 } else if (!Name) {
6371 if (!D.isInvalidType()) // Reject this if we think it is valid.
6372 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6374 return nullptr;
6376 return nullptr;
6377
6378 DeclContext *DC = CurContext;
6379 if (D.getCXXScopeSpec().isInvalid())
6380 D.setInvalidType();
6381 else if (D.getCXXScopeSpec().isSet()) {
6384 return nullptr;
6385
6386 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6387 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6388 if (!DC || isa<EnumDecl>(DC)) {
6389 // If we could not compute the declaration context, it's because the
6390 // declaration context is dependent but does not refer to a class,
6391 // class template, or class template partial specialization. Complain
6392 // and return early, to avoid the coming semantic disaster.
6394 diag::err_template_qualified_declarator_no_match)
6396 << D.getCXXScopeSpec().getRange();
6397 return nullptr;
6398 }
6399 bool IsDependentContext = DC->isDependentContext();
6400
6401 if (!IsDependentContext &&
6403 return nullptr;
6404
6405 // If a class is incomplete, do not parse entities inside it.
6406 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6408 diag::err_member_def_undefined_record)
6409 << Name << DC << D.getCXXScopeSpec().getRange();
6410 return nullptr;
6411 }
6412 if (!D.getDeclSpec().isFriendSpecified()) {
6413 TemplateIdAnnotation *TemplateId =
6415 ? D.getName().TemplateId
6416 : nullptr;
6418 D.getIdentifierLoc(), TemplateId,
6419 /*IsMemberSpecialization=*/false)) {
6420 if (DC->isRecord())
6421 return nullptr;
6422
6423 D.setInvalidType();
6424 }
6425 }
6426
6427 // Check whether we need to rebuild the type of the given
6428 // declaration in the current instantiation.
6429 if (EnteringContext && IsDependentContext &&
6430 TemplateParamLists.size() != 0) {
6431 ContextRAII SavedContext(*this, DC);
6432 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6433 D.setInvalidType();
6434 }
6435 }
6436
6438 QualType R = TInfo->getType();
6439
6442 D.setInvalidType();
6443
6444 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6446
6447 // See if this is a redefinition of a variable in the same scope.
6448 if (!D.getCXXScopeSpec().isSet()) {
6449 bool IsLinkageLookup = false;
6450 bool CreateBuiltins = false;
6451
6452 // If the declaration we're planning to build will be a function
6453 // or object with linkage, then look for another declaration with
6454 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6455 //
6456 // If the declaration we're planning to build will be declared with
6457 // external linkage in the translation unit, create any builtin with
6458 // the same name.
6460 /* Do nothing*/;
6461 else if (CurContext->isFunctionOrMethod() &&
6463 R->isFunctionType())) {
6464 IsLinkageLookup = true;
6465 CreateBuiltins =
6469 CreateBuiltins = true;
6470
6471 if (IsLinkageLookup) {
6473 Previous.setRedeclarationKind(
6474 RedeclarationKind::ForExternalRedeclaration);
6475 }
6476
6477 LookupName(Previous, S, CreateBuiltins);
6478 } else { // Something like "int foo::x;"
6480
6481 // C++ [dcl.meaning]p1:
6482 // When the declarator-id is qualified, the declaration shall refer to a
6483 // previously declared member of the class or namespace to which the
6484 // qualifier refers (or, in the case of a namespace, of an element of the
6485 // inline namespace set of that namespace (7.3.1)) or to a specialization
6486 // thereof; [...]
6487 //
6488 // Note that we already checked the context above, and that we do not have
6489 // enough information to make sure that Previous contains the declaration
6490 // we want to match. For example, given:
6491 //
6492 // class X {
6493 // void f();
6494 // void f(float);
6495 // };
6496 //
6497 // void X::f(int) { } // ill-formed
6498 //
6499 // In this case, Previous will point to the overload set
6500 // containing the two f's declared in X, but neither of them
6501 // matches.
6502
6504 }
6505
6506 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6507 TPD && TPD->isTemplateParameter()) {
6508 // Older versions of clang allowed the names of function/variable templates
6509 // to shadow the names of their template parameters. For the compatibility
6510 // purposes we detect such cases and issue a default-to-error warning that
6511 // can be disabled with -Wno-strict-primary-template-shadow.
6512 if (!D.isInvalidType()) {
6513 bool AllowForCompatibility = false;
6514 if (Scope *DeclParent = S->getDeclParent();
6515 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6516 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6517 TemplateParamParent->isDeclScope(TPD);
6518 }
6520 AllowForCompatibility);
6521 }
6522
6523 // Just pretend that we didn't see the previous declaration.
6524 Previous.clear();
6525 }
6526
6527 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6528 // Forget that the previous declaration is the injected-class-name.
6529 Previous.clear();
6530
6531 // In C++, the previous declaration we find might be a tag type
6532 // (class or enum). In this case, the new declaration will hide the
6533 // tag type. Note that this applies to functions, function templates, and
6534 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6535 if (Previous.isSingleTagDecl() &&
6537 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6538 Previous.clear();
6539
6540 // Check that there are no default arguments other than in the parameters
6541 // of a function declaration (C++ only).
6542 if (getLangOpts().CPlusPlus)
6544
6545 /// Get the innermost enclosing declaration scope.
6546 S = S->getDeclParent();
6547
6548 NamedDecl *New;
6549
6550 bool AddToScope = true;
6552 if (TemplateParamLists.size()) {
6553 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6554 return nullptr;
6555 }
6556
6557 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6558 } else if (R->isFunctionType()) {
6559 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6560 TemplateParamLists,
6561 AddToScope);
6562 } else {
6563 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6564 AddToScope);
6565 }
6566
6567 if (!New)
6568 return nullptr;
6569
6570 // If this has an identifier and is not a function template specialization,
6571 // add it to the scope stack.
6572 if (New->getDeclName() && AddToScope)
6573 PushOnScopeChains(New, S);
6574
6575 if (OpenMP().isInOpenMPDeclareTargetContext())
6577
6578 return New;
6579}
6580
6581/// Helper method to turn variable array types into constant array
6582/// types in certain situations which would otherwise be errors (for
6583/// GCC compatibility).
6585 ASTContext &Context,
6586 bool &SizeIsNegative,
6587 llvm::APSInt &Oversized) {
6588 // This method tries to turn a variable array into a constant
6589 // array even when the size isn't an ICE. This is necessary
6590 // for compatibility with code that depends on gcc's buggy
6591 // constant expression folding, like struct {char x[(int)(char*)2];}
6592 SizeIsNegative = false;
6593 Oversized = 0;
6594
6595 if (T->isDependentType())
6596 return QualType();
6597
6599 const Type *Ty = Qs.strip(T);
6600
6601 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6602 QualType Pointee = PTy->getPointeeType();
6603 QualType FixedType =
6604 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6605 Oversized);
6606 if (FixedType.isNull()) return FixedType;
6607 FixedType = Context.getPointerType(FixedType);
6608 return Qs.apply(Context, FixedType);
6609 }
6610 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6611 QualType Inner = PTy->getInnerType();
6612 QualType FixedType =
6613 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6614 Oversized);
6615 if (FixedType.isNull()) return FixedType;
6616 FixedType = Context.getParenType(FixedType);
6617 return Qs.apply(Context, FixedType);
6618 }
6619
6620 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6621 if (!VLATy)
6622 return QualType();
6623
6624 QualType ElemTy = VLATy->getElementType();
6625 if (ElemTy->isVariablyModifiedType()) {
6626 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6627 SizeIsNegative, Oversized);
6628 if (ElemTy.isNull())
6629 return QualType();
6630 }
6631
6633 if (!VLATy->getSizeExpr() ||
6634 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6635 return QualType();
6636
6637 llvm::APSInt Res = Result.Val.getInt();
6638
6639 // Check whether the array size is negative.
6640 if (Res.isSigned() && Res.isNegative()) {
6641 SizeIsNegative = true;
6642 return QualType();
6643 }
6644
6645 // Check whether the array is too large to be addressed.
6646 unsigned ActiveSizeBits =
6647 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6648 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6649 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6650 : Res.getActiveBits();
6651 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6652 Oversized = Res;
6653 return QualType();
6654 }
6655
6656 QualType FoldedArrayType = Context.getConstantArrayType(
6657 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6658 return Qs.apply(Context, FoldedArrayType);
6659}
6660
6661static void
6663 SrcTL = SrcTL.getUnqualifiedLoc();
6664 DstTL = DstTL.getUnqualifiedLoc();
6665 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6666 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6667 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6668 DstPTL.getPointeeLoc());
6669 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6670 return;
6671 }
6672 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6673 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6674 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6675 DstPTL.getInnerLoc());
6676 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6677 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6678 return;
6679 }
6680 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6681 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6682 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6683 TypeLoc DstElemTL = DstATL.getElementLoc();
6684 if (VariableArrayTypeLoc SrcElemATL =
6685 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6686 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6687 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6688 } else {
6689 DstElemTL.initializeFullCopy(SrcElemTL);
6690 }
6691 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6692 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6693 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6694}
6695
6696/// Helper method to turn variable array types into constant array
6697/// types in certain situations which would otherwise be errors (for
6698/// GCC compatibility).
6699static TypeSourceInfo*
6701 ASTContext &Context,
6702 bool &SizeIsNegative,
6703 llvm::APSInt &Oversized) {
6704 QualType FixedTy
6705 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6706 SizeIsNegative, Oversized);
6707 if (FixedTy.isNull())
6708 return nullptr;
6709 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6711 FixedTInfo->getTypeLoc());
6712 return FixedTInfo;
6713}
6714
6715/// Attempt to fold a variable-sized type to a constant-sized type, returning
6716/// true if we were successful.
6719 unsigned FailedFoldDiagID) {
6720 bool SizeIsNegative;
6721 llvm::APSInt Oversized;
6723 TInfo, Context, SizeIsNegative, Oversized);
6724 if (FixedTInfo) {
6725 Diag(Loc, diag::ext_vla_folded_to_constant);
6726 TInfo = FixedTInfo;
6727 T = FixedTInfo->getType();
6728 return true;
6729 }
6730
6731 if (SizeIsNegative)
6732 Diag(Loc, diag::err_typecheck_negative_array_size);
6733 else if (Oversized.getBoolValue())
6734 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6735 else if (FailedFoldDiagID)
6736 Diag(Loc, FailedFoldDiagID);
6737 return false;
6738}
6739
6740/// Register the given locally-scoped extern "C" declaration so
6741/// that it can be found later for redeclarations. We include any extern "C"
6742/// declaration that is not visible in the translation unit here, not just
6743/// function-scope declarations.
6744void
6746 if (!getLangOpts().CPlusPlus &&
6748 // Don't need to track declarations in the TU in C.
6749 return;
6750
6751 // Note that we have a locally-scoped external with this name.
6753}
6754
6756 // FIXME: We can have multiple results via __attribute__((overloadable)).
6758 return Result.empty() ? nullptr : *Result.begin();
6759}
6760
6761/// Diagnose function specifiers on a declaration of an identifier that
6762/// does not identify a function.
6764 // FIXME: We should probably indicate the identifier in question to avoid
6765 // confusion for constructs like "virtual int a(), b;"
6766 if (DS.isVirtualSpecified())
6768 diag::err_virtual_non_function);
6769
6770 if (DS.hasExplicitSpecifier())
6772 diag::err_explicit_non_function);
6773
6774 if (DS.isNoreturnSpecified())
6776 diag::err_noreturn_non_function);
6777}
6778
6779NamedDecl*
6782 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6783 if (D.getCXXScopeSpec().isSet()) {
6784 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6785 << D.getCXXScopeSpec().getRange();
6786 D.setInvalidType();
6787 // Pretend we didn't see the scope specifier.
6788 DC = CurContext;
6789 Previous.clear();
6790 }
6791
6793
6795 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6796 << getLangOpts().CPlusPlus17;
6798 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6799 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6800
6804 diag::err_deduction_guide_invalid_specifier)
6805 << "typedef";
6806 else
6807 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6808 << D.getName().getSourceRange();
6809 return nullptr;
6810 }
6811
6812 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6813 if (!NewTD) return nullptr;
6814
6815 // Handle attributes prior to checking for duplicates in MergeVarDecl
6816 ProcessDeclAttributes(S, NewTD, D);
6817
6819
6820 bool Redeclaration = D.isRedeclaration();
6821 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6822 D.setRedeclaration(Redeclaration);
6823 return ND;
6824}
6825
6826void
6828 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6829 // then it shall have block scope.
6830 // Note that variably modified types must be fixed before merging the decl so
6831 // that redeclarations will match.
6832 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6833 QualType T = TInfo->getType();
6834 if (T->isVariablyModifiedType()) {
6836
6837 if (S->getFnParent() == nullptr) {
6838 bool SizeIsNegative;
6839 llvm::APSInt Oversized;
6840 TypeSourceInfo *FixedTInfo =
6842 SizeIsNegative,
6843 Oversized);
6844 if (FixedTInfo) {
6845 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6846 NewTD->setTypeSourceInfo(FixedTInfo);
6847 } else {
6848 if (SizeIsNegative)
6849 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6850 else if (T->isVariableArrayType())
6851 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6852 else if (Oversized.getBoolValue())
6853 Diag(NewTD->getLocation(), diag::err_array_too_large)
6854 << toString(Oversized, 10);
6855 else
6856 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6857 NewTD->setInvalidDecl();
6858 }
6859 }
6860 }
6861}
6862
6863/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6864/// declares a typedef-name, either using the 'typedef' type specifier or via
6865/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6866NamedDecl*
6868 LookupResult &Previous, bool &Redeclaration) {
6869
6870 // Find the shadowed declaration before filtering for scope.
6871 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6872
6873 // Merge the decl with the existing one if appropriate. If the decl is
6874 // in an outer scope, it isn't the same thing.
6875 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6876 /*AllowInlineNamespace*/false);
6878 if (!Previous.empty()) {
6879 Redeclaration = true;
6880 MergeTypedefNameDecl(S, NewTD, Previous);
6881 } else {
6883 }
6884
6885 if (ShadowedDecl && !Redeclaration)
6886 CheckShadow(NewTD, ShadowedDecl, Previous);
6887
6888 // If this is the C FILE type, notify the AST context.
6889 if (IdentifierInfo *II = NewTD->getIdentifier())
6890 if (!NewTD->isInvalidDecl() &&
6892 switch (II->getNotableIdentifierID()) {
6893 case tok::NotableIdentifierKind::FILE:
6894 Context.setFILEDecl(NewTD);
6895 break;
6896 case tok::NotableIdentifierKind::jmp_buf:
6897 Context.setjmp_bufDecl(NewTD);
6898 break;
6899 case tok::NotableIdentifierKind::sigjmp_buf:
6901 break;
6902 case tok::NotableIdentifierKind::ucontext_t:
6904 break;
6905 case tok::NotableIdentifierKind::float_t:
6906 case tok::NotableIdentifierKind::double_t:
6907 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6908 break;
6909 default:
6910 break;
6911 }
6912 }
6913
6914 return NewTD;
6915}
6916
6917/// Determines whether the given declaration is an out-of-scope
6918/// previous declaration.
6919///
6920/// This routine should be invoked when name lookup has found a
6921/// previous declaration (PrevDecl) that is not in the scope where a
6922/// new declaration by the same name is being introduced. If the new
6923/// declaration occurs in a local scope, previous declarations with
6924/// linkage may still be considered previous declarations (C99
6925/// 6.2.2p4-5, C++ [basic.link]p6).
6926///
6927/// \param PrevDecl the previous declaration found by name
6928/// lookup
6929///
6930/// \param DC the context in which the new declaration is being
6931/// declared.
6932///
6933/// \returns true if PrevDecl is an out-of-scope previous declaration
6934/// for a new delcaration with the same name.
6935static bool
6937 ASTContext &Context) {
6938 if (!PrevDecl)
6939 return false;
6940
6941 if (!PrevDecl->hasLinkage())
6942 return false;
6943
6944 if (Context.getLangOpts().CPlusPlus) {
6945 // C++ [basic.link]p6:
6946 // If there is a visible declaration of an entity with linkage
6947 // having the same name and type, ignoring entities declared
6948 // outside the innermost enclosing namespace scope, the block
6949 // scope declaration declares that same entity and receives the
6950 // linkage of the previous declaration.
6951 DeclContext *OuterContext = DC->getRedeclContext();
6952 if (!OuterContext->isFunctionOrMethod())
6953 // This rule only applies to block-scope declarations.
6954 return false;
6955
6956 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6957 if (PrevOuterContext->isRecord())
6958 // We found a member function: ignore it.
6959 return false;
6960
6961 // Find the innermost enclosing namespace for the new and
6962 // previous declarations.
6963 OuterContext = OuterContext->getEnclosingNamespaceContext();
6964 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6965
6966 // The previous declaration is in a different namespace, so it
6967 // isn't the same function.
6968 if (!OuterContext->Equals(PrevOuterContext))
6969 return false;
6970 }
6971
6972 return true;
6973}
6974
6976 CXXScopeSpec &SS = D.getCXXScopeSpec();
6977 if (!SS.isSet()) return;
6979}
6980
6982 QualType type = decl->getType();
6983 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6984 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6985 // Various kinds of declaration aren't allowed to be __autoreleasing.
6986 unsigned kind = -1U;
6987 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6988 if (var->hasAttr<BlocksAttr>())
6989 kind = 0; // __block
6990 else if (!var->hasLocalStorage())
6991 kind = 1; // global
6992 } else if (isa<ObjCIvarDecl>(decl)) {
6993 kind = 3; // ivar
6994 } else if (isa<FieldDecl>(decl)) {
6995 kind = 2; // field
6996 }
6997
6998 if (kind != -1U) {
6999 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
7000 << kind;
7001 }
7002 } else if (lifetime == Qualifiers::OCL_None) {
7003 // Try to infer lifetime.
7004 if (!type->isObjCLifetimeType())
7005 return false;
7006
7007 lifetime = type->getObjCARCImplicitLifetime();
7009 decl->setType(type);
7010 }
7011
7012 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
7013 // Thread-local variables cannot have lifetime.
7014 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
7015 var->getTLSKind()) {
7016 Diag(var->getLocation(), diag::err_arc_thread_ownership)
7017 << var->getType();
7018 return true;
7019 }
7020 }
7021
7022 return false;
7023}
7024
7026 if (Decl->getType().hasAddressSpace())
7027 return;
7028 if (Decl->getType()->isDependentType())
7029 return;
7030 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
7031 QualType Type = Var->getType();
7032 if (Type->isSamplerT() || Type->isVoidType())
7033 return;
7035 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7036 // __opencl_c_program_scope_global_variables feature, the address space
7037 // for a variable at program scope or a static or extern variable inside
7038 // a function are inferred to be __global.
7039 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7040 Var->hasGlobalStorage())
7041 ImplAS = LangAS::opencl_global;
7042 // If the original type from a decayed type is an array type and that array
7043 // type has no address space yet, deduce it now.
7044 if (auto DT = dyn_cast<DecayedType>(Type)) {
7045 auto OrigTy = DT->getOriginalType();
7046 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7047 // Add the address space to the original array type and then propagate
7048 // that to the element type through `getAsArrayType`.
7049 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7050 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7051 // Re-generate the decayed type.
7052 Type = Context.getDecayedType(OrigTy);
7053 }
7054 }
7056 // Apply any qualifiers (including address space) from the array type to
7057 // the element type. This implements C99 6.7.3p8: "If the specification of
7058 // an array type includes any type qualifiers, the element type is so
7059 // qualified, not the array type."
7060 if (Type->isArrayType())
7062 Decl->setType(Type);
7063 }
7064}
7065
7067 // Ensure that an auto decl is deduced otherwise the checks below might cache
7068 // the wrong linkage.
7069 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7070
7071 // 'weak' only applies to declarations with external linkage.
7072 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7073 if (!ND.isExternallyVisible()) {
7074 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7075 ND.dropAttr<WeakAttr>();
7076 }
7077 }
7078 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7079 if (ND.isExternallyVisible()) {
7080 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7081 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7082 }
7083 }
7084
7085 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7086 if (VD->hasInit()) {
7087 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7088 assert(VD->isThisDeclarationADefinition() &&
7089 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7090 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7091 VD->dropAttr<AliasAttr>();
7092 }
7093 }
7094 }
7095
7096 // 'selectany' only applies to externally visible variable declarations.
7097 // It does not apply to functions.
7098 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7099 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7100 S.Diag(Attr->getLocation(),
7101 diag::err_attribute_selectany_non_extern_data);
7102 ND.dropAttr<SelectAnyAttr>();
7103 }
7104 }
7105
7106 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7107 auto *VD = dyn_cast<VarDecl>(&ND);
7108 bool IsAnonymousNS = false;
7109 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7110 if (VD) {
7111 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7112 while (NS && !IsAnonymousNS) {
7113 IsAnonymousNS = NS->isAnonymousNamespace();
7114 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7115 }
7116 }
7117 // dll attributes require external linkage. Static locals may have external
7118 // linkage but still cannot be explicitly imported or exported.
7119 // In Microsoft mode, a variable defined in anonymous namespace must have
7120 // external linkage in order to be exported.
7121 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7122 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7123 (!AnonNSInMicrosoftMode &&
7124 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7125 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7126 << &ND << Attr;
7127 ND.setInvalidDecl();
7128 }
7129 }
7130
7131 // Check the attributes on the function type, if any.
7132 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7133 // Don't declare this variable in the second operand of the for-statement;
7134 // GCC miscompiles that by ending its lifetime before evaluating the
7135 // third operand. See gcc.gnu.org/PR86769.
7137 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7138 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7139 TL = ATL.getModifiedLoc()) {
7140 // The [[lifetimebound]] attribute can be applied to the implicit object
7141 // parameter of a non-static member function (other than a ctor or dtor)
7142 // by applying it to the function type.
7143 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7144 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7145 if (!MD || MD->isStatic()) {
7146 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7147 << !MD << A->getRange();
7148 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7149 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7150 << isa<CXXDestructorDecl>(MD) << A->getRange();
7151 }
7152 }
7153 }
7154 }
7155}
7156
7158 NamedDecl *NewDecl,
7159 bool IsSpecialization,
7160 bool IsDefinition) {
7161 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7162 return;
7163
7164 bool IsTemplate = false;
7165 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7166 OldDecl = OldTD->getTemplatedDecl();
7167 IsTemplate = true;
7168 if (!IsSpecialization)
7169 IsDefinition = false;
7170 }
7171 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7172 NewDecl = NewTD->getTemplatedDecl();
7173 IsTemplate = true;
7174 }
7175
7176 if (!OldDecl || !NewDecl)
7177 return;
7178
7179 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7180 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7181 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7182 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7183
7184 // dllimport and dllexport are inheritable attributes so we have to exclude
7185 // inherited attribute instances.
7186 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7187 (NewExportAttr && !NewExportAttr->isInherited());
7188
7189 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7190 // the only exception being explicit specializations.
7191 // Implicitly generated declarations are also excluded for now because there
7192 // is no other way to switch these to use dllimport or dllexport.
7193 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7194
7195 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7196 // Allow with a warning for free functions and global variables.
7197 bool JustWarn = false;
7198 if (!OldDecl->isCXXClassMember()) {
7199 auto *VD = dyn_cast<VarDecl>(OldDecl);
7200 if (VD && !VD->getDescribedVarTemplate())
7201 JustWarn = true;
7202 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7203 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7204 JustWarn = true;
7205 }
7206
7207 // We cannot change a declaration that's been used because IR has already
7208 // been emitted. Dllimported functions will still work though (modulo
7209 // address equality) as they can use the thunk.
7210 if (OldDecl->isUsed())
7211 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7212 JustWarn = false;
7213
7214 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7215 : diag::err_attribute_dll_redeclaration;
7216 S.Diag(NewDecl->getLocation(), DiagID)
7217 << NewDecl
7218 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7219 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7220 if (!JustWarn) {
7221 NewDecl->setInvalidDecl();
7222 return;
7223 }
7224 }
7225
7226 // A redeclaration is not allowed to drop a dllimport attribute, the only
7227 // exceptions being inline function definitions (except for function
7228 // templates), local extern declarations, qualified friend declarations or
7229 // special MSVC extension: in the last case, the declaration is treated as if
7230 // it were marked dllexport.
7231 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7232 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7233 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7234 // Ignore static data because out-of-line definitions are diagnosed
7235 // separately.
7236 IsStaticDataMember = VD->isStaticDataMember();
7237 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7239 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7240 IsInline = FD->isInlined();
7241 IsQualifiedFriend = FD->getQualifier() &&
7242 FD->getFriendObjectKind() == Decl::FOK_Declared;
7243 }
7244
7245 if (OldImportAttr && !HasNewAttr &&
7246 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7247 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7248 if (IsMicrosoftABI && IsDefinition) {
7249 if (IsSpecialization) {
7250 S.Diag(
7251 NewDecl->getLocation(),
7252 diag::err_attribute_dllimport_function_specialization_definition);
7253 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7254 NewDecl->dropAttr<DLLImportAttr>();
7255 } else {
7256 S.Diag(NewDecl->getLocation(),
7257 diag::warn_redeclaration_without_import_attribute)
7258 << NewDecl;
7259 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7260 NewDecl->dropAttr<DLLImportAttr>();
7261 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7262 S.Context, NewImportAttr->getRange()));
7263 }
7264 } else if (IsMicrosoftABI && IsSpecialization) {
7265 assert(!IsDefinition);
7266 // MSVC allows this. Keep the inherited attribute.
7267 } else {
7268 S.Diag(NewDecl->getLocation(),
7269 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7270 << NewDecl << OldImportAttr;
7271 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7272 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7273 OldDecl->dropAttr<DLLImportAttr>();
7274 NewDecl->dropAttr<DLLImportAttr>();
7275 }
7276 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7277 // In MinGW, seeing a function declared inline drops the dllimport
7278 // attribute.
7279 OldDecl->dropAttr<DLLImportAttr>();
7280 NewDecl->dropAttr<DLLImportAttr>();
7281 S.Diag(NewDecl->getLocation(),
7282 diag::warn_dllimport_dropped_from_inline_function)
7283 << NewDecl << OldImportAttr;
7284 }
7285
7286 // A specialization of a class template member function is processed here
7287 // since it's a redeclaration. If the parent class is dllexport, the
7288 // specialization inherits that attribute. This doesn't happen automatically
7289 // since the parent class isn't instantiated until later.
7290 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7291 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7292 !NewImportAttr && !NewExportAttr) {
7293 if (const DLLExportAttr *ParentExportAttr =
7294 MD->getParent()->getAttr<DLLExportAttr>()) {
7295 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7296 NewAttr->setInherited(true);
7297 NewDecl->addAttr(NewAttr);
7298 }
7299 }
7300 }
7301}
7302
7303/// Given that we are within the definition of the given function,
7304/// will that definition behave like C99's 'inline', where the
7305/// definition is discarded except for optimization purposes?
7307 // Try to avoid calling GetGVALinkageForFunction.
7308
7309 // All cases of this require the 'inline' keyword.
7310 if (!FD->isInlined()) return false;
7311
7312 // This is only possible in C++ with the gnu_inline attribute.
7313 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7314 return false;
7315
7316 // Okay, go ahead and call the relatively-more-expensive function.
7318}
7319
7320/// Determine whether a variable is extern "C" prior to attaching
7321/// an initializer. We can't just call isExternC() here, because that
7322/// will also compute and cache whether the declaration is externally
7323/// visible, which might change when we attach the initializer.
7324///
7325/// This can only be used if the declaration is known to not be a
7326/// redeclaration of an internal linkage declaration.
7327///
7328/// For instance:
7329///
7330/// auto x = []{};
7331///
7332/// Attaching the initializer here makes this declaration not externally
7333/// visible, because its type has internal linkage.
7334///
7335/// FIXME: This is a hack.
7336template<typename T>
7337static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7338 if (S.getLangOpts().CPlusPlus) {
7339 // In C++, the overloadable attribute negates the effects of extern "C".
7340 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7341 return false;
7342
7343 // So do CUDA's host/device attributes.
7344 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7345 D->template hasAttr<CUDAHostAttr>()))
7346 return false;
7347 }
7348 return D->isExternC();
7349}
7350
7351static bool shouldConsiderLinkage(const VarDecl *VD) {
7352 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7353 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7354 isa<OMPDeclareMapperDecl>(DC))
7355 return VD->hasExternalStorage();
7356 if (DC->isFileContext())
7357 return true;
7358 if (DC->isRecord())
7359 return false;
7360 if (DC->getDeclKind() == Decl::HLSLBuffer)
7361 return false;
7362
7363 if (isa<RequiresExprBodyDecl>(DC))
7364 return false;
7365 llvm_unreachable("Unexpected context");
7366}
7367
7368static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7369 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7370 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7371 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7372 return true;
7373 if (DC->isRecord())
7374 return false;
7375 llvm_unreachable("Unexpected context");
7376}
7377
7378static bool hasParsedAttr(Scope *S, const Declarator &PD,
7379 ParsedAttr::Kind Kind) {
7380 // Check decl attributes on the DeclSpec.
7381 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7382 return true;
7383
7384 // Walk the declarator structure, checking decl attributes that were in a type
7385 // position to the decl itself.
7386 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7387 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7388 return true;
7389 }
7390
7391 // Finally, check attributes on the decl itself.
7392 return PD.getAttributes().hasAttribute(Kind) ||
7394}
7395
7396/// Adjust the \c DeclContext for a function or variable that might be a
7397/// function-local external declaration.
7399 if (!DC->isFunctionOrMethod())
7400 return false;
7401
7402 // If this is a local extern function or variable declared within a function
7403 // template, don't add it into the enclosing namespace scope until it is
7404 // instantiated; it might have a dependent type right now.
7405 if (DC->isDependentContext())
7406 return true;
7407
7408 // C++11 [basic.link]p7:
7409 // When a block scope declaration of an entity with linkage is not found to
7410 // refer to some other declaration, then that entity is a member of the
7411 // innermost enclosing namespace.
7412 //
7413 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7414 // semantically-enclosing namespace, not a lexically-enclosing one.
7415 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7416 DC = DC->getParent();
7417 return true;
7418}
7419
7420/// Returns true if given declaration has external C language linkage.
7421static bool isDeclExternC(const Decl *D) {
7422 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7423 return FD->isExternC();
7424 if (const auto *VD = dyn_cast<VarDecl>(D))
7425 return VD->isExternC();
7426
7427 llvm_unreachable("Unknown type of decl!");
7428}
7429
7430/// Returns true if there hasn't been any invalid type diagnosed.
7431static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7432 DeclContext *DC = NewVD->getDeclContext();
7433 QualType R = NewVD->getType();
7434
7435 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7436 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7437 // argument.
7438 if (R->isImageType() || R->isPipeType()) {
7439 Se.Diag(NewVD->getLocation(),
7440 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7441 << R;
7442 NewVD->setInvalidDecl();
7443 return false;
7444 }
7445
7446 // OpenCL v1.2 s6.9.r:
7447 // The event type cannot be used to declare a program scope variable.
7448 // OpenCL v2.0 s6.9.q:
7449 // The clk_event_t and reserve_id_t types cannot be declared in program
7450 // scope.
7451 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7452 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7453 Se.Diag(NewVD->getLocation(),
7454 diag::err_invalid_type_for_program_scope_var)
7455 << R;
7456 NewVD->setInvalidDecl();
7457 return false;
7458 }
7459 }
7460
7461 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7462 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7463 Se.getLangOpts())) {
7464 QualType NR = R.getCanonicalType();
7465 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7466 NR->isReferenceType()) {
7469 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7470 << NR->isReferenceType();
7471 NewVD->setInvalidDecl();
7472 return false;
7473 }
7474 NR = NR->getPointeeType();
7475 }
7476 }
7477
7478 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7479 Se.getLangOpts())) {
7480 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7481 // half array type (unless the cl_khr_fp16 extension is enabled).
7482 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7483 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7484 NewVD->setInvalidDecl();
7485 return false;
7486 }
7487 }
7488
7489 // OpenCL v1.2 s6.9.r:
7490 // The event type cannot be used with the __local, __constant and __global
7491 // address space qualifiers.
7492 if (R->isEventT()) {
7494 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7495 NewVD->setInvalidDecl();
7496 return false;
7497 }
7498 }
7499
7500 if (R->isSamplerT()) {
7501 // OpenCL v1.2 s6.9.b p4:
7502 // The sampler type cannot be used with the __local and __global address
7503 // space qualifiers.
7506 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7507 NewVD->setInvalidDecl();
7508 }
7509
7510 // OpenCL v1.2 s6.12.14.1:
7511 // A global sampler must be declared with either the constant address
7512 // space qualifier or with the const qualifier.
7513 if (DC->isTranslationUnit() &&
7515 R.isConstQualified())) {
7516 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7517 NewVD->setInvalidDecl();
7518 }
7519 if (NewVD->isInvalidDecl())
7520 return false;
7521 }
7522
7523 return true;
7524}
7525
7526template <typename AttrTy>
7527static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7528 const TypedefNameDecl *TND = TT->getDecl();
7529 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7530 AttrTy *Clone = Attribute->clone(S.Context);
7531 Clone->setInherited(true);
7532 D->addAttr(Clone);
7533 }
7534}
7535
7536// This function emits warning and a corresponding note based on the
7537// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7538// declarations of an annotated type must be const qualified.
7540 QualType VarType = VD->getType().getCanonicalType();
7541
7542 // Ignore local declarations (for now) and those with const qualification.
7543 // TODO: Local variables should not be allowed if their type declaration has
7544 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7545 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7546 return;
7547
7548 if (VarType->isArrayType()) {
7549 // Retrieve element type for array declarations.
7550 VarType = S.getASTContext().getBaseElementType(VarType);
7551 }
7552
7553 const RecordDecl *RD = VarType->getAsRecordDecl();
7554
7555 // Check if the record declaration is present and if it has any attributes.
7556 if (RD == nullptr)
7557 return;
7558
7559 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7560 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7561 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7562 return;
7563 }
7564}
7565
7567 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7568 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7569 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7570 QualType R = TInfo->getType();
7572
7573 IdentifierInfo *II = Name.getAsIdentifierInfo();
7574 bool IsPlaceholderVariable = false;
7575
7576 if (D.isDecompositionDeclarator()) {
7577 // Take the name of the first declarator as our name for diagnostic
7578 // purposes.
7579 auto &Decomp = D.getDecompositionDeclarator();
7580 if (!Decomp.bindings().empty()) {
7581 II = Decomp.bindings()[0].Name;
7582 Name = II;
7583 }
7584 } else if (!II) {
7585 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7586 return nullptr;
7587 }
7588
7589
7592
7593 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7594 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7595 IsPlaceholderVariable = true;
7596 if (!Previous.empty()) {
7597 NamedDecl *PrevDecl = *Previous.begin();
7598 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7599 DC->getRedeclContext());
7600 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7602 }
7603 }
7604
7605 // dllimport globals without explicit storage class are treated as extern. We
7606 // have to change the storage class this early to get the right DeclContext.
7607 if (SC == SC_None && !DC->isRecord() &&
7608 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7609 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7610 SC = SC_Extern;
7611
7612 DeclContext *OriginalDC = DC;
7613 bool IsLocalExternDecl = SC == SC_Extern &&
7615
7616 if (SCSpec == DeclSpec::SCS_mutable) {
7617 // mutable can only appear on non-static class members, so it's always
7618 // an error here
7619 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7620 D.setInvalidType();
7621 SC = SC_None;
7622 }
7623
7624 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7625 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7627 // In C++11, the 'register' storage class specifier is deprecated.
7628 // Suppress the warning in system macros, it's used in macros in some
7629 // popular C system headers, such as in glibc's htonl() macro.
7631 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7632 : diag::warn_deprecated_register)
7634 }
7635
7637
7638 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7639 // C99 6.9p2: The storage-class specifiers auto and register shall not
7640 // appear in the declaration specifiers in an external declaration.
7641 // Global Register+Asm is a GNU extension we support.
7642 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7643 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7644 D.setInvalidType();
7645 }
7646 }
7647
7648 // If this variable has a VLA type and an initializer, try to
7649 // fold to a constant-sized type. This is otherwise invalid.
7650 if (D.hasInitializer() && R->isVariableArrayType())
7652 /*DiagID=*/0);
7653
7654 bool IsMemberSpecialization = false;
7655 bool IsVariableTemplateSpecialization = false;
7656 bool IsPartialSpecialization = false;
7657 bool IsVariableTemplate = false;
7658 VarDecl *NewVD = nullptr;
7659 VarTemplateDecl *NewTemplate = nullptr;
7660 TemplateParameterList *TemplateParams = nullptr;
7661 if (!getLangOpts().CPlusPlus) {
7663 II, R, TInfo, SC);
7664
7665 if (R->getContainedDeducedType())
7666 ParsingInitForAutoVars.insert(NewVD);
7667
7668 if (D.isInvalidType())
7669 NewVD->setInvalidDecl();
7670
7672 NewVD->hasLocalStorage())
7673 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7675 } else {
7676 bool Invalid = false;
7677
7678 if (DC->isRecord() && !CurContext->isRecord()) {
7679 // This is an out-of-line definition of a static data member.
7680 switch (SC) {
7681 case SC_None:
7682 break;
7683 case SC_Static:
7685 diag::err_static_out_of_line)
7687 break;
7688 case SC_Auto:
7689 case SC_Register:
7690 case SC_Extern:
7691 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7692 // to names of variables declared in a block or to function parameters.
7693 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7694 // of class members
7695
7697 diag::err_storage_class_for_static_member)
7699 break;
7700 case SC_PrivateExtern:
7701 llvm_unreachable("C storage class in c++!");
7702 }
7703 }
7704
7705 if (SC == SC_Static && CurContext->isRecord()) {
7706 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7707 // Walk up the enclosing DeclContexts to check for any that are
7708 // incompatible with static data members.
7709 const DeclContext *FunctionOrMethod = nullptr;
7710 const CXXRecordDecl *AnonStruct = nullptr;
7711 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7712 if (Ctxt->isFunctionOrMethod()) {
7713 FunctionOrMethod = Ctxt;
7714 break;
7715 }
7716 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7717 if (ParentDecl && !ParentDecl->getDeclName()) {
7718 AnonStruct = ParentDecl;
7719 break;
7720 }
7721 }
7722 if (FunctionOrMethod) {
7723 // C++ [class.static.data]p5: A local class shall not have static data
7724 // members.
7726 diag::err_static_data_member_not_allowed_in_local_class)
7727 << Name << RD->getDeclName()
7728 << llvm::to_underlying(RD->getTagKind());
7729 } else if (AnonStruct) {
7730 // C++ [class.static.data]p4: Unnamed classes and classes contained
7731 // directly or indirectly within unnamed classes shall not contain
7732 // static data members.
7734 diag::err_static_data_member_not_allowed_in_anon_struct)
7735 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7736 Invalid = true;
7737 } else if (RD->isUnion()) {
7738 // C++98 [class.union]p1: If a union contains a static data member,
7739 // the program is ill-formed. C++11 drops this restriction.
7742 ? diag::warn_cxx98_compat_static_data_member_in_union
7743 : diag::ext_static_data_member_in_union) << Name;
7744 }
7745 }
7746 }
7747
7748 // Match up the template parameter lists with the scope specifier, then
7749 // determine whether we have a template or a template specialization.
7750 bool InvalidScope = false;
7753 D.getCXXScopeSpec(),
7755 ? D.getName().TemplateId
7756 : nullptr,
7757 TemplateParamLists,
7758 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7759 Invalid |= InvalidScope;
7760
7761 if (TemplateParams) {
7762 if (!TemplateParams->size() &&
7764 // There is an extraneous 'template<>' for this variable. Complain
7765 // about it, but allow the declaration of the variable.
7766 Diag(TemplateParams->getTemplateLoc(),
7767 diag::err_template_variable_noparams)
7768 << II
7769 << SourceRange(TemplateParams->getTemplateLoc(),
7770 TemplateParams->getRAngleLoc());
7771 TemplateParams = nullptr;
7772 } else {
7773 // Check that we can declare a template here.
7774 if (CheckTemplateDeclScope(S, TemplateParams))
7775 return nullptr;
7776
7778 // This is an explicit specialization or a partial specialization.
7779 IsVariableTemplateSpecialization = true;
7780 IsPartialSpecialization = TemplateParams->size() > 0;
7781 } else { // if (TemplateParams->size() > 0)
7782 // This is a template declaration.
7783 IsVariableTemplate = true;
7784
7785 // Only C++1y supports variable templates (N3651).
7788 ? diag::warn_cxx11_compat_variable_template
7789 : diag::ext_variable_template);
7790 }
7791 }
7792 } else {
7793 // Check that we can declare a member specialization here.
7794 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7795 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7796 return nullptr;
7797 assert((Invalid ||
7799 "should have a 'template<>' for this decl");
7800 }
7801
7802 if (IsVariableTemplateSpecialization) {
7803 SourceLocation TemplateKWLoc =
7804 TemplateParamLists.size() > 0
7805 ? TemplateParamLists[0]->getTemplateLoc()
7806 : SourceLocation();
7808 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7810 if (Res.isInvalid())
7811 return nullptr;
7812 NewVD = cast<VarDecl>(Res.get());
7813 AddToScope = false;
7814 } else if (D.isDecompositionDeclarator()) {
7816 D.getIdentifierLoc(), R, TInfo, SC,
7817 Bindings);
7818 } else
7819 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7820 D.getIdentifierLoc(), II, R, TInfo, SC);
7821
7822 // If this is supposed to be a variable template, create it as such.
7823 if (IsVariableTemplate) {
7824 NewTemplate =
7826 TemplateParams, NewVD);
7827 NewVD->setDescribedVarTemplate(NewTemplate);
7828 }
7829
7830 // If this decl has an auto type in need of deduction, make a note of the
7831 // Decl so we can diagnose uses of it in its own initializer.
7832 if (R->getContainedDeducedType())
7833 ParsingInitForAutoVars.insert(NewVD);
7834
7835 if (D.isInvalidType() || Invalid) {
7836 NewVD->setInvalidDecl();
7837 if (NewTemplate)
7838 NewTemplate->setInvalidDecl();
7839 }
7840
7841 SetNestedNameSpecifier(*this, NewVD, D);
7842
7843 // If we have any template parameter lists that don't directly belong to
7844 // the variable (matching the scope specifier), store them.
7845 // An explicit variable template specialization does not own any template
7846 // parameter lists.
7847 bool IsExplicitSpecialization =
7848 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7849 unsigned VDTemplateParamLists =
7850 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7851 if (TemplateParamLists.size() > VDTemplateParamLists)
7853 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7854 }
7855
7856 if (D.getDeclSpec().isInlineSpecified()) {
7857 if (!getLangOpts().CPlusPlus) {
7858 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7859 << 0;
7860 } else if (CurContext->isFunctionOrMethod()) {
7861 // 'inline' is not allowed on block scope variable declaration.
7863 diag::err_inline_declaration_block_scope) << Name
7865 } else {
7867 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7868 : diag::ext_inline_variable);
7869 NewVD->setInlineSpecified();
7870 }
7871 }
7872
7873 // Set the lexical context. If the declarator has a C++ scope specifier, the
7874 // lexical context will be different from the semantic context.
7876 if (NewTemplate)
7877 NewTemplate->setLexicalDeclContext(CurContext);
7878
7879 if (IsLocalExternDecl) {
7881 for (auto *B : Bindings)
7882 B->setLocalExternDecl();
7883 else
7884 NewVD->setLocalExternDecl();
7885 }
7886
7887 bool EmitTLSUnsupportedError = false;
7889 // C++11 [dcl.stc]p4:
7890 // When thread_local is applied to a variable of block scope the
7891 // storage-class-specifier static is implied if it does not appear
7892 // explicitly.
7893 // Core issue: 'static' is not implied if the variable is declared
7894 // 'extern'.
7895 if (NewVD->hasLocalStorage() &&
7896 (SCSpec != DeclSpec::SCS_unspecified ||
7898 !DC->isFunctionOrMethod()))
7900 diag::err_thread_non_global)
7902 else if (!Context.getTargetInfo().isTLSSupported()) {
7903 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7904 getLangOpts().SYCLIsDevice) {
7905 // Postpone error emission until we've collected attributes required to
7906 // figure out whether it's a host or device variable and whether the
7907 // error should be ignored.
7908 EmitTLSUnsupportedError = true;
7909 // We still need to mark the variable as TLS so it shows up in AST with
7910 // proper storage class for other tools to use even if we're not going
7911 // to emit any code for it.
7912 NewVD->setTSCSpec(TSCS);
7913 } else
7915 diag::err_thread_unsupported);
7916 } else
7917 NewVD->setTSCSpec(TSCS);
7918 }
7919
7920 switch (D.getDeclSpec().getConstexprSpecifier()) {
7922 break;
7923
7926 diag::err_constexpr_wrong_decl_kind)
7927 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7928 [[fallthrough]];
7929
7931 NewVD->setConstexpr(true);
7932 // C++1z [dcl.spec.constexpr]p1:
7933 // A static data member declared with the constexpr specifier is
7934 // implicitly an inline variable.
7935 if (NewVD->isStaticDataMember() &&
7936 (getLangOpts().CPlusPlus17 ||
7938 NewVD->setImplicitlyInline();
7939 break;
7940
7942 if (!NewVD->hasGlobalStorage())
7944 diag::err_constinit_local_variable);
7945 else
7946 NewVD->addAttr(
7947 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7948 ConstInitAttr::Keyword_constinit));
7949 break;
7950 }
7951
7952 // C99 6.7.4p3
7953 // An inline definition of a function with external linkage shall
7954 // not contain a definition of a modifiable object with static or
7955 // thread storage duration...
7956 // We only apply this when the function is required to be defined
7957 // elsewhere, i.e. when the function is not 'extern inline'. Note
7958 // that a local variable with thread storage duration still has to
7959 // be marked 'static'. Also note that it's possible to get these
7960 // semantics in C++ using __attribute__((gnu_inline)).
7961 if (SC == SC_Static && S->getFnParent() != nullptr &&
7962 !NewVD->getType().isConstQualified()) {
7964 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7966 diag::warn_static_local_in_extern_inline);
7968 }
7969 }
7970
7972 if (IsVariableTemplateSpecialization)
7973 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7974 << (IsPartialSpecialization ? 1 : 0)
7977 else if (IsMemberSpecialization)
7978 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7979 << 2
7981 else if (NewVD->hasLocalStorage())
7982 Diag(NewVD->getLocation(), diag::err_module_private_local)
7983 << 0 << NewVD
7987 else {
7988 NewVD->setModulePrivate();
7989 if (NewTemplate)
7990 NewTemplate->setModulePrivate();
7991 for (auto *B : Bindings)
7992 B->setModulePrivate();
7993 }
7994 }
7995
7996 if (getLangOpts().OpenCL) {
7998
8000 if (TSC != TSCS_unspecified) {
8002 diag::err_opencl_unknown_type_specifier)
8004 << DeclSpec::getSpecifierName(TSC) << 1;
8005 NewVD->setInvalidDecl();
8006 }
8007 }
8008
8009 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8010 // address space if the table has local storage (semantic checks elsewhere
8011 // will produce an error anyway).
8012 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8013 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8014 !NewVD->hasLocalStorage()) {
8017 NewVD->setType(Type);
8018 }
8019 }
8020
8021 // Handle attributes prior to checking for duplicates in MergeVarDecl
8022 ProcessDeclAttributes(S, NewVD, D);
8023
8024 // FIXME: This is probably the wrong location to be doing this and we should
8025 // probably be doing this for more attributes (especially for function
8026 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8027 // the code to copy attributes would be generated by TableGen.
8028 if (R->isFunctionPointerType())
8029 if (const auto *TT = R->getAs<TypedefType>())
8030 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
8031
8032 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
8033 getLangOpts().SYCLIsDevice) {
8034 if (EmitTLSUnsupportedError &&
8036 (getLangOpts().OpenMPIsTargetDevice &&
8037 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8039 diag::err_thread_unsupported);
8040
8041 if (EmitTLSUnsupportedError &&
8042 (LangOpts.SYCLIsDevice ||
8043 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8044 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8045 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8046 // storage [duration]."
8047 if (SC == SC_None && S->getFnParent() != nullptr &&
8048 (NewVD->hasAttr<CUDASharedAttr>() ||
8049 NewVD->hasAttr<CUDAConstantAttr>())) {
8050 NewVD->setStorageClass(SC_Static);
8051 }
8052 }
8053
8054 // Ensure that dllimport globals without explicit storage class are treated as
8055 // extern. The storage class is set above using parsed attributes. Now we can
8056 // check the VarDecl itself.
8057 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8058 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8059 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8060
8061 // In auto-retain/release, infer strong retension for variables of
8062 // retainable type.
8063 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
8064 NewVD->setInvalidDecl();
8065
8066 // Handle GNU asm-label extension (encoded as an attribute).
8067 if (Expr *E = (Expr*)D.getAsmLabel()) {
8068 // The parser guarantees this is a string.
8069 StringLiteral *SE = cast<StringLiteral>(E);
8070 StringRef Label = SE->getString();
8071 if (S->getFnParent() != nullptr) {
8072 switch (SC) {
8073 case SC_None:
8074 case SC_Auto:
8075 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8076 break;
8077 case SC_Register:
8078 // Local Named register
8081 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8082 break;
8083 case SC_Static:
8084 case SC_Extern:
8085 case SC_PrivateExtern:
8086 break;
8087 }
8088 } else if (SC == SC_Register) {
8089 // Global Named register
8090 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8091 const auto &TI = Context.getTargetInfo();
8092 bool HasSizeMismatch;
8093
8094 if (!TI.isValidGCCRegisterName(Label))
8095 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8096 else if (!TI.validateGlobalRegisterVariable(Label,
8098 HasSizeMismatch))
8099 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8100 else if (HasSizeMismatch)
8101 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8102 }
8103
8104 if (!R->isIntegralType(Context) && !R->isPointerType()) {
8105 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
8106 NewVD->setInvalidDecl(true);
8107 }
8108 }
8109
8110 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8111 /*IsLiteralLabel=*/true,
8112 SE->getStrTokenLoc(0)));
8113 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8114 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8116 if (I != ExtnameUndeclaredIdentifiers.end()) {
8117 if (isDeclExternC(NewVD)) {
8118 NewVD->addAttr(I->second);
8120 } else
8121 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8122 << /*Variable*/1 << NewVD;
8123 }
8124 }
8125
8126 // Find the shadowed declaration before filtering for scope.
8127 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8129 : nullptr;
8130
8131 // Don't consider existing declarations that are in a different
8132 // scope and are out-of-semantic-context declarations (if the new
8133 // declaration has linkage).
8136 IsMemberSpecialization ||
8137 IsVariableTemplateSpecialization);
8138
8139 // Check whether the previous declaration is in the same block scope. This
8140 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8141 if (getLangOpts().CPlusPlus &&
8142 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8144 Previous.isSingleResult() && !Previous.isShadowed() &&
8145 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8146
8147 if (!getLangOpts().CPlusPlus) {
8149 } else {
8150 // If this is an explicit specialization of a static data member, check it.
8151 if (IsMemberSpecialization && !IsVariableTemplateSpecialization &&
8153 NewVD->setInvalidDecl();
8154
8155 // Merge the decl with the existing one if appropriate.
8156 if (!Previous.empty()) {
8157 if (Previous.isSingleResult() &&
8158 isa<FieldDecl>(Previous.getFoundDecl()) &&
8159 D.getCXXScopeSpec().isSet()) {
8160 // The user tried to define a non-static data member
8161 // out-of-line (C++ [dcl.meaning]p1).
8162 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8163 << D.getCXXScopeSpec().getRange();
8164 Previous.clear();
8165 NewVD->setInvalidDecl();
8166 }
8167 } else if (D.getCXXScopeSpec().isSet() &&
8168 !IsVariableTemplateSpecialization) {
8169 // No previous declaration in the qualifying scope.
8170 Diag(D.getIdentifierLoc(), diag::err_no_member)
8171 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8172 << D.getCXXScopeSpec().getRange();
8173 NewVD->setInvalidDecl();
8174 }
8175
8176 if (!IsPlaceholderVariable)
8178
8179 // CheckVariableDeclaration will set NewVD as invalid if something is in
8180 // error like WebAssembly tables being declared as arrays with a non-zero
8181 // size, but then parsing continues and emits further errors on that line.
8182 // To avoid that we check here if it happened and return nullptr.
8183 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8184 return nullptr;
8185
8186 if (NewTemplate) {
8187 VarTemplateDecl *PrevVarTemplate =
8188 NewVD->getPreviousDecl()
8190 : nullptr;
8191
8192 // Check the template parameter list of this declaration, possibly
8193 // merging in the template parameter list from the previous variable
8194 // template declaration.
8196 TemplateParams,
8197 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8198 : nullptr,
8199 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8200 DC->isDependentContext())
8202 : TPC_VarTemplate))
8203 NewVD->setInvalidDecl();
8204
8205 // If we are providing an explicit specialization of a static variable
8206 // template, make a note of that.
8207 if (PrevVarTemplate &&
8208 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8209 PrevVarTemplate->setMemberSpecialization();
8210 }
8211 }
8212
8213 // Diagnose shadowed variables iff this isn't a redeclaration.
8214 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8215 CheckShadow(NewVD, ShadowedDecl, Previous);
8216
8217 ProcessPragmaWeak(S, NewVD);
8218
8219 // If this is the first declaration of an extern C variable, update
8220 // the map of such variables.
8221 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8222 isIncompleteDeclExternC(*this, NewVD))
8224
8225 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8227 Decl *ManglingContextDecl;
8228 std::tie(MCtx, ManglingContextDecl) =
8230 if (MCtx) {
8232 NewVD, MCtx->getManglingNumber(
8233 NewVD, getMSManglingNumber(getLangOpts(), S)));
8235 }
8236 }
8237
8238 // Special handling of variable named 'main'.
8239 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8241 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8242
8243 // C++ [basic.start.main]p3
8244 // A program that declares a variable main at global scope is ill-formed.
8245 if (getLangOpts().CPlusPlus)
8246 Diag(D.getBeginLoc(), diag::err_main_global_variable);
8247
8248 // In C, and external-linkage variable named main results in undefined
8249 // behavior.
8250 else if (NewVD->hasExternalFormalLinkage())
8251 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8252 }
8253
8254 if (D.isRedeclaration() && !Previous.empty()) {
8255 NamedDecl *Prev = Previous.getRepresentativeDecl();
8256 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8258 }
8259
8260 if (NewTemplate) {
8261 if (NewVD->isInvalidDecl())
8262 NewTemplate->setInvalidDecl();
8263 ActOnDocumentableDecl(NewTemplate);
8264 return NewTemplate;
8265 }
8266
8267 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8269
8271
8272 return NewVD;
8273}
8274
8275/// Enum describing the %select options in diag::warn_decl_shadow.
8285
8286/// Determine what kind of declaration we're shadowing.
8288 const DeclContext *OldDC) {
8289 if (isa<TypeAliasDecl>(ShadowedDecl))
8290 return SDK_Using;
8291 else if (isa<TypedefDecl>(ShadowedDecl))
8292 return SDK_Typedef;
8293 else if (isa<BindingDecl>(ShadowedDecl))
8294 return SDK_StructuredBinding;
8295 else if (isa<RecordDecl>(OldDC))
8296 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8297
8298 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8299}
8300
8301/// Return the location of the capture if the given lambda captures the given
8302/// variable \p VD, or an invalid source location otherwise.
8304 const VarDecl *VD) {
8305 for (const Capture &Capture : LSI->Captures) {
8307 return Capture.getLocation();
8308 }
8309 return SourceLocation();
8310}
8311
8313 const LookupResult &R) {
8314 // Only diagnose if we're shadowing an unambiguous field or variable.
8316 return false;
8317
8318 // Return false if warning is ignored.
8319 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8320}
8321
8322/// Return the declaration shadowed by the given variable \p D, or null
8323/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8325 const LookupResult &R) {
8327 return nullptr;
8328
8329 // Don't diagnose declarations at file scope.
8330 if (D->hasGlobalStorage() && !D->isStaticLocal())
8331 return nullptr;
8332
8333 NamedDecl *ShadowedDecl = R.getFoundDecl();
8334 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8335 : nullptr;
8336}
8337
8338/// Return the declaration shadowed by the given typedef \p D, or null
8339/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8341 const LookupResult &R) {
8342 // Don't warn if typedef declaration is part of a class
8343 if (D->getDeclContext()->isRecord())
8344 return nullptr;
8345
8347 return nullptr;
8348
8349 NamedDecl *ShadowedDecl = R.getFoundDecl();
8350 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8351}
8352
8353/// Return the declaration shadowed by the given variable \p D, or null
8354/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8356 const LookupResult &R) {
8358 return nullptr;
8359
8360 NamedDecl *ShadowedDecl = R.getFoundDecl();
8361 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8362 : nullptr;
8363}
8364
8365/// Diagnose variable or built-in function shadowing. Implements
8366/// -Wshadow.
8367///
8368/// This method is called whenever a VarDecl is added to a "useful"
8369/// scope.
8370///
8371/// \param ShadowedDecl the declaration that is shadowed by the given variable
8372/// \param R the lookup of the name
8373///
8375 const LookupResult &R) {
8376 DeclContext *NewDC = D->getDeclContext();
8377
8378 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8379 // Fields are not shadowed by variables in C++ static methods.
8380 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8381 if (MD->isStatic())
8382 return;
8383
8384 // Fields shadowed by constructor parameters are a special case. Usually
8385 // the constructor initializes the field with the parameter.
8386 if (isa<CXXConstructorDecl>(NewDC))
8387 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8388 // Remember that this was shadowed so we can either warn about its
8389 // modification or its existence depending on warning settings.
8390 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8391 return;
8392 }
8393 }
8394
8395 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8396 if (shadowedVar->isExternC()) {
8397 // For shadowing external vars, make sure that we point to the global
8398 // declaration, not a locally scoped extern declaration.
8399 for (auto *I : shadowedVar->redecls())
8400 if (I->isFileVarDecl()) {
8401 ShadowedDecl = I;
8402 break;
8403 }
8404 }
8405
8406 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8407
8408 unsigned WarningDiag = diag::warn_decl_shadow;
8409 SourceLocation CaptureLoc;
8410 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8411 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8412 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8413 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8414 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8415 if (RD->getLambdaCaptureDefault() == LCD_None) {
8416 // Try to avoid warnings for lambdas with an explicit capture
8417 // list. Warn only when the lambda captures the shadowed decl
8418 // explicitly.
8419 CaptureLoc = getCaptureLocation(LSI, VD);
8420 if (CaptureLoc.isInvalid())
8421 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8422 } else {
8423 // Remember that this was shadowed so we can avoid the warning if
8424 // the shadowed decl isn't captured and the warning settings allow
8425 // it.
8426 cast<LambdaScopeInfo>(getCurFunction())
8427 ->ShadowingDecls.push_back({D, VD});
8428 return;
8429 }
8430 }
8431 if (isa<FieldDecl>(ShadowedDecl)) {
8432 // If lambda can capture this, then emit default shadowing warning,
8433 // Otherwise it is not really a shadowing case since field is not
8434 // available in lambda's body.
8435 // At this point we don't know that lambda can capture this, so
8436 // remember that this was shadowed and delay until we know.
8437 cast<LambdaScopeInfo>(getCurFunction())
8438 ->ShadowingDecls.push_back({D, ShadowedDecl});
8439 return;
8440 }
8441 }
8442 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8443 VD && VD->hasLocalStorage()) {
8444 // A variable can't shadow a local variable in an enclosing scope, if
8445 // they are separated by a non-capturing declaration context.
8446 for (DeclContext *ParentDC = NewDC;
8447 ParentDC && !ParentDC->Equals(OldDC);
8448 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8449 // Only block literals, captured statements, and lambda expressions
8450 // can capture; other scopes don't.
8451 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8452 !isLambdaCallOperator(ParentDC)) {
8453 return;
8454 }
8455 }
8456 }
8457 }
8458 }
8459
8460 // Never warn about shadowing a placeholder variable.
8461 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8462 return;
8463
8464 // Only warn about certain kinds of shadowing for class members.
8465 if (NewDC && NewDC->isRecord()) {
8466 // In particular, don't warn about shadowing non-class members.
8467 if (!OldDC->isRecord())
8468 return;
8469
8470 // TODO: should we warn about static data members shadowing
8471 // static data members from base classes?
8472
8473 // TODO: don't diagnose for inaccessible shadowed members.
8474 // This is hard to do perfectly because we might friend the
8475 // shadowing context, but that's just a false negative.
8476 }
8477
8478
8479 DeclarationName Name = R.getLookupName();
8480
8481 // Emit warning and note.
8482 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8483 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8484 if (!CaptureLoc.isInvalid())
8485 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8486 << Name << /*explicitly*/ 1;
8487 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8488}
8489
8490/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8491/// when these variables are captured by the lambda.
8493 for (const auto &Shadow : LSI->ShadowingDecls) {
8494 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8495 // Try to avoid the warning when the shadowed decl isn't captured.
8496 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8497 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8498 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8499 Diag(Shadow.VD->getLocation(),
8500 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8501 : diag::warn_decl_shadow)
8502 << Shadow.VD->getDeclName()
8503 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8504 if (CaptureLoc.isValid())
8505 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8506 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8507 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8508 } else if (isa<FieldDecl>(ShadowedDecl)) {
8509 Diag(Shadow.VD->getLocation(),
8510 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8511 : diag::warn_decl_shadow_uncaptured_local)
8512 << Shadow.VD->getDeclName()
8513 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8514 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8515 }
8516 }
8517}
8518
8519/// Check -Wshadow without the advantage of a previous lookup.
8521 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8522 return;
8523
8524 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8526 RedeclarationKind::ForVisibleRedeclaration);
8527 LookupName(R, S);
8528 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8529 CheckShadow(D, ShadowedDecl, R);
8530}
8531
8532/// Check if 'E', which is an expression that is about to be modified, refers
8533/// to a constructor parameter that shadows a field.
8535 // Quickly ignore expressions that can't be shadowing ctor parameters.
8536 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8537 return;
8538 E = E->IgnoreParenImpCasts();
8539 auto *DRE = dyn_cast<DeclRefExpr>(E);
8540 if (!DRE)
8541 return;
8542 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8543 auto I = ShadowingDecls.find(D);
8544 if (I == ShadowingDecls.end())
8545 return;
8546 const NamedDecl *ShadowedDecl = I->second;
8547 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8548 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8549 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8550 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8551
8552 // Avoid issuing multiple warnings about the same decl.
8553 ShadowingDecls.erase(I);
8554}
8555
8556/// Check for conflict between this global or extern "C" declaration and
8557/// previous global or extern "C" declarations. This is only used in C++.
8558template<typename T>
8560 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8561 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8562 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8563
8564 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8565 // The common case: this global doesn't conflict with any extern "C"
8566 // declaration.
8567 return false;
8568 }
8569
8570 if (Prev) {
8571 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8572 // Both the old and new declarations have C language linkage. This is a
8573 // redeclaration.
8574 Previous.clear();
8575 Previous.addDecl(Prev);
8576 return true;
8577 }
8578
8579 // This is a global, non-extern "C" declaration, and there is a previous
8580 // non-global extern "C" declaration. Diagnose if this is a variable
8581 // declaration.
8582 if (!isa<VarDecl>(ND))
8583 return false;
8584 } else {
8585 // The declaration is extern "C". Check for any declaration in the
8586 // translation unit which might conflict.
8587 if (IsGlobal) {
8588 // We have already performed the lookup into the translation unit.
8589 IsGlobal = false;
8590 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8591 I != E; ++I) {
8592 if (isa<VarDecl>(*I)) {
8593 Prev = *I;
8594 break;
8595 }
8596 }
8597 } else {
8599 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8600 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8601 I != E; ++I) {
8602 if (isa<VarDecl>(*I)) {
8603 Prev = *I;
8604 break;
8605 }
8606 // FIXME: If we have any other entity with this name in global scope,
8607 // the declaration is ill-formed, but that is a defect: it breaks the
8608 // 'stat' hack, for instance. Only variables can have mangled name
8609 // clashes with extern "C" declarations, so only they deserve a
8610 // diagnostic.
8611 }
8612 }
8613
8614 if (!Prev)
8615 return false;
8616 }
8617
8618 // Use the first declaration's location to ensure we point at something which
8619 // is lexically inside an extern "C" linkage-spec.
8620 assert(Prev && "should have found a previous declaration to diagnose");
8621 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8622 Prev = FD->getFirstDecl();
8623 else
8624 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8625
8626 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8627 << IsGlobal << ND;
8628 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8629 << IsGlobal;
8630 return false;
8631}
8632
8633/// Apply special rules for handling extern "C" declarations. Returns \c true
8634/// if we have found that this is a redeclaration of some prior entity.
8635///
8636/// Per C++ [dcl.link]p6:
8637/// Two declarations [for a function or variable] with C language linkage
8638/// with the same name that appear in different scopes refer to the same
8639/// [entity]. An entity with C language linkage shall not be declared with
8640/// the same name as an entity in global scope.
8641template<typename T>
8644 if (!S.getLangOpts().CPlusPlus) {
8645 // In C, when declaring a global variable, look for a corresponding 'extern'
8646 // variable declared in function scope. We don't need this in C++, because
8647 // we find local extern decls in the surrounding file-scope DeclContext.
8648 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8649 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8650 Previous.clear();
8651 Previous.addDecl(Prev);
8652 return true;
8653 }
8654 }
8655 return false;
8656 }
8657
8658 // A declaration in the translation unit can conflict with an extern "C"
8659 // declaration.
8660 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8661 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8662
8663 // An extern "C" declaration can conflict with a declaration in the
8664 // translation unit or can be a redeclaration of an extern "C" declaration
8665 // in another scope.
8666 if (isIncompleteDeclExternC(S,ND))
8667 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8668
8669 // Neither global nor extern "C": nothing to do.
8670 return false;
8671}
8672
8673static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8674 QualType T) {
8675 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8676 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8677 // any of its members, even recursively, shall not have an atomic type, or a
8678 // variably modified type, or a type that is volatile or restrict qualified.
8679 if (CanonT->isVariablyModifiedType()) {
8680 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8681 return true;
8682 }
8683
8684 // Arrays are qualified by their element type, so get the base type (this
8685 // works on non-arrays as well).
8686 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8687
8688 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8689 CanonT.isRestrictQualified()) {
8690 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8691 return true;
8692 }
8693
8694 if (CanonT->isRecordType()) {
8695 const RecordDecl *RD = CanonT->getAsRecordDecl();
8696 if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8697 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8698 }))
8699 return true;
8700 }
8701
8702 return false;
8703}
8704
8706 // If the decl is already known invalid, don't check it.
8707 if (NewVD->isInvalidDecl())
8708 return;
8709
8710 QualType T = NewVD->getType();
8711
8712 // Defer checking an 'auto' type until its initializer is attached.
8713 if (T->isUndeducedType())
8714 return;
8715
8716 if (NewVD->hasAttrs())
8718
8719 if (T->isObjCObjectType()) {
8720 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8721 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8723 NewVD->setType(T);
8724 }
8725
8726 // Emit an error if an address space was applied to decl with local storage.
8727 // This includes arrays of objects with address space qualifiers, but not
8728 // automatic variables that point to other address spaces.
8729 // ISO/IEC TR 18037 S5.1.2
8730 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8731 T.getAddressSpace() != LangAS::Default) {
8732 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8733 NewVD->setInvalidDecl();
8734 return;
8735 }
8736
8737 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8738 // scope.
8739 if (getLangOpts().OpenCLVersion == 120 &&
8740 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8741 getLangOpts()) &&
8742 NewVD->isStaticLocal()) {
8743 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8744 NewVD->setInvalidDecl();
8745 return;
8746 }
8747
8748 if (getLangOpts().OpenCL) {
8749 if (!diagnoseOpenCLTypes(*this, NewVD))
8750 return;
8751
8752 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8753 if (NewVD->hasAttr<BlocksAttr>()) {
8754 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8755 return;
8756 }
8757
8758 if (T->isBlockPointerType()) {
8759 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8760 // can't use 'extern' storage class.
8761 if (!T.isConstQualified()) {
8762 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8763 << 0 /*const*/;
8764 NewVD->setInvalidDecl();
8765 return;
8766 }
8767 if (NewVD->hasExternalStorage()) {
8768 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8769 NewVD->setInvalidDecl();
8770 return;
8771 }
8772 }
8773
8774 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8775 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8776 NewVD->hasExternalStorage()) {
8777 if (!T->isSamplerT() && !T->isDependentType() &&
8778 !(T.getAddressSpace() == LangAS::opencl_constant ||
8779 (T.getAddressSpace() == LangAS::opencl_global &&
8780 getOpenCLOptions().areProgramScopeVariablesSupported(
8781 getLangOpts())))) {
8782 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8783 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8784 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8785 << Scope << "global or constant";
8786 else
8787 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8788 << Scope << "constant";
8789 NewVD->setInvalidDecl();
8790 return;
8791 }
8792 } else {
8793 if (T.getAddressSpace() == LangAS::opencl_global) {
8794 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8795 << 1 /*is any function*/ << "global";
8796 NewVD->setInvalidDecl();
8797 return;
8798 }
8799 if (T.getAddressSpace() == LangAS::opencl_constant ||
8800 T.getAddressSpace() == LangAS::opencl_local) {
8802 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8803 // in functions.
8804 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8805 if (T.getAddressSpace() == LangAS::opencl_constant)
8806 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8807 << 0 /*non-kernel only*/ << "constant";
8808 else
8809 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8810 << 0 /*non-kernel only*/ << "local";
8811 NewVD->setInvalidDecl();
8812 return;
8813 }
8814 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8815 // in the outermost scope of a kernel function.
8816 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8817 if (!getCurScope()->isFunctionScope()) {
8818 if (T.getAddressSpace() == LangAS::opencl_constant)
8819 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8820 << "constant";
8821 else
8822 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8823 << "local";
8824 NewVD->setInvalidDecl();
8825 return;
8826 }
8827 }
8828 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8829 // If we are parsing a template we didn't deduce an addr
8830 // space yet.
8831 T.getAddressSpace() != LangAS::Default) {
8832 // Do not allow other address spaces on automatic variable.
8833 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8834 NewVD->setInvalidDecl();
8835 return;
8836 }
8837 }
8838 }
8839
8840 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8841 && !NewVD->hasAttr<BlocksAttr>()) {
8842 if (getLangOpts().getGC() != LangOptions::NonGC)
8843 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8844 else {
8845 assert(!getLangOpts().ObjCAutoRefCount);
8846 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8847 }
8848 }
8849
8850 // WebAssembly tables must be static with a zero length and can't be
8851 // declared within functions.
8852 if (T->isWebAssemblyTableType()) {
8853 if (getCurScope()->getParent()) { // Parent is null at top-level
8854 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8855 NewVD->setInvalidDecl();
8856 return;
8857 }
8858 if (NewVD->getStorageClass() != SC_Static) {
8859 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8860 NewVD->setInvalidDecl();
8861 return;
8862 }
8863 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8864 if (!ATy || ATy->getZExtSize() != 0) {
8865 Diag(NewVD->getLocation(),
8866 diag::err_typecheck_wasm_table_must_have_zero_length);
8867 NewVD->setInvalidDecl();
8868 return;
8869 }
8870 }
8871
8872 bool isVM = T->isVariablyModifiedType();
8873 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8874 NewVD->hasAttr<BlocksAttr>())
8876
8877 if ((isVM && NewVD->hasLinkage()) ||
8878 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8879 bool SizeIsNegative;
8880 llvm::APSInt Oversized;
8882 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8883 QualType FixedT;
8884 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8885 FixedT = FixedTInfo->getType();
8886 else if (FixedTInfo) {
8887 // Type and type-as-written are canonically different. We need to fix up
8888 // both types separately.
8889 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8890 Oversized);
8891 }
8892 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8894 // FIXME: This won't give the correct result for
8895 // int a[10][n];
8896 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8897
8898 if (NewVD->isFileVarDecl())
8899 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8900 << SizeRange;
8901 else if (NewVD->isStaticLocal())
8902 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8903 << SizeRange;
8904 else
8905 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8906 << SizeRange;
8907 NewVD->setInvalidDecl();
8908 return;
8909 }
8910
8911 if (!FixedTInfo) {
8912 if (NewVD->isFileVarDecl())
8913 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8914 else
8915 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8916 NewVD->setInvalidDecl();
8917 return;
8918 }
8919
8920 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8921 NewVD->setType(FixedT);
8922 NewVD->setTypeSourceInfo(FixedTInfo);
8923 }
8924
8925 if (T->isVoidType()) {
8926 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8927 // of objects and functions.
8929 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8930 << T;
8931 NewVD->setInvalidDecl();
8932 return;
8933 }
8934 }
8935
8936 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8937 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8938 NewVD->setInvalidDecl();
8939 return;
8940 }
8941
8942 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8943 !T.isWebAssemblyReferenceType()) {
8944 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8945 NewVD->setInvalidDecl();
8946 return;
8947 }
8948
8949 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8950 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8951 NewVD->setInvalidDecl();
8952 return;
8953 }
8954
8955 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8956 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8957 NewVD->setInvalidDecl();
8958 return;
8959 }
8960
8961 if (NewVD->isConstexpr() && !T->isDependentType() &&
8963 diag::err_constexpr_var_non_literal)) {
8964 NewVD->setInvalidDecl();
8965 return;
8966 }
8967
8968 // PPC MMA non-pointer types are not allowed as non-local variable types.
8969 if (Context.getTargetInfo().getTriple().isPPC64() &&
8970 !NewVD->isLocalVarDecl() &&
8971 CheckPPCMMAType(T, NewVD->getLocation())) {
8972 NewVD->setInvalidDecl();
8973 return;
8974 }
8975
8976 // Check that SVE types are only used in functions with SVE available.
8977 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8978 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8979 llvm::StringMap<bool> CallerFeatureMap;
8980 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8982 "sve", CallerFeatureMap)) {
8983 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8984 NewVD->setInvalidDecl();
8985 return;
8986 }
8987 }
8988
8989 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8990 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8991 llvm::StringMap<bool> CallerFeatureMap;
8992 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8993 checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
8994 CallerFeatureMap);
8995 }
8996}
8997
8998/// Perform semantic checking on a newly-created variable
8999/// declaration.
9000///
9001/// This routine performs all of the type-checking required for a
9002/// variable declaration once it has been built. It is used both to
9003/// check variables after they have been parsed and their declarators
9004/// have been translated into a declaration, and to check variables
9005/// that have been instantiated from a template.
9006///
9007/// Sets NewVD->isInvalidDecl() if an error was encountered.
9008///
9009/// Returns true if the variable declaration is a redeclaration.
9012
9013 // If the decl is already known invalid, don't check it.
9014 if (NewVD->isInvalidDecl())
9015 return false;
9016
9017 // If we did not find anything by this name, look for a non-visible
9018 // extern "C" declaration with the same name.
9019 if (Previous.empty() &&
9021 Previous.setShadowed();
9022
9023 if (!Previous.empty()) {
9024 MergeVarDecl(NewVD, Previous);
9025 return true;
9026 }
9027 return false;
9028}
9029
9030/// AddOverriddenMethods - See if a method overrides any in the base classes,
9031/// and if so, check that it's a valid override and remember it.
9034
9035 // Look for methods in base classes that this method might override.
9036 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9037 /*DetectVirtual=*/false);
9038 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9039 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9040 DeclarationName Name = MD->getDeclName();
9041
9042 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9043 // We really want to find the base class destructor here.
9044 QualType T = Context.getTypeDeclType(BaseRecord);
9047 }
9048
9049 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9050 CXXMethodDecl *BaseMD =
9051 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9052 if (!BaseMD || !BaseMD->isVirtual() ||
9053 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9054 /*ConsiderCudaAttrs=*/true))
9055 continue;
9056 if (!CheckExplicitObjectOverride(MD, BaseMD))
9057 continue;
9058 if (Overridden.insert(BaseMD).second) {
9059 MD->addOverriddenMethod(BaseMD);
9064 }
9065
9066 // A method can only override one function from each base class. We
9067 // don't track indirectly overridden methods from bases of bases.
9068 return true;
9069 }
9070
9071 return false;
9072 };
9073
9074 DC->lookupInBases(VisitBase, Paths);
9075 return !Overridden.empty();
9076}
9077
9078namespace {
9079 // Struct for holding all of the extra arguments needed by
9080 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9081 struct ActOnFDArgs {
9082 Scope *S;
9083 Declarator &D;
9084 MultiTemplateParamsArg TemplateParamLists;
9085 bool AddToScope;
9086 };
9087} // end anonymous namespace
9088
9089namespace {
9090
9091// Callback to only accept typo corrections that have a non-zero edit distance.
9092// Also only accept corrections that have the same parent decl.
9093class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9094 public:
9095 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9097 : Context(Context), OriginalFD(TypoFD),
9098 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9099
9100 bool ValidateCandidate(const TypoCorrection &candidate) override {
9101 if (candidate.getEditDistance() == 0)
9102 return false;
9103
9104 SmallVector<unsigned, 1> MismatchedParams;
9105 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9106 CDeclEnd = candidate.end();
9107 CDecl != CDeclEnd; ++CDecl) {
9108 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9109
9110 if (FD && !FD->hasBody() &&
9111 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9112 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9113 CXXRecordDecl *Parent = MD->getParent();
9114 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9115 return true;
9116 } else if (!ExpectedParent) {
9117 return true;
9118 }
9119 }
9120 }
9121
9122 return false;
9123 }
9124
9125 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9126 return std::make_unique<DifferentNameValidatorCCC>(*this);
9127 }
9128
9129 private:
9130 ASTContext &Context;
9131 FunctionDecl *OriginalFD;
9132 CXXRecordDecl *ExpectedParent;
9133};
9134
9135} // end anonymous namespace
9136
9139}
9140
9141/// Generate diagnostics for an invalid function redeclaration.
9142///
9143/// This routine handles generating the diagnostic messages for an invalid
9144/// function redeclaration, including finding possible similar declarations
9145/// or performing typo correction if there are no previous declarations with
9146/// the same name.
9147///
9148/// Returns a NamedDecl iff typo correction was performed and substituting in
9149/// the new declaration name does not cause new errors.
9151 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9152 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9153 DeclarationName Name = NewFD->getDeclName();
9154 DeclContext *NewDC = NewFD->getDeclContext();
9155 SmallVector<unsigned, 1> MismatchedParams;
9157 TypoCorrection Correction;
9158 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9159 unsigned DiagMsg =
9160 IsLocalFriend ? diag::err_no_matching_local_friend :
9161 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9162 diag::err_member_decl_does_not_match;
9163 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9164 IsLocalFriend ? Sema::LookupLocalFriendName
9166 RedeclarationKind::ForVisibleRedeclaration);
9167
9168 NewFD->setInvalidDecl();
9169 if (IsLocalFriend)
9170 SemaRef.LookupName(Prev, S);
9171 else
9172 SemaRef.LookupQualifiedName(Prev, NewDC);
9173 assert(!Prev.isAmbiguous() &&
9174 "Cannot have an ambiguity in previous-declaration lookup");
9175 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9176 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9177 MD ? MD->getParent() : nullptr);
9178 if (!Prev.empty()) {
9179 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9180 Func != FuncEnd; ++Func) {
9181 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9182 if (FD &&
9183 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9184 // Add 1 to the index so that 0 can mean the mismatch didn't
9185 // involve a parameter
9186 unsigned ParamNum =
9187 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9188 NearMatches.push_back(std::make_pair(FD, ParamNum));
9189 }
9190 }
9191 // If the qualified name lookup yielded nothing, try typo correction
9192 } else if ((Correction = SemaRef.CorrectTypo(
9193 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9194 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9195 IsLocalFriend ? nullptr : NewDC))) {
9196 // Set up everything for the call to ActOnFunctionDeclarator
9197 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9198 ExtraArgs.D.getIdentifierLoc());
9199 Previous.clear();
9200 Previous.setLookupName(Correction.getCorrection());
9201 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9202 CDeclEnd = Correction.end();
9203 CDecl != CDeclEnd; ++CDecl) {
9204 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9205 if (FD && !FD->hasBody() &&
9206 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9207 Previous.addDecl(FD);
9208 }
9209 }
9210 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9211
9213 // Retry building the function declaration with the new previous
9214 // declarations, and with errors suppressed.
9215 {
9216 // Trap errors.
9217 Sema::SFINAETrap Trap(SemaRef);
9218
9219 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9220 // pieces need to verify the typo-corrected C++ declaration and hopefully
9221 // eliminate the need for the parameter pack ExtraArgs.
9223 ExtraArgs.S, ExtraArgs.D,
9224 Correction.getCorrectionDecl()->getDeclContext(),
9225 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9226 ExtraArgs.AddToScope);
9227
9228 if (Trap.hasErrorOccurred())
9229 Result = nullptr;
9230 }
9231
9232 if (Result) {
9233 // Determine which correction we picked.
9234 Decl *Canonical = Result->getCanonicalDecl();
9235 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9236 I != E; ++I)
9237 if ((*I)->getCanonicalDecl() == Canonical)
9238 Correction.setCorrectionDecl(*I);
9239
9240 // Let Sema know about the correction.
9242 SemaRef.diagnoseTypo(
9243 Correction,
9244 SemaRef.PDiag(IsLocalFriend
9245 ? diag::err_no_matching_local_friend_suggest
9246 : diag::err_member_decl_does_not_match_suggest)
9247 << Name << NewDC << IsDefinition);
9248 return Result;
9249 }
9250
9251 // Pretend the typo correction never occurred
9252 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9253 ExtraArgs.D.getIdentifierLoc());
9254 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9255 Previous.clear();
9256 Previous.setLookupName(Name);
9257 }
9258
9259 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9260 << Name << NewDC << IsDefinition << NewFD->getLocation();
9261
9262 bool NewFDisConst = false;
9263 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9264 NewFDisConst = NewMD->isConst();
9265
9266 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9267 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9268 NearMatch != NearMatchEnd; ++NearMatch) {
9269 FunctionDecl *FD = NearMatch->first;
9270 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9271 bool FDisConst = MD && MD->isConst();
9272 bool IsMember = MD || !IsLocalFriend;
9273
9274 // FIXME: These notes are poorly worded for the local friend case.
9275 if (unsigned Idx = NearMatch->second) {
9276 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9277 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9278 if (Loc.isInvalid()) Loc = FD->getLocation();
9279 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9280 : diag::note_local_decl_close_param_match)
9281 << Idx << FDParam->getType()
9282 << NewFD->getParamDecl(Idx - 1)->getType();
9283 } else if (FDisConst != NewFDisConst) {
9284 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9285 << NewFDisConst << FD->getSourceRange().getEnd()
9286 << (NewFDisConst
9287 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9288 .getConstQualifierLoc())
9289 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9290 .getRParenLoc()
9291 .getLocWithOffset(1),
9292 " const"));
9293 } else
9294 SemaRef.Diag(FD->getLocation(),
9295 IsMember ? diag::note_member_def_close_match
9296 : diag::note_local_decl_close_match);
9297 }
9298 return nullptr;
9299}
9300
9302 switch (D.getDeclSpec().getStorageClassSpec()) {
9303 default: llvm_unreachable("Unknown storage class!");
9304 case DeclSpec::SCS_auto:
9308 diag::err_typecheck_sclass_func);
9310 D.setInvalidType();
9311 break;
9312 case DeclSpec::SCS_unspecified: break;
9315 return SC_None;
9316 return SC_Extern;
9317 case DeclSpec::SCS_static: {
9319 // C99 6.7.1p5:
9320 // The declaration of an identifier for a function that has
9321 // block scope shall have no explicit storage-class specifier
9322 // other than extern
9323 // See also (C++ [dcl.stc]p4).
9325 diag::err_static_block_func);
9326 break;
9327 } else
9328 return SC_Static;
9329 }
9331 }
9332
9333 // No explicit storage class has already been returned
9334 return SC_None;
9335}
9336
9338 DeclContext *DC, QualType &R,
9339 TypeSourceInfo *TInfo,
9340 StorageClass SC,
9341 bool &IsVirtualOkay) {
9342 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9343 DeclarationName Name = NameInfo.getName();
9344
9345 FunctionDecl *NewFD = nullptr;
9346 bool isInline = D.getDeclSpec().isInlineSpecified();
9347
9349 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9350 (SemaRef.getLangOpts().C23 &&
9351 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9352
9353 if (SemaRef.getLangOpts().C23)
9354 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9355 diag::err_c23_constexpr_not_variable);
9356 else
9357 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9358 diag::err_constexpr_wrong_decl_kind)
9359 << static_cast<int>(ConstexprKind);
9360 ConstexprKind = ConstexprSpecKind::Unspecified;
9362 }
9363
9364 if (!SemaRef.getLangOpts().CPlusPlus) {
9365 // Determine whether the function was written with a prototype. This is
9366 // true when:
9367 // - there is a prototype in the declarator, or
9368 // - the type R of the function is some kind of typedef or other non-
9369 // attributed reference to a type name (which eventually refers to a
9370 // function type). Note, we can't always look at the adjusted type to
9371 // check this case because attributes may cause a non-function
9372 // declarator to still have a function type. e.g.,
9373 // typedef void func(int a);
9374 // __attribute__((noreturn)) func other_func; // This has a prototype
9375 bool HasPrototype =
9377 (D.getDeclSpec().isTypeRep() &&
9378 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9379 ->isFunctionProtoType()) ||
9381 assert(
9382 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9383 "Strict prototypes are required");
9384
9385 NewFD = FunctionDecl::Create(
9386 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9387 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9389 /*TrailingRequiresClause=*/nullptr);
9390 if (D.isInvalidType())
9391 NewFD->setInvalidDecl();
9392
9393 return NewFD;
9394 }
9395
9397 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9398
9399 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9400
9401 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9402 // This is a C++ constructor declaration.
9403 assert(DC->isRecord() &&
9404 "Constructors can only be declared in a member context");
9405
9406 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9408 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9410 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9411 InheritedConstructor(), TrailingRequiresClause);
9412
9413 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9414 // This is a C++ destructor declaration.
9415 if (DC->isRecord()) {
9416 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9417 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9419 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9420 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9421 /*isImplicitlyDeclared=*/false, ConstexprKind,
9422 TrailingRequiresClause);
9423 // User defined destructors start as not selected if the class definition is still
9424 // not done.
9425 if (Record->isBeingDefined())
9426 NewDD->setIneligibleOrNotSelected(true);
9427
9428 // If the destructor needs an implicit exception specification, set it
9429 // now. FIXME: It'd be nice to be able to create the right type to start
9430 // with, but the type needs to reference the destructor declaration.
9431 if (SemaRef.getLangOpts().CPlusPlus11)
9432 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9433
9434 IsVirtualOkay = true;
9435 return NewDD;
9436
9437 } else {
9438 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9439 D.setInvalidType();
9440
9441 // Create a FunctionDecl to satisfy the function definition parsing
9442 // code path.
9443 return FunctionDecl::Create(
9444 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9445 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9446 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9447 }
9448
9449 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9450 if (!DC->isRecord()) {
9451 SemaRef.Diag(D.getIdentifierLoc(),
9452 diag::err_conv_function_not_member);
9453 return nullptr;
9454 }
9455
9456 SemaRef.CheckConversionDeclarator(D, R, SC);
9457 if (D.isInvalidType())
9458 return nullptr;
9459
9460 IsVirtualOkay = true;
9462 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9463 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9464 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9465 TrailingRequiresClause);
9466
9467 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9468 if (TrailingRequiresClause)
9469 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9470 diag::err_trailing_requires_clause_on_deduction_guide)
9471 << TrailingRequiresClause->getSourceRange();
9472 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9473 return nullptr;
9474 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9475 ExplicitSpecifier, NameInfo, R, TInfo,
9476 D.getEndLoc());
9477 } else if (DC->isRecord()) {
9478 // If the name of the function is the same as the name of the record,
9479 // then this must be an invalid constructor that has a return type.
9480 // (The parser checks for a return type and makes the declarator a
9481 // constructor if it has no return type).
9482 if (Name.getAsIdentifierInfo() &&
9483 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9484 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9487 return nullptr;
9488 }
9489
9490 // This is a C++ method declaration.
9492 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9493 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9494 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9495 IsVirtualOkay = !Ret->isStatic();
9496 return Ret;
9497 } else {
9498 bool isFriend =
9499 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9500 if (!isFriend && SemaRef.CurContext->isRecord())
9501 return nullptr;
9502
9503 // Determine whether the function was written with a
9504 // prototype. This true when:
9505 // - we're in C++ (where every function has a prototype),
9506 return FunctionDecl::Create(
9507 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9508 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9509 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9510 }
9511}
9512
9521
9523 // Size dependent types are just typedefs to normal integer types
9524 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9525 // integers other than by their names.
9526 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9527
9528 // Remove typedefs one by one until we reach a typedef
9529 // for a size dependent type.
9530 QualType DesugaredTy = Ty;
9531 do {
9532 ArrayRef<StringRef> Names(SizeTypeNames);
9533 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9534 if (Names.end() != Match)
9535 return true;
9536
9537 Ty = DesugaredTy;
9538 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9539 } while (DesugaredTy != Ty);
9540
9541 return false;
9542}
9543
9545 if (PT->isDependentType())
9546 return InvalidKernelParam;
9547
9548 if (PT->isPointerType() || PT->isReferenceType()) {
9549 QualType PointeeType = PT->getPointeeType();
9550 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9551 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9552 PointeeType.getAddressSpace() == LangAS::Default)
9554
9555 if (PointeeType->isPointerType()) {
9556 // This is a pointer to pointer parameter.
9557 // Recursively check inner type.
9558 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9559 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9560 ParamKind == InvalidKernelParam)
9561 return ParamKind;
9562
9563 // OpenCL v3.0 s6.11.a:
9564 // A restriction to pass pointers to pointers only applies to OpenCL C
9565 // v1.2 or below.
9567 return ValidKernelParam;
9568
9569 return PtrPtrKernelParam;
9570 }
9571
9572 // C++ for OpenCL v1.0 s2.4:
9573 // Moreover the types used in parameters of the kernel functions must be:
9574 // Standard layout types for pointer parameters. The same applies to
9575 // reference if an implementation supports them in kernel parameters.
9576 if (S.getLangOpts().OpenCLCPlusPlus &&
9578 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9579 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9580 bool IsStandardLayoutType = true;
9581 if (CXXRec) {
9582 // If template type is not ODR-used its definition is only available
9583 // in the template definition not its instantiation.
9584 // FIXME: This logic doesn't work for types that depend on template
9585 // parameter (PR58590).
9586 if (!CXXRec->hasDefinition())
9587 CXXRec = CXXRec->getTemplateInstantiationPattern();
9588 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9589 IsStandardLayoutType = false;
9590 }
9591 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9592 !IsStandardLayoutType)
9593 return InvalidKernelParam;
9594 }
9595
9596 // OpenCL v1.2 s6.9.p:
9597 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9599 return ValidKernelParam;
9600
9601 return PtrKernelParam;
9602 }
9603
9604 // OpenCL v1.2 s6.9.k:
9605 // Arguments to kernel functions in a program cannot be declared with the
9606 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9607 // uintptr_t or a struct and/or union that contain fields declared to be one
9608 // of these built-in scalar types.
9610 return InvalidKernelParam;
9611
9612 if (PT->isImageType())
9613 return PtrKernelParam;
9614
9615 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9616 return InvalidKernelParam;
9617
9618 // OpenCL extension spec v1.2 s9.5:
9619 // This extension adds support for half scalar and vector types as built-in
9620 // types that can be used for arithmetic operations, conversions etc.
9621 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9622 PT->isHalfType())
9623 return InvalidKernelParam;
9624
9625 // Look into an array argument to check if it has a forbidden type.
9626 if (PT->isArrayType()) {
9627 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9628 // Call ourself to check an underlying type of an array. Since the
9629 // getPointeeOrArrayElementType returns an innermost type which is not an
9630 // array, this recursive call only happens once.
9631 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9632 }
9633
9634 // C++ for OpenCL v1.0 s2.4:
9635 // Moreover the types used in parameters of the kernel functions must be:
9636 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9637 // types) for parameters passed by value;
9638 if (S.getLangOpts().OpenCLCPlusPlus &&
9640 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9641 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9642 return InvalidKernelParam;
9643
9644 if (PT->isRecordType())
9645 return RecordKernelParam;
9646
9647 return ValidKernelParam;
9648}
9649
9651 Sema &S,
9652 Declarator &D,
9653 ParmVarDecl *Param,
9654 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9655 QualType PT = Param->getType();
9656
9657 // Cache the valid types we encounter to avoid rechecking structs that are
9658 // used again
9659 if (ValidTypes.count(PT.getTypePtr()))
9660 return;
9661
9662 switch (getOpenCLKernelParameterType(S, PT)) {
9663 case PtrPtrKernelParam:
9664 // OpenCL v3.0 s6.11.a:
9665 // A kernel function argument cannot be declared as a pointer to a pointer
9666 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9667 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9668 D.setInvalidType();
9669 return;
9670
9672 // OpenCL v1.0 s6.5:
9673 // __kernel function arguments declared to be a pointer of a type can point
9674 // to one of the following address spaces only : __global, __local or
9675 // __constant.
9676 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9677 D.setInvalidType();
9678 return;
9679
9680 // OpenCL v1.2 s6.9.k:
9681 // Arguments to kernel functions in a program cannot be declared with the
9682 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9683 // uintptr_t or a struct and/or union that contain fields declared to be
9684 // one of these built-in scalar types.
9685
9686 case InvalidKernelParam:
9687 // OpenCL v1.2 s6.8 n:
9688 // A kernel function argument cannot be declared
9689 // of event_t type.
9690 // Do not diagnose half type since it is diagnosed as invalid argument
9691 // type for any function elsewhere.
9692 if (!PT->isHalfType()) {
9693 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9694
9695 // Explain what typedefs are involved.
9696 const TypedefType *Typedef = nullptr;
9697 while ((Typedef = PT->getAs<TypedefType>())) {
9698 SourceLocation Loc = Typedef->getDecl()->getLocation();
9699 // SourceLocation may be invalid for a built-in type.
9700 if (Loc.isValid())
9701 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9702 PT = Typedef->desugar();
9703 }
9704 }
9705
9706 D.setInvalidType();
9707 return;
9708
9709 case PtrKernelParam:
9710 case ValidKernelParam:
9711 ValidTypes.insert(PT.getTypePtr());
9712 return;
9713
9714 case RecordKernelParam:
9715 break;
9716 }
9717
9718 // Track nested structs we will inspect
9720
9721 // Track where we are in the nested structs. Items will migrate from
9722 // VisitStack to HistoryStack as we do the DFS for bad field.
9724 HistoryStack.push_back(nullptr);
9725
9726 // At this point we already handled everything except of a RecordType or
9727 // an ArrayType of a RecordType.
9728 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9729 const RecordType *RecTy =
9731 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9732
9733 VisitStack.push_back(RecTy->getDecl());
9734 assert(VisitStack.back() && "First decl null?");
9735
9736 do {
9737 const Decl *Next = VisitStack.pop_back_val();
9738 if (!Next) {
9739 assert(!HistoryStack.empty());
9740 // Found a marker, we have gone up a level
9741 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9742 ValidTypes.insert(Hist->getType().getTypePtr());
9743
9744 continue;
9745 }
9746
9747 // Adds everything except the original parameter declaration (which is not a
9748 // field itself) to the history stack.
9749 const RecordDecl *RD;
9750 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9751 HistoryStack.push_back(Field);
9752
9753 QualType FieldTy = Field->getType();
9754 // Other field types (known to be valid or invalid) are handled while we
9755 // walk around RecordDecl::fields().
9756 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9757 "Unexpected type.");
9758 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9759
9760 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9761 } else {
9762 RD = cast<RecordDecl>(Next);
9763 }
9764
9765 // Add a null marker so we know when we've gone back up a level
9766 VisitStack.push_back(nullptr);
9767
9768 for (const auto *FD : RD->fields()) {
9769 QualType QT = FD->getType();
9770
9771 if (ValidTypes.count(QT.getTypePtr()))
9772 continue;
9773
9775 if (ParamType == ValidKernelParam)
9776 continue;
9777
9778 if (ParamType == RecordKernelParam) {
9779 VisitStack.push_back(FD);
9780 continue;
9781 }
9782
9783 // OpenCL v1.2 s6.9.p:
9784 // Arguments to kernel functions that are declared to be a struct or union
9785 // do not allow OpenCL objects to be passed as elements of the struct or
9786 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9787 // of SVM.
9788 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9789 ParamType == InvalidAddrSpacePtrKernelParam) {
9790 S.Diag(Param->getLocation(),
9791 diag::err_record_with_pointers_kernel_param)
9792 << PT->isUnionType()
9793 << PT;
9794 } else {
9795 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9796 }
9797
9798 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9799 << OrigRecDecl->getDeclName();
9800
9801 // We have an error, now let's go back up through history and show where
9802 // the offending field came from
9804 I = HistoryStack.begin() + 1,
9805 E = HistoryStack.end();
9806 I != E; ++I) {
9807 const FieldDecl *OuterField = *I;
9808 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9809 << OuterField->getType();
9810 }
9811
9812 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9813 << QT->isPointerType()
9814 << QT;
9815 D.setInvalidType();
9816 return;
9817 }
9818 } while (!VisitStack.empty());
9819}
9820
9821/// Find the DeclContext in which a tag is implicitly declared if we see an
9822/// elaborated type specifier in the specified context, and lookup finds
9823/// nothing.
9825 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9826 DC = DC->getParent();
9827 return DC;
9828}
9829
9830/// Find the Scope in which a tag is implicitly declared if we see an
9831/// elaborated type specifier in the specified context, and lookup finds
9832/// nothing.
9833static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9834 while (S->isClassScope() ||
9835 (LangOpts.CPlusPlus &&
9836 S->isFunctionPrototypeScope()) ||
9837 ((S->getFlags() & Scope::DeclScope) == 0) ||
9838 (S->getEntity() && S->getEntity()->isTransparentContext()))
9839 S = S->getParent();
9840 return S;
9841}
9842
9843/// Determine whether a declaration matches a known function in namespace std.
9845 unsigned BuiltinID) {
9846 switch (BuiltinID) {
9847 case Builtin::BI__GetExceptionInfo:
9848 // No type checking whatsoever.
9849 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9850
9851 case Builtin::BIaddressof:
9852 case Builtin::BI__addressof:
9853 case Builtin::BIforward:
9854 case Builtin::BIforward_like:
9855 case Builtin::BImove:
9856 case Builtin::BImove_if_noexcept:
9857 case Builtin::BIas_const: {
9858 // Ensure that we don't treat the algorithm
9859 // OutputIt std::move(InputIt, InputIt, OutputIt)
9860 // as the builtin std::move.
9861 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9862 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9863 }
9864
9865 default:
9866 return false;
9867 }
9868}
9869
9870NamedDecl*
9873 MultiTemplateParamsArg TemplateParamListsRef,
9874 bool &AddToScope) {
9875 QualType R = TInfo->getType();
9876
9877 assert(R->isFunctionType());
9879 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9880
9881 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9882 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9884 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9885 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9886 TemplateParamLists.back() = Invented;
9887 else
9888 TemplateParamLists.push_back(Invented);
9889 }
9890
9891 // TODO: consider using NameInfo for diagnostic.
9893 DeclarationName Name = NameInfo.getName();
9895
9898 diag::err_invalid_thread)
9900
9905
9906 bool isFriend = false;
9908 bool isMemberSpecialization = false;
9909 bool isFunctionTemplateSpecialization = false;
9910
9911 bool HasExplicitTemplateArgs = false;
9912 TemplateArgumentListInfo TemplateArgs;
9913
9914 bool isVirtualOkay = false;
9915
9916 DeclContext *OriginalDC = DC;
9917 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9918
9919 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9920 isVirtualOkay);
9921 if (!NewFD) return nullptr;
9922
9925
9926 // Set the lexical context. If this is a function-scope declaration, or has a
9927 // C++ scope specifier, or is the object of a friend declaration, the lexical
9928 // context will be different from the semantic context.
9930
9931 if (IsLocalExternDecl)
9932 NewFD->setLocalExternDecl();
9933
9934 if (getLangOpts().CPlusPlus) {
9935 // The rules for implicit inlines changed in C++20 for methods and friends
9936 // with an in-class definition (when such a definition is not attached to
9937 // the global module). User-specified 'inline' overrides this (set when
9938 // the function decl is created above).
9939 // FIXME: We need a better way to separate C++ standard and clang modules.
9940 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9941 !NewFD->getOwningModule() ||
9942 NewFD->isFromExplicitGlobalModule() ||
9944 bool isInline = D.getDeclSpec().isInlineSpecified();
9945 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9946 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9947 isFriend = D.getDeclSpec().isFriendSpecified();
9948 if (isFriend && !isInline && D.isFunctionDefinition()) {
9949 // Pre-C++20 [class.friend]p5
9950 // A function can be defined in a friend declaration of a
9951 // class . . . . Such a function is implicitly inline.
9952 // Post C++20 [class.friend]p7
9953 // Such a function is implicitly an inline function if it is attached
9954 // to the global module.
9955 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9956 }
9957
9958 // If this is a method defined in an __interface, and is not a constructor
9959 // or an overloaded operator, then set the pure flag (isVirtual will already
9960 // return true).
9961 if (const CXXRecordDecl *Parent =
9962 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9963 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9964 NewFD->setIsPureVirtual(true);
9965
9966 // C++ [class.union]p2
9967 // A union can have member functions, but not virtual functions.
9968 if (isVirtual && Parent->isUnion()) {
9969 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9970 NewFD->setInvalidDecl();
9971 }
9972 if ((Parent->isClass() || Parent->isStruct()) &&
9973 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9974 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9975 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9976 if (auto *Def = Parent->getDefinition())
9977 Def->setInitMethod(true);
9978 }
9979 }
9980
9981 SetNestedNameSpecifier(*this, NewFD, D);
9982 isMemberSpecialization = false;
9983 isFunctionTemplateSpecialization = false;
9984 if (D.isInvalidType())
9985 NewFD->setInvalidDecl();
9986
9987 // Match up the template parameter lists with the scope specifier, then
9988 // determine whether we have a template or a template specialization.
9989 bool Invalid = false;
9990 TemplateIdAnnotation *TemplateId =
9992 ? D.getName().TemplateId
9993 : nullptr;
9994 TemplateParameterList *TemplateParams =
9997 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
9998 isMemberSpecialization, Invalid);
9999 if (TemplateParams) {
10000 // Check that we can declare a template here.
10001 if (CheckTemplateDeclScope(S, TemplateParams))
10002 NewFD->setInvalidDecl();
10003
10004 if (TemplateParams->size() > 0) {
10005 // This is a function template
10006
10007 // A destructor cannot be a template.
10008 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10009 Diag(NewFD->getLocation(), diag::err_destructor_template);
10010 NewFD->setInvalidDecl();
10011 // Function template with explicit template arguments.
10012 } else if (TemplateId) {
10013 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10014 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10015 NewFD->setInvalidDecl();
10016 }
10017
10018 // If we're adding a template to a dependent context, we may need to
10019 // rebuilding some of the types used within the template parameter list,
10020 // now that we know what the current instantiation is.
10021 if (DC->isDependentContext()) {
10022 ContextRAII SavedContext(*this, DC);
10024 Invalid = true;
10025 }
10026
10028 NewFD->getLocation(),
10029 Name, TemplateParams,
10030 NewFD);
10031 FunctionTemplate->setLexicalDeclContext(CurContext);
10033
10034 // For source fidelity, store the other template param lists.
10035 if (TemplateParamLists.size() > 1) {
10037 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10038 .drop_back(1));
10039 }
10040 } else {
10041 // This is a function template specialization.
10042 isFunctionTemplateSpecialization = true;
10043 // For source fidelity, store all the template param lists.
10044 if (TemplateParamLists.size() > 0)
10045 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10046
10047 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10048 if (isFriend) {
10049 // We want to remove the "template<>", found here.
10050 SourceRange RemoveRange = TemplateParams->getSourceRange();
10051
10052 // If we remove the template<> and the name is not a
10053 // template-id, we're actually silently creating a problem:
10054 // the friend declaration will refer to an untemplated decl,
10055 // and clearly the user wants a template specialization. So
10056 // we need to insert '<>' after the name.
10057 SourceLocation InsertLoc;
10059 InsertLoc = D.getName().getSourceRange().getEnd();
10060 InsertLoc = getLocForEndOfToken(InsertLoc);
10061 }
10062
10063 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10064 << Name << RemoveRange
10065 << FixItHint::CreateRemoval(RemoveRange)
10066 << FixItHint::CreateInsertion(InsertLoc, "<>");
10067 Invalid = true;
10068
10069 // Recover by faking up an empty template argument list.
10070 HasExplicitTemplateArgs = true;
10071 TemplateArgs.setLAngleLoc(InsertLoc);
10072 TemplateArgs.setRAngleLoc(InsertLoc);
10073 }
10074 }
10075 } else {
10076 // Check that we can declare a template here.
10077 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10078 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10079 NewFD->setInvalidDecl();
10080
10081 // All template param lists were matched against the scope specifier:
10082 // this is NOT (an explicit specialization of) a template.
10083 if (TemplateParamLists.size() > 0)
10084 // For source fidelity, store all the template param lists.
10085 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10086
10087 // "friend void foo<>(int);" is an implicit specialization decl.
10088 if (isFriend && TemplateId)
10089 isFunctionTemplateSpecialization = true;
10090 }
10091
10092 // If this is a function template specialization and the unqualified-id of
10093 // the declarator-id is a template-id, convert the template argument list
10094 // into our AST format and check for unexpanded packs.
10095 if (isFunctionTemplateSpecialization && TemplateId) {
10096 HasExplicitTemplateArgs = true;
10097
10098 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10099 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10100 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10101 TemplateId->NumArgs);
10102 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10103
10104 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10105 // declaration of a function template partial specialization? Should we
10106 // consider the unexpanded pack context to be a partial specialization?
10107 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10109 ArgLoc, isFriend ? UPPC_FriendDeclaration
10111 NewFD->setInvalidDecl();
10112 }
10113 }
10114
10115 if (Invalid) {
10116 NewFD->setInvalidDecl();
10117 if (FunctionTemplate)
10118 FunctionTemplate->setInvalidDecl();
10119 }
10120
10121 // C++ [dcl.fct.spec]p5:
10122 // The virtual specifier shall only be used in declarations of
10123 // nonstatic class member functions that appear within a
10124 // member-specification of a class declaration; see 10.3.
10125 //
10126 if (isVirtual && !NewFD->isInvalidDecl()) {
10127 if (!isVirtualOkay) {
10129 diag::err_virtual_non_function);
10130 } else if (!CurContext->isRecord()) {
10131 // 'virtual' was specified outside of the class.
10133 diag::err_virtual_out_of_class)
10135 } else if (NewFD->getDescribedFunctionTemplate()) {
10136 // C++ [temp.mem]p3:
10137 // A member function template shall not be virtual.
10139 diag::err_virtual_member_function_template)
10141 } else {
10142 // Okay: Add virtual to the method.
10143 NewFD->setVirtualAsWritten(true);
10144 }
10145
10146 if (getLangOpts().CPlusPlus14 &&
10147 NewFD->getReturnType()->isUndeducedType())
10148 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10149 }
10150
10151 // C++ [dcl.fct.spec]p3:
10152 // The inline specifier shall not appear on a block scope function
10153 // declaration.
10154 if (isInline && !NewFD->isInvalidDecl()) {
10156 // 'inline' is not allowed on block scope function declaration.
10158 diag::err_inline_declaration_block_scope) << Name
10160 }
10161 }
10162
10163 // C++ [dcl.fct.spec]p6:
10164 // The explicit specifier shall be used only in the declaration of a
10165 // constructor or conversion function within its class definition;
10166 // see 12.3.1 and 12.3.2.
10167 if (hasExplicit && !NewFD->isInvalidDecl() &&
10168 !isa<CXXDeductionGuideDecl>(NewFD)) {
10169 if (!CurContext->isRecord()) {
10170 // 'explicit' was specified outside of the class.
10172 diag::err_explicit_out_of_class)
10174 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10175 !isa<CXXConversionDecl>(NewFD)) {
10176 // 'explicit' was specified on a function that wasn't a constructor
10177 // or conversion function.
10179 diag::err_explicit_non_ctor_or_conv_function)
10181 }
10182 }
10183
10185 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10186 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10187 // are implicitly inline.
10188 NewFD->setImplicitlyInline();
10189
10190 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10191 // be either constructors or to return a literal type. Therefore,
10192 // destructors cannot be declared constexpr.
10193 if (isa<CXXDestructorDecl>(NewFD) &&
10195 ConstexprKind == ConstexprSpecKind::Consteval)) {
10196 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10197 << static_cast<int>(ConstexprKind);
10198 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10201 }
10202 // C++20 [dcl.constexpr]p2: An allocation function, or a
10203 // deallocation function shall not be declared with the consteval
10204 // specifier.
10205 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10206 (NewFD->getOverloadedOperator() == OO_New ||
10207 NewFD->getOverloadedOperator() == OO_Array_New ||
10208 NewFD->getOverloadedOperator() == OO_Delete ||
10209 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10211 diag::err_invalid_consteval_decl_kind)
10212 << NewFD;
10214 }
10215 }
10216
10217 // If __module_private__ was specified, mark the function accordingly.
10219 if (isFunctionTemplateSpecialization) {
10220 SourceLocation ModulePrivateLoc
10222 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10223 << 0
10224 << FixItHint::CreateRemoval(ModulePrivateLoc);
10225 } else {
10226 NewFD->setModulePrivate();
10227 if (FunctionTemplate)
10228 FunctionTemplate->setModulePrivate();
10229 }
10230 }
10231
10232 if (isFriend) {
10233 if (FunctionTemplate) {
10234 FunctionTemplate->setObjectOfFriendDecl();
10235 FunctionTemplate->setAccess(AS_public);
10236 }
10237 NewFD->setObjectOfFriendDecl();
10238 NewFD->setAccess(AS_public);
10239 }
10240
10241 // If a function is defined as defaulted or deleted, mark it as such now.
10242 // We'll do the relevant checks on defaulted / deleted functions later.
10243 switch (D.getFunctionDefinitionKind()) {
10246 break;
10247
10249 NewFD->setDefaulted();
10250 break;
10251
10253 NewFD->setDeletedAsWritten();
10254 break;
10255 }
10256
10257 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10258 D.isFunctionDefinition() && !isInline) {
10259 // Pre C++20 [class.mfct]p2:
10260 // A member function may be defined (8.4) in its class definition, in
10261 // which case it is an inline member function (7.1.2)
10262 // Post C++20 [class.mfct]p1:
10263 // If a member function is attached to the global module and is defined
10264 // in its class definition, it is inline.
10265 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10266 }
10267
10268 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
10269 !CurContext->isRecord()) {
10270 // C++ [class.static]p1:
10271 // A data or function member of a class may be declared static
10272 // in a class definition, in which case it is a static member of
10273 // the class.
10274
10275 // Complain about the 'static' specifier if it's on an out-of-line
10276 // member function definition.
10277
10278 // MSVC permits the use of a 'static' storage specifier on an out-of-line
10279 // member function template declaration and class member template
10280 // declaration (MSVC versions before 2015), warn about this.
10282 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10283 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10284 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
10285 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
10287 }
10288
10289 // C++11 [except.spec]p15:
10290 // A deallocation function with no exception-specification is treated
10291 // as if it were specified with noexcept(true).
10292 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10293 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10294 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10295 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10297 FPT->getReturnType(), FPT->getParamTypes(),
10299
10300 // C++20 [dcl.inline]/7
10301 // If an inline function or variable that is attached to a named module
10302 // is declared in a definition domain, it shall be defined in that
10303 // domain.
10304 // So, if the current declaration does not have a definition, we must
10305 // check at the end of the TU (or when the PMF starts) to see that we
10306 // have a definition at that point.
10307 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10308 NewFD->hasOwningModule() && NewFD->getOwningModule()->isNamedModule()) {
10309 PendingInlineFuncDecls.insert(NewFD);
10310 }
10311 }
10312
10313 // Filter out previous declarations that don't match the scope.
10316 isMemberSpecialization ||
10317 isFunctionTemplateSpecialization);
10318
10319 // Handle GNU asm-label extension (encoded as an attribute).
10320 if (Expr *E = (Expr*) D.getAsmLabel()) {
10321 // The parser guarantees this is a string.
10322 StringLiteral *SE = cast<StringLiteral>(E);
10323 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10324 /*IsLiteralLabel=*/true,
10325 SE->getStrTokenLoc(0)));
10326 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10327 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10329 if (I != ExtnameUndeclaredIdentifiers.end()) {
10330 if (isDeclExternC(NewFD)) {
10331 NewFD->addAttr(I->second);
10333 } else
10334 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10335 << /*Variable*/0 << NewFD;
10336 }
10337 }
10338
10339 // Copy the parameter declarations from the declarator D to the function
10340 // declaration NewFD, if they are available. First scavenge them into Params.
10342 unsigned FTIIdx;
10343 if (D.isFunctionDeclarator(FTIIdx)) {
10345
10346 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10347 // function that takes no arguments, not a function that takes a
10348 // single void argument.
10349 // We let through "const void" here because Sema::GetTypeForDeclarator
10350 // already checks for that case.
10351 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10352 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10353 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10354 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10355 Param->setDeclContext(NewFD);
10356 Params.push_back(Param);
10357
10358 if (Param->isInvalidDecl())
10359 NewFD->setInvalidDecl();
10360 }
10361 }
10362
10363 if (!getLangOpts().CPlusPlus) {
10364 // In C, find all the tag declarations from the prototype and move them
10365 // into the function DeclContext. Remove them from the surrounding tag
10366 // injection context of the function, which is typically but not always
10367 // the TU.
10368 DeclContext *PrototypeTagContext =
10370 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10371 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10372
10373 // We don't want to reparent enumerators. Look at their parent enum
10374 // instead.
10375 if (!TD) {
10376 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10377 TD = cast<EnumDecl>(ECD->getDeclContext());
10378 }
10379 if (!TD)
10380 continue;
10381 DeclContext *TagDC = TD->getLexicalDeclContext();
10382 if (!TagDC->containsDecl(TD))
10383 continue;
10384 TagDC->removeDecl(TD);
10385 TD->setDeclContext(NewFD);
10386 NewFD->addDecl(TD);
10387
10388 // Preserve the lexical DeclContext if it is not the surrounding tag
10389 // injection context of the FD. In this example, the semantic context of
10390 // E will be f and the lexical context will be S, while both the
10391 // semantic and lexical contexts of S will be f:
10392 // void f(struct S { enum E { a } f; } s);
10393 if (TagDC != PrototypeTagContext)
10394 TD->setLexicalDeclContext(TagDC);
10395 }
10396 }
10397 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10398 // When we're declaring a function with a typedef, typeof, etc as in the
10399 // following example, we'll need to synthesize (unnamed)
10400 // parameters for use in the declaration.
10401 //
10402 // @code
10403 // typedef void fn(int);
10404 // fn f;
10405 // @endcode
10406
10407 // Synthesize a parameter for each argument type.
10408 for (const auto &AI : FT->param_types()) {
10409 ParmVarDecl *Param =
10411 Param->setScopeInfo(0, Params.size());
10412 Params.push_back(Param);
10413 }
10414 } else {
10415 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10416 "Should not need args for typedef of non-prototype fn");
10417 }
10418
10419 // Finally, we know we have the right number of parameters, install them.
10420 NewFD->setParams(Params);
10421
10423 NewFD->addAttr(
10424 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10425
10426 // Functions returning a variably modified type violate C99 6.7.5.2p2
10427 // because all functions have linkage.
10428 if (!NewFD->isInvalidDecl() &&
10430 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10431 NewFD->setInvalidDecl();
10432 }
10433
10434 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10436 !NewFD->hasAttr<SectionAttr>())
10437 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10440
10441 // Apply an implicit SectionAttr if #pragma code_seg is active.
10442 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10443 !NewFD->hasAttr<SectionAttr>()) {
10444 NewFD->addAttr(SectionAttr::CreateImplicit(
10445 Context, CodeSegStack.CurrentValue->getString(),
10446 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10447 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10450 NewFD))
10451 NewFD->dropAttr<SectionAttr>();
10452 }
10453
10454 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10455 // active.
10457 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10458 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10460
10461 // Apply an implicit CodeSegAttr from class declspec or
10462 // apply an implicit SectionAttr from #pragma code_seg if active.
10463 if (!NewFD->hasAttr<CodeSegAttr>()) {
10465 D.isFunctionDefinition())) {
10466 NewFD->addAttr(SAttr);
10467 }
10468 }
10469
10470 // Handle attributes.
10471 ProcessDeclAttributes(S, NewFD, D);
10472 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10473 if (NewTVA && !NewTVA->isDefaultVersion() &&
10474 !Context.getTargetInfo().hasFeature("fmv")) {
10475 // Don't add to scope fmv functions declarations if fmv disabled
10476 AddToScope = false;
10477 return NewFD;
10478 }
10479
10480 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10481 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10482 // type.
10483 //
10484 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10485 // type declaration will generate a compilation error.
10486 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10487 if (AddressSpace != LangAS::Default) {
10488 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10489 NewFD->setInvalidDecl();
10490 }
10491 }
10492
10493 if (!getLangOpts().CPlusPlus) {
10494 // Perform semantic checking on the function declaration.
10495 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10496 CheckMain(NewFD, D.getDeclSpec());
10497
10498 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10499 CheckMSVCRTEntryPoint(NewFD);
10500
10501 if (!NewFD->isInvalidDecl())
10503 isMemberSpecialization,
10505 else if (!Previous.empty())
10506 // Recover gracefully from an invalid redeclaration.
10507 D.setRedeclaration(true);
10508 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10509 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10510 "previous declaration set still overloaded");
10511
10512 // Diagnose no-prototype function declarations with calling conventions that
10513 // don't support variadic calls. Only do this in C and do it after merging
10514 // possibly prototyped redeclarations.
10515 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10516 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10517 CallingConv CC = FT->getExtInfo().getCC();
10518 if (!supportsVariadicCall(CC)) {
10519 // Windows system headers sometimes accidentally use stdcall without
10520 // (void) parameters, so we relax this to a warning.
10521 int DiagID =
10522 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10523 Diag(NewFD->getLocation(), DiagID)
10525 }
10526 }
10527
10533 } else {
10534 // C++11 [replacement.functions]p3:
10535 // The program's definitions shall not be specified as inline.
10536 //
10537 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10538 //
10539 // Suppress the diagnostic if the function is __attribute__((used)), since
10540 // that forces an external definition to be emitted.
10541 if (D.getDeclSpec().isInlineSpecified() &&
10543 !NewFD->hasAttr<UsedAttr>())
10545 diag::ext_operator_new_delete_declared_inline)
10546 << NewFD->getDeclName();
10547
10548 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10549 // C++20 [dcl.decl.general]p4:
10550 // The optional requires-clause in an init-declarator or
10551 // member-declarator shall be present only if the declarator declares a
10552 // templated function.
10553 //
10554 // C++20 [temp.pre]p8:
10555 // An entity is templated if it is
10556 // - a template,
10557 // - an entity defined or created in a templated entity,
10558 // - a member of a templated entity,
10559 // - an enumerator for an enumeration that is a templated entity, or
10560 // - the closure type of a lambda-expression appearing in the
10561 // declaration of a templated entity.
10562 //
10563 // [Note 6: A local class, a local or block variable, or a friend
10564 // function defined in a templated entity is a templated entity.
10565 // — end note]
10566 //
10567 // A templated function is a function template or a function that is
10568 // templated. A templated class is a class template or a class that is
10569 // templated. A templated variable is a variable template or a variable
10570 // that is templated.
10571 if (!FunctionTemplate) {
10572 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10573 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10574 // An explicit specialization shall not have a trailing
10575 // requires-clause unless it declares a function template.
10576 //
10577 // Since a friend function template specialization cannot be
10578 // definition, and since a non-template friend declaration with a
10579 // trailing requires-clause must be a definition, we diagnose
10580 // friend function template specializations with trailing
10581 // requires-clauses on the same path as explicit specializations
10582 // even though they aren't necessarily prohibited by the same
10583 // language rule.
10584 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10585 << isFriend;
10586 } else if (isFriend && NewFD->isTemplated() &&
10587 !D.isFunctionDefinition()) {
10588 // C++ [temp.friend]p9:
10589 // A non-template friend declaration with a requires-clause shall be
10590 // a definition.
10591 Diag(NewFD->getBeginLoc(),
10592 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10593 NewFD->setInvalidDecl();
10594 } else if (!NewFD->isTemplated() ||
10595 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10596 Diag(TRC->getBeginLoc(),
10597 diag::err_constrained_non_templated_function);
10598 }
10599 }
10600 }
10601
10602 // We do not add HD attributes to specializations here because
10603 // they may have different constexpr-ness compared to their
10604 // templates and, after maybeAddHostDeviceAttrs() is applied,
10605 // may end up with different effective targets. Instead, a
10606 // specialization inherits its target attributes from its template
10607 // in the CheckFunctionTemplateSpecialization() call below.
10608 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10610
10611 // Handle explict specializations of function templates
10612 // and friend function declarations with an explicit
10613 // template argument list.
10614 if (isFunctionTemplateSpecialization) {
10615 bool isDependentSpecialization = false;
10616 if (isFriend) {
10617 // For friend function specializations, this is a dependent
10618 // specialization if its semantic context is dependent, its
10619 // type is dependent, or if its template-id is dependent.
10620 isDependentSpecialization =
10621 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10622 (HasExplicitTemplateArgs &&
10625 TemplateArgs.arguments()));
10626 assert((!isDependentSpecialization ||
10627 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10628 "dependent friend function specialization without template "
10629 "args");
10630 } else {
10631 // For class-scope explicit specializations of function templates,
10632 // if the lexical context is dependent, then the specialization
10633 // is dependent.
10634 isDependentSpecialization =
10636 }
10637
10638 TemplateArgumentListInfo *ExplicitTemplateArgs =
10639 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10640 if (isDependentSpecialization) {
10641 // If it's a dependent specialization, it may not be possible
10642 // to determine the primary template (for explicit specializations)
10643 // or befriended declaration (for friends) until the enclosing
10644 // template is instantiated. In such cases, we store the declarations
10645 // found by name lookup and defer resolution until instantiation.
10647 NewFD, ExplicitTemplateArgs, Previous))
10648 NewFD->setInvalidDecl();
10649 } else if (!NewFD->isInvalidDecl()) {
10650 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10651 Previous))
10652 NewFD->setInvalidDecl();
10653 }
10654
10655 // C++ [dcl.stc]p1:
10656 // A storage-class-specifier shall not be specified in an explicit
10657 // specialization (14.7.3)
10658 // FIXME: We should be checking this for dependent specializations.
10661 if (Info && SC != SC_None) {
10662 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10663 Diag(NewFD->getLocation(),
10664 diag::err_explicit_specialization_inconsistent_storage_class)
10665 << SC
10668
10669 else
10670 Diag(NewFD->getLocation(),
10671 diag::ext_explicit_specialization_storage_class)
10674 }
10675 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10677 NewFD->setInvalidDecl();
10678 }
10679
10680 // Perform semantic checking on the function declaration.
10681 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10682 CheckMain(NewFD, D.getDeclSpec());
10683
10684 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10685 CheckMSVCRTEntryPoint(NewFD);
10686
10687 if (!NewFD->isInvalidDecl())
10689 isMemberSpecialization,
10691 else if (!Previous.empty())
10692 // Recover gracefully from an invalid redeclaration.
10693 D.setRedeclaration(true);
10694
10695 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10696 !D.isRedeclaration() ||
10697 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10698 "previous declaration set still overloaded");
10699
10700 NamedDecl *PrincipalDecl = (FunctionTemplate
10701 ? cast<NamedDecl>(FunctionTemplate)
10702 : NewFD);
10703
10704 if (isFriend && NewFD->getPreviousDecl()) {
10705 AccessSpecifier Access = AS_public;
10706 if (!NewFD->isInvalidDecl())
10707 Access = NewFD->getPreviousDecl()->getAccess();
10708
10709 NewFD->setAccess(Access);
10710 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10711 }
10712
10713 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10715 PrincipalDecl->setNonMemberOperator();
10716
10717 // If we have a function template, check the template parameter
10718 // list. This will check and merge default template arguments.
10719 if (FunctionTemplate) {
10720 FunctionTemplateDecl *PrevTemplate =
10721 FunctionTemplate->getPreviousDecl();
10722 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10723 PrevTemplate ? PrevTemplate->getTemplateParameters()
10724 : nullptr,
10729 : (D.getCXXScopeSpec().isSet() &&
10730 DC && DC->isRecord() &&
10731 DC->isDependentContext())
10734 }
10735
10736 if (NewFD->isInvalidDecl()) {
10737 // Ignore all the rest of this.
10738 } else if (!D.isRedeclaration()) {
10739 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10740 AddToScope };
10741 // Fake up an access specifier if it's supposed to be a class member.
10742 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10743 NewFD->setAccess(AS_public);
10744
10745 // Qualified decls generally require a previous declaration.
10746 if (D.getCXXScopeSpec().isSet()) {
10747 // ...with the major exception of templated-scope or
10748 // dependent-scope friend declarations.
10749
10750 // TODO: we currently also suppress this check in dependent
10751 // contexts because (1) the parameter depth will be off when
10752 // matching friend templates and (2) we might actually be
10753 // selecting a friend based on a dependent factor. But there
10754 // are situations where these conditions don't apply and we
10755 // can actually do this check immediately.
10756 //
10757 // Unless the scope is dependent, it's always an error if qualified
10758 // redeclaration lookup found nothing at all. Diagnose that now;
10759 // nothing will diagnose that error later.
10760 if (isFriend &&
10762 (!Previous.empty() && CurContext->isDependentContext()))) {
10763 // ignore these
10764 } else if (NewFD->isCPUDispatchMultiVersion() ||
10765 NewFD->isCPUSpecificMultiVersion()) {
10766 // ignore this, we allow the redeclaration behavior here to create new
10767 // versions of the function.
10768 } else {
10769 // The user tried to provide an out-of-line definition for a
10770 // function that is a member of a class or namespace, but there
10771 // was no such member function declared (C++ [class.mfct]p2,
10772 // C++ [namespace.memdef]p2). For example:
10773 //
10774 // class X {
10775 // void f() const;
10776 // };
10777 //
10778 // void X::f() { } // ill-formed
10779 //
10780 // Complain about this problem, and attempt to suggest close
10781 // matches (e.g., those that differ only in cv-qualifiers and
10782 // whether the parameter types are references).
10783
10785 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10786 AddToScope = ExtraArgs.AddToScope;
10787 return Result;
10788 }
10789 }
10790
10791 // Unqualified local friend declarations are required to resolve
10792 // to something.
10793 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10795 *this, Previous, NewFD, ExtraArgs, true, S)) {
10796 AddToScope = ExtraArgs.AddToScope;
10797 return Result;
10798 }
10799 }
10800 } else if (!D.isFunctionDefinition() &&
10801 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10802 !isFriend && !isFunctionTemplateSpecialization &&
10803 !isMemberSpecialization) {
10804 // An out-of-line member function declaration must also be a
10805 // definition (C++ [class.mfct]p2).
10806 // Note that this is not the case for explicit specializations of
10807 // function templates or member functions of class templates, per
10808 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10809 // extension for compatibility with old SWIG code which likes to
10810 // generate them.
10811 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10812 << D.getCXXScopeSpec().getRange();
10813 }
10814 }
10815
10816 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10817 // Any top level function could potentially be specified as an entry.
10818 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10819 HLSL().ActOnTopLevelFunction(NewFD);
10820
10821 if (NewFD->hasAttr<HLSLShaderAttr>())
10822 HLSL().CheckEntryPoint(NewFD);
10823 }
10824
10825 // If this is the first declaration of a library builtin function, add
10826 // attributes as appropriate.
10827 if (!D.isRedeclaration()) {
10828 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10829 if (unsigned BuiltinID = II->getBuiltinID()) {
10830 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10831 if (!InStdNamespace &&
10833 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10834 // Validate the type matches unless this builtin is specified as
10835 // matching regardless of its declared type.
10836 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10837 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10838 } else {
10840 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10841 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10842
10843 if (!Error && !BuiltinType.isNull() &&
10845 NewFD->getType(), BuiltinType))
10846 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10847 }
10848 }
10849 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10850 isStdBuiltin(Context, NewFD, BuiltinID)) {
10851 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10852 }
10853 }
10854 }
10855 }
10856
10857 ProcessPragmaWeak(S, NewFD);
10858 checkAttributesAfterMerging(*this, *NewFD);
10859
10861
10862 if (NewFD->hasAttr<OverloadableAttr>() &&
10863 !NewFD->getType()->getAs<FunctionProtoType>()) {
10864 Diag(NewFD->getLocation(),
10865 diag::err_attribute_overloadable_no_prototype)
10866 << NewFD;
10867 NewFD->dropAttr<OverloadableAttr>();
10868 }
10869
10870 // If there's a #pragma GCC visibility in scope, and this isn't a class
10871 // member, set the visibility of this function.
10872 if (!DC->isRecord() && NewFD->isExternallyVisible())
10874
10875 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10876 // marking the function.
10877 AddCFAuditedAttribute(NewFD);
10878
10879 // If this is a function definition, check if we have to apply any
10880 // attributes (i.e. optnone and no_builtin) due to a pragma.
10881 if (D.isFunctionDefinition()) {
10882 AddRangeBasedOptnone(NewFD);
10884 AddSectionMSAllocText(NewFD);
10886 }
10887
10888 // If this is the first declaration of an extern C variable, update
10889 // the map of such variables.
10890 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10891 isIncompleteDeclExternC(*this, NewFD))
10893
10894 // Set this FunctionDecl's range up to the right paren.
10895 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10896
10897 if (D.isRedeclaration() && !Previous.empty()) {
10898 NamedDecl *Prev = Previous.getRepresentativeDecl();
10899 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10900 isMemberSpecialization ||
10901 isFunctionTemplateSpecialization,
10903 }
10904
10905 if (getLangOpts().CUDA) {
10906 IdentifierInfo *II = NewFD->getIdentifier();
10907 if (II && II->isStr(CUDA().getConfigureFuncName()) &&
10908 !NewFD->isInvalidDecl() &&
10911 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10914 }
10915
10916 // Variadic functions, other than a *declaration* of printf, are not allowed
10917 // in device-side CUDA code, unless someone passed
10918 // -fcuda-allow-variadic-functions.
10919 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10920 (NewFD->hasAttr<CUDADeviceAttr>() ||
10921 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10922 !(II && II->isStr("printf") && NewFD->isExternC() &&
10923 !D.isFunctionDefinition())) {
10924 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10925 }
10926 }
10927
10929
10930
10931
10932 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10933 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10934 if (SC == SC_Static) {
10935 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10936 D.setInvalidType();
10937 }
10938
10939 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10940 if (!NewFD->getReturnType()->isVoidType()) {
10941 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10942 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10943 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10944 : FixItHint());
10945 D.setInvalidType();
10946 }
10947
10949 for (auto *Param : NewFD->parameters())
10950 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10951
10952 if (getLangOpts().OpenCLCPlusPlus) {
10953 if (DC->isRecord()) {
10954 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10955 D.setInvalidType();
10956 }
10957 if (FunctionTemplate) {
10958 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10959 D.setInvalidType();
10960 }
10961 }
10962 }
10963
10964 if (getLangOpts().CPlusPlus) {
10965 // Precalculate whether this is a friend function template with a constraint
10966 // that depends on an enclosing template, per [temp.friend]p9.
10967 if (isFriend && FunctionTemplate &&
10970
10971 // C++ [temp.friend]p9:
10972 // A friend function template with a constraint that depends on a
10973 // template parameter from an enclosing template shall be a definition.
10974 if (!D.isFunctionDefinition()) {
10975 Diag(NewFD->getBeginLoc(),
10976 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10977 NewFD->setInvalidDecl();
10978 }
10979 }
10980
10981 if (FunctionTemplate) {
10982 if (NewFD->isInvalidDecl())
10983 FunctionTemplate->setInvalidDecl();
10984 return FunctionTemplate;
10985 }
10986
10987 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10989 }
10990
10991 for (const ParmVarDecl *Param : NewFD->parameters()) {
10992 QualType PT = Param->getType();
10993
10994 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10995 // types.
10996 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10997 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10998 QualType ElemTy = PipeTy->getElementType();
10999 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
11000 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
11001 D.setInvalidType();
11002 }
11003 }
11004 }
11005 // WebAssembly tables can't be used as function parameters.
11006 if (Context.getTargetInfo().getTriple().isWasm()) {
11008 Diag(Param->getTypeSpecStartLoc(),
11009 diag::err_wasm_table_as_function_parameter);
11010 D.setInvalidType();
11011 }
11012 }
11013 }
11014
11015 // Diagnose availability attributes. Availability cannot be used on functions
11016 // that are run during load/unload.
11017 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11018 if (NewFD->hasAttr<ConstructorAttr>()) {
11019 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11020 << 1;
11021 NewFD->dropAttr<AvailabilityAttr>();
11022 }
11023 if (NewFD->hasAttr<DestructorAttr>()) {
11024 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11025 << 2;
11026 NewFD->dropAttr<AvailabilityAttr>();
11027 }
11028 }
11029
11030 // Diagnose no_builtin attribute on function declaration that are not a
11031 // definition.
11032 // FIXME: We should really be doing this in
11033 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11034 // the FunctionDecl and at this point of the code
11035 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11036 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11037 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11038 switch (D.getFunctionDefinitionKind()) {
11041 Diag(NBA->getLocation(),
11042 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11043 << NBA->getSpelling();
11044 break;
11046 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11047 << NBA->getSpelling();
11048 break;
11050 break;
11051 }
11052
11053 return NewFD;
11054}
11055
11056/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11057/// when __declspec(code_seg) "is applied to a class, all member functions of
11058/// the class and nested classes -- this includes compiler-generated special
11059/// member functions -- are put in the specified segment."
11060/// The actual behavior is a little more complicated. The Microsoft compiler
11061/// won't check outer classes if there is an active value from #pragma code_seg.
11062/// The CodeSeg is always applied from the direct parent but only from outer
11063/// classes when the #pragma code_seg stack is empty. See:
11064/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11065/// available since MS has removed the page.
11067 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11068 if (!Method)
11069 return nullptr;
11070 const CXXRecordDecl *Parent = Method->getParent();
11071 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11072 Attr *NewAttr = SAttr->clone(S.getASTContext());
11073 NewAttr->setImplicit(true);
11074 return NewAttr;
11075 }
11076
11077 // The Microsoft compiler won't check outer classes for the CodeSeg
11078 // when the #pragma code_seg stack is active.
11079 if (S.CodeSegStack.CurrentValue)
11080 return nullptr;
11081
11082 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11083 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11084 Attr *NewAttr = SAttr->clone(S.getASTContext());
11085 NewAttr->setImplicit(true);
11086 return NewAttr;
11087 }
11088 }
11089 return nullptr;
11090}
11091
11092/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
11093/// containing class. Otherwise it will return implicit SectionAttr if the
11094/// function is a definition and there is an active value on CodeSegStack
11095/// (from the current #pragma code-seg value).
11096///
11097/// \param FD Function being declared.
11098/// \param IsDefinition Whether it is a definition or just a declaration.
11099/// \returns A CodeSegAttr or SectionAttr to apply to the function or
11100/// nullptr if no attribute should be added.
11102 bool IsDefinition) {
11103 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11104 return A;
11105 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11106 CodeSegStack.CurrentValue)
11107 return SectionAttr::CreateImplicit(
11108 getASTContext(), CodeSegStack.CurrentValue->getString(),
11109 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11110 return nullptr;
11111}
11112
11113/// Determines if we can perform a correct type check for \p D as a
11114/// redeclaration of \p PrevDecl. If not, we can generally still perform a
11115/// best-effort check.
11116///
11117/// \param NewD The new declaration.
11118/// \param OldD The old declaration.
11119/// \param NewT The portion of the type of the new declaration to check.
11120/// \param OldT The portion of the type of the old declaration to check.
11122 QualType NewT, QualType OldT) {
11124 return true;
11125
11126 // For dependently-typed local extern declarations and friends, we can't
11127 // perform a correct type check in general until instantiation:
11128 //
11129 // int f();
11130 // template<typename T> void g() { T f(); }
11131 //
11132 // (valid if g() is only instantiated with T = int).
11133 if (NewT->isDependentType() &&
11134 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11135 return false;
11136
11137 // Similarly, if the previous declaration was a dependent local extern
11138 // declaration, we don't really know its type yet.
11139 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11140 return false;
11141
11142 return true;
11143}
11144
11145/// Checks if the new declaration declared in dependent context must be
11146/// put in the same redeclaration chain as the specified declaration.
11147///
11148/// \param D Declaration that is checked.
11149/// \param PrevDecl Previous declaration found with proper lookup method for the
11150/// same declaration name.
11151/// \returns True if D must be added to the redeclaration chain which PrevDecl
11152/// belongs to.
11153///
11156 return true;
11157
11158 // Don't chain dependent friend function definitions until instantiation, to
11159 // permit cases like
11160 //
11161 // void func();
11162 // template<typename T> class C1 { friend void func() {} };
11163 // template<typename T> class C2 { friend void func() {} };
11164 //
11165 // ... which is valid if only one of C1 and C2 is ever instantiated.
11166 //
11167 // FIXME: This need only apply to function definitions. For now, we proxy
11168 // this by checking for a file-scope function. We do not want this to apply
11169 // to friend declarations nominating member functions, because that gets in
11170 // the way of access checks.
11172 return false;
11173
11174 auto *VD = dyn_cast<ValueDecl>(D);
11175 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11176 return !VD || !PrevVD ||
11177 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11178 PrevVD->getType());
11179}
11180
11181/// Check the target or target_version attribute of the function for
11182/// MultiVersion validity.
11183///
11184/// Returns true if there was an error, false otherwise.
11185static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11186 const auto *TA = FD->getAttr<TargetAttr>();
11187 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11188 assert(
11189 (TA || TVA) &&
11190 "MultiVersion candidate requires a target or target_version attribute");
11192 enum ErrType { Feature = 0, Architecture = 1 };
11193
11194 if (TA) {
11195 ParsedTargetAttr ParseInfo =
11196 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11197 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11198 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11199 << Architecture << ParseInfo.CPU;
11200 return true;
11201 }
11202 for (const auto &Feat : ParseInfo.Features) {
11203 auto BareFeat = StringRef{Feat}.substr(1);
11204 if (Feat[0] == '-') {
11205 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11206 << Feature << ("no-" + BareFeat).str();
11207 return true;
11208 }
11209
11210 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11211 !TargetInfo.isValidFeatureName(BareFeat)) {
11212 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11213 << Feature << BareFeat;
11214 return true;
11215 }
11216 }
11217 }
11218
11219 if (TVA) {
11221 TVA->getFeatures(Feats);
11222 for (const auto &Feat : Feats) {
11223 if (!TargetInfo.validateCpuSupports(Feat)) {
11224 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11225 << Feature << Feat;
11226 return true;
11227 }
11228 }
11229 }
11230 return false;
11231}
11232
11233// Provide a white-list of attributes that are allowed to be combined with
11234// multiversion functions.
11236 MultiVersionKind MVKind) {
11237 // Note: this list/diagnosis must match the list in
11238 // checkMultiversionAttributesAllSame.
11239 switch (Kind) {
11240 default:
11241 return false;
11242 case attr::Used:
11243 return MVKind == MultiVersionKind::Target;
11244 case attr::NonNull:
11245 case attr::NoThrow:
11246 return true;
11247 }
11248}
11249
11251 const FunctionDecl *FD,
11252 const FunctionDecl *CausedFD,
11253 MultiVersionKind MVKind) {
11254 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11255 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11256 << static_cast<unsigned>(MVKind) << A;
11257 if (CausedFD)
11258 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11259 return true;
11260 };
11261
11262 for (const Attr *A : FD->attrs()) {
11263 switch (A->getKind()) {
11264 case attr::CPUDispatch:
11265 case attr::CPUSpecific:
11266 if (MVKind != MultiVersionKind::CPUDispatch &&
11268 return Diagnose(S, A);
11269 break;
11270 case attr::Target:
11271 if (MVKind != MultiVersionKind::Target)
11272 return Diagnose(S, A);
11273 break;
11274 case attr::TargetVersion:
11275 if (MVKind != MultiVersionKind::TargetVersion &&
11277 return Diagnose(S, A);
11278 break;
11279 case attr::TargetClones:
11280 if (MVKind != MultiVersionKind::TargetClones &&
11282 return Diagnose(S, A);
11283 break;
11284 default:
11285 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11286 return Diagnose(S, A);
11287 break;
11288 }
11289 }
11290 return false;
11291}
11292
11294 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11295 const PartialDiagnostic &NoProtoDiagID,
11296 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11297 const PartialDiagnosticAt &NoSupportDiagIDAt,
11298 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11299 bool ConstexprSupported, bool CLinkageMayDiffer) {
11300 enum DoesntSupport {
11301 FuncTemplates = 0,
11302 VirtFuncs = 1,
11303 DeducedReturn = 2,
11304 Constructors = 3,
11305 Destructors = 4,
11306 DeletedFuncs = 5,
11307 DefaultedFuncs = 6,
11308 ConstexprFuncs = 7,
11309 ConstevalFuncs = 8,
11310 Lambda = 9,
11311 };
11312 enum Different {
11313 CallingConv = 0,
11314 ReturnType = 1,
11315 ConstexprSpec = 2,
11316 InlineSpec = 3,
11317 Linkage = 4,
11318 LanguageLinkage = 5,
11319 };
11320
11321 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11322 !OldFD->getType()->getAs<FunctionProtoType>()) {
11323 Diag(OldFD->getLocation(), NoProtoDiagID);
11324 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11325 return true;
11326 }
11327
11328 if (NoProtoDiagID.getDiagID() != 0 &&
11329 !NewFD->getType()->getAs<FunctionProtoType>())
11330 return Diag(NewFD->getLocation(), NoProtoDiagID);
11331
11332 if (!TemplatesSupported &&
11334 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11335 << FuncTemplates;
11336
11337 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11338 if (NewCXXFD->isVirtual())
11339 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11340 << VirtFuncs;
11341
11342 if (isa<CXXConstructorDecl>(NewCXXFD))
11343 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11344 << Constructors;
11345
11346 if (isa<CXXDestructorDecl>(NewCXXFD))
11347 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11348 << Destructors;
11349 }
11350
11351 if (NewFD->isDeleted())
11352 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11353 << DeletedFuncs;
11354
11355 if (NewFD->isDefaulted())
11356 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11357 << DefaultedFuncs;
11358
11359 if (!ConstexprSupported && NewFD->isConstexpr())
11360 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11361 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11362
11363 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11364 const auto *NewType = cast<FunctionType>(NewQType);
11365 QualType NewReturnType = NewType->getReturnType();
11366
11367 if (NewReturnType->isUndeducedType())
11368 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11369 << DeducedReturn;
11370
11371 // Ensure the return type is identical.
11372 if (OldFD) {
11373 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11374 const auto *OldType = cast<FunctionType>(OldQType);
11375 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11376 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11377
11378 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11379 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11380
11381 QualType OldReturnType = OldType->getReturnType();
11382
11383 if (OldReturnType != NewReturnType)
11384 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11385
11386 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11387 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11388
11389 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11390 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11391
11392 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11393 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11394
11395 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11396 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11397
11399 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11400 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11401 return true;
11402 }
11403 return false;
11404}
11405
11407 const FunctionDecl *NewFD,
11408 bool CausesMV,
11409 MultiVersionKind MVKind) {
11411 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11412 if (OldFD)
11413 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11414 return true;
11415 }
11416
11417 bool IsCPUSpecificCPUDispatchMVKind =
11420
11421 if (CausesMV && OldFD &&
11422 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11423 return true;
11424
11425 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11426 return true;
11427
11428 // Only allow transition to MultiVersion if it hasn't been used.
11429 if (OldFD && CausesMV && OldFD->isUsed(false))
11430 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11431
11433 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11435 S.PDiag(diag::note_multiversioning_caused_here)),
11437 S.PDiag(diag::err_multiversion_doesnt_support)
11438 << static_cast<unsigned>(MVKind)),
11440 S.PDiag(diag::err_multiversion_diff)),
11441 /*TemplatesSupported=*/false,
11442 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11443 /*CLinkageMayDiffer=*/false);
11444}
11445
11446/// Check the validity of a multiversion function declaration that is the
11447/// first of its kind. Also sets the multiversion'ness' of the function itself.
11448///
11449/// This sets NewFD->isInvalidDecl() to true if there was an error.
11450///
11451/// Returns true if there was an error, false otherwise.
11454 assert(MVKind != MultiVersionKind::None &&
11455 "Function lacks multiversion attribute");
11456 const auto *TA = FD->getAttr<TargetAttr>();
11457 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11458 // The target attribute only causes MV if this declaration is the default,
11459 // otherwise it is treated as a normal function.
11460 if (TA && !TA->isDefaultVersion())
11461 return false;
11462
11463 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11464 FD->setInvalidDecl();
11465 return true;
11466 }
11467
11468 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11469 FD->setInvalidDecl();
11470 return true;
11471 }
11472
11473 FD->setIsMultiVersion();
11474 return false;
11475}
11476
11478 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11480 return true;
11481 }
11482
11483 return false;
11484}
11485
11487 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64())
11488 return;
11489
11490 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11491 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11492
11493 if (MVKindTo == MultiVersionKind::None &&
11494 (MVKindFrom == MultiVersionKind::TargetVersion ||
11495 MVKindFrom == MultiVersionKind::TargetClones)) {
11496 To->setIsMultiVersion();
11497 To->addAttr(TargetVersionAttr::CreateImplicit(
11498 To->getASTContext(), "default", To->getSourceRange()));
11499 }
11500}
11501
11503 FunctionDecl *NewFD,
11504 bool &Redeclaration,
11505 NamedDecl *&OldDecl,
11507 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11508
11509 // The definitions should be allowed in any order. If we have discovered
11510 // a new target version and the preceeding was the default, then add the
11511 // corresponding attribute to it.
11512 patchDefaultTargetVersion(NewFD, OldFD);
11513
11514 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11515 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11516 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11517 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11518 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11519 // to change, this is a simple redeclaration.
11520 if ((NewTA && !NewTA->isDefaultVersion() &&
11521 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11522 (NewTVA && !NewTVA->isDefaultVersion() &&
11523 (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11524 return false;
11525
11526 // Otherwise, this decl causes MultiVersioning.
11527 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11530 NewFD->setInvalidDecl();
11531 return true;
11532 }
11533
11534 if (CheckMultiVersionValue(S, NewFD)) {
11535 NewFD->setInvalidDecl();
11536 return true;
11537 }
11538
11539 // If this is 'default', permit the forward declaration.
11540 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11541 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11542 Redeclaration = true;
11543 OldDecl = OldFD;
11544 OldFD->setIsMultiVersion();
11545 NewFD->setIsMultiVersion();
11546 return false;
11547 }
11548
11549 if (CheckMultiVersionValue(S, OldFD)) {
11550 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11551 NewFD->setInvalidDecl();
11552 return true;
11553 }
11554
11555 if (NewTA) {
11556 ParsedTargetAttr OldParsed =
11558 OldTA->getFeaturesStr());
11559 llvm::sort(OldParsed.Features);
11560 ParsedTargetAttr NewParsed =
11562 NewTA->getFeaturesStr());
11563 // Sort order doesn't matter, it just needs to be consistent.
11564 llvm::sort(NewParsed.Features);
11565 if (OldParsed == NewParsed) {
11566 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11567 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11568 NewFD->setInvalidDecl();
11569 return true;
11570 }
11571 }
11572
11573 if (NewTVA) {
11575 OldTVA->getFeatures(Feats);
11576 llvm::sort(Feats);
11578 NewTVA->getFeatures(NewFeats);
11579 llvm::sort(NewFeats);
11580
11581 if (Feats == NewFeats) {
11582 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11583 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11584 NewFD->setInvalidDecl();
11585 return true;
11586 }
11587 }
11588
11589 for (const auto *FD : OldFD->redecls()) {
11590 const auto *CurTA = FD->getAttr<TargetAttr>();
11591 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11592 // We allow forward declarations before ANY multiversioning attributes, but
11593 // nothing after the fact.
11595 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11596 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11597 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11598 << (NewTA ? 0 : 2);
11599 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11600 NewFD->setInvalidDecl();
11601 return true;
11602 }
11603 }
11604
11605 OldFD->setIsMultiVersion();
11606 NewFD->setIsMultiVersion();
11607 Redeclaration = false;
11608 OldDecl = nullptr;
11609 Previous.clear();
11610 return false;
11611}
11612
11614 MultiVersionKind OldKind = Old->getMultiVersionKind();
11615 MultiVersionKind NewKind = New->getMultiVersionKind();
11616
11617 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11618 NewKind == MultiVersionKind::None)
11619 return true;
11620
11621 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11622 switch (OldKind) {
11624 return NewKind == MultiVersionKind::TargetClones;
11626 return NewKind == MultiVersionKind::TargetVersion;
11627 default:
11628 return false;
11629 }
11630 } else {
11631 switch (OldKind) {
11633 return NewKind == MultiVersionKind::CPUSpecific;
11635 return NewKind == MultiVersionKind::CPUDispatch;
11636 default:
11637 return false;
11638 }
11639 }
11640}
11641
11642/// Check the validity of a new function declaration being added to an existing
11643/// multiversioned declaration collection.
11645 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11646 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11647 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11649
11650 // Disallow mixing of multiversioning types.
11651 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11652 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11653 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11654 NewFD->setInvalidDecl();
11655 return true;
11656 }
11657
11658 // Add the default target_version attribute if it's missing.
11659 patchDefaultTargetVersion(OldFD, NewFD);
11660 patchDefaultTargetVersion(NewFD, OldFD);
11661
11662 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11663 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11664 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11665 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11666
11667 ParsedTargetAttr NewParsed;
11668 if (NewTA) {
11670 NewTA->getFeaturesStr());
11671 llvm::sort(NewParsed.Features);
11672 }
11674 if (NewTVA) {
11675 NewTVA->getFeatures(NewFeats);
11676 llvm::sort(NewFeats);
11677 }
11678
11679 bool UseMemberUsingDeclRules =
11680 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11681
11682 bool MayNeedOverloadableChecks =
11684
11685 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11686 // of a previous member of the MultiVersion set.
11687 for (NamedDecl *ND : Previous) {
11688 FunctionDecl *CurFD = ND->getAsFunction();
11689 if (!CurFD || CurFD->isInvalidDecl())
11690 continue;
11691 if (MayNeedOverloadableChecks &&
11692 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11693 continue;
11694
11695 switch (NewMVKind) {
11697 assert(OldMVKind == MultiVersionKind::TargetClones &&
11698 "Only target_clones can be omitted in subsequent declarations");
11699 break;
11701 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11702 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11703 NewFD->setIsMultiVersion();
11704 Redeclaration = true;
11705 OldDecl = ND;
11706 return false;
11707 }
11708
11709 ParsedTargetAttr CurParsed =
11711 CurTA->getFeaturesStr());
11712 llvm::sort(CurParsed.Features);
11713 if (CurParsed == NewParsed) {
11714 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11715 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11716 NewFD->setInvalidDecl();
11717 return true;
11718 }
11719 break;
11720 }
11722 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11723 if (CurTVA->getName() == NewTVA->getName()) {
11724 NewFD->setIsMultiVersion();
11725 Redeclaration = true;
11726 OldDecl = ND;
11727 return false;
11728 }
11730 CurTVA->getFeatures(CurFeats);
11731 llvm::sort(CurFeats);
11732
11733 if (CurFeats == NewFeats) {
11734 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11735 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11736 NewFD->setInvalidDecl();
11737 return true;
11738 }
11739 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11740 // Default
11741 if (NewFeats.empty())
11742 break;
11743
11744 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11746 CurClones->getFeatures(CurFeats, I);
11747 llvm::sort(CurFeats);
11748
11749 if (CurFeats == NewFeats) {
11750 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11751 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11752 NewFD->setInvalidDecl();
11753 return true;
11754 }
11755 }
11756 }
11757 break;
11758 }
11760 assert(NewClones && "MultiVersionKind does not match attribute type");
11761 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11762 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11763 !std::equal(CurClones->featuresStrs_begin(),
11764 CurClones->featuresStrs_end(),
11765 NewClones->featuresStrs_begin())) {
11766 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11767 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11768 NewFD->setInvalidDecl();
11769 return true;
11770 }
11771 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11773 CurTVA->getFeatures(CurFeats);
11774 llvm::sort(CurFeats);
11775
11776 // Default
11777 if (CurFeats.empty())
11778 break;
11779
11780 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11781 NewFeats.clear();
11782 NewClones->getFeatures(NewFeats, I);
11783 llvm::sort(NewFeats);
11784
11785 if (CurFeats == NewFeats) {
11786 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11787 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11788 NewFD->setInvalidDecl();
11789 return true;
11790 }
11791 }
11792 break;
11793 }
11794 Redeclaration = true;
11795 OldDecl = CurFD;
11796 NewFD->setIsMultiVersion();
11797 return false;
11798 }
11801 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11802 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11803 // Handle CPUDispatch/CPUSpecific versions.
11804 // Only 1 CPUDispatch function is allowed, this will make it go through
11805 // the redeclaration errors.
11806 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11807 CurFD->hasAttr<CPUDispatchAttr>()) {
11808 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11809 std::equal(
11810 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11811 NewCPUDisp->cpus_begin(),
11812 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11813 return Cur->getName() == New->getName();
11814 })) {
11815 NewFD->setIsMultiVersion();
11816 Redeclaration = true;
11817 OldDecl = ND;
11818 return false;
11819 }
11820
11821 // If the declarations don't match, this is an error condition.
11822 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11823 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11824 NewFD->setInvalidDecl();
11825 return true;
11826 }
11827 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11828 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11829 std::equal(
11830 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11831 NewCPUSpec->cpus_begin(),
11832 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11833 return Cur->getName() == New->getName();
11834 })) {
11835 NewFD->setIsMultiVersion();
11836 Redeclaration = true;
11837 OldDecl = ND;
11838 return false;
11839 }
11840
11841 // Only 1 version of CPUSpecific is allowed for each CPU.
11842 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11843 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11844 if (CurII == NewII) {
11845 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11846 << NewII;
11847 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11848 NewFD->setInvalidDecl();
11849 return true;
11850 }
11851 }
11852 }
11853 }
11854 break;
11855 }
11856 }
11857 }
11858
11859 // Else, this is simply a non-redecl case. Checking the 'value' is only
11860 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11861 // handled in the attribute adding step.
11862 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11863 NewMVKind == MultiVersionKind::Target) &&
11864 CheckMultiVersionValue(S, NewFD)) {
11865 NewFD->setInvalidDecl();
11866 return true;
11867 }
11868
11869 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11870 !OldFD->isMultiVersion(), NewMVKind)) {
11871 NewFD->setInvalidDecl();
11872 return true;
11873 }
11874
11875 // Permit forward declarations in the case where these two are compatible.
11876 if (!OldFD->isMultiVersion()) {
11877 OldFD->setIsMultiVersion();
11878 NewFD->setIsMultiVersion();
11879 Redeclaration = true;
11880 OldDecl = OldFD;
11881 return false;
11882 }
11883
11884 NewFD->setIsMultiVersion();
11885 Redeclaration = false;
11886 OldDecl = nullptr;
11887 Previous.clear();
11888 return false;
11889}
11890
11891/// Check the validity of a mulitversion function declaration.
11892/// Also sets the multiversion'ness' of the function itself.
11893///
11894/// This sets NewFD->isInvalidDecl() to true if there was an error.
11895///
11896/// Returns true if there was an error, false otherwise.
11898 bool &Redeclaration, NamedDecl *&OldDecl,
11900 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11901 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11902 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11903 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11904 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11905 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11906
11907 // Main isn't allowed to become a multiversion function, however it IS
11908 // permitted to have 'main' be marked with the 'target' optimization hint,
11909 // for 'target_version' only default is allowed.
11910 if (NewFD->isMain()) {
11911 if (MVKind != MultiVersionKind::None &&
11912 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11913 !(MVKind == MultiVersionKind::TargetVersion &&
11914 NewTVA->isDefaultVersion())) {
11915 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11916 NewFD->setInvalidDecl();
11917 return true;
11918 }
11919 return false;
11920 }
11921
11922 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
11923
11924 // Target attribute on AArch64 is not used for multiversioning
11925 if (NewTA && T.isAArch64())
11926 return false;
11927
11928 // Target attribute on RISCV is not used for multiversioning
11929 if (NewTA && T.isRISCV())
11930 return false;
11931
11932 if (!OldDecl || !OldDecl->getAsFunction() ||
11933 OldDecl->getDeclContext()->getRedeclContext() !=
11934 NewFD->getDeclContext()->getRedeclContext()) {
11935 // If there's no previous declaration, AND this isn't attempting to cause
11936 // multiversioning, this isn't an error condition.
11937 if (MVKind == MultiVersionKind::None)
11938 return false;
11939 return CheckMultiVersionFirstFunction(S, NewFD);
11940 }
11941
11942 FunctionDecl *OldFD = OldDecl->getAsFunction();
11943
11944 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11945 if (NewTVA || !OldFD->getAttr<TargetVersionAttr>())
11946 return false;
11947 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
11948 // Multiversion declaration doesn't have prototype.
11949 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
11950 NewFD->setInvalidDecl();
11951 } else {
11952 // No "target_version" attribute is equivalent to "default" attribute.
11953 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11954 S.Context, "default", NewFD->getSourceRange()));
11955 NewFD->setIsMultiVersion();
11956 OldFD->setIsMultiVersion();
11957 OldDecl = OldFD;
11958 Redeclaration = true;
11959 }
11960 return true;
11961 }
11962
11963 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11964 // for target_clones and target_version.
11965 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11968 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11970 NewFD->setInvalidDecl();
11971 return true;
11972 }
11973
11974 if (!OldFD->isMultiVersion()) {
11975 switch (MVKind) {
11978 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11979 OldDecl, Previous);
11981 if (OldFD->isUsed(false)) {
11982 NewFD->setInvalidDecl();
11983 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11984 }
11985 OldFD->setIsMultiVersion();
11986 break;
11987
11991 break;
11992 }
11993 }
11994
11995 // At this point, we have a multiversion function decl (in OldFD) AND an
11996 // appropriate attribute in the current function decl. Resolve that these are
11997 // still compatible with previous declarations.
11998 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11999 NewCPUSpec, NewClones, Redeclaration,
12000 OldDecl, Previous);
12001}
12002
12004 bool IsPure = NewFD->hasAttr<PureAttr>();
12005 bool IsConst = NewFD->hasAttr<ConstAttr>();
12006
12007 // If there are no pure or const attributes, there's nothing to check.
12008 if (!IsPure && !IsConst)
12009 return;
12010
12011 // If the function is marked both pure and const, we retain the const
12012 // attribute because it makes stronger guarantees than the pure attribute, and
12013 // we drop the pure attribute explicitly to prevent later confusion about
12014 // semantics.
12015 if (IsPure && IsConst) {
12016 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12017 NewFD->dropAttrs<PureAttr>();
12018 }
12019
12020 // Constructors and destructors are functions which return void, so are
12021 // handled here as well.
12022 if (NewFD->getReturnType()->isVoidType()) {
12023 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12024 << IsConst;
12025 NewFD->dropAttrs<PureAttr, ConstAttr>();
12026 }
12027}
12028
12029/// Perform semantic checking of a new function declaration.
12030///
12031/// Performs semantic analysis of the new function declaration
12032/// NewFD. This routine performs all semantic checking that does not
12033/// require the actual declarator involved in the declaration, and is
12034/// used both for the declaration of functions as they are parsed
12035/// (called via ActOnDeclarator) and for the declaration of functions
12036/// that have been instantiated via C++ template instantiation (called
12037/// via InstantiateDecl).
12038///
12039/// \param IsMemberSpecialization whether this new function declaration is
12040/// a member specialization (that replaces any definition provided by the
12041/// previous declaration).
12042///
12043/// This sets NewFD->isInvalidDecl() to true if there was an error.
12044///
12045/// \returns true if the function declaration is a redeclaration.
12048 bool IsMemberSpecialization,
12049 bool DeclIsDefn) {
12050 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12051 "Variably modified return types are not handled here");
12052
12053 // Determine whether the type of this function should be merged with
12054 // a previous visible declaration. This never happens for functions in C++,
12055 // and always happens in C if the previous declaration was visible.
12056 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12057 !Previous.isShadowed();
12058
12059 bool Redeclaration = false;
12060 NamedDecl *OldDecl = nullptr;
12061 bool MayNeedOverloadableChecks = false;
12062
12063 // Merge or overload the declaration with an existing declaration of
12064 // the same name, if appropriate.
12065 if (!Previous.empty()) {
12066 // Determine whether NewFD is an overload of PrevDecl or
12067 // a declaration that requires merging. If it's an overload,
12068 // there's no more work to do here; we'll just add the new
12069 // function to the scope.
12071 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12072 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12073 Redeclaration = true;
12074 OldDecl = Candidate;
12075 }
12076 } else {
12077 MayNeedOverloadableChecks = true;
12078 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12079 /*NewIsUsingDecl*/ false)) {
12080 case Ovl_Match:
12081 Redeclaration = true;
12082 break;
12083
12084 case Ovl_NonFunction:
12085 Redeclaration = true;
12086 break;
12087
12088 case Ovl_Overload:
12089 Redeclaration = false;
12090 break;
12091 }
12092 }
12093 }
12094
12095 // Check for a previous extern "C" declaration with this name.
12096 if (!Redeclaration &&
12098 if (!Previous.empty()) {
12099 // This is an extern "C" declaration with the same name as a previous
12100 // declaration, and thus redeclares that entity...
12101 Redeclaration = true;
12102 OldDecl = Previous.getFoundDecl();
12103 MergeTypeWithPrevious = false;
12104
12105 // ... except in the presence of __attribute__((overloadable)).
12106 if (OldDecl->hasAttr<OverloadableAttr>() ||
12107 NewFD->hasAttr<OverloadableAttr>()) {
12108 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12109 MayNeedOverloadableChecks = true;
12110 Redeclaration = false;
12111 OldDecl = nullptr;
12112 }
12113 }
12114 }
12115 }
12116
12117 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12118 return Redeclaration;
12119
12120 // PPC MMA non-pointer types are not allowed as function return types.
12121 if (Context.getTargetInfo().getTriple().isPPC64() &&
12122 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12123 NewFD->setInvalidDecl();
12124 }
12125
12126 CheckConstPureAttributesUsage(*this, NewFD);
12127
12128 // C++ [dcl.spec.auto.general]p12:
12129 // Return type deduction for a templated function with a placeholder in its
12130 // declared type occurs when the definition is instantiated even if the
12131 // function body contains a return statement with a non-type-dependent
12132 // operand.
12133 //
12134 // C++ [temp.dep.expr]p3:
12135 // An id-expression is type-dependent if it is a template-id that is not a
12136 // concept-id and is dependent; or if its terminal name is:
12137 // - [...]
12138 // - associated by name lookup with one or more declarations of member
12139 // functions of a class that is the current instantiation declared with a
12140 // return type that contains a placeholder type,
12141 // - [...]
12142 //
12143 // If this is a templated function with a placeholder in its return type,
12144 // make the placeholder type dependent since it won't be deduced until the
12145 // definition is instantiated. We do this here because it needs to happen
12146 // for implicitly instantiated member functions/member function templates.
12147 if (getLangOpts().CPlusPlus14 &&
12148 (NewFD->isDependentContext() &&
12149 NewFD->getReturnType()->isUndeducedType())) {
12150 const FunctionProtoType *FPT =
12151 NewFD->getType()->castAs<FunctionProtoType>();
12152 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12153 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12154 FPT->getExtProtoInfo()));
12155 }
12156
12157 // C++11 [dcl.constexpr]p8:
12158 // A constexpr specifier for a non-static member function that is not
12159 // a constructor declares that member function to be const.
12160 //
12161 // This needs to be delayed until we know whether this is an out-of-line
12162 // definition of a static member function.
12163 //
12164 // This rule is not present in C++1y, so we produce a backwards
12165 // compatibility warning whenever it happens in C++11.
12166 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12167 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12168 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12169 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
12170 CXXMethodDecl *OldMD = nullptr;
12171 if (OldDecl)
12172 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12173 if (!OldMD || !OldMD->isStatic()) {
12174 const FunctionProtoType *FPT =
12177 EPI.TypeQuals.addConst();
12179 FPT->getParamTypes(), EPI));
12180
12181 // Warn that we did this, if we're not performing template instantiation.
12182 // In that case, we'll have warned already when the template was defined.
12183 if (!inTemplateInstantiation()) {
12184 SourceLocation AddConstLoc;
12187 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12188
12189 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12190 << FixItHint::CreateInsertion(AddConstLoc, " const");
12191 }
12192 }
12193 }
12194
12195 if (Redeclaration) {
12196 // NewFD and OldDecl represent declarations that need to be
12197 // merged.
12198 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12199 DeclIsDefn)) {
12200 NewFD->setInvalidDecl();
12201 return Redeclaration;
12202 }
12203
12204 Previous.clear();
12205 Previous.addDecl(OldDecl);
12206
12207 if (FunctionTemplateDecl *OldTemplateDecl =
12208 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12209 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12210 FunctionTemplateDecl *NewTemplateDecl
12212 assert(NewTemplateDecl && "Template/non-template mismatch");
12213
12214 // The call to MergeFunctionDecl above may have created some state in
12215 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12216 // can add it as a redeclaration.
12217 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12218
12219 NewFD->setPreviousDeclaration(OldFD);
12220 if (NewFD->isCXXClassMember()) {
12221 NewFD->setAccess(OldTemplateDecl->getAccess());
12222 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12223 }
12224
12225 // If this is an explicit specialization of a member that is a function
12226 // template, mark it as a member specialization.
12227 if (IsMemberSpecialization &&
12228 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12229 NewTemplateDecl->setMemberSpecialization();
12230 assert(OldTemplateDecl->isMemberSpecialization());
12231 // Explicit specializations of a member template do not inherit deleted
12232 // status from the parent member template that they are specializing.
12233 if (OldFD->isDeleted()) {
12234 // FIXME: This assert will not hold in the presence of modules.
12235 assert(OldFD->getCanonicalDecl() == OldFD);
12236 // FIXME: We need an update record for this AST mutation.
12237 OldFD->setDeletedAsWritten(false);
12238 }
12239 }
12240
12241 } else {
12242 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12243 auto *OldFD = cast<FunctionDecl>(OldDecl);
12244 // This needs to happen first so that 'inline' propagates.
12245 NewFD->setPreviousDeclaration(OldFD);
12246 if (NewFD->isCXXClassMember())
12247 NewFD->setAccess(OldFD->getAccess());
12248 }
12249 }
12250 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12251 !NewFD->getAttr<OverloadableAttr>()) {
12252 assert((Previous.empty() ||
12253 llvm::any_of(Previous,
12254 [](const NamedDecl *ND) {
12255 return ND->hasAttr<OverloadableAttr>();
12256 })) &&
12257 "Non-redecls shouldn't happen without overloadable present");
12258
12259 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12260 const auto *FD = dyn_cast<FunctionDecl>(ND);
12261 return FD && !FD->hasAttr<OverloadableAttr>();
12262 });
12263
12264 if (OtherUnmarkedIter != Previous.end()) {
12265 Diag(NewFD->getLocation(),
12266 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12267 Diag((*OtherUnmarkedIter)->getLocation(),
12268 diag::note_attribute_overloadable_prev_overload)
12269 << false;
12270
12271 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12272 }
12273 }
12274
12275 if (LangOpts.OpenMP)
12277
12278 // Semantic checking for this function declaration (in isolation).
12279
12280 if (getLangOpts().CPlusPlus) {
12281 // C++-specific checks.
12282 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12283 CheckConstructor(Constructor);
12284 } else if (CXXDestructorDecl *Destructor =
12285 dyn_cast<CXXDestructorDecl>(NewFD)) {
12286 // We check here for invalid destructor names.
12287 // If we have a friend destructor declaration that is dependent, we can't
12288 // diagnose right away because cases like this are still valid:
12289 // template <class T> struct A { friend T::X::~Y(); };
12290 // struct B { struct Y { ~Y(); }; using X = Y; };
12291 // template struct A<B>;
12293 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12294 CXXRecordDecl *Record = Destructor->getParent();
12296
12298 Context.getCanonicalType(ClassType));
12299 if (NewFD->getDeclName() != Name) {
12300 Diag(NewFD->getLocation(), diag::err_destructor_name);
12301 NewFD->setInvalidDecl();
12302 return Redeclaration;
12303 }
12304 }
12305 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12306 if (auto *TD = Guide->getDescribedFunctionTemplate())
12308
12309 // A deduction guide is not on the list of entities that can be
12310 // explicitly specialized.
12311 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12312 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12313 << /*explicit specialization*/ 1;
12314 }
12315
12316 // Find any virtual functions that this function overrides.
12317 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12318 if (!Method->isFunctionTemplateSpecialization() &&
12319 !Method->getDescribedFunctionTemplate() &&
12320 Method->isCanonicalDecl()) {
12321 AddOverriddenMethods(Method->getParent(), Method);
12322 }
12323 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12324 // C++2a [class.virtual]p6
12325 // A virtual method shall not have a requires-clause.
12327 diag::err_constrained_virtual_method);
12328
12329 if (Method->isStatic())
12331 }
12332
12333 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12334 ActOnConversionDeclarator(Conversion);
12335
12336 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12337 if (NewFD->isOverloadedOperator() &&
12339 NewFD->setInvalidDecl();
12340 return Redeclaration;
12341 }
12342
12343 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12344 if (NewFD->getLiteralIdentifier() &&
12346 NewFD->setInvalidDecl();
12347 return Redeclaration;
12348 }
12349
12350 // In C++, check default arguments now that we have merged decls. Unless
12351 // the lexical context is the class, because in this case this is done
12352 // during delayed parsing anyway.
12353 if (!CurContext->isRecord())
12355
12356 // If this function is declared as being extern "C", then check to see if
12357 // the function returns a UDT (class, struct, or union type) that is not C
12358 // compatible, and if it does, warn the user.
12359 // But, issue any diagnostic on the first declaration only.
12360 if (Previous.empty() && NewFD->isExternC()) {
12361 QualType R = NewFD->getReturnType();
12362 if (R->isIncompleteType() && !R->isVoidType())
12363 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12364 << NewFD << R;
12365 else if (!R.isPODType(Context) && !R->isVoidType() &&
12367 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12368 }
12369
12370 // C++1z [dcl.fct]p6:
12371 // [...] whether the function has a non-throwing exception-specification
12372 // [is] part of the function type
12373 //
12374 // This results in an ABI break between C++14 and C++17 for functions whose
12375 // declared type includes an exception-specification in a parameter or
12376 // return type. (Exception specifications on the function itself are OK in
12377 // most cases, and exception specifications are not permitted in most other
12378 // contexts where they could make it into a mangling.)
12379 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12380 auto HasNoexcept = [&](QualType T) -> bool {
12381 // Strip off declarator chunks that could be between us and a function
12382 // type. We don't need to look far, exception specifications are very
12383 // restricted prior to C++17.
12384 if (auto *RT = T->getAs<ReferenceType>())
12385 T = RT->getPointeeType();
12386 else if (T->isAnyPointerType())
12387 T = T->getPointeeType();
12388 else if (auto *MPT = T->getAs<MemberPointerType>())
12389 T = MPT->getPointeeType();
12390 if (auto *FPT = T->getAs<FunctionProtoType>())
12391 if (FPT->isNothrow())
12392 return true;
12393 return false;
12394 };
12395
12396 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12397 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12398 for (QualType T : FPT->param_types())
12399 AnyNoexcept |= HasNoexcept(T);
12400 if (AnyNoexcept)
12401 Diag(NewFD->getLocation(),
12402 diag::warn_cxx17_compat_exception_spec_in_signature)
12403 << NewFD;
12404 }
12405
12406 if (!Redeclaration && LangOpts.CUDA)
12408 }
12409
12410 // Check if the function definition uses any AArch64 SME features without
12411 // having the '+sme' feature enabled and warn user if sme locally streaming
12412 // function returns or uses arguments with VL-based types.
12413 if (DeclIsDefn) {
12414 const auto *Attr = NewFD->getAttr<ArmNewAttr>();
12415 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12416 bool UsesZA = Attr && Attr->isNewZA();
12417 bool UsesZT0 = Attr && Attr->isNewZT0();
12418
12419 if (NewFD->hasAttr<ArmLocallyStreamingAttr>()) {
12420 if (NewFD->getReturnType()->isSizelessVectorType())
12421 Diag(NewFD->getLocation(),
12422 diag::warn_sme_locally_streaming_has_vl_args_returns)
12423 << /*IsArg=*/false;
12424 if (llvm::any_of(NewFD->parameters(), [](ParmVarDecl *P) {
12425 return P->getOriginalType()->isSizelessVectorType();
12426 }))
12427 Diag(NewFD->getLocation(),
12428 diag::warn_sme_locally_streaming_has_vl_args_returns)
12429 << /*IsArg=*/true;
12430 }
12431 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12432 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12433 UsesSM |=
12439 }
12440
12441 if (UsesSM || UsesZA) {
12442 llvm::StringMap<bool> FeatureMap;
12443 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12444 if (!FeatureMap.contains("sme")) {
12445 if (UsesSM)
12446 Diag(NewFD->getLocation(),
12447 diag::err_sme_definition_using_sm_in_non_sme_target);
12448 else
12449 Diag(NewFD->getLocation(),
12450 diag::err_sme_definition_using_za_in_non_sme_target);
12451 }
12452 }
12453 if (UsesZT0) {
12454 llvm::StringMap<bool> FeatureMap;
12455 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12456 if (!FeatureMap.contains("sme2")) {
12457 Diag(NewFD->getLocation(),
12458 diag::err_sme_definition_using_zt0_in_non_sme2_target);
12459 }
12460 }
12461 }
12462
12463 return Redeclaration;
12464}
12465
12467 // C++11 [basic.start.main]p3:
12468 // A program that [...] declares main to be inline, static or
12469 // constexpr is ill-formed.
12470 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12471 // appear in a declaration of main.
12472 // static main is not an error under C99, but we should warn about it.
12473 // We accept _Noreturn main as an extension.
12474 if (FD->getStorageClass() == SC_Static)
12476 ? diag::err_static_main : diag::warn_static_main)
12478 if (FD->isInlineSpecified())
12479 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12481 if (DS.isNoreturnSpecified()) {
12482 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12483 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12484 Diag(NoreturnLoc, diag::ext_noreturn_main);
12485 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12486 << FixItHint::CreateRemoval(NoreturnRange);
12487 }
12488 if (FD->isConstexpr()) {
12489 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12490 << FD->isConsteval()
12493 }
12494
12495 if (getLangOpts().OpenCL) {
12496 Diag(FD->getLocation(), diag::err_opencl_no_main)
12497 << FD->hasAttr<OpenCLKernelAttr>();
12498 FD->setInvalidDecl();
12499 return;
12500 }
12501
12502 // Functions named main in hlsl are default entries, but don't have specific
12503 // signatures they are required to conform to.
12504 if (getLangOpts().HLSL)
12505 return;
12506
12507 QualType T = FD->getType();
12508 assert(T->isFunctionType() && "function decl is not of function type");
12509 const FunctionType* FT = T->castAs<FunctionType>();
12510
12511 // Set default calling convention for main()
12512 if (FT->getCallConv() != CC_C) {
12514 FD->setType(QualType(FT, 0));
12516 }
12517
12518 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12519 // In C with GNU extensions we allow main() to have non-integer return
12520 // type, but we should warn about the extension, and we disable the
12521 // implicit-return-zero rule.
12522
12523 // GCC in C mode accepts qualified 'int'.
12525 FD->setHasImplicitReturnZero(true);
12526 else {
12527 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12528 SourceRange RTRange = FD->getReturnTypeSourceRange();
12529 if (RTRange.isValid())
12530 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12531 << FixItHint::CreateReplacement(RTRange, "int");
12532 }
12533 } else {
12534 // In C and C++, main magically returns 0 if you fall off the end;
12535 // set the flag which tells us that.
12536 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12537
12538 // All the standards say that main() should return 'int'.
12540 FD->setHasImplicitReturnZero(true);
12541 else {
12542 // Otherwise, this is just a flat-out error.
12543 SourceRange RTRange = FD->getReturnTypeSourceRange();
12544 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12545 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12546 : FixItHint());
12547 FD->setInvalidDecl(true);
12548 }
12549 }
12550
12551 // Treat protoless main() as nullary.
12552 if (isa<FunctionNoProtoType>(FT)) return;
12553
12554 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12555 unsigned nparams = FTP->getNumParams();
12556 assert(FD->getNumParams() == nparams);
12557
12558 bool HasExtraParameters = (nparams > 3);
12559
12560 if (FTP->isVariadic()) {
12561 Diag(FD->getLocation(), diag::ext_variadic_main);
12562 // FIXME: if we had information about the location of the ellipsis, we
12563 // could add a FixIt hint to remove it as a parameter.
12564 }
12565
12566 // Darwin passes an undocumented fourth argument of type char**. If
12567 // other platforms start sprouting these, the logic below will start
12568 // getting shifty.
12569 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12570 HasExtraParameters = false;
12571
12572 if (HasExtraParameters) {
12573 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12574 FD->setInvalidDecl(true);
12575 nparams = 3;
12576 }
12577
12578 // FIXME: a lot of the following diagnostics would be improved
12579 // if we had some location information about types.
12580
12581 QualType CharPP =
12583 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12584
12585 for (unsigned i = 0; i < nparams; ++i) {
12586 QualType AT = FTP->getParamType(i);
12587
12588 bool mismatch = true;
12589
12591 mismatch = false;
12592 else if (Expected[i] == CharPP) {
12593 // As an extension, the following forms are okay:
12594 // char const **
12595 // char const * const *
12596 // char * const *
12597
12599 const PointerType* PT;
12600 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12601 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12603 Context.CharTy)) {
12604 qs.removeConst();
12605 mismatch = !qs.empty();
12606 }
12607 }
12608
12609 if (mismatch) {
12610 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12611 // TODO: suggest replacing given type with expected type
12612 FD->setInvalidDecl(true);
12613 }
12614 }
12615
12616 if (nparams == 1 && !FD->isInvalidDecl()) {
12617 Diag(FD->getLocation(), diag::warn_main_one_arg);
12618 }
12619
12620 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12621 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12622 FD->setInvalidDecl();
12623 }
12624}
12625
12626static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12627
12628 // Default calling convention for main and wmain is __cdecl
12629 if (FD->getName() == "main" || FD->getName() == "wmain")
12630 return false;
12631
12632 // Default calling convention for MinGW is __cdecl
12633 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12634 if (T.isWindowsGNUEnvironment())
12635 return false;
12636
12637 // Default calling convention for WinMain, wWinMain and DllMain
12638 // is __stdcall on 32 bit Windows
12639 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12640 return true;
12641
12642 return false;
12643}
12644
12646 QualType T = FD->getType();
12647 assert(T->isFunctionType() && "function decl is not of function type");
12648 const FunctionType *FT = T->castAs<FunctionType>();
12649
12650 // Set an implicit return of 'zero' if the function can return some integral,
12651 // enumeration, pointer or nullptr type.
12655 // DllMain is exempt because a return value of zero means it failed.
12656 if (FD->getName() != "DllMain")
12657 FD->setHasImplicitReturnZero(true);
12658
12659 // Explicity specified calling conventions are applied to MSVC entry points
12660 if (!hasExplicitCallingConv(T)) {
12661 if (isDefaultStdCall(FD, *this)) {
12662 if (FT->getCallConv() != CC_X86StdCall) {
12665 FD->setType(QualType(FT, 0));
12666 }
12667 } else if (FT->getCallConv() != CC_C) {
12670 FD->setType(QualType(FT, 0));
12671 }
12672 }
12673
12674 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12675 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12676 FD->setInvalidDecl();
12677 }
12678}
12679
12681 // FIXME: Need strict checking. In C89, we need to check for
12682 // any assignment, increment, decrement, function-calls, or
12683 // commas outside of a sizeof. In C99, it's the same list,
12684 // except that the aforementioned are allowed in unevaluated
12685 // expressions. Everything else falls under the
12686 // "may accept other forms of constant expressions" exception.
12687 //
12688 // Regular C++ code will not end up here (exceptions: language extensions,
12689 // OpenCL C++ etc), so the constant expression rules there don't matter.
12690 if (Init->isValueDependent()) {
12691 assert(Init->containsErrors() &&
12692 "Dependent code should only occur in error-recovery path.");
12693 return true;
12694 }
12695 const Expr *Culprit;
12696 if (Init->isConstantInitializer(Context, false, &Culprit))
12697 return false;
12698 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12699 return true;
12700}
12701
12702namespace {
12703 // Visits an initialization expression to see if OrigDecl is evaluated in
12704 // its own initialization and throws a warning if it does.
12705 class SelfReferenceChecker
12706 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12707 Sema &S;
12708 Decl *OrigDecl;
12709 bool isRecordType;
12710 bool isPODType;
12711 bool isReferenceType;
12712
12713 bool isInitList;
12714 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12715
12716 public:
12718
12719 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12720 S(S), OrigDecl(OrigDecl) {
12721 isPODType = false;
12722 isRecordType = false;
12723 isReferenceType = false;
12724 isInitList = false;
12725 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12726 isPODType = VD->getType().isPODType(S.Context);
12727 isRecordType = VD->getType()->isRecordType();
12728 isReferenceType = VD->getType()->isReferenceType();
12729 }
12730 }
12731
12732 // For most expressions, just call the visitor. For initializer lists,
12733 // track the index of the field being initialized since fields are
12734 // initialized in order allowing use of previously initialized fields.
12735 void CheckExpr(Expr *E) {
12736 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12737 if (!InitList) {
12738 Visit(E);
12739 return;
12740 }
12741
12742 // Track and increment the index here.
12743 isInitList = true;
12744 InitFieldIndex.push_back(0);
12745 for (auto *Child : InitList->children()) {
12746 CheckExpr(cast<Expr>(Child));
12747 ++InitFieldIndex.back();
12748 }
12749 InitFieldIndex.pop_back();
12750 }
12751
12752 // Returns true if MemberExpr is checked and no further checking is needed.
12753 // Returns false if additional checking is required.
12754 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12756 Expr *Base = E;
12757 bool ReferenceField = false;
12758
12759 // Get the field members used.
12760 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12761 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12762 if (!FD)
12763 return false;
12764 Fields.push_back(FD);
12765 if (FD->getType()->isReferenceType())
12766 ReferenceField = true;
12767 Base = ME->getBase()->IgnoreParenImpCasts();
12768 }
12769
12770 // Keep checking only if the base Decl is the same.
12771 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12772 if (!DRE || DRE->getDecl() != OrigDecl)
12773 return false;
12774
12775 // A reference field can be bound to an unininitialized field.
12776 if (CheckReference && !ReferenceField)
12777 return true;
12778
12779 // Convert FieldDecls to their index number.
12780 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12781 for (const FieldDecl *I : llvm::reverse(Fields))
12782 UsedFieldIndex.push_back(I->getFieldIndex());
12783
12784 // See if a warning is needed by checking the first difference in index
12785 // numbers. If field being used has index less than the field being
12786 // initialized, then the use is safe.
12787 for (auto UsedIter = UsedFieldIndex.begin(),
12788 UsedEnd = UsedFieldIndex.end(),
12789 OrigIter = InitFieldIndex.begin(),
12790 OrigEnd = InitFieldIndex.end();
12791 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12792 if (*UsedIter < *OrigIter)
12793 return true;
12794 if (*UsedIter > *OrigIter)
12795 break;
12796 }
12797
12798 // TODO: Add a different warning which will print the field names.
12799 HandleDeclRefExpr(DRE);
12800 return true;
12801 }
12802
12803 // For most expressions, the cast is directly above the DeclRefExpr.
12804 // For conditional operators, the cast can be outside the conditional
12805 // operator if both expressions are DeclRefExpr's.
12806 void HandleValue(Expr *E) {
12807 E = E->IgnoreParens();
12808 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12809 HandleDeclRefExpr(DRE);
12810 return;
12811 }
12812
12813 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12814 Visit(CO->getCond());
12815 HandleValue(CO->getTrueExpr());
12816 HandleValue(CO->getFalseExpr());
12817 return;
12818 }
12819
12820 if (BinaryConditionalOperator *BCO =
12821 dyn_cast<BinaryConditionalOperator>(E)) {
12822 Visit(BCO->getCond());
12823 HandleValue(BCO->getFalseExpr());
12824 return;
12825 }
12826
12827 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12828 if (Expr *SE = OVE->getSourceExpr())
12829 HandleValue(SE);
12830 return;
12831 }
12832
12833 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12834 if (BO->getOpcode() == BO_Comma) {
12835 Visit(BO->getLHS());
12836 HandleValue(BO->getRHS());
12837 return;
12838 }
12839 }
12840
12841 if (isa<MemberExpr>(E)) {
12842 if (isInitList) {
12843 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12844 false /*CheckReference*/))
12845 return;
12846 }
12847
12849 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12850 // Check for static member variables and don't warn on them.
12851 if (!isa<FieldDecl>(ME->getMemberDecl()))
12852 return;
12853 Base = ME->getBase()->IgnoreParenImpCasts();
12854 }
12855 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12856 HandleDeclRefExpr(DRE);
12857 return;
12858 }
12859
12860 Visit(E);
12861 }
12862
12863 // Reference types not handled in HandleValue are handled here since all
12864 // uses of references are bad, not just r-value uses.
12865 void VisitDeclRefExpr(DeclRefExpr *E) {
12866 if (isReferenceType)
12867 HandleDeclRefExpr(E);
12868 }
12869
12870 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12871 if (E->getCastKind() == CK_LValueToRValue) {
12872 HandleValue(E->getSubExpr());
12873 return;
12874 }
12875
12876 Inherited::VisitImplicitCastExpr(E);
12877 }
12878
12879 void VisitMemberExpr(MemberExpr *E) {
12880 if (isInitList) {
12881 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12882 return;
12883 }
12884
12885 // Don't warn on arrays since they can be treated as pointers.
12886 if (E->getType()->canDecayToPointerType()) return;
12887
12888 // Warn when a non-static method call is followed by non-static member
12889 // field accesses, which is followed by a DeclRefExpr.
12890 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12891 bool Warn = (MD && !MD->isStatic());
12893 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12894 if (!isa<FieldDecl>(ME->getMemberDecl()))
12895 Warn = false;
12896 Base = ME->getBase()->IgnoreParenImpCasts();
12897 }
12898
12899 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12900 if (Warn)
12901 HandleDeclRefExpr(DRE);
12902 return;
12903 }
12904
12905 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12906 // Visit that expression.
12907 Visit(Base);
12908 }
12909
12910 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12911 Expr *Callee = E->getCallee();
12912
12913 if (isa<UnresolvedLookupExpr>(Callee))
12914 return Inherited::VisitCXXOperatorCallExpr(E);
12915
12916 Visit(Callee);
12917 for (auto Arg: E->arguments())
12918 HandleValue(Arg->IgnoreParenImpCasts());
12919 }
12920
12921 void VisitUnaryOperator(UnaryOperator *E) {
12922 // For POD record types, addresses of its own members are well-defined.
12923 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12924 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12925 if (!isPODType)
12926 HandleValue(E->getSubExpr());
12927 return;
12928 }
12929
12930 if (E->isIncrementDecrementOp()) {
12931 HandleValue(E->getSubExpr());
12932 return;
12933 }
12934
12935 Inherited::VisitUnaryOperator(E);
12936 }
12937
12938 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12939
12940 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12941 if (E->getConstructor()->isCopyConstructor()) {
12942 Expr *ArgExpr = E->getArg(0);
12943 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12944 if (ILE->getNumInits() == 1)
12945 ArgExpr = ILE->getInit(0);
12946 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12947 if (ICE->getCastKind() == CK_NoOp)
12948 ArgExpr = ICE->getSubExpr();
12949 HandleValue(ArgExpr);
12950 return;
12951 }
12952 Inherited::VisitCXXConstructExpr(E);
12953 }
12954
12955 void VisitCallExpr(CallExpr *E) {
12956 // Treat std::move as a use.
12957 if (E->isCallToStdMove()) {
12958 HandleValue(E->getArg(0));
12959 return;
12960 }
12961
12962 Inherited::VisitCallExpr(E);
12963 }
12964
12965 void VisitBinaryOperator(BinaryOperator *E) {
12966 if (E->isCompoundAssignmentOp()) {
12967 HandleValue(E->getLHS());
12968 Visit(E->getRHS());
12969 return;
12970 }
12971
12972 Inherited::VisitBinaryOperator(E);
12973 }
12974
12975 // A custom visitor for BinaryConditionalOperator is needed because the
12976 // regular visitor would check the condition and true expression separately
12977 // but both point to the same place giving duplicate diagnostics.
12978 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12979 Visit(E->getCond());
12980 Visit(E->getFalseExpr());
12981 }
12982
12983 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12984 Decl* ReferenceDecl = DRE->getDecl();
12985 if (OrigDecl != ReferenceDecl) return;
12986 unsigned diag;
12987 if (isReferenceType) {
12988 diag = diag::warn_uninit_self_reference_in_reference_init;
12989 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12990 diag = diag::warn_static_self_reference_in_init;
12991 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12992 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12993 DRE->getDecl()->getType()->isRecordType()) {
12994 diag = diag::warn_uninit_self_reference_in_init;
12995 } else {
12996 // Local variables will be handled by the CFG analysis.
12997 return;
12998 }
12999
13000 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13001 S.PDiag(diag)
13002 << DRE->getDecl() << OrigDecl->getLocation()
13003 << DRE->getSourceRange());
13004 }
13005 };
13006
13007 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13008 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13009 bool DirectInit) {
13010 // Parameters arguments are occassionially constructed with itself,
13011 // for instance, in recursive functions. Skip them.
13012 if (isa<ParmVarDecl>(OrigDecl))
13013 return;
13014
13015 E = E->IgnoreParens();
13016
13017 // Skip checking T a = a where T is not a record or reference type.
13018 // Doing so is a way to silence uninitialized warnings.
13019 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13020 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13021 if (ICE->getCastKind() == CK_LValueToRValue)
13022 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13023 if (DRE->getDecl() == OrigDecl)
13024 return;
13025
13026 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13027 }
13028} // end anonymous namespace
13029
13030namespace {
13031 // Simple wrapper to add the name of a variable or (if no variable is
13032 // available) a DeclarationName into a diagnostic.
13033 struct VarDeclOrName {
13034 VarDecl *VDecl;
13035 DeclarationName Name;
13036
13037 friend const Sema::SemaDiagnosticBuilder &
13038 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13039 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13040 }
13041 };
13042} // end anonymous namespace
13043
13046 TypeSourceInfo *TSI,
13047 SourceRange Range, bool DirectInit,
13048 Expr *Init) {
13049 bool IsInitCapture = !VDecl;
13050 assert((!VDecl || !VDecl->isInitCapture()) &&
13051 "init captures are expected to be deduced prior to initialization");
13052
13053 VarDeclOrName VN{VDecl, Name};
13054
13056 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13057
13058 // Diagnose auto array declarations in C23, unless it's a supported extension.
13059 if (getLangOpts().C23 && Type->isArrayType() &&
13060 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13061 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13062 << (int)Deduced->getContainedAutoType()->getKeyword()
13063 << /*in array decl*/ 23 << Range;
13064 return QualType();
13065 }
13066
13067 // C++11 [dcl.spec.auto]p3
13068 if (!Init) {
13069 assert(VDecl && "no init for init capture deduction?");
13070
13071 // Except for class argument deduction, and then for an initializing
13072 // declaration only, i.e. no static at class scope or extern.
13073 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
13074 VDecl->hasExternalStorage() ||
13075 VDecl->isStaticDataMember()) {
13076 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13077 << VDecl->getDeclName() << Type;
13078 return QualType();
13079 }
13080 }
13081
13082 ArrayRef<Expr*> DeduceInits;
13083 if (Init)
13084 DeduceInits = Init;
13085
13086 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13087 if (DirectInit && PL)
13088 DeduceInits = PL->exprs();
13089
13090 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
13091 assert(VDecl && "non-auto type for init capture deduction?");
13094 VDecl->getLocation(), DirectInit, Init);
13095 // FIXME: Initialization should not be taking a mutable list of inits.
13096 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
13097 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13098 InitsCopy);
13099 }
13100
13101 if (DirectInit) {
13102 if (auto *IL = dyn_cast<InitListExpr>(Init))
13103 DeduceInits = IL->inits();
13104 }
13105
13106 // Deduction only works if we have exactly one source expression.
13107 if (DeduceInits.empty()) {
13108 // It isn't possible to write this directly, but it is possible to
13109 // end up in this situation with "auto x(some_pack...);"
13110 Diag(Init->getBeginLoc(), IsInitCapture
13111 ? diag::err_init_capture_no_expression
13112 : diag::err_auto_var_init_no_expression)
13113 << VN << Type << Range;
13114 return QualType();
13115 }
13116
13117 if (DeduceInits.size() > 1) {
13118 Diag(DeduceInits[1]->getBeginLoc(),
13119 IsInitCapture ? diag::err_init_capture_multiple_expressions
13120 : diag::err_auto_var_init_multiple_expressions)
13121 << VN << Type << Range;
13122 return QualType();
13123 }
13124
13125 Expr *DeduceInit = DeduceInits[0];
13126 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13127 Diag(Init->getBeginLoc(), IsInitCapture
13128 ? diag::err_init_capture_paren_braces
13129 : diag::err_auto_var_init_paren_braces)
13130 << isa<InitListExpr>(Init) << VN << Type << Range;
13131 return QualType();
13132 }
13133
13134 // Expressions default to 'id' when we're in a debugger.
13135 bool DefaultedAnyToId = false;
13136 if (getLangOpts().DebuggerCastResultToId &&
13137 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13139 if (Result.isInvalid()) {
13140 return QualType();
13141 }
13142 Init = Result.get();
13143 DefaultedAnyToId = true;
13144 }
13145
13146 // C++ [dcl.decomp]p1:
13147 // If the assignment-expression [...] has array type A and no ref-qualifier
13148 // is present, e has type cv A
13149 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13151 DeduceInit->getType()->isConstantArrayType())
13152 return Context.getQualifiedType(DeduceInit->getType(),
13153 Type.getQualifiers());
13154
13156 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13158 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13161 if (!IsInitCapture)
13162 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13163 else if (isa<InitListExpr>(Init))
13164 Diag(Range.getBegin(),
13165 diag::err_init_capture_deduction_failure_from_init_list)
13166 << VN
13167 << (DeduceInit->getType().isNull() ? TSI->getType()
13168 : DeduceInit->getType())
13169 << DeduceInit->getSourceRange();
13170 else
13171 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13172 << VN << TSI->getType()
13173 << (DeduceInit->getType().isNull() ? TSI->getType()
13174 : DeduceInit->getType())
13175 << DeduceInit->getSourceRange();
13176 }
13177
13178 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13179 // 'id' instead of a specific object type prevents most of our usual
13180 // checks.
13181 // We only want to warn outside of template instantiations, though:
13182 // inside a template, the 'id' could have come from a parameter.
13183 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13184 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13185 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13186 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13187 }
13188
13189 return DeducedType;
13190}
13191
13193 Expr *Init) {
13194 assert(!Init || !Init->containsErrors());
13196 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13197 VDecl->getSourceRange(), DirectInit, Init);
13198 if (DeducedType.isNull()) {
13199 VDecl->setInvalidDecl();
13200 return true;
13201 }
13202
13203 VDecl->setType(DeducedType);
13204 assert(VDecl->isLinkageValid());
13205
13206 // In ARC, infer lifetime.
13207 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
13208 VDecl->setInvalidDecl();
13209
13210 if (getLangOpts().OpenCL)
13212
13213 // If this is a redeclaration, check that the type we just deduced matches
13214 // the previously declared type.
13215 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13216 // We never need to merge the type, because we cannot form an incomplete
13217 // array of auto, nor deduce such a type.
13218 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13219 }
13220
13221 // Check the deduced type is valid for a variable declaration.
13223 return VDecl->isInvalidDecl();
13224}
13225
13227 SourceLocation Loc) {
13228 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13229 Init = EWC->getSubExpr();
13230
13231 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13232 Init = CE->getSubExpr();
13233
13234 QualType InitType = Init->getType();
13237 "shouldn't be called if type doesn't have a non-trivial C struct");
13238 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13239 for (auto *I : ILE->inits()) {
13240 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13241 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13242 continue;
13243 SourceLocation SL = I->getExprLoc();
13244 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13245 }
13246 return;
13247 }
13248
13249 if (isa<ImplicitValueInitExpr>(Init)) {
13252 NTCUK_Init);
13253 } else {
13254 // Assume all other explicit initializers involving copying some existing
13255 // object.
13256 // TODO: ignore any explicit initializers where we can guarantee
13257 // copy-elision.
13260 }
13261}
13262
13263namespace {
13264
13265bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13266 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13267 // in the source code or implicitly by the compiler if it is in a union
13268 // defined in a system header and has non-trivial ObjC ownership
13269 // qualifications. We don't want those fields to participate in determining
13270 // whether the containing union is non-trivial.
13271 return FD->hasAttr<UnavailableAttr>();
13272}
13273
13274struct DiagNonTrivalCUnionDefaultInitializeVisitor
13275 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13276 void> {
13277 using Super =
13278 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13279 void>;
13280
13281 DiagNonTrivalCUnionDefaultInitializeVisitor(
13282 QualType OrigTy, SourceLocation OrigLoc,
13283 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13284 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13285
13286 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13287 const FieldDecl *FD, bool InNonTrivialUnion) {
13288 if (const auto *AT = S.Context.getAsArrayType(QT))
13289 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13290 InNonTrivialUnion);
13291 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13292 }
13293
13294 void visitARCStrong(QualType QT, const FieldDecl *FD,
13295 bool InNonTrivialUnion) {
13296 if (InNonTrivialUnion)
13297 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13298 << 1 << 0 << QT << FD->getName();
13299 }
13300
13301 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13302 if (InNonTrivialUnion)
13303 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13304 << 1 << 0 << QT << FD->getName();
13305 }
13306
13307 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13308 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13309 if (RD->isUnion()) {
13310 if (OrigLoc.isValid()) {
13311 bool IsUnion = false;
13312 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13313 IsUnion = OrigRD->isUnion();
13314 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13315 << 0 << OrigTy << IsUnion << UseContext;
13316 // Reset OrigLoc so that this diagnostic is emitted only once.
13317 OrigLoc = SourceLocation();
13318 }
13319 InNonTrivialUnion = true;
13320 }
13321
13322 if (InNonTrivialUnion)
13323 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13324 << 0 << 0 << QT.getUnqualifiedType() << "";
13325
13326 for (const FieldDecl *FD : RD->fields())
13327 if (!shouldIgnoreForRecordTriviality(FD))
13328 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13329 }
13330
13331 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13332
13333 // The non-trivial C union type or the struct/union type that contains a
13334 // non-trivial C union.
13335 QualType OrigTy;
13336 SourceLocation OrigLoc;
13338 Sema &S;
13339};
13340
13341struct DiagNonTrivalCUnionDestructedTypeVisitor
13342 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13343 using Super =
13345
13346 DiagNonTrivalCUnionDestructedTypeVisitor(
13347 QualType OrigTy, SourceLocation OrigLoc,
13348 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13349 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13350
13351 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13352 const FieldDecl *FD, bool InNonTrivialUnion) {
13353 if (const auto *AT = S.Context.getAsArrayType(QT))
13354 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13355 InNonTrivialUnion);
13356 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13357 }
13358
13359 void visitARCStrong(QualType QT, const FieldDecl *FD,
13360 bool InNonTrivialUnion) {
13361 if (InNonTrivialUnion)
13362 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13363 << 1 << 1 << QT << FD->getName();
13364 }
13365
13366 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13367 if (InNonTrivialUnion)
13368 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13369 << 1 << 1 << QT << FD->getName();
13370 }
13371
13372 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13373 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13374 if (RD->isUnion()) {
13375 if (OrigLoc.isValid()) {
13376 bool IsUnion = false;
13377 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13378 IsUnion = OrigRD->isUnion();
13379 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13380 << 1 << OrigTy << IsUnion << UseContext;
13381 // Reset OrigLoc so that this diagnostic is emitted only once.
13382 OrigLoc = SourceLocation();
13383 }
13384 InNonTrivialUnion = true;
13385 }
13386
13387 if (InNonTrivialUnion)
13388 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13389 << 0 << 1 << QT.getUnqualifiedType() << "";
13390
13391 for (const FieldDecl *FD : RD->fields())
13392 if (!shouldIgnoreForRecordTriviality(FD))
13393 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13394 }
13395
13396 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13397 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13398 bool InNonTrivialUnion) {}
13399
13400 // The non-trivial C union type or the struct/union type that contains a
13401 // non-trivial C union.
13402 QualType OrigTy;
13403 SourceLocation OrigLoc;
13405 Sema &S;
13406};
13407
13408struct DiagNonTrivalCUnionCopyVisitor
13409 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13411
13412 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13414 Sema &S)
13415 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13416
13417 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13418 const FieldDecl *FD, bool InNonTrivialUnion) {
13419 if (const auto *AT = S.Context.getAsArrayType(QT))
13420 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13421 InNonTrivialUnion);
13422 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13423 }
13424
13425 void visitARCStrong(QualType QT, const FieldDecl *FD,
13426 bool InNonTrivialUnion) {
13427 if (InNonTrivialUnion)
13428 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13429 << 1 << 2 << QT << FD->getName();
13430 }
13431
13432 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13433 if (InNonTrivialUnion)
13434 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13435 << 1 << 2 << QT << FD->getName();
13436 }
13437
13438 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13439 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13440 if (RD->isUnion()) {
13441 if (OrigLoc.isValid()) {
13442 bool IsUnion = false;
13443 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13444 IsUnion = OrigRD->isUnion();
13445 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13446 << 2 << OrigTy << IsUnion << UseContext;
13447 // Reset OrigLoc so that this diagnostic is emitted only once.
13448 OrigLoc = SourceLocation();
13449 }
13450 InNonTrivialUnion = true;
13451 }
13452
13453 if (InNonTrivialUnion)
13454 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13455 << 0 << 2 << QT.getUnqualifiedType() << "";
13456
13457 for (const FieldDecl *FD : RD->fields())
13458 if (!shouldIgnoreForRecordTriviality(FD))
13459 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13460 }
13461
13462 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13463 const FieldDecl *FD, bool InNonTrivialUnion) {}
13464 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13465 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13466 bool InNonTrivialUnion) {}
13467
13468 // The non-trivial C union type or the struct/union type that contains a
13469 // non-trivial C union.
13470 QualType OrigTy;
13471 SourceLocation OrigLoc;
13473 Sema &S;
13474};
13475
13476} // namespace
13477
13479 NonTrivialCUnionContext UseContext,
13480 unsigned NonTrivialKind) {
13484 "shouldn't be called if type doesn't have a non-trivial C union");
13485
13486 if ((NonTrivialKind & NTCUK_Init) &&
13488 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13489 .visit(QT, nullptr, false);
13490 if ((NonTrivialKind & NTCUK_Destruct) &&
13492 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13493 .visit(QT, nullptr, false);
13494 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13495 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13496 .visit(QT, nullptr, false);
13497}
13498
13499/// AddInitializerToDecl - Adds the initializer Init to the
13500/// declaration dcl. If DirectInit is true, this is C++ direct
13501/// initialization rather than copy initialization.
13503 // If there is no declaration, there was an error parsing it. Just ignore
13504 // the initializer.
13505 if (!RealDecl) {
13506 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13507 return;
13508 }
13509
13510 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13511 if (!Method->isInvalidDecl()) {
13512 // Pure-specifiers are handled in ActOnPureSpecifier.
13513 Diag(Method->getLocation(), diag::err_member_function_initialization)
13514 << Method->getDeclName() << Init->getSourceRange();
13515 Method->setInvalidDecl();
13516 }
13517 return;
13518 }
13519
13520 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13521 if (!VDecl) {
13522 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13523 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13524 RealDecl->setInvalidDecl();
13525 return;
13526 }
13527
13528 if (VDecl->isInvalidDecl()) {
13530 ExprResult Recovery =
13531 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13532 if (Expr *E = Recovery.get())
13533 VDecl->setInit(E);
13534 return;
13535 }
13536
13537 // WebAssembly tables can't be used to initialise a variable.
13538 if (Init && !Init->getType().isNull() &&
13539 Init->getType()->isWebAssemblyTableType()) {
13540 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13541 VDecl->setInvalidDecl();
13542 return;
13543 }
13544
13545 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13546 if (VDecl->getType()->isUndeducedType()) {
13547 // Attempt typo correction early so that the type of the init expression can
13548 // be deduced based on the chosen correction if the original init contains a
13549 // TypoExpr.
13551 if (!Res.isUsable()) {
13552 // There are unresolved typos in Init, just drop them.
13553 // FIXME: improve the recovery strategy to preserve the Init.
13554 RealDecl->setInvalidDecl();
13555 return;
13556 }
13557 if (Res.get()->containsErrors()) {
13558 // Invalidate the decl as we don't know the type for recovery-expr yet.
13559 RealDecl->setInvalidDecl();
13560 VDecl->setInit(Res.get());
13561 return;
13562 }
13563 Init = Res.get();
13564
13566 return;
13567 }
13568
13569 // dllimport cannot be used on variable definitions.
13570 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13571 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13572 VDecl->setInvalidDecl();
13573 return;
13574 }
13575
13576 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13577 // the identifier has external or internal linkage, the declaration shall
13578 // have no initializer for the identifier.
13579 // C++14 [dcl.init]p5 is the same restriction for C++.
13580 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13581 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13582 VDecl->setInvalidDecl();
13583 return;
13584 }
13585
13586 if (!VDecl->getType()->isDependentType()) {
13587 // A definition must end up with a complete type, which means it must be
13588 // complete with the restriction that an array type might be completed by
13589 // the initializer; note that later code assumes this restriction.
13590 QualType BaseDeclType = VDecl->getType();
13591 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13592 BaseDeclType = Array->getElementType();
13593 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13594 diag::err_typecheck_decl_incomplete_type)) {
13595 RealDecl->setInvalidDecl();
13596 return;
13597 }
13598
13599 // The variable can not have an abstract class type.
13600 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13601 diag::err_abstract_type_in_decl,
13603 VDecl->setInvalidDecl();
13604 }
13605
13606 // C++ [module.import/6] external definitions are not permitted in header
13607 // units.
13608 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13609 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13610 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13611 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl)) {
13612 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13613 VDecl->setInvalidDecl();
13614 }
13615
13616 // If adding the initializer will turn this declaration into a definition,
13617 // and we already have a definition for this variable, diagnose or otherwise
13618 // handle the situation.
13619 if (VarDecl *Def = VDecl->getDefinition())
13620 if (Def != VDecl &&
13621 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13623 checkVarDeclRedefinition(Def, VDecl))
13624 return;
13625
13626 if (getLangOpts().CPlusPlus) {
13627 // C++ [class.static.data]p4
13628 // If a static data member is of const integral or const
13629 // enumeration type, its declaration in the class definition can
13630 // specify a constant-initializer which shall be an integral
13631 // constant expression (5.19). In that case, the member can appear
13632 // in integral constant expressions. The member shall still be
13633 // defined in a namespace scope if it is used in the program and the
13634 // namespace scope definition shall not contain an initializer.
13635 //
13636 // We already performed a redefinition check above, but for static
13637 // data members we also need to check whether there was an in-class
13638 // declaration with an initializer.
13639 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13640 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13641 << VDecl->getDeclName();
13642 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13643 diag::note_previous_initializer)
13644 << 0;
13645 return;
13646 }
13647
13648 if (VDecl->hasLocalStorage())
13650
13652 VDecl->setInvalidDecl();
13653 return;
13654 }
13655 }
13656
13657 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13658 // a kernel function cannot be initialized."
13659 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13660 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13661 VDecl->setInvalidDecl();
13662 return;
13663 }
13664
13665 // The LoaderUninitialized attribute acts as a definition (of undef).
13666 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13667 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13668 VDecl->setInvalidDecl();
13669 return;
13670 }
13671
13672 // Get the decls type and save a reference for later, since
13673 // CheckInitializerTypes may change it.
13674 QualType DclT = VDecl->getType(), SavT = DclT;
13675
13676 // Expressions default to 'id' when we're in a debugger
13677 // and we are assigning it to a variable of Objective-C pointer type.
13678 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13679 Init->getType() == Context.UnknownAnyTy) {
13681 if (Result.isInvalid()) {
13682 VDecl->setInvalidDecl();
13683 return;
13684 }
13685 Init = Result.get();
13686 }
13687
13688 // Perform the initialization.
13689 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13690 bool IsParenListInit = false;
13691 if (!VDecl->isInvalidDecl()) {
13694 VDecl->getLocation(), DirectInit, Init);
13695
13696 MultiExprArg Args = Init;
13697 if (CXXDirectInit)
13698 Args = MultiExprArg(CXXDirectInit->getExprs(),
13699 CXXDirectInit->getNumExprs());
13700
13701 // Try to correct any TypoExprs in the initialization arguments.
13702 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13704 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13705 [this, Entity, Kind](Expr *E) {
13706 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13707 return Init.Failed() ? ExprError() : E;
13708 });
13709 if (Res.isInvalid()) {
13710 VDecl->setInvalidDecl();
13711 } else if (Res.get() != Args[Idx]) {
13712 Args[Idx] = Res.get();
13713 }
13714 }
13715 if (VDecl->isInvalidDecl())
13716 return;
13717
13718 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13719 /*TopLevelOfInitList=*/false,
13720 /*TreatUnavailableAsInvalid=*/false);
13721 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13722 if (Result.isInvalid()) {
13723 // If the provided initializer fails to initialize the var decl,
13724 // we attach a recovery expr for better recovery.
13725 auto RecoveryExpr =
13726 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13727 if (RecoveryExpr.get())
13728 VDecl->setInit(RecoveryExpr.get());
13729 // In general, for error recovery purposes, the initalizer doesn't play
13730 // part in the valid bit of the declaration. There are a few exceptions:
13731 // 1) if the var decl has a deduced auto type, and the type cannot be
13732 // deduced by an invalid initializer;
13733 // 2) if the var decl is decompsition decl with a non-deduced type, and
13734 // the initialization fails (e.g. `int [a] = {1, 2};`);
13735 // Case 1) was already handled elsewhere.
13736 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13737 VDecl->setInvalidDecl();
13738 return;
13739 }
13740
13741 Init = Result.getAs<Expr>();
13742 IsParenListInit = !InitSeq.steps().empty() &&
13743 InitSeq.step_begin()->Kind ==
13745 QualType VDeclType = VDecl->getType();
13746 if (Init && !Init->getType().isNull() &&
13747 !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13748 Context.getAsIncompleteArrayType(VDeclType) &&
13750 // Bail out if it is not possible to deduce array size from the
13751 // initializer.
13752 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13753 << VDeclType;
13754 VDecl->setInvalidDecl();
13755 return;
13756 }
13757 }
13758
13759 // Check for self-references within variable initializers.
13760 // Variables declared within a function/method body (except for references)
13761 // are handled by a dataflow analysis.
13762 // This is undefined behavior in C++, but valid in C.
13763 if (getLangOpts().CPlusPlus)
13764 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13765 VDecl->getType()->isReferenceType())
13766 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13767
13768 // If the type changed, it means we had an incomplete type that was
13769 // completed by the initializer. For example:
13770 // int ary[] = { 1, 3, 5 };
13771 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13772 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13773 VDecl->setType(DclT);
13774
13775 if (!VDecl->isInvalidDecl()) {
13776 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13777
13778 if (VDecl->hasAttr<BlocksAttr>())
13779 checkRetainCycles(VDecl, Init);
13780
13781 // It is safe to assign a weak reference into a strong variable.
13782 // Although this code can still have problems:
13783 // id x = self.weakProp;
13784 // id y = self.weakProp;
13785 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13786 // paths through the function. This should be revisited if
13787 // -Wrepeated-use-of-weak is made flow-sensitive.
13788 if (FunctionScopeInfo *FSI = getCurFunction())
13789 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13791 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13792 Init->getBeginLoc()))
13793 FSI->markSafeWeakUse(Init);
13794 }
13795
13796 // The initialization is usually a full-expression.
13797 //
13798 // FIXME: If this is a braced initialization of an aggregate, it is not
13799 // an expression, and each individual field initializer is a separate
13800 // full-expression. For instance, in:
13801 //
13802 // struct Temp { ~Temp(); };
13803 // struct S { S(Temp); };
13804 // struct T { S a, b; } t = { Temp(), Temp() }
13805 //
13806 // we should destroy the first Temp before constructing the second.
13809 /*DiscardedValue*/ false, VDecl->isConstexpr());
13810 if (Result.isInvalid()) {
13811 VDecl->setInvalidDecl();
13812 return;
13813 }
13814 Init = Result.get();
13815
13816 // Attach the initializer to the decl.
13817 VDecl->setInit(Init);
13818
13819 if (VDecl->isLocalVarDecl()) {
13820 // Don't check the initializer if the declaration is malformed.
13821 if (VDecl->isInvalidDecl()) {
13822 // do nothing
13823
13824 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13825 // This is true even in C++ for OpenCL.
13826 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13828
13829 // Otherwise, C++ does not restrict the initializer.
13830 } else if (getLangOpts().CPlusPlus) {
13831 // do nothing
13832
13833 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13834 // static storage duration shall be constant expressions or string literals.
13835 } else if (VDecl->getStorageClass() == SC_Static) {
13837
13838 // C89 is stricter than C99 for aggregate initializers.
13839 // C89 6.5.7p3: All the expressions [...] in an initializer list
13840 // for an object that has aggregate or union type shall be
13841 // constant expressions.
13842 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13843 isa<InitListExpr>(Init)) {
13844 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13845 }
13846
13847 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13848 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13849 if (VDecl->hasLocalStorage())
13850 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13851 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13852 VDecl->getLexicalDeclContext()->isRecord()) {
13853 // This is an in-class initialization for a static data member, e.g.,
13854 //
13855 // struct S {
13856 // static const int value = 17;
13857 // };
13858
13859 // C++ [class.mem]p4:
13860 // A member-declarator can contain a constant-initializer only
13861 // if it declares a static member (9.4) of const integral or
13862 // const enumeration type, see 9.4.2.
13863 //
13864 // C++11 [class.static.data]p3:
13865 // If a non-volatile non-inline const static data member is of integral
13866 // or enumeration type, its declaration in the class definition can
13867 // specify a brace-or-equal-initializer in which every initializer-clause
13868 // that is an assignment-expression is a constant expression. A static
13869 // data member of literal type can be declared in the class definition
13870 // with the constexpr specifier; if so, its declaration shall specify a
13871 // brace-or-equal-initializer in which every initializer-clause that is
13872 // an assignment-expression is a constant expression.
13873
13874 // Do nothing on dependent types.
13875 if (DclT->isDependentType()) {
13876
13877 // Allow any 'static constexpr' members, whether or not they are of literal
13878 // type. We separately check that every constexpr variable is of literal
13879 // type.
13880 } else if (VDecl->isConstexpr()) {
13881
13882 // Require constness.
13883 } else if (!DclT.isConstQualified()) {
13884 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13885 << Init->getSourceRange();
13886 VDecl->setInvalidDecl();
13887
13888 // We allow integer constant expressions in all cases.
13889 } else if (DclT->isIntegralOrEnumerationType()) {
13890 // Check whether the expression is a constant expression.
13891 SourceLocation Loc;
13893 // In C++11, a non-constexpr const static data member with an
13894 // in-class initializer cannot be volatile.
13895 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13896 else if (Init->isValueDependent())
13897 ; // Nothing to check.
13898 else if (Init->isIntegerConstantExpr(Context, &Loc))
13899 ; // Ok, it's an ICE!
13900 else if (Init->getType()->isScopedEnumeralType() &&
13901 Init->isCXX11ConstantExpr(Context))
13902 ; // Ok, it is a scoped-enum constant expression.
13903 else if (Init->isEvaluatable(Context)) {
13904 // If we can constant fold the initializer through heroics, accept it,
13905 // but report this as a use of an extension for -pedantic.
13906 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13907 << Init->getSourceRange();
13908 } else {
13909 // Otherwise, this is some crazy unknown case. Report the issue at the
13910 // location provided by the isIntegerConstantExpr failed check.
13911 Diag(Loc, diag::err_in_class_initializer_non_constant)
13912 << Init->getSourceRange();
13913 VDecl->setInvalidDecl();
13914 }
13915
13916 // We allow foldable floating-point constants as an extension.
13917 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13918 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13919 // it anyway and provide a fixit to add the 'constexpr'.
13920 if (getLangOpts().CPlusPlus11) {
13921 Diag(VDecl->getLocation(),
13922 diag::ext_in_class_initializer_float_type_cxx11)
13923 << DclT << Init->getSourceRange();
13924 Diag(VDecl->getBeginLoc(),
13925 diag::note_in_class_initializer_float_type_cxx11)
13926 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13927 } else {
13928 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13929 << DclT << Init->getSourceRange();
13930
13931 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13932 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13933 << Init->getSourceRange();
13934 VDecl->setInvalidDecl();
13935 }
13936 }
13937
13938 // Suggest adding 'constexpr' in C++11 for literal types.
13939 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13940 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13941 << DclT << Init->getSourceRange()
13942 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13943 VDecl->setConstexpr(true);
13944
13945 } else {
13946 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13947 << DclT << Init->getSourceRange();
13948 VDecl->setInvalidDecl();
13949 }
13950 } else if (VDecl->isFileVarDecl()) {
13951 // In C, extern is typically used to avoid tentative definitions when
13952 // declaring variables in headers, but adding an intializer makes it a
13953 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13954 // In C++, extern is often used to give implictly static const variables
13955 // external linkage, so don't warn in that case. If selectany is present,
13956 // this might be header code intended for C and C++ inclusion, so apply the
13957 // C++ rules.
13958 if (VDecl->getStorageClass() == SC_Extern &&
13959 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13961 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13963 Diag(VDecl->getLocation(), diag::warn_extern_init);
13964
13965 // In Microsoft C++ mode, a const variable defined in namespace scope has
13966 // external linkage by default if the variable is declared with
13967 // __declspec(dllexport).
13970 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13971 VDecl->setStorageClass(SC_Extern);
13972
13973 // C99 6.7.8p4. All file scoped initializers need to be constant.
13974 // Avoid duplicate diagnostics for constexpr variables.
13975 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13976 !VDecl->isConstexpr())
13978 }
13979
13980 QualType InitType = Init->getType();
13981 if (!InitType.isNull() &&
13985
13986 // We will represent direct-initialization similarly to copy-initialization:
13987 // int x(1); -as-> int x = 1;
13988 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13989 //
13990 // Clients that want to distinguish between the two forms, can check for
13991 // direct initializer using VarDecl::getInitStyle().
13992 // A major benefit is that clients that don't particularly care about which
13993 // exactly form was it (like the CodeGen) can handle both cases without
13994 // special case code.
13995
13996 // C++ 8.5p11:
13997 // The form of initialization (using parentheses or '=') is generally
13998 // insignificant, but does matter when the entity being initialized has a
13999 // class type.
14000 if (CXXDirectInit) {
14001 assert(DirectInit && "Call-style initializer must be direct init.");
14002 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14004 } else if (DirectInit) {
14005 // This must be list-initialization. No other way is direct-initialization.
14007 }
14008
14009 if (LangOpts.OpenMP &&
14010 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14011 VDecl->isFileVarDecl())
14012 DeclsToCheckForDeferredDiags.insert(VDecl);
14014}
14015
14016/// ActOnInitializerError - Given that there was an error parsing an
14017/// initializer for the given declaration, try to at least re-establish
14018/// invariants such as whether a variable's type is either dependent or
14019/// complete.
14021 // Our main concern here is re-establishing invariants like "a
14022 // variable's type is either dependent or complete".
14023 if (!D || D->isInvalidDecl()) return;
14024
14025 VarDecl *VD = dyn_cast<VarDecl>(D);
14026 if (!VD) return;
14027
14028 // Bindings are not usable if we can't make sense of the initializer.
14029 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14030 for (auto *BD : DD->bindings())
14031 BD->setInvalidDecl();
14032
14033 // Auto types are meaningless if we can't make sense of the initializer.
14034 if (VD->getType()->isUndeducedType()) {
14035 D->setInvalidDecl();
14036 return;
14037 }
14038
14039 QualType Ty = VD->getType();
14040 if (Ty->isDependentType()) return;
14041
14042 // Require a complete type.
14045 diag::err_typecheck_decl_incomplete_type)) {
14046 VD->setInvalidDecl();
14047 return;
14048 }
14049
14050 // Require a non-abstract type.
14051 if (RequireNonAbstractType(VD->getLocation(), Ty,
14052 diag::err_abstract_type_in_decl,
14054 VD->setInvalidDecl();
14055 return;
14056 }
14057
14058 // Don't bother complaining about constructors or destructors,
14059 // though.
14060}
14061
14063 // If there is no declaration, there was an error parsing it. Just ignore it.
14064 if (!RealDecl)
14065 return;
14066
14067 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14068 QualType Type = Var->getType();
14069
14070 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14071 if (isa<DecompositionDecl>(RealDecl)) {
14072 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14073 Var->setInvalidDecl();
14074 return;
14075 }
14076
14077 if (Type->isUndeducedType() &&
14078 DeduceVariableDeclarationType(Var, false, nullptr))
14079 return;
14080
14081 // C++11 [class.static.data]p3: A static data member can be declared with
14082 // the constexpr specifier; if so, its declaration shall specify
14083 // a brace-or-equal-initializer.
14084 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14085 // the definition of a variable [...] or the declaration of a static data
14086 // member.
14087 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14088 !Var->isThisDeclarationADemotedDefinition()) {
14089 if (Var->isStaticDataMember()) {
14090 // C++1z removes the relevant rule; the in-class declaration is always
14091 // a definition there.
14092 if (!getLangOpts().CPlusPlus17 &&
14094 Diag(Var->getLocation(),
14095 diag::err_constexpr_static_mem_var_requires_init)
14096 << Var;
14097 Var->setInvalidDecl();
14098 return;
14099 }
14100 } else {
14101 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14102 Var->setInvalidDecl();
14103 return;
14104 }
14105 }
14106
14107 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14108 // be initialized.
14109 if (!Var->isInvalidDecl() &&
14110 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14111 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14112 bool HasConstExprDefaultConstructor = false;
14113 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14114 for (auto *Ctor : RD->ctors()) {
14115 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14116 Ctor->getMethodQualifiers().getAddressSpace() ==
14118 HasConstExprDefaultConstructor = true;
14119 }
14120 }
14121 }
14122 if (!HasConstExprDefaultConstructor) {
14123 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14124 Var->setInvalidDecl();
14125 return;
14126 }
14127 }
14128
14129 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14130 if (Var->getStorageClass() == SC_Extern) {
14131 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14132 << Var;
14133 Var->setInvalidDecl();
14134 return;
14135 }
14136 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14137 diag::err_typecheck_decl_incomplete_type)) {
14138 Var->setInvalidDecl();
14139 return;
14140 }
14141 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14142 if (!RD->hasTrivialDefaultConstructor()) {
14143 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14144 Var->setInvalidDecl();
14145 return;
14146 }
14147 }
14148 // The declaration is unitialized, no need for further checks.
14149 return;
14150 }
14151
14152 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14153 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14154 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14155 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14157
14158
14159 switch (DefKind) {
14161 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14162 break;
14163
14164 // We have an out-of-line definition of a static data member
14165 // that has an in-class initializer, so we type-check this like
14166 // a declaration.
14167 //
14168 [[fallthrough]];
14169
14171 // It's only a declaration.
14172
14173 // Block scope. C99 6.7p7: If an identifier for an object is
14174 // declared with no linkage (C99 6.2.2p6), the type for the
14175 // object shall be complete.
14176 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14177 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14178 RequireCompleteType(Var->getLocation(), Type,
14179 diag::err_typecheck_decl_incomplete_type))
14180 Var->setInvalidDecl();
14181
14182 // Make sure that the type is not abstract.
14183 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14184 RequireNonAbstractType(Var->getLocation(), Type,
14185 diag::err_abstract_type_in_decl,
14187 Var->setInvalidDecl();
14188 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14189 Var->getStorageClass() == SC_PrivateExtern) {
14190 Diag(Var->getLocation(), diag::warn_private_extern);
14191 Diag(Var->getLocation(), diag::note_private_extern);
14192 }
14193
14195 !Var->isInvalidDecl())
14196 ExternalDeclarations.push_back(Var);
14197
14198 return;
14199
14201 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14202 // object that has file scope without an initializer, and without a
14203 // storage-class specifier or with the storage-class specifier "static",
14204 // constitutes a tentative definition. Note: A tentative definition with
14205 // external linkage is valid (C99 6.2.2p5).
14206 if (!Var->isInvalidDecl()) {
14207 if (const IncompleteArrayType *ArrayT
14210 Var->getLocation(), ArrayT->getElementType(),
14211 diag::err_array_incomplete_or_sizeless_type))
14212 Var->setInvalidDecl();
14213 } else if (Var->getStorageClass() == SC_Static) {
14214 // C99 6.9.2p3: If the declaration of an identifier for an object is
14215 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14216 // declared type shall not be an incomplete type.
14217 // NOTE: code such as the following
14218 // static struct s;
14219 // struct s { int a; };
14220 // is accepted by gcc. Hence here we issue a warning instead of
14221 // an error and we do not invalidate the static declaration.
14222 // NOTE: to avoid multiple warnings, only check the first declaration.
14223 if (Var->isFirstDecl())
14224 RequireCompleteType(Var->getLocation(), Type,
14225 diag::ext_typecheck_decl_incomplete_type);
14226 }
14227 }
14228
14229 // Record the tentative definition; we're done.
14230 if (!Var->isInvalidDecl())
14232 return;
14233 }
14234
14235 // Provide a specific diagnostic for uninitialized variable
14236 // definitions with incomplete array type.
14237 if (Type->isIncompleteArrayType()) {
14238 if (Var->isConstexpr())
14239 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14240 << Var;
14241 else
14242 Diag(Var->getLocation(),
14243 diag::err_typecheck_incomplete_array_needs_initializer);
14244 Var->setInvalidDecl();
14245 return;
14246 }
14247
14248 // Provide a specific diagnostic for uninitialized variable
14249 // definitions with reference type.
14250 if (Type->isReferenceType()) {
14251 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14252 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14253 return;
14254 }
14255
14256 // Do not attempt to type-check the default initializer for a
14257 // variable with dependent type.
14258 if (Type->isDependentType())
14259 return;
14260
14261 if (Var->isInvalidDecl())
14262 return;
14263
14264 if (!Var->hasAttr<AliasAttr>()) {
14265 if (RequireCompleteType(Var->getLocation(),
14267 diag::err_typecheck_decl_incomplete_type)) {
14268 Var->setInvalidDecl();
14269 return;
14270 }
14271 } else {
14272 return;
14273 }
14274
14275 // The variable can not have an abstract class type.
14276 if (RequireNonAbstractType(Var->getLocation(), Type,
14277 diag::err_abstract_type_in_decl,
14279 Var->setInvalidDecl();
14280 return;
14281 }
14282
14283 // Check for jumps past the implicit initializer. C++0x
14284 // clarifies that this applies to a "variable with automatic
14285 // storage duration", not a "local variable".
14286 // C++11 [stmt.dcl]p3
14287 // A program that jumps from a point where a variable with automatic
14288 // storage duration is not in scope to a point where it is in scope is
14289 // ill-formed unless the variable has scalar type, class type with a
14290 // trivial default constructor and a trivial destructor, a cv-qualified
14291 // version of one of these types, or an array of one of the preceding
14292 // types and is declared without an initializer.
14293 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14294 if (const RecordType *Record
14296 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14297 // Mark the function (if we're in one) for further checking even if the
14298 // looser rules of C++11 do not require such checks, so that we can
14299 // diagnose incompatibilities with C++98.
14300 if (!CXXRecord->isPOD())
14302 }
14303 }
14304 // In OpenCL, we can't initialize objects in the __local address space,
14305 // even implicitly, so don't synthesize an implicit initializer.
14306 if (getLangOpts().OpenCL &&
14307 Var->getType().getAddressSpace() == LangAS::opencl_local)
14308 return;
14309 // C++03 [dcl.init]p9:
14310 // If no initializer is specified for an object, and the
14311 // object is of (possibly cv-qualified) non-POD class type (or
14312 // array thereof), the object shall be default-initialized; if
14313 // the object is of const-qualified type, the underlying class
14314 // type shall have a user-declared default
14315 // constructor. Otherwise, if no initializer is specified for
14316 // a non- static object, the object and its subobjects, if
14317 // any, have an indeterminate initial value); if the object
14318 // or any of its subobjects are of const-qualified type, the
14319 // program is ill-formed.
14320 // C++0x [dcl.init]p11:
14321 // If no initializer is specified for an object, the object is
14322 // default-initialized; [...].
14325 = InitializationKind::CreateDefault(Var->getLocation());
14326
14327 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14328 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
14329
14330 if (Init.get()) {
14331 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14332 // This is important for template substitution.
14333 Var->setInitStyle(VarDecl::CallInit);
14334 } else if (Init.isInvalid()) {
14335 // If default-init fails, attach a recovery-expr initializer to track
14336 // that initialization was attempted and failed.
14337 auto RecoveryExpr =
14338 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14339 if (RecoveryExpr.get())
14340 Var->setInit(RecoveryExpr.get());
14341 }
14342
14344 }
14345}
14346
14348 // If there is no declaration, there was an error parsing it. Ignore it.
14349 if (!D)
14350 return;
14351
14352 VarDecl *VD = dyn_cast<VarDecl>(D);
14353 if (!VD) {
14354 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14355 D->setInvalidDecl();
14356 return;
14357 }
14358
14359 VD->setCXXForRangeDecl(true);
14360
14361 // for-range-declaration cannot be given a storage class specifier.
14362 int Error = -1;
14363 switch (VD->getStorageClass()) {
14364 case SC_None:
14365 break;
14366 case SC_Extern:
14367 Error = 0;
14368 break;
14369 case SC_Static:
14370 Error = 1;
14371 break;
14372 case SC_PrivateExtern:
14373 Error = 2;
14374 break;
14375 case SC_Auto:
14376 Error = 3;
14377 break;
14378 case SC_Register:
14379 Error = 4;
14380 break;
14381 }
14382
14383 // for-range-declaration cannot be given a storage class specifier con't.
14384 switch (VD->getTSCSpec()) {
14385 case TSCS_thread_local:
14386 Error = 6;
14387 break;
14388 case TSCS___thread:
14389 case TSCS__Thread_local:
14390 case TSCS_unspecified:
14391 break;
14392 }
14393
14394 if (Error != -1) {
14395 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14396 << VD << Error;
14397 D->setInvalidDecl();
14398 }
14399}
14400
14402 IdentifierInfo *Ident,
14403 ParsedAttributes &Attrs) {
14404 // C++1y [stmt.iter]p1:
14405 // A range-based for statement of the form
14406 // for ( for-range-identifier : for-range-initializer ) statement
14407 // is equivalent to
14408 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14409 DeclSpec DS(Attrs.getPool().getFactory());
14410
14411 const char *PrevSpec;
14412 unsigned DiagID;
14413 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14415
14417 D.SetIdentifier(Ident, IdentLoc);
14418 D.takeAttributes(Attrs);
14419
14420 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14421 IdentLoc);
14422 Decl *Var = ActOnDeclarator(S, D);
14423 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14425 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14426 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14427 : IdentLoc);
14428}
14429
14431 if (var->isInvalidDecl()) return;
14432
14434
14435 if (getLangOpts().OpenCL) {
14436 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14437 // initialiser
14438 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14439 !var->hasInit()) {
14440 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14441 << 1 /*Init*/;
14442 var->setInvalidDecl();
14443 return;
14444 }
14445 }
14446
14447 // In Objective-C, don't allow jumps past the implicit initialization of a
14448 // local retaining variable.
14449 if (getLangOpts().ObjC &&
14450 var->hasLocalStorage()) {
14451 switch (var->getType().getObjCLifetime()) {
14455 break;
14456
14460 break;
14461 }
14462 }
14463
14464 if (var->hasLocalStorage() &&
14467
14468 // Warn about externally-visible variables being defined without a
14469 // prior declaration. We only want to do this for global
14470 // declarations, but we also specifically need to avoid doing it for
14471 // class members because the linkage of an anonymous class can
14472 // change if it's later given a typedef name.
14473 if (var->isThisDeclarationADefinition() &&
14475 var->isExternallyVisible() && var->hasLinkage() &&
14476 !var->isInline() && !var->getDescribedVarTemplate() &&
14477 var->getStorageClass() != SC_Register &&
14478 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14480 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14481 var->getLocation())) {
14482 // Find a previous declaration that's not a definition.
14483 VarDecl *prev = var->getPreviousDecl();
14484 while (prev && prev->isThisDeclarationADefinition())
14485 prev = prev->getPreviousDecl();
14486
14487 if (!prev) {
14488 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14489 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14490 << /* variable */ 0;
14491 }
14492 }
14493
14494 // Cache the result of checking for constant initialization.
14495 std::optional<bool> CacheHasConstInit;
14496 const Expr *CacheCulprit = nullptr;
14497 auto checkConstInit = [&]() mutable {
14498 if (!CacheHasConstInit)
14499 CacheHasConstInit = var->getInit()->isConstantInitializer(
14500 Context, var->getType()->isReferenceType(), &CacheCulprit);
14501 return *CacheHasConstInit;
14502 };
14503
14504 if (var->getTLSKind() == VarDecl::TLS_Static) {
14505 if (var->getType().isDestructedType()) {
14506 // GNU C++98 edits for __thread, [basic.start.term]p3:
14507 // The type of an object with thread storage duration shall not
14508 // have a non-trivial destructor.
14509 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14511 Diag(var->getLocation(), diag::note_use_thread_local);
14512 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14513 if (!checkConstInit()) {
14514 // GNU C++98 edits for __thread, [basic.start.init]p4:
14515 // An object of thread storage duration shall not require dynamic
14516 // initialization.
14517 // FIXME: Need strict checking here.
14518 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14519 << CacheCulprit->getSourceRange();
14521 Diag(var->getLocation(), diag::note_use_thread_local);
14522 }
14523 }
14524 }
14525
14526
14527 if (!var->getType()->isStructureType() && var->hasInit() &&
14528 isa<InitListExpr>(var->getInit())) {
14529 const auto *ILE = cast<InitListExpr>(var->getInit());
14530 unsigned NumInits = ILE->getNumInits();
14531 if (NumInits > 2)
14532 for (unsigned I = 0; I < NumInits; ++I) {
14533 const auto *Init = ILE->getInit(I);
14534 if (!Init)
14535 break;
14536 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14537 if (!SL)
14538 break;
14539
14540 unsigned NumConcat = SL->getNumConcatenated();
14541 // Diagnose missing comma in string array initialization.
14542 // Do not warn when all the elements in the initializer are concatenated
14543 // together. Do not warn for macros too.
14544 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14545 bool OnlyOneMissingComma = true;
14546 for (unsigned J = I + 1; J < NumInits; ++J) {
14547 const auto *Init = ILE->getInit(J);
14548 if (!Init)
14549 break;
14550 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14551 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14552 OnlyOneMissingComma = false;
14553 break;
14554 }
14555 }
14556
14557 if (OnlyOneMissingComma) {
14559 for (unsigned i = 0; i < NumConcat - 1; ++i)
14560 Hints.push_back(FixItHint::CreateInsertion(
14561 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14562
14563 Diag(SL->getStrTokenLoc(1),
14564 diag::warn_concatenated_literal_array_init)
14565 << Hints;
14566 Diag(SL->getBeginLoc(),
14567 diag::note_concatenated_string_literal_silence);
14568 }
14569 // In any case, stop now.
14570 break;
14571 }
14572 }
14573 }
14574
14575
14576 QualType type = var->getType();
14577
14578 if (var->hasAttr<BlocksAttr>())
14580
14581 Expr *Init = var->getInit();
14582 bool GlobalStorage = var->hasGlobalStorage();
14583 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14585 bool HasConstInit = true;
14586
14587 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14588 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14589 << var;
14590
14591 // Check whether the initializer is sufficiently constant.
14592 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14593 !type->isDependentType() && Init && !Init->isValueDependent() &&
14594 (GlobalStorage || var->isConstexpr() ||
14596 // If this variable might have a constant initializer or might be usable in
14597 // constant expressions, check whether or not it actually is now. We can't
14598 // do this lazily, because the result might depend on things that change
14599 // later, such as which constexpr functions happen to be defined.
14601 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14602 // Prior to C++11, in contexts where a constant initializer is required,
14603 // the set of valid constant initializers is described by syntactic rules
14604 // in [expr.const]p2-6.
14605 // FIXME: Stricter checking for these rules would be useful for constinit /
14606 // -Wglobal-constructors.
14607 HasConstInit = checkConstInit();
14608
14609 // Compute and cache the constant value, and remember that we have a
14610 // constant initializer.
14611 if (HasConstInit) {
14612 (void)var->checkForConstantInitialization(Notes);
14613 Notes.clear();
14614 } else if (CacheCulprit) {
14615 Notes.emplace_back(CacheCulprit->getExprLoc(),
14616 PDiag(diag::note_invalid_subexpr_in_const_expr));
14617 Notes.back().second << CacheCulprit->getSourceRange();
14618 }
14619 } else {
14620 // Evaluate the initializer to see if it's a constant initializer.
14621 HasConstInit = var->checkForConstantInitialization(Notes);
14622 }
14623
14624 if (HasConstInit) {
14625 // FIXME: Consider replacing the initializer with a ConstantExpr.
14626 } else if (var->isConstexpr()) {
14627 SourceLocation DiagLoc = var->getLocation();
14628 // If the note doesn't add any useful information other than a source
14629 // location, fold it into the primary diagnostic.
14630 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14631 diag::note_invalid_subexpr_in_const_expr) {
14632 DiagLoc = Notes[0].first;
14633 Notes.clear();
14634 }
14635 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14636 << var << Init->getSourceRange();
14637 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14638 Diag(Notes[I].first, Notes[I].second);
14639 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14640 auto *Attr = var->getAttr<ConstInitAttr>();
14641 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14642 << Init->getSourceRange();
14643 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14644 << Attr->getRange() << Attr->isConstinit();
14645 for (auto &it : Notes)
14646 Diag(it.first, it.second);
14647 } else if (IsGlobal &&
14648 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14649 var->getLocation())) {
14650 // Warn about globals which don't have a constant initializer. Don't
14651 // warn about globals with a non-trivial destructor because we already
14652 // warned about them.
14653 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14654 if (!(RD && !RD->hasTrivialDestructor())) {
14655 // checkConstInit() here permits trivial default initialization even in
14656 // C++11 onwards, where such an initializer is not a constant initializer
14657 // but nonetheless doesn't require a global constructor.
14658 if (!checkConstInit())
14659 Diag(var->getLocation(), diag::warn_global_constructor)
14660 << Init->getSourceRange();
14661 }
14662 }
14663 }
14664
14665 // Apply section attributes and pragmas to global variables.
14666 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14668 PragmaStack<StringLiteral *> *Stack = nullptr;
14669 int SectionFlags = ASTContext::PSF_Read;
14670 bool MSVCEnv =
14671 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14672 std::optional<QualType::NonConstantStorageReason> Reason;
14673 if (HasConstInit &&
14674 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14675 Stack = &ConstSegStack;
14676 } else {
14677 SectionFlags |= ASTContext::PSF_Write;
14678 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14679 }
14680 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14681 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14682 SectionFlags |= ASTContext::PSF_Implicit;
14683 UnifySection(SA->getName(), SectionFlags, var);
14684 } else if (Stack->CurrentValue) {
14685 if (Stack != &ConstSegStack && MSVCEnv &&
14686 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14687 var->getType().isConstQualified()) {
14688 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14689 NonConstNonReferenceType) &&
14690 "This case should've already been handled elsewhere");
14691 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14692 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14694 : *Reason);
14695 }
14696 SectionFlags |= ASTContext::PSF_Implicit;
14697 auto SectionName = Stack->CurrentValue->getString();
14698 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14699 Stack->CurrentPragmaLocation,
14700 SectionAttr::Declspec_allocate));
14701 if (UnifySection(SectionName, SectionFlags, var))
14702 var->dropAttr<SectionAttr>();
14703 }
14704
14705 // Apply the init_seg attribute if this has an initializer. If the
14706 // initializer turns out to not be dynamic, we'll end up ignoring this
14707 // attribute.
14708 if (CurInitSeg && var->getInit())
14709 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14710 CurInitSegLoc));
14711 }
14712
14713 // All the following checks are C++ only.
14714 if (!getLangOpts().CPlusPlus) {
14715 // If this variable must be emitted, add it as an initializer for the
14716 // current module.
14717 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14718 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14719 return;
14720 }
14721
14722 // Require the destructor.
14723 if (!type->isDependentType())
14724 if (const RecordType *recordType = baseType->getAs<RecordType>())
14726
14727 // If this variable must be emitted, add it as an initializer for the current
14728 // module.
14729 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14730 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14731
14732 // Build the bindings if this is a structured binding declaration.
14733 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14735}
14736
14737/// Check if VD needs to be dllexport/dllimport due to being in a
14738/// dllexport/import function.
14740 assert(VD->isStaticLocal());
14741
14742 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14743
14744 // Find outermost function when VD is in lambda function.
14745 while (FD && !getDLLAttr(FD) &&
14746 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14747 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14748 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14749 }
14750
14751 if (!FD)
14752 return;
14753
14754 // Static locals inherit dll attributes from their function.
14755 if (Attr *A = getDLLAttr(FD)) {
14756 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14757 NewAttr->setInherited(true);
14758 VD->addAttr(NewAttr);
14759 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14760 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14761 NewAttr->setInherited(true);
14762 VD->addAttr(NewAttr);
14763
14764 // Export this function to enforce exporting this static variable even
14765 // if it is not used in this compilation unit.
14766 if (!FD->hasAttr<DLLExportAttr>())
14767 FD->addAttr(NewAttr);
14768
14769 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14770 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14771 NewAttr->setInherited(true);
14772 VD->addAttr(NewAttr);
14773 }
14774}
14775
14777 assert(VD->getTLSKind());
14778
14779 // Perform TLS alignment check here after attributes attached to the variable
14780 // which may affect the alignment have been processed. Only perform the check
14781 // if the target has a maximum TLS alignment (zero means no constraints).
14782 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14783 // Protect the check so that it's not performed on dependent types and
14784 // dependent alignments (we can't determine the alignment in that case).
14785 if (!VD->hasDependentAlignment()) {
14786 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14787 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14788 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14790 << (unsigned)MaxAlignChars.getQuantity();
14791 }
14792 }
14793 }
14794}
14795
14796/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14797/// any semantic actions necessary after any initializer has been attached.
14799 // Note that we are no longer parsing the initializer for this declaration.
14800 ParsingInitForAutoVars.erase(ThisDecl);
14801
14802 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14803 if (!VD)
14804 return;
14805
14806 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14808 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14810 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14814 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14818 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14822 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14825 }
14826
14827 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14828 for (auto *BD : DD->bindings()) {
14830 }
14831 }
14832
14833 checkAttributesAfterMerging(*this, *VD);
14834
14835 if (VD->isStaticLocal())
14837
14838 if (VD->getTLSKind())
14840
14841 // Perform check for initializers of device-side global variables.
14842 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14843 // 7.5). We must also apply the same checks to all __shared__
14844 // variables whether they are local or not. CUDA also allows
14845 // constant initializers for __constant__ and __device__ variables.
14846 if (getLangOpts().CUDA)
14848
14849 // Grab the dllimport or dllexport attribute off of the VarDecl.
14850 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14851
14852 // Imported static data members cannot be defined out-of-line.
14853 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14854 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14856 // We allow definitions of dllimport class template static data members
14857 // with a warning.
14859 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14860 bool IsClassTemplateMember =
14861 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14862 Context->getDescribedClassTemplate();
14863
14864 Diag(VD->getLocation(),
14865 IsClassTemplateMember
14866 ? diag::warn_attribute_dllimport_static_field_definition
14867 : diag::err_attribute_dllimport_static_field_definition);
14868 Diag(IA->getLocation(), diag::note_attribute);
14869 if (!IsClassTemplateMember)
14870 VD->setInvalidDecl();
14871 }
14872 }
14873
14874 // dllimport/dllexport variables cannot be thread local, their TLS index
14875 // isn't exported with the variable.
14876 if (DLLAttr && VD->getTLSKind()) {
14877 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14878 if (F && getDLLAttr(F)) {
14879 assert(VD->isStaticLocal());
14880 // But if this is a static local in a dlimport/dllexport function, the
14881 // function will never be inlined, which means the var would never be
14882 // imported, so having it marked import/export is safe.
14883 } else {
14884 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14885 << DLLAttr;
14886 VD->setInvalidDecl();
14887 }
14888 }
14889
14890 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14891 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14892 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14893 << Attr;
14894 VD->dropAttr<UsedAttr>();
14895 }
14896 }
14897 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14898 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14899 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14900 << Attr;
14901 VD->dropAttr<RetainAttr>();
14902 }
14903 }
14904
14905 const DeclContext *DC = VD->getDeclContext();
14906 // If there's a #pragma GCC visibility in scope, and this isn't a class
14907 // member, set the visibility of this variable.
14910
14911 // FIXME: Warn on unused var template partial specializations.
14912 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14914
14915 // Now we have parsed the initializer and can update the table of magic
14916 // tag values.
14917 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14919 return;
14920
14921 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14922 const Expr *MagicValueExpr = VD->getInit();
14923 if (!MagicValueExpr) {
14924 continue;
14925 }
14926 std::optional<llvm::APSInt> MagicValueInt;
14927 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14928 Diag(I->getRange().getBegin(),
14929 diag::err_type_tag_for_datatype_not_ice)
14930 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14931 continue;
14932 }
14933 if (MagicValueInt->getActiveBits() > 64) {
14934 Diag(I->getRange().getBegin(),
14935 diag::err_type_tag_for_datatype_too_large)
14936 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14937 continue;
14938 }
14939 uint64_t MagicValue = MagicValueInt->getZExtValue();
14940 RegisterTypeTagForDatatype(I->getArgumentKind(),
14941 MagicValue,
14942 I->getMatchingCType(),
14943 I->getLayoutCompatible(),
14944 I->getMustBeNull());
14945 }
14946}
14947
14949 auto *VD = dyn_cast<VarDecl>(DD);
14950 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14951}
14952
14954 ArrayRef<Decl *> Group) {
14956
14957 if (DS.isTypeSpecOwned())
14958 Decls.push_back(DS.getRepAsDecl());
14959
14960 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14961 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14962 bool DiagnosedMultipleDecomps = false;
14963 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14964 bool DiagnosedNonDeducedAuto = false;
14965
14966 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14967 if (Decl *D = Group[i]) {
14968 // Check if the Decl has been declared in '#pragma omp declare target'
14969 // directive and has static storage duration.
14970 if (auto *VD = dyn_cast<VarDecl>(D);
14971 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14972 VD->hasGlobalStorage())
14974 // For declarators, there are some additional syntactic-ish checks we need
14975 // to perform.
14976 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14977 if (!FirstDeclaratorInGroup)
14978 FirstDeclaratorInGroup = DD;
14979 if (!FirstDecompDeclaratorInGroup)
14980 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14981 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14982 !hasDeducedAuto(DD))
14983 FirstNonDeducedAutoInGroup = DD;
14984
14985 if (FirstDeclaratorInGroup != DD) {
14986 // A decomposition declaration cannot be combined with any other
14987 // declaration in the same group.
14988 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14989 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14990 diag::err_decomp_decl_not_alone)
14991 << FirstDeclaratorInGroup->getSourceRange()
14992 << DD->getSourceRange();
14993 DiagnosedMultipleDecomps = true;
14994 }
14995
14996 // A declarator that uses 'auto' in any way other than to declare a
14997 // variable with a deduced type cannot be combined with any other
14998 // declarator in the same group.
14999 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15000 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15001 diag::err_auto_non_deduced_not_alone)
15002 << FirstNonDeducedAutoInGroup->getType()
15004 << FirstDeclaratorInGroup->getSourceRange()
15005 << DD->getSourceRange();
15006 DiagnosedNonDeducedAuto = true;
15007 }
15008 }
15009 }
15010
15011 Decls.push_back(D);
15012 }
15013 }
15014
15016 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15017 handleTagNumbering(Tag, S);
15018 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15020 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15021 }
15022 }
15023
15024 return BuildDeclaratorGroup(Decls);
15025}
15026
15027/// BuildDeclaratorGroup - convert a list of declarations into a declaration
15028/// group, performing any necessary semantic checking.
15031 // C++14 [dcl.spec.auto]p7: (DR1347)
15032 // If the type that replaces the placeholder type is not the same in each
15033 // deduction, the program is ill-formed.
15034 if (Group.size() > 1) {
15035 QualType Deduced;
15036 VarDecl *DeducedDecl = nullptr;
15037 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15038 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15039 if (!D || D->isInvalidDecl())
15040 break;
15042 if (!DT || DT->getDeducedType().isNull())
15043 continue;
15044 if (Deduced.isNull()) {
15045 Deduced = DT->getDeducedType();
15046 DeducedDecl = D;
15047 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15048 auto *AT = dyn_cast<AutoType>(DT);
15049 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15050 diag::err_auto_different_deductions)
15051 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15052 << DeducedDecl->getDeclName() << DT->getDeducedType()
15053 << D->getDeclName();
15054 if (DeducedDecl->hasInit())
15055 Dia << DeducedDecl->getInit()->getSourceRange();
15056 if (D->getInit())
15057 Dia << D->getInit()->getSourceRange();
15058 D->setInvalidDecl();
15059 break;
15060 }
15061 }
15062 }
15063
15065
15066 return DeclGroupPtrTy::make(
15067 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15068}
15069
15072}
15073
15075 // Don't parse the comment if Doxygen diagnostics are ignored.
15076 if (Group.empty() || !Group[0])
15077 return;
15078
15079 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15080 Group[0]->getLocation()) &&
15081 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15082 Group[0]->getLocation()))
15083 return;
15084
15085 if (Group.size() >= 2) {
15086 // This is a decl group. Normally it will contain only declarations
15087 // produced from declarator list. But in case we have any definitions or
15088 // additional declaration references:
15089 // 'typedef struct S {} S;'
15090 // 'typedef struct S *S;'
15091 // 'struct S *pS;'
15092 // FinalizeDeclaratorGroup adds these as separate declarations.
15093 Decl *MaybeTagDecl = Group[0];
15094 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15095 Group = Group.slice(1);
15096 }
15097 }
15098
15099 // FIMXE: We assume every Decl in the group is in the same file.
15100 // This is false when preprocessor constructs the group from decls in
15101 // different files (e. g. macros or #include).
15103}
15104
15105/// Common checks for a parameter-declaration that should apply to both function
15106/// parameters and non-type template parameters.
15108 // Check that there are no default arguments inside the type of this
15109 // parameter.
15110 if (getLangOpts().CPlusPlus)
15112
15113 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15114 if (D.getCXXScopeSpec().isSet()) {
15115 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15116 << D.getCXXScopeSpec().getRange();
15117 }
15118
15119 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15120 // simple identifier except [...irrelevant cases...].
15121 switch (D.getName().getKind()) {
15123 break;
15124
15132 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15134 break;
15135
15138 // GetNameForDeclarator would not produce a useful name in this case.
15139 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15140 break;
15141 }
15142}
15143
15145 SourceLocation ExplicitThisLoc) {
15146 if (!ExplicitThisLoc.isValid())
15147 return;
15148 assert(S.getLangOpts().CPlusPlus &&
15149 "explicit parameter in non-cplusplus mode");
15150 if (!S.getLangOpts().CPlusPlus23)
15151 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15152 << P->getSourceRange();
15153
15154 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15155 // parameter pack.
15156 if (P->isParameterPack()) {
15157 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15158 << P->getSourceRange();
15159 return;
15160 }
15161 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15162 if (LambdaScopeInfo *LSI = S.getCurLambda())
15163 LSI->ExplicitObjectParameter = P;
15164}
15165
15166/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
15167/// to introduce parameters into function prototype scope.
15169 SourceLocation ExplicitThisLoc) {
15170 const DeclSpec &DS = D.getDeclSpec();
15171
15172 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15173
15174 // C++03 [dcl.stc]p2 also permits 'auto'.
15175 StorageClass SC = SC_None;
15177 SC = SC_Register;
15178 // In C++11, the 'register' storage class specifier is deprecated.
15179 // In C++17, it is not allowed, but we tolerate it as an extension.
15180 if (getLangOpts().CPlusPlus11) {
15182 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
15183 : diag::warn_deprecated_register)
15185 }
15186 } else if (getLangOpts().CPlusPlus &&
15188 SC = SC_Auto;
15191 diag::err_invalid_storage_class_in_func_decl);
15193 }
15194
15196 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15198 if (DS.isInlineSpecified())
15199 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15200 << getLangOpts().CPlusPlus17;
15201 if (DS.hasConstexprSpecifier())
15202 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15203 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15204
15206
15208
15210 QualType parmDeclType = TInfo->getType();
15211
15212 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15213 const IdentifierInfo *II = D.getIdentifier();
15214 if (II) {
15216 RedeclarationKind::ForVisibleRedeclaration);
15217 LookupName(R, S);
15218 if (!R.empty()) {
15219 NamedDecl *PrevDecl = *R.begin();
15220 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15221 // Maybe we will complain about the shadowed template parameter.
15223 // Just pretend that we didn't see the previous declaration.
15224 PrevDecl = nullptr;
15225 }
15226 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15227 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15228 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15229 // Recover by removing the name
15230 II = nullptr;
15231 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15232 D.setInvalidType(true);
15233 }
15234 }
15235 }
15236
15237 // Temporarily put parameter variables in the translation unit, not
15238 // the enclosing context. This prevents them from accidentally
15239 // looking like class members in C++.
15240 ParmVarDecl *New =
15242 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15243
15244 if (D.isInvalidType())
15245 New->setInvalidDecl();
15246
15247 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15248
15249 assert(S->isFunctionPrototypeScope());
15250 assert(S->getFunctionPrototypeDepth() >= 1);
15251 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15252 S->getNextFunctionPrototypeIndex());
15253
15254 // Add the parameter declaration into this scope.
15255 S->AddDecl(New);
15256 if (II)
15257 IdResolver.AddDecl(New);
15258
15259 ProcessDeclAttributes(S, New, D);
15260
15262 Diag(New->getLocation(), diag::err_module_private_local)
15263 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15265
15266 if (New->hasAttr<BlocksAttr>()) {
15267 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15268 }
15269
15270 if (getLangOpts().OpenCL)
15272
15273 return New;
15274}
15275
15276/// Synthesizes a variable for a parameter arising from a
15277/// typedef.
15279 SourceLocation Loc,
15280 QualType T) {
15281 /* FIXME: setting StartLoc == Loc.
15282 Would it be worth to modify callers so as to provide proper source
15283 location for the unnamed parameters, embedding the parameter's type? */
15284 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15286 SC_None, nullptr);
15287 Param->setImplicit();
15288 return Param;
15289}
15290
15292 // Don't diagnose unused-parameter errors in template instantiations; we
15293 // will already have done so in the template itself.
15295 return;
15296
15297 for (const ParmVarDecl *Parameter : Parameters) {
15298 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15299 !Parameter->hasAttr<UnusedAttr>() &&
15300 !Parameter->getIdentifier()->isPlaceholder()) {
15301 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15302 << Parameter->getDeclName();
15303 }
15304 }
15305}
15306
15308 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15309 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15310 return;
15311
15312 // Warn if the return value is pass-by-value and larger than the specified
15313 // threshold.
15314 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15315 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15316 if (Size > LangOpts.NumLargeByValueCopy)
15317 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15318 }
15319
15320 // Warn if any parameter is pass-by-value and larger than the specified
15321 // threshold.
15322 for (const ParmVarDecl *Parameter : Parameters) {
15323 QualType T = Parameter->getType();
15324 if (T->isDependentType() || !T.isPODType(Context))
15325 continue;
15326 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15327 if (Size > LangOpts.NumLargeByValueCopy)
15328 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15329 << Parameter << Size;
15330 }
15331}
15332
15334 SourceLocation NameLoc,
15335 TypeSourceInfo *TSInfo) {
15336 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15337 if (!getLangOpts().ObjCAutoRefCount ||
15338 T.getObjCLifetime() != Qualifiers::OCL_None || !T->isObjCLifetimeType())
15339 return T;
15340
15341 Qualifiers::ObjCLifetime Lifetime;
15342
15343 // Special cases for arrays:
15344 // - if it's const, use __unsafe_unretained
15345 // - otherwise, it's an error
15346 if (T->isArrayType()) {
15347 if (!T.isConstQualified()) {
15350 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15351 else
15352 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15353 << TSInfo->getTypeLoc().getSourceRange();
15354 }
15356 } else {
15357 Lifetime = T->getObjCARCImplicitLifetime();
15358 }
15359 T = Context.getLifetimeQualifiedType(T, Lifetime);
15360
15361 return T;
15362}
15363
15365 SourceLocation NameLoc,
15366 const IdentifierInfo *Name, QualType T,
15367 TypeSourceInfo *TSInfo, StorageClass SC) {
15368 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15369 if (getLangOpts().ObjCAutoRefCount &&
15370 T.getObjCLifetime() == Qualifiers::OCL_None &&
15371 T->isObjCLifetimeType()) {
15372
15373 Qualifiers::ObjCLifetime lifetime;
15374
15375 // Special cases for arrays:
15376 // - if it's const, use __unsafe_unretained
15377 // - otherwise, it's an error
15378 if (T->isArrayType()) {
15379 if (!T.isConstQualified()) {
15383 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15384 else
15385 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15386 << TSInfo->getTypeLoc().getSourceRange();
15387 }
15389 } else {
15390 lifetime = T->getObjCARCImplicitLifetime();
15391 }
15392 T = Context.getLifetimeQualifiedType(T, lifetime);
15393 }
15394
15395 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15397 TSInfo, SC, nullptr);
15398
15399 // Make a note if we created a new pack in the scope of a lambda, so that
15400 // we know that references to that pack must also be expanded within the
15401 // lambda scope.
15402 if (New->isParameterPack())
15403 if (auto *LSI = getEnclosingLambda())
15404 LSI->LocalPacks.push_back(New);
15405
15410
15411 // Parameter declarators cannot be interface types. All ObjC objects are
15412 // passed by reference.
15413 if (T->isObjCObjectType()) {
15414 SourceLocation TypeEndLoc =
15416 Diag(NameLoc,
15417 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15418 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15420 New->setType(T);
15421 }
15422
15423 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15424 // duration shall not be qualified by an address-space qualifier."
15425 // Since all parameters have automatic store duration, they can not have
15426 // an address space.
15427 if (T.getAddressSpace() != LangAS::Default &&
15428 // OpenCL allows function arguments declared to be an array of a type
15429 // to be qualified with an address space.
15430 !(getLangOpts().OpenCL &&
15431 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15432 // WebAssembly allows reference types as parameters. Funcref in particular
15433 // lives in a different address space.
15434 !(T->isFunctionPointerType() &&
15435 T.getAddressSpace() == LangAS::wasm_funcref)) {
15436 Diag(NameLoc, diag::err_arg_with_address_space);
15437 New->setInvalidDecl();
15438 }
15439
15440 // PPC MMA non-pointer types are not allowed as function argument types.
15441 if (Context.getTargetInfo().getTriple().isPPC64() &&
15442 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15443 New->setInvalidDecl();
15444 }
15445
15446 return New;
15447}
15448
15450 SourceLocation LocAfterDecls) {
15452
15453 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15454 // in the declaration list shall have at least one declarator, those
15455 // declarators shall only declare identifiers from the identifier list, and
15456 // every identifier in the identifier list shall be declared.
15457 //
15458 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15459 // identifiers it names shall be declared in the declaration list."
15460 //
15461 // This is why we only diagnose in C99 and later. Note, the other conditions
15462 // listed are checked elsewhere.
15463 if (!FTI.hasPrototype) {
15464 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15465 --i;
15466 if (FTI.Params[i].Param == nullptr) {
15467 if (getLangOpts().C99) {
15468 SmallString<256> Code;
15469 llvm::raw_svector_ostream(Code)
15470 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15471 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15472 << FTI.Params[i].Ident
15473 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15474 }
15475
15476 // Implicitly declare the argument as type 'int' for lack of a better
15477 // type.
15478 AttributeFactory attrs;
15479 DeclSpec DS(attrs);
15480 const char* PrevSpec; // unused
15481 unsigned DiagID; // unused
15482 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15483 DiagID, Context.getPrintingPolicy());
15484 // Use the identifier location for the type source range.
15485 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15486 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15489 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15490 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15491 }
15492 }
15493 }
15494}
15495
15496Decl *
15498 MultiTemplateParamsArg TemplateParameterLists,
15499 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15500 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15501 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15502 Scope *ParentScope = FnBodyScope->getParent();
15503
15504 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15505 // we define a non-templated function definition, we will create a declaration
15506 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15507 // The base function declaration will have the equivalent of an `omp declare
15508 // variant` annotation which specifies the mangled definition as a
15509 // specialization function under the OpenMP context defined as part of the
15510 // `omp begin declare variant`.
15512 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15514 ParentScope, D, TemplateParameterLists, Bases);
15515
15517 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15518 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15519
15520 if (!Bases.empty())
15522 Bases);
15523
15524 return Dcl;
15525}
15526
15529}
15530
15532 const FunctionDecl *&PossiblePrototype) {
15533 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15534 Prev = Prev->getPreviousDecl()) {
15535 // Ignore any declarations that occur in function or method
15536 // scope, because they aren't visible from the header.
15537 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15538 continue;
15539
15540 PossiblePrototype = Prev;
15541 return Prev->getType()->isFunctionProtoType();
15542 }
15543 return false;
15544}
15545
15546static bool
15548 const FunctionDecl *&PossiblePrototype) {
15549 // Don't warn about invalid declarations.
15550 if (FD->isInvalidDecl())
15551 return false;
15552
15553 // Or declarations that aren't global.
15554 if (!FD->isGlobal())
15555 return false;
15556
15557 // Don't warn about C++ member functions.
15558 if (isa<CXXMethodDecl>(FD))
15559 return false;
15560
15561 // Don't warn about 'main'.
15562 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15563 if (IdentifierInfo *II = FD->getIdentifier())
15564 if (II->isStr("main") || II->isStr("efi_main"))
15565 return false;
15566
15567 // Don't warn about inline functions.
15568 if (FD->isInlined())
15569 return false;
15570
15571 // Don't warn about function templates.
15573 return false;
15574
15575 // Don't warn about function template specializations.
15577 return false;
15578
15579 // Don't warn for OpenCL kernels.
15580 if (FD->hasAttr<OpenCLKernelAttr>())
15581 return false;
15582
15583 // Don't warn on explicitly deleted functions.
15584 if (FD->isDeleted())
15585 return false;
15586
15587 // Don't warn on implicitly local functions (such as having local-typed
15588 // parameters).
15589 if (!FD->isExternallyVisible())
15590 return false;
15591
15592 // If we were able to find a potential prototype, don't warn.
15593 if (FindPossiblePrototype(FD, PossiblePrototype))
15594 return false;
15595
15596 return true;
15597}
15598
15599void
15601 const FunctionDecl *EffectiveDefinition,
15602 SkipBodyInfo *SkipBody) {
15603 const FunctionDecl *Definition = EffectiveDefinition;
15604 if (!Definition &&
15605 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15606 return;
15607
15608 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15609 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15610 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15611 // A merged copy of the same function, instantiated as a member of
15612 // the same class, is OK.
15613 if (declaresSameEntity(OrigFD, OrigDef) &&
15614 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15615 cast<Decl>(FD->getLexicalDeclContext())))
15616 return;
15617 }
15618 }
15619 }
15620
15622 return;
15623
15624 // Don't emit an error when this is redefinition of a typo-corrected
15625 // definition.
15627 return;
15628
15629 // If we don't have a visible definition of the function, and it's inline or
15630 // a template, skip the new definition.
15631 if (SkipBody && !hasVisibleDefinition(Definition) &&
15632 (Definition->getFormalLinkage() == Linkage::Internal ||
15633 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15634 Definition->getNumTemplateParameterLists())) {
15635 SkipBody->ShouldSkip = true;
15636 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15637 if (auto *TD = Definition->getDescribedFunctionTemplate())
15640 return;
15641 }
15642
15643 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15644 Definition->getStorageClass() == SC_Extern)
15645 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15646 << FD << getLangOpts().CPlusPlus;
15647 else
15648 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15649
15650 Diag(Definition->getLocation(), diag::note_previous_definition);
15651 FD->setInvalidDecl();
15652}
15653
15655 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15656
15658 LSI->CallOperator = CallOperator;
15659 LSI->Lambda = LambdaClass;
15660 LSI->ReturnType = CallOperator->getReturnType();
15661 // This function in calls in situation where the context of the call operator
15662 // is not entered, so we set AfterParameterList to false, so that
15663 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15664 LSI->AfterParameterList = false;
15665 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15666
15667 if (LCD == LCD_None)
15669 else if (LCD == LCD_ByCopy)
15671 else if (LCD == LCD_ByRef)
15673 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15674
15676 LSI->Mutable = !CallOperator->isConst();
15677 if (CallOperator->isExplicitObjectMemberFunction())
15678 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15679
15680 // Add the captures to the LSI so they can be noted as already
15681 // captured within tryCaptureVar.
15682 auto I = LambdaClass->field_begin();
15683 for (const auto &C : LambdaClass->captures()) {
15684 if (C.capturesVariable()) {
15685 ValueDecl *VD = C.getCapturedVar();
15686 if (VD->isInitCapture())
15688 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15689 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15690 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15691 /*EllipsisLoc*/C.isPackExpansion()
15692 ? C.getEllipsisLoc() : SourceLocation(),
15693 I->getType(), /*Invalid*/false);
15694
15695 } else if (C.capturesThis()) {
15696 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15697 C.getCaptureKind() == LCK_StarThis);
15698 } else {
15699 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15700 I->getType());
15701 }
15702 ++I;
15703 }
15704 return LSI;
15705}
15706
15708 SkipBodyInfo *SkipBody,
15709 FnBodyKind BodyKind) {
15710 if (!D) {
15711 // Parsing the function declaration failed in some way. Push on a fake scope
15712 // anyway so we can try to parse the function body.
15715 return D;
15716 }
15717
15718 FunctionDecl *FD = nullptr;
15719
15720 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15721 FD = FunTmpl->getTemplatedDecl();
15722 else
15723 FD = cast<FunctionDecl>(D);
15724
15725 // Do not push if it is a lambda because one is already pushed when building
15726 // the lambda in ActOnStartOfLambdaDefinition().
15727 if (!isLambdaCallOperator(FD))
15728 // [expr.const]/p14.1
15729 // An expression or conversion is in an immediate function context if it is
15730 // potentially evaluated and either: its innermost enclosing non-block scope
15731 // is a function parameter scope of an immediate function.
15734 : ExprEvalContexts.back().Context);
15735
15736 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15737 // context is nested in an immediate function context, so smaller contexts
15738 // that appear inside immediate functions (like variable initializers) are
15739 // considered to be inside an immediate function context even though by
15740 // themselves they are not immediate function contexts. But when a new
15741 // function is entered, we need to reset this tracking, since the entered
15742 // function might be not an immediate function.
15743 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15744 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15745 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15746
15747 // Check for defining attributes before the check for redefinition.
15748 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15749 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15750 FD->dropAttr<AliasAttr>();
15751 FD->setInvalidDecl();
15752 }
15753 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15754 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15755 FD->dropAttr<IFuncAttr>();
15756 FD->setInvalidDecl();
15757 }
15758 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15759 if (!Context.getTargetInfo().hasFeature("fmv") &&
15760 !Attr->isDefaultVersion()) {
15761 // If function multi versioning disabled skip parsing function body
15762 // defined with non-default target_version attribute
15763 if (SkipBody)
15764 SkipBody->ShouldSkip = true;
15765 return nullptr;
15766 }
15767 }
15768
15769 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15770 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15771 Ctor->isDefaultConstructor() &&
15773 // If this is an MS ABI dllexport default constructor, instantiate any
15774 // default arguments.
15776 }
15777 }
15778
15779 // See if this is a redefinition. If 'will have body' (or similar) is already
15780 // set, then these checks were already performed when it was set.
15781 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15783 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15784
15785 // If we're skipping the body, we're done. Don't enter the scope.
15786 if (SkipBody && SkipBody->ShouldSkip)
15787 return D;
15788 }
15789
15790 // Mark this function as "will have a body eventually". This lets users to
15791 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15792 // this function.
15793 FD->setWillHaveBody();
15794
15795 // If we are instantiating a generic lambda call operator, push
15796 // a LambdaScopeInfo onto the function stack. But use the information
15797 // that's already been calculated (ActOnLambdaExpr) to prime the current
15798 // LambdaScopeInfo.
15799 // When the template operator is being specialized, the LambdaScopeInfo,
15800 // has to be properly restored so that tryCaptureVariable doesn't try
15801 // and capture any new variables. In addition when calculating potential
15802 // captures during transformation of nested lambdas, it is necessary to
15803 // have the LSI properly restored.
15805 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15806 // instantiated, explicitly specialized.
15809 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15810 FD->setInvalidDecl();
15812 } else {
15813 assert(inTemplateInstantiation() &&
15814 "There should be an active template instantiation on the stack "
15815 "when instantiating a generic lambda!");
15816 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15817 }
15818 } else {
15819 // Enter a new function scope
15821 }
15822
15823 // Builtin functions cannot be defined.
15824 if (unsigned BuiltinID = FD->getBuiltinID()) {
15827 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15828 FD->setInvalidDecl();
15829 }
15830 }
15831
15832 // The return type of a function definition must be complete (C99 6.9.1p3).
15833 // C++23 [dcl.fct.def.general]/p2
15834 // The type of [...] the return for a function definition
15835 // shall not be a (possibly cv-qualified) class type that is incomplete
15836 // or abstract within the function body unless the function is deleted.
15837 QualType ResultType = FD->getReturnType();
15838 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15839 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15840 (RequireCompleteType(FD->getLocation(), ResultType,
15841 diag::err_func_def_incomplete_result) ||
15843 diag::err_abstract_type_in_decl,
15845 FD->setInvalidDecl();
15846
15847 if (FnBodyScope)
15848 PushDeclContext(FnBodyScope, FD);
15849
15850 // Check the validity of our function parameters
15851 if (BodyKind != FnBodyKind::Delete)
15853 /*CheckParameterNames=*/true);
15854
15855 // Add non-parameter declarations already in the function to the current
15856 // scope.
15857 if (FnBodyScope) {
15858 for (Decl *NPD : FD->decls()) {
15859 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15860 if (!NonParmDecl)
15861 continue;
15862 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15863 "parameters should not be in newly created FD yet");
15864
15865 // If the decl has a name, make it accessible in the current scope.
15866 if (NonParmDecl->getDeclName())
15867 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15868
15869 // Similarly, dive into enums and fish their constants out, making them
15870 // accessible in this scope.
15871 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15872 for (auto *EI : ED->enumerators())
15873 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15874 }
15875 }
15876 }
15877
15878 // Introduce our parameters into the function scope
15879 for (auto *Param : FD->parameters()) {
15880 Param->setOwningFunction(FD);
15881
15882 // If this has an identifier, add it to the scope stack.
15883 if (Param->getIdentifier() && FnBodyScope) {
15884 CheckShadow(FnBodyScope, Param);
15885
15886 PushOnScopeChains(Param, FnBodyScope);
15887 }
15888 }
15889
15890 // C++ [module.import/6] external definitions are not permitted in header
15891 // units. Deleted and Defaulted functions are implicitly inline (but the
15892 // inline state is not set at this point, so check the BodyKind explicitly).
15893 // FIXME: Consider an alternate location for the test where the inlined()
15894 // state is complete.
15895 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15896 !FD->isInvalidDecl() && !FD->isInlined() &&
15897 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15898 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15899 !FD->isTemplateInstantiation()) {
15900 assert(FD->isThisDeclarationADefinition());
15901 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15902 FD->setInvalidDecl();
15903 }
15904
15905 // Ensure that the function's exception specification is instantiated.
15906 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15908
15909 // dllimport cannot be applied to non-inline function definitions.
15910 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15911 !FD->isTemplateInstantiation()) {
15912 assert(!FD->hasAttr<DLLExportAttr>());
15913 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15914 FD->setInvalidDecl();
15915 return D;
15916 }
15917
15918 // Some function attributes (like OptimizeNoneAttr) need actions before
15919 // parsing body started.
15921
15922 // We want to attach documentation to original Decl (which might be
15923 // a function template).
15925 if (getCurLexicalContext()->isObjCContainer() &&
15926 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15927 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15928 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15929
15930 return D;
15931}
15932
15934 if (!FD || FD->isInvalidDecl())
15935 return;
15936 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
15937 FD = TD->getTemplatedDecl();
15938 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
15942 FpPragmaStack.CurrentValue =
15944 }
15945}
15946
15947/// Given the set of return statements within a function body,
15948/// compute the variables that are subject to the named return value
15949/// optimization.
15950///
15951/// Each of the variables that is subject to the named return value
15952/// optimization will be marked as NRVO variables in the AST, and any
15953/// return statement that has a marked NRVO variable as its NRVO candidate can
15954/// use the named return value optimization.
15955///
15956/// This function applies a very simplistic algorithm for NRVO: if every return
15957/// statement in the scope of a variable has the same NRVO candidate, that
15958/// candidate is an NRVO variable.
15960 ReturnStmt **Returns = Scope->Returns.data();
15961
15962 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15963 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15964 if (!NRVOCandidate->isNRVOVariable())
15965 Returns[I]->setNRVOCandidate(nullptr);
15966 }
15967 }
15968}
15969
15971 // We can't delay parsing the body of a constexpr function template (yet).
15973 return false;
15974
15975 // We can't delay parsing the body of a function template with a deduced
15976 // return type (yet).
15977 if (D.getDeclSpec().hasAutoTypeSpec()) {
15978 // If the placeholder introduces a non-deduced trailing return type,
15979 // we can still delay parsing it.
15980 if (D.getNumTypeObjects()) {
15981 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15982 if (Outer.Kind == DeclaratorChunk::Function &&
15983 Outer.Fun.hasTrailingReturnType()) {
15984 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15985 return Ty.isNull() || !Ty->isUndeducedType();
15986 }
15987 }
15988 return false;
15989 }
15990
15991 return true;
15992}
15993
15995 // We cannot skip the body of a function (or function template) which is
15996 // constexpr, since we may need to evaluate its body in order to parse the
15997 // rest of the file.
15998 // We cannot skip the body of a function with an undeduced return type,
15999 // because any callers of that function need to know the type.
16000 if (const FunctionDecl *FD = D->getAsFunction()) {
16001 if (FD->isConstexpr())
16002 return false;
16003 // We can't simply call Type::isUndeducedType here, because inside template
16004 // auto can be deduced to a dependent type, which is not considered
16005 // "undeduced".
16006 if (FD->getReturnType()->getContainedDeducedType())
16007 return false;
16008 }
16010}
16011
16013 if (!Decl)
16014 return nullptr;
16015 if (FunctionDecl *FD = Decl->getAsFunction())
16016 FD->setHasSkippedBody();
16017 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16018 MD->setHasSkippedBody();
16019 return Decl;
16020}
16021
16023 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
16024}
16025
16026/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16027/// body.
16029public:
16030 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16032 if (!IsLambda)
16034 }
16035
16036private:
16037 Sema &S;
16038 bool IsLambda = false;
16039};
16040
16042 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16043
16044 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16045 if (EscapeInfo.count(BD))
16046 return EscapeInfo[BD];
16047
16048 bool R = false;
16049 const BlockDecl *CurBD = BD;
16050
16051 do {
16052 R = !CurBD->doesNotEscape();
16053 if (R)
16054 break;
16055 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16056 } while (CurBD);
16057
16058 return EscapeInfo[BD] = R;
16059 };
16060
16061 // If the location where 'self' is implicitly retained is inside a escaping
16062 // block, emit a diagnostic.
16063 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16065 if (IsOrNestedInEscapingBlock(P.second))
16066 S.Diag(P.first, diag::warn_implicitly_retains_self)
16067 << FixItHint::CreateInsertion(P.first, "self->");
16068}
16069
16070static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16071 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16072 FD->getDeclName().isIdentifier() && FD->getName().equals(Name);
16073}
16074
16076 return methodHasName(FD, "get_return_object");
16077}
16078
16080 return FD->isStatic() &&
16081 methodHasName(FD, "get_return_object_on_allocation_failure");
16082}
16083
16086 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16087 return;
16088 // Allow some_promise_type::get_return_object().
16090 return;
16091 if (!FD->hasAttr<CoroWrapperAttr>())
16092 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16093}
16094
16096 bool IsInstantiation) {
16098 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16099
16100 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16101 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16102
16104 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16105
16106 // If we skip function body, we can't tell if a function is a coroutine.
16107 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16108 if (FSI->isCoroutine())
16110 else
16112 }
16113
16114 {
16115 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16116 // one is already popped when finishing the lambda in BuildLambdaExpr().
16117 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16118 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16119 if (FD) {
16120 // If this is called by Parser::ParseFunctionDefinition() after marking
16121 // the declaration as deleted, and if the deleted-function-body contains
16122 // a message (C++26), then a DefaultedOrDeletedInfo will have already been
16123 // added to store that message; do not overwrite it in that case.
16124 //
16125 // Since this would always set the body to 'nullptr' in that case anyway,
16126 // which is already done when the function decl is initially created,
16127 // always skipping this irrespective of whether there is a delete message
16128 // should not be a problem.
16129 if (!FD->isDeletedAsWritten())
16130 FD->setBody(Body);
16131 FD->setWillHaveBody(false);
16133
16134 if (getLangOpts().CPlusPlus14) {
16135 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16136 FD->getReturnType()->isUndeducedType()) {
16137 // For a function with a deduced result type to return void,
16138 // the result type as written must be 'auto' or 'decltype(auto)',
16139 // possibly cv-qualified or constrained, but not ref-qualified.
16140 if (!FD->getReturnType()->getAs<AutoType>()) {
16141 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16142 << FD->getReturnType();
16143 FD->setInvalidDecl();
16144 } else {
16145 // Falling off the end of the function is the same as 'return;'.
16146 Expr *Dummy = nullptr;
16148 FD, dcl->getLocation(), Dummy,
16149 FD->getReturnType()->getAs<AutoType>()))
16150 FD->setInvalidDecl();
16151 }
16152 }
16153 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16154 // In C++11, we don't use 'auto' deduction rules for lambda call
16155 // operators because we don't support return type deduction.
16156 auto *LSI = getCurLambda();
16157 if (LSI->HasImplicitReturnType) {
16159
16160 // C++11 [expr.prim.lambda]p4:
16161 // [...] if there are no return statements in the compound-statement
16162 // [the deduced type is] the type void
16163 QualType RetType =
16164 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16165
16166 // Update the return type to the deduced type.
16167 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16168 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16169 Proto->getExtProtoInfo()));
16170 }
16171 }
16172
16173 // If the function implicitly returns zero (like 'main') or is naked,
16174 // don't complain about missing return statements.
16175 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
16177
16178 // MSVC permits the use of pure specifier (=0) on function definition,
16179 // defined at class scope, warn about this non-standard construct.
16180 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16181 !FD->isOutOfLine())
16182 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16183
16184 if (!FD->isInvalidDecl()) {
16185 // Don't diagnose unused parameters of defaulted, deleted or naked
16186 // functions.
16187 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16188 !FD->hasAttr<NakedAttr>())
16191 FD->getReturnType(), FD);
16192
16193 // If this is a structor, we need a vtable.
16194 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16195 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16196 else if (CXXDestructorDecl *Destructor =
16197 dyn_cast<CXXDestructorDecl>(FD))
16198 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16199
16200 // Try to apply the named return value optimization. We have to check
16201 // if we can do this here because lambdas keep return statements around
16202 // to deduce an implicit return type.
16203 if (FD->getReturnType()->isRecordType() &&
16205 computeNRVO(Body, FSI);
16206 }
16207
16208 // GNU warning -Wmissing-prototypes:
16209 // Warn if a global function is defined without a previous
16210 // prototype declaration. This warning is issued even if the
16211 // definition itself provides a prototype. The aim is to detect
16212 // global functions that fail to be declared in header files.
16213 const FunctionDecl *PossiblePrototype = nullptr;
16214 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16215 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16216
16217 if (PossiblePrototype) {
16218 // We found a declaration that is not a prototype,
16219 // but that could be a zero-parameter prototype
16220 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16221 TypeLoc TL = TI->getTypeLoc();
16223 Diag(PossiblePrototype->getLocation(),
16224 diag::note_declaration_not_a_prototype)
16225 << (FD->getNumParams() != 0)
16227 FTL.getRParenLoc(), "void")
16228 : FixItHint{});
16229 }
16230 } else {
16231 // Returns true if the token beginning at this Loc is `const`.
16232 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16233 const LangOptions &LangOpts) {
16234 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
16235 if (LocInfo.first.isInvalid())
16236 return false;
16237
16238 bool Invalid = false;
16239 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16240 if (Invalid)
16241 return false;
16242
16243 if (LocInfo.second > Buffer.size())
16244 return false;
16245
16246 const char *LexStart = Buffer.data() + LocInfo.second;
16247 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16248
16249 return StartTok.consume_front("const") &&
16250 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16251 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16252 };
16253
16254 auto findBeginLoc = [&]() {
16255 // If the return type has `const` qualifier, we want to insert
16256 // `static` before `const` (and not before the typename).
16257 if ((FD->getReturnType()->isAnyPointerType() &&
16260 // But only do this if we can determine where the `const` is.
16261
16262 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16263 getLangOpts()))
16264
16265 return FD->getBeginLoc();
16266 }
16267 return FD->getTypeSpecStartLoc();
16268 };
16270 diag::note_static_for_internal_linkage)
16271 << /* function */ 1
16272 << (FD->getStorageClass() == SC_None
16273 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16274 : FixItHint{});
16275 }
16276 }
16277
16278 // We might not have found a prototype because we didn't wish to warn on
16279 // the lack of a missing prototype. Try again without the checks for
16280 // whether we want to warn on the missing prototype.
16281 if (!PossiblePrototype)
16282 (void)FindPossiblePrototype(FD, PossiblePrototype);
16283
16284 // If the function being defined does not have a prototype, then we may
16285 // need to diagnose it as changing behavior in C23 because we now know
16286 // whether the function accepts arguments or not. This only handles the
16287 // case where the definition has no prototype but does have parameters
16288 // and either there is no previous potential prototype, or the previous
16289 // potential prototype also has no actual prototype. This handles cases
16290 // like:
16291 // void f(); void f(a) int a; {}
16292 // void g(a) int a; {}
16293 // See MergeFunctionDecl() for other cases of the behavior change
16294 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16295 // type without a prototype.
16296 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16297 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16298 !PossiblePrototype->isImplicit()))) {
16299 // The function definition has parameters, so this will change behavior
16300 // in C23. If there is a possible prototype, it comes before the
16301 // function definition.
16302 // FIXME: The declaration may have already been diagnosed as being
16303 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16304 // there's no way to test for the "changes behavior" condition in
16305 // SemaType.cpp when forming the declaration's function type. So, we do
16306 // this awkward dance instead.
16307 //
16308 // If we have a possible prototype and it declares a function with a
16309 // prototype, we don't want to diagnose it; if we have a possible
16310 // prototype and it has no prototype, it may have already been
16311 // diagnosed in SemaType.cpp as deprecated depending on whether
16312 // -Wstrict-prototypes is enabled. If we already warned about it being
16313 // deprecated, add a note that it also changes behavior. If we didn't
16314 // warn about it being deprecated (because the diagnostic is not
16315 // enabled), warn now that it is deprecated and changes behavior.
16316
16317 // This K&R C function definition definitely changes behavior in C23,
16318 // so diagnose it.
16319 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16320 << /*definition*/ 1 << /* not supported in C23 */ 0;
16321
16322 // If we have a possible prototype for the function which is a user-
16323 // visible declaration, we already tested that it has no prototype.
16324 // This will change behavior in C23. This gets a warning rather than a
16325 // note because it's the same behavior-changing problem as with the
16326 // definition.
16327 if (PossiblePrototype)
16328 Diag(PossiblePrototype->getLocation(),
16329 diag::warn_non_prototype_changes_behavior)
16330 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16331 << /*definition*/ 1;
16332 }
16333
16334 // Warn on CPUDispatch with an actual body.
16335 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16336 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16337 if (!CmpndBody->body_empty())
16338 Diag(CmpndBody->body_front()->getBeginLoc(),
16339 diag::warn_dispatch_body_ignored);
16340
16341 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16342 const CXXMethodDecl *KeyFunction;
16343 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16344 MD->isVirtual() &&
16345 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16346 MD == KeyFunction->getCanonicalDecl()) {
16347 // Update the key-function state if necessary for this ABI.
16348 if (FD->isInlined() &&
16351
16352 // If the newly-chosen key function is already defined, then we
16353 // need to mark the vtable as used retroactively.
16354 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16355 const FunctionDecl *Definition;
16356 if (KeyFunction && KeyFunction->isDefined(Definition))
16357 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16358 } else {
16359 // We just defined they key function; mark the vtable as used.
16360 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16361 }
16362 }
16363 }
16364
16365 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16366 "Function parsing confused");
16367 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16368 assert(MD == getCurMethodDecl() && "Method parsing confused");
16369 MD->setBody(Body);
16370 if (!MD->isInvalidDecl()) {
16372 MD->getReturnType(), MD);
16373
16374 if (Body)
16375 computeNRVO(Body, FSI);
16376 }
16377 if (FSI->ObjCShouldCallSuper) {
16378 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16379 << MD->getSelector().getAsString();
16380 FSI->ObjCShouldCallSuper = false;
16381 }
16383 const ObjCMethodDecl *InitMethod = nullptr;
16384 bool isDesignated =
16385 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16386 assert(isDesignated && InitMethod);
16387 (void)isDesignated;
16388
16389 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16390 auto IFace = MD->getClassInterface();
16391 if (!IFace)
16392 return false;
16393 auto SuperD = IFace->getSuperClass();
16394 if (!SuperD)
16395 return false;
16396 return SuperD->getIdentifier() ==
16397 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16398 };
16399 // Don't issue this warning for unavailable inits or direct subclasses
16400 // of NSObject.
16401 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16402 Diag(MD->getLocation(),
16403 diag::warn_objc_designated_init_missing_super_call);
16404 Diag(InitMethod->getLocation(),
16405 diag::note_objc_designated_init_marked_here);
16406 }
16408 }
16409 if (FSI->ObjCWarnForNoInitDelegation) {
16410 // Don't issue this warning for unavaialable inits.
16411 if (!MD->isUnavailable())
16412 Diag(MD->getLocation(),
16413 diag::warn_objc_secondary_init_missing_init_call);
16414 FSI->ObjCWarnForNoInitDelegation = false;
16415 }
16416
16418 } else {
16419 // Parsing the function declaration failed in some way. Pop the fake scope
16420 // we pushed on.
16421 PopFunctionScopeInfo(ActivePolicy, dcl);
16422 return nullptr;
16423 }
16424
16425 if (Body && FSI->HasPotentialAvailabilityViolations)
16427
16428 assert(!FSI->ObjCShouldCallSuper &&
16429 "This should only be set for ObjC methods, which should have been "
16430 "handled in the block above.");
16431
16432 // Verify and clean out per-function state.
16433 if (Body && (!FD || !FD->isDefaulted())) {
16434 // C++ constructors that have function-try-blocks can't have return
16435 // statements in the handlers of that block. (C++ [except.handle]p14)
16436 // Verify this.
16437 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16438 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16439
16440 // Verify that gotos and switch cases don't jump into scopes illegally.
16443
16444 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16445 if (!Destructor->getParent()->isDependentType())
16447
16449 Destructor->getParent());
16450 }
16451
16452 // If any errors have occurred, clear out any temporaries that may have
16453 // been leftover. This ensures that these temporaries won't be picked up
16454 // for deletion in some later function.
16457 getDiagnostics().getSuppressAllDiagnostics()) {
16459 }
16460 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16461 // Since the body is valid, issue any analysis-based warnings that are
16462 // enabled.
16463 ActivePolicy = &WP;
16464 }
16465
16466 if (!IsInstantiation && FD &&
16467 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16468 !FD->isInvalidDecl() &&
16470 FD->setInvalidDecl();
16471
16472 if (FD && FD->hasAttr<NakedAttr>()) {
16473 for (const Stmt *S : Body->children()) {
16474 // Allow local register variables without initializer as they don't
16475 // require prologue.
16476 bool RegisterVariables = false;
16477 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16478 for (const auto *Decl : DS->decls()) {
16479 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16480 RegisterVariables =
16481 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16482 if (!RegisterVariables)
16483 break;
16484 }
16485 }
16486 }
16487 if (RegisterVariables)
16488 continue;
16489 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16490 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16491 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16492 FD->setInvalidDecl();
16493 break;
16494 }
16495 }
16496 }
16497
16498 assert(ExprCleanupObjects.size() ==
16499 ExprEvalContexts.back().NumCleanupObjects &&
16500 "Leftover temporaries in function");
16501 assert(!Cleanup.exprNeedsCleanups() &&
16502 "Unaccounted cleanups in function");
16503 assert(MaybeODRUseExprs.empty() &&
16504 "Leftover expressions for odr-use checking");
16505 }
16506 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16507 // the declaration context below. Otherwise, we're unable to transform
16508 // 'this' expressions when transforming immediate context functions.
16509
16510 if (!IsInstantiation)
16512
16513 PopFunctionScopeInfo(ActivePolicy, dcl);
16514 // If any errors have occurred, clear out any temporaries that may have
16515 // been leftover. This ensures that these temporaries won't be picked up for
16516 // deletion in some later function.
16519 }
16520
16521 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16522 !LangOpts.OMPTargetTriples.empty())) ||
16523 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16524 auto ES = getEmissionStatus(FD);
16527 DeclsToCheckForDeferredDiags.insert(FD);
16528 }
16529
16530 if (FD && !FD->isDeleted())
16531 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16532
16533 return dcl;
16534}
16535
16536/// When we finish delayed parsing of an attribute, we must attach it to the
16537/// relevant Decl.
16539 ParsedAttributes &Attrs) {
16540 // Always attach attributes to the underlying decl.
16541 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16542 D = TD->getTemplatedDecl();
16543 ProcessDeclAttributeList(S, D, Attrs);
16544 ProcessAPINotes(D);
16545
16546 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16547 if (Method->isStatic())
16549}
16550
16551/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
16552/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
16554 IdentifierInfo &II, Scope *S) {
16555 // It is not valid to implicitly define a function in C23.
16557 "Implicit function declarations aren't allowed in this language mode");
16558
16559 // Find the scope in which the identifier is injected and the corresponding
16560 // DeclContext.
16561 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16562 // In that case, we inject the declaration into the translation unit scope
16563 // instead.
16564 Scope *BlockScope = S;
16565 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16566 BlockScope = BlockScope->getParent();
16567
16568 // Loop until we find a DeclContext that is either a function/method or the
16569 // translation unit, which are the only two valid places to implicitly define
16570 // a function. This avoids accidentally defining the function within a tag
16571 // declaration, for example.
16572 Scope *ContextScope = BlockScope;
16573 while (!ContextScope->getEntity() ||
16574 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16575 !ContextScope->getEntity()->isTranslationUnit()))
16576 ContextScope = ContextScope->getParent();
16577 ContextRAII SavedContext(*this, ContextScope->getEntity());
16578
16579 // Before we produce a declaration for an implicitly defined
16580 // function, see whether there was a locally-scoped declaration of
16581 // this name as a function or variable. If so, use that
16582 // (non-visible) declaration, and complain about it.
16583 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16584 if (ExternCPrev) {
16585 // We still need to inject the function into the enclosing block scope so
16586 // that later (non-call) uses can see it.
16587 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16588
16589 // C89 footnote 38:
16590 // If in fact it is not defined as having type "function returning int",
16591 // the behavior is undefined.
16592 if (!isa<FunctionDecl>(ExternCPrev) ||
16594 cast<FunctionDecl>(ExternCPrev)->getType(),
16596 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16597 << ExternCPrev << !getLangOpts().C99;
16598 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16599 return ExternCPrev;
16600 }
16601 }
16602
16603 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16604 unsigned diag_id;
16605 if (II.getName().starts_with("__builtin_"))
16606 diag_id = diag::warn_builtin_unknown;
16607 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16608 else if (getLangOpts().C99)
16609 diag_id = diag::ext_implicit_function_decl_c99;
16610 else
16611 diag_id = diag::warn_implicit_function_decl;
16612
16613 TypoCorrection Corrected;
16614 // Because typo correction is expensive, only do it if the implicit
16615 // function declaration is going to be treated as an error.
16616 //
16617 // Perform the correction before issuing the main diagnostic, as some
16618 // consumers use typo-correction callbacks to enhance the main diagnostic.
16619 if (S && !ExternCPrev &&
16622 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16623 S, nullptr, CCC, CTK_NonError);
16624 }
16625
16626 Diag(Loc, diag_id) << &II;
16627 if (Corrected) {
16628 // If the correction is going to suggest an implicitly defined function,
16629 // skip the correction as not being a particularly good idea.
16630 bool Diagnose = true;
16631 if (const auto *D = Corrected.getCorrectionDecl())
16632 Diagnose = !D->isImplicit();
16633 if (Diagnose)
16634 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16635 /*ErrorRecovery*/ false);
16636 }
16637
16638 // If we found a prior declaration of this function, don't bother building
16639 // another one. We've already pushed that one into scope, so there's nothing
16640 // more to do.
16641 if (ExternCPrev)
16642 return ExternCPrev;
16643
16644 // Set a Declarator for the implicit definition: int foo();
16645 const char *Dummy;
16646 AttributeFactory attrFactory;
16647 DeclSpec DS(attrFactory);
16648 unsigned DiagID;
16649 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16651 (void)Error; // Silence warning.
16652 assert(!Error && "Error setting up implicit decl!");
16653 SourceLocation NoLoc;
16655 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16656 /*IsAmbiguous=*/false,
16657 /*LParenLoc=*/NoLoc,
16658 /*Params=*/nullptr,
16659 /*NumParams=*/0,
16660 /*EllipsisLoc=*/NoLoc,
16661 /*RParenLoc=*/NoLoc,
16662 /*RefQualifierIsLvalueRef=*/true,
16663 /*RefQualifierLoc=*/NoLoc,
16664 /*MutableLoc=*/NoLoc, EST_None,
16665 /*ESpecRange=*/SourceRange(),
16666 /*Exceptions=*/nullptr,
16667 /*ExceptionRanges=*/nullptr,
16668 /*NumExceptions=*/0,
16669 /*NoexceptExpr=*/nullptr,
16670 /*ExceptionSpecTokens=*/nullptr,
16671 /*DeclsInPrototype=*/std::nullopt,
16672 Loc, Loc, D),
16673 std::move(DS.getAttributes()), SourceLocation());
16674 D.SetIdentifier(&II, Loc);
16675
16676 // Insert this function into the enclosing block scope.
16677 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16678 FD->setImplicit();
16679
16681
16682 return FD;
16683}
16684
16685/// If this function is a C++ replaceable global allocation function
16686/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16687/// adds any function attributes that we know a priori based on the standard.
16688///
16689/// We need to check for duplicate attributes both here and where user-written
16690/// attributes are applied to declarations.
16692 FunctionDecl *FD) {
16693 if (FD->isInvalidDecl())
16694 return;
16695
16696 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16697 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16698 return;
16699
16700 std::optional<unsigned> AlignmentParam;
16701 bool IsNothrow = false;
16702 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16703 return;
16704
16705 // C++2a [basic.stc.dynamic.allocation]p4:
16706 // An allocation function that has a non-throwing exception specification
16707 // indicates failure by returning a null pointer value. Any other allocation
16708 // function never returns a null pointer value and indicates failure only by
16709 // throwing an exception [...]
16710 //
16711 // However, -fcheck-new invalidates this possible assumption, so don't add
16712 // NonNull when that is enabled.
16713 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16714 !getLangOpts().CheckNew)
16715 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16716
16717 // C++2a [basic.stc.dynamic.allocation]p2:
16718 // An allocation function attempts to allocate the requested amount of
16719 // storage. [...] If the request succeeds, the value returned by a
16720 // replaceable allocation function is a [...] pointer value p0 different
16721 // from any previously returned value p1 [...]
16722 //
16723 // However, this particular information is being added in codegen,
16724 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16725
16726 // C++2a [basic.stc.dynamic.allocation]p2:
16727 // An allocation function attempts to allocate the requested amount of
16728 // storage. If it is successful, it returns the address of the start of a
16729 // block of storage whose length in bytes is at least as large as the
16730 // requested size.
16731 if (!FD->hasAttr<AllocSizeAttr>()) {
16732 FD->addAttr(AllocSizeAttr::CreateImplicit(
16733 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16734 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16735 }
16736
16737 // C++2a [basic.stc.dynamic.allocation]p3:
16738 // For an allocation function [...], the pointer returned on a successful
16739 // call shall represent the address of storage that is aligned as follows:
16740 // (3.1) If the allocation function takes an argument of type
16741 // std​::​align_­val_­t, the storage will have the alignment
16742 // specified by the value of this argument.
16743 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16744 FD->addAttr(AllocAlignAttr::CreateImplicit(
16745 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16746 }
16747
16748 // FIXME:
16749 // C++2a [basic.stc.dynamic.allocation]p3:
16750 // For an allocation function [...], the pointer returned on a successful
16751 // call shall represent the address of storage that is aligned as follows:
16752 // (3.2) Otherwise, if the allocation function is named operator new[],
16753 // the storage is aligned for any object that does not have
16754 // new-extended alignment ([basic.align]) and is no larger than the
16755 // requested size.
16756 // (3.3) Otherwise, the storage is aligned for any object that does not
16757 // have new-extended alignment and is of the requested size.
16758}
16759
16760/// Adds any function attributes that we know a priori based on
16761/// the declaration of this function.
16762///
16763/// These attributes can apply both to implicitly-declared builtins
16764/// (like __builtin___printf_chk) or to library-declared functions
16765/// like NSLog or printf.
16766///
16767/// We need to check for duplicate attributes both here and where user-written
16768/// attributes are applied to declarations.
16770 if (FD->isInvalidDecl())
16771 return;
16772
16773 // If this is a built-in function, map its builtin attributes to
16774 // actual attributes.
16775 if (unsigned BuiltinID = FD->getBuiltinID()) {
16776 // Handle printf-formatting attributes.
16777 unsigned FormatIdx;
16778 bool HasVAListArg;
16779 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16780 if (!FD->hasAttr<FormatAttr>()) {
16781 const char *fmt = "printf";
16782 unsigned int NumParams = FD->getNumParams();
16783 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16784 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16785 fmt = "NSString";
16786 FD->addAttr(FormatAttr::CreateImplicit(Context,
16787 &Context.Idents.get(fmt),
16788 FormatIdx+1,
16789 HasVAListArg ? 0 : FormatIdx+2,
16790 FD->getLocation()));
16791 }
16792 }
16793 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16794 HasVAListArg)) {
16795 if (!FD->hasAttr<FormatAttr>())
16796 FD->addAttr(FormatAttr::CreateImplicit(Context,
16797 &Context.Idents.get("scanf"),
16798 FormatIdx+1,
16799 HasVAListArg ? 0 : FormatIdx+2,
16800 FD->getLocation()));
16801 }
16802
16803 // Handle automatically recognized callbacks.
16804 SmallVector<int, 4> Encoding;
16805 if (!FD->hasAttr<CallbackAttr>() &&
16806 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16807 FD->addAttr(CallbackAttr::CreateImplicit(
16808 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16809
16810 // Mark const if we don't care about errno and/or floating point exceptions
16811 // that are the only thing preventing the function from being const. This
16812 // allows IRgen to use LLVM intrinsics for such functions.
16813 bool NoExceptions =
16815 bool ConstWithoutErrnoAndExceptions =
16817 bool ConstWithoutExceptions =
16819 if (!FD->hasAttr<ConstAttr>() &&
16820 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16821 (!ConstWithoutErrnoAndExceptions ||
16822 (!getLangOpts().MathErrno && NoExceptions)) &&
16823 (!ConstWithoutExceptions || NoExceptions))
16824 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16825
16826 // We make "fma" on GNU or Windows const because we know it does not set
16827 // errno in those environments even though it could set errno based on the
16828 // C standard.
16829 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16830 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16831 !FD->hasAttr<ConstAttr>()) {
16832 switch (BuiltinID) {
16833 case Builtin::BI__builtin_fma:
16834 case Builtin::BI__builtin_fmaf:
16835 case Builtin::BI__builtin_fmal:
16836 case Builtin::BIfma:
16837 case Builtin::BIfmaf:
16838 case Builtin::BIfmal:
16839 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16840 break;
16841 default:
16842 break;
16843 }
16844 }
16845
16846 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16847 !FD->hasAttr<ReturnsTwiceAttr>())
16848 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16849 FD->getLocation()));
16850 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16851 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16852 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16853 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16854 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16855 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16856 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16857 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16858 // Add the appropriate attribute, depending on the CUDA compilation mode
16859 // and which target the builtin belongs to. For example, during host
16860 // compilation, aux builtins are __device__, while the rest are __host__.
16861 if (getLangOpts().CUDAIsDevice !=
16863 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16864 else
16865 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16866 }
16867
16868 // Add known guaranteed alignment for allocation functions.
16869 switch (BuiltinID) {
16870 case Builtin::BImemalign:
16871 case Builtin::BIaligned_alloc:
16872 if (!FD->hasAttr<AllocAlignAttr>())
16873 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16874 FD->getLocation()));
16875 break;
16876 default:
16877 break;
16878 }
16879
16880 // Add allocsize attribute for allocation functions.
16881 switch (BuiltinID) {
16882 case Builtin::BIcalloc:
16883 FD->addAttr(AllocSizeAttr::CreateImplicit(
16884 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16885 break;
16886 case Builtin::BImemalign:
16887 case Builtin::BIaligned_alloc:
16888 case Builtin::BIrealloc:
16889 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16890 ParamIdx(), FD->getLocation()));
16891 break;
16892 case Builtin::BImalloc:
16893 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16894 ParamIdx(), FD->getLocation()));
16895 break;
16896 default:
16897 break;
16898 }
16899
16900 // Add lifetime attribute to std::move, std::fowrard et al.
16901 switch (BuiltinID) {
16902 case Builtin::BIaddressof:
16903 case Builtin::BI__addressof:
16904 case Builtin::BI__builtin_addressof:
16905 case Builtin::BIas_const:
16906 case Builtin::BIforward:
16907 case Builtin::BIforward_like:
16908 case Builtin::BImove:
16909 case Builtin::BImove_if_noexcept:
16910 if (ParmVarDecl *P = FD->getParamDecl(0u);
16911 !P->hasAttr<LifetimeBoundAttr>())
16912 P->addAttr(
16913 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16914 break;
16915 default:
16916 break;
16917 }
16918 }
16919
16921
16922 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16923 // throw, add an implicit nothrow attribute to any extern "C" function we come
16924 // across.
16925 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16926 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16927 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16928 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16929 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16930 }
16931
16932 IdentifierInfo *Name = FD->getIdentifier();
16933 if (!Name)
16934 return;
16936 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16937 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16939 // Okay: this could be a libc/libm/Objective-C function we know
16940 // about.
16941 } else
16942 return;
16943
16944 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16945 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16946 // target-specific builtins, perhaps?
16947 if (!FD->hasAttr<FormatAttr>())
16948 FD->addAttr(FormatAttr::CreateImplicit(Context,
16949 &Context.Idents.get("printf"), 2,
16950 Name->isStr("vasprintf") ? 0 : 3,
16951 FD->getLocation()));
16952 }
16953
16954 if (Name->isStr("__CFStringMakeConstantString")) {
16955 // We already have a __builtin___CFStringMakeConstantString,
16956 // but builds that use -fno-constant-cfstrings don't go through that.
16957 if (!FD->hasAttr<FormatArgAttr>())
16958 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16959 FD->getLocation()));
16960 }
16961}
16962
16964 TypeSourceInfo *TInfo) {
16965 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16966 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16967
16968 if (!TInfo) {
16969 assert(D.isInvalidType() && "no declarator info for valid type");
16971 }
16972
16973 // Scope manipulation handled by caller.
16974 TypedefDecl *NewTD =
16976 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16977
16978 // Bail out immediately if we have an invalid declaration.
16979 if (D.isInvalidType()) {
16980 NewTD->setInvalidDecl();
16981 return NewTD;
16982 }
16983
16986 Diag(NewTD->getLocation(), diag::err_module_private_local)
16987 << 2 << NewTD
16991 else
16992 NewTD->setModulePrivate();
16993 }
16994
16995 // C++ [dcl.typedef]p8:
16996 // If the typedef declaration defines an unnamed class (or
16997 // enum), the first typedef-name declared by the declaration
16998 // to be that class type (or enum type) is used to denote the
16999 // class type (or enum type) for linkage purposes only.
17000 // We need to check whether the type was declared in the declaration.
17001 switch (D.getDeclSpec().getTypeSpecType()) {
17002 case TST_enum:
17003 case TST_struct:
17004 case TST_interface:
17005 case TST_union:
17006 case TST_class: {
17007 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17008 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17009 break;
17010 }
17011
17012 default:
17013 break;
17014 }
17015
17016 return NewTD;
17017}
17018
17019/// Check that this is a valid underlying type for an enum declaration.
17021 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17022 QualType T = TI->getType();
17023
17024 if (T->isDependentType())
17025 return false;
17026
17027 // This doesn't use 'isIntegralType' despite the error message mentioning
17028 // integral type because isIntegralType would also allow enum types in C.
17029 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17030 if (BT->isInteger())
17031 return false;
17032
17033 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17034 << T << T->isBitIntType();
17035}
17036
17037/// Check whether this is a valid redeclaration of a previous enumeration.
17038/// \return true if the redeclaration was invalid.
17040 QualType EnumUnderlyingTy, bool IsFixed,
17041 const EnumDecl *Prev) {
17042 if (IsScoped != Prev->isScoped()) {
17043 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17044 << Prev->isScoped();
17045 Diag(Prev->getLocation(), diag::note_previous_declaration);
17046 return true;
17047 }
17048
17049 if (IsFixed && Prev->isFixed()) {
17050 if (!EnumUnderlyingTy->isDependentType() &&
17051 !Prev->getIntegerType()->isDependentType() &&
17052 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17053 Prev->getIntegerType())) {
17054 // TODO: Highlight the underlying type of the redeclaration.
17055 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17056 << EnumUnderlyingTy << Prev->getIntegerType();
17057 Diag(Prev->getLocation(), diag::note_previous_declaration)
17058 << Prev->getIntegerTypeRange();
17059 return true;
17060 }
17061 } else if (IsFixed != Prev->isFixed()) {
17062 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17063 << Prev->isFixed();
17064 Diag(Prev->getLocation(), diag::note_previous_declaration);
17065 return true;
17066 }
17067
17068 return false;
17069}
17070
17071/// Get diagnostic %select index for tag kind for
17072/// redeclaration diagnostic message.
17073/// WARNING: Indexes apply to particular diagnostics only!
17074///
17075/// \returns diagnostic %select index.
17077 switch (Tag) {
17079 return 0;
17081 return 1;
17082 case TagTypeKind::Class:
17083 return 2;
17084 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17085 }
17086}
17087
17088/// Determine if tag kind is a class-key compatible with
17089/// class for redeclaration (class, struct, or __interface).
17090///
17091/// \returns true iff the tag kind is compatible.
17093{
17094 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17096}
17097
17099 TagTypeKind TTK) {
17100 if (isa<TypedefDecl>(PrevDecl))
17101 return NTK_Typedef;
17102 else if (isa<TypeAliasDecl>(PrevDecl))
17103 return NTK_TypeAlias;
17104 else if (isa<ClassTemplateDecl>(PrevDecl))
17105 return NTK_Template;
17106 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17107 return NTK_TypeAliasTemplate;
17108 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17110 switch (TTK) {
17113 case TagTypeKind::Class:
17114 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
17115 case TagTypeKind::Union:
17116 return NTK_NonUnion;
17117 case TagTypeKind::Enum:
17118 return NTK_NonEnum;
17119 }
17120 llvm_unreachable("invalid TTK");
17121}
17122
17123/// Determine whether a tag with a given kind is acceptable
17124/// as a redeclaration of the given tag declaration.
17125///
17126/// \returns true if the new tag kind is acceptable, false otherwise.
17128 TagTypeKind NewTag, bool isDefinition,
17129 SourceLocation NewTagLoc,
17130 const IdentifierInfo *Name) {
17131 // C++ [dcl.type.elab]p3:
17132 // The class-key or enum keyword present in the
17133 // elaborated-type-specifier shall agree in kind with the
17134 // declaration to which the name in the elaborated-type-specifier
17135 // refers. This rule also applies to the form of
17136 // elaborated-type-specifier that declares a class-name or
17137 // friend class since it can be construed as referring to the
17138 // definition of the class. Thus, in any
17139 // elaborated-type-specifier, the enum keyword shall be used to
17140 // refer to an enumeration (7.2), the union class-key shall be
17141 // used to refer to a union (clause 9), and either the class or
17142 // struct class-key shall be used to refer to a class (clause 9)
17143 // declared using the class or struct class-key.
17144 TagTypeKind OldTag = Previous->getTagKind();
17145 if (OldTag != NewTag &&
17146 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
17147 return false;
17148
17149 // Tags are compatible, but we might still want to warn on mismatched tags.
17150 // Non-class tags can't be mismatched at this point.
17151 if (!isClassCompatTagKind(NewTag))
17152 return true;
17153
17154 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17155 // by our warning analysis. We don't want to warn about mismatches with (eg)
17156 // declarations in system headers that are designed to be specialized, but if
17157 // a user asks us to warn, we should warn if their code contains mismatched
17158 // declarations.
17159 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17160 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17161 Loc);
17162 };
17163 if (IsIgnoredLoc(NewTagLoc))
17164 return true;
17165
17166 auto IsIgnored = [&](const TagDecl *Tag) {
17167 return IsIgnoredLoc(Tag->getLocation());
17168 };
17169 while (IsIgnored(Previous)) {
17170 Previous = Previous->getPreviousDecl();
17171 if (!Previous)
17172 return true;
17173 OldTag = Previous->getTagKind();
17174 }
17175
17176 bool isTemplate = false;
17177 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17178 isTemplate = Record->getDescribedClassTemplate();
17179
17181 if (OldTag != NewTag) {
17182 // In a template instantiation, do not offer fix-its for tag mismatches
17183 // since they usually mess up the template instead of fixing the problem.
17184 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17185 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17186 << getRedeclDiagFromTagKind(OldTag);
17187 // FIXME: Note previous location?
17188 }
17189 return true;
17190 }
17191
17192 if (isDefinition) {
17193 // On definitions, check all previous tags and issue a fix-it for each
17194 // one that doesn't match the current tag.
17195 if (Previous->getDefinition()) {
17196 // Don't suggest fix-its for redefinitions.
17197 return true;
17198 }
17199
17200 bool previousMismatch = false;
17201 for (const TagDecl *I : Previous->redecls()) {
17202 if (I->getTagKind() != NewTag) {
17203 // Ignore previous declarations for which the warning was disabled.
17204 if (IsIgnored(I))
17205 continue;
17206
17207 if (!previousMismatch) {
17208 previousMismatch = true;
17209 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17210 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17211 << getRedeclDiagFromTagKind(I->getTagKind());
17212 }
17213 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17214 << getRedeclDiagFromTagKind(NewTag)
17215 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17217 }
17218 }
17219 return true;
17220 }
17221
17222 // Identify the prevailing tag kind: this is the kind of the definition (if
17223 // there is a non-ignored definition), or otherwise the kind of the prior
17224 // (non-ignored) declaration.
17225 const TagDecl *PrevDef = Previous->getDefinition();
17226 if (PrevDef && IsIgnored(PrevDef))
17227 PrevDef = nullptr;
17228 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17229 if (Redecl->getTagKind() != NewTag) {
17230 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17231 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17232 << getRedeclDiagFromTagKind(OldTag);
17233 Diag(Redecl->getLocation(), diag::note_previous_use);
17234
17235 // If there is a previous definition, suggest a fix-it.
17236 if (PrevDef) {
17237 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17241 }
17242 }
17243
17244 return true;
17245}
17246
17247/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17248/// from an outer enclosing namespace or file scope inside a friend declaration.
17249/// This should provide the commented out code in the following snippet:
17250/// namespace N {
17251/// struct X;
17252/// namespace M {
17253/// struct Y { friend struct /*N::*/ X; };
17254/// }
17255/// }
17257 SourceLocation NameLoc) {
17258 // While the decl is in a namespace, do repeated lookup of that name and see
17259 // if we get the same namespace back. If we do not, continue until
17260 // translation unit scope, at which point we have a fully qualified NNS.
17263 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17264 // This tag should be declared in a namespace, which can only be enclosed by
17265 // other namespaces. Bail if there's an anonymous namespace in the chain.
17266 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17267 if (!Namespace || Namespace->isAnonymousNamespace())
17268 return FixItHint();
17269 IdentifierInfo *II = Namespace->getIdentifier();
17270 Namespaces.push_back(II);
17271 NamedDecl *Lookup = SemaRef.LookupSingleName(
17272 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17273 if (Lookup == Namespace)
17274 break;
17275 }
17276
17277 // Once we have all the namespaces, reverse them to go outermost first, and
17278 // build an NNS.
17279 SmallString<64> Insertion;
17280 llvm::raw_svector_ostream OS(Insertion);
17281 if (DC->isTranslationUnit())
17282 OS << "::";
17283 std::reverse(Namespaces.begin(), Namespaces.end());
17284 for (auto *II : Namespaces)
17285 OS << II->getName() << "::";
17286 return FixItHint::CreateInsertion(NameLoc, Insertion);
17287}
17288
17289/// Determine whether a tag originally declared in context \p OldDC can
17290/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17291/// found a declaration in \p OldDC as a previous decl, perhaps through a
17292/// using-declaration).
17294 DeclContext *NewDC) {
17295 OldDC = OldDC->getRedeclContext();
17296 NewDC = NewDC->getRedeclContext();
17297
17298 if (OldDC->Equals(NewDC))
17299 return true;
17300
17301 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17302 // encloses the other).
17303 if (S.getLangOpts().MSVCCompat &&
17304 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17305 return true;
17306
17307 return false;
17308}
17309
17310/// This is invoked when we see 'struct foo' or 'struct {'. In the
17311/// former case, Name will be non-null. In the later case, Name will be null.
17312/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
17313/// reference/declaration/definition of a tag.
17314///
17315/// \param IsTypeSpecifier \c true if this is a type-specifier (or
17316/// trailing-type-specifier) other than one in an alias-declaration.
17317///
17318/// \param SkipBody If non-null, will be set to indicate if the caller should
17319/// skip the definition of this tag and treat it as if it were a declaration.
17321Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17322 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17323 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17324 SourceLocation ModulePrivateLoc,
17325 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17326 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17327 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17328 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17329 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17330 // If this is not a definition, it must have a name.
17331 IdentifierInfo *OrigName = Name;
17332 assert((Name != nullptr || TUK == TUK_Definition) &&
17333 "Nameless record must be a definition!");
17334 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
17335
17336 OwnedDecl = false;
17338 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17339
17340 // FIXME: Check member specializations more carefully.
17341 bool isMemberSpecialization = false;
17342 bool Invalid = false;
17343
17344 // We only need to do this matching if we have template parameters
17345 // or a scope specifier, which also conveniently avoids this work
17346 // for non-C++ cases.
17347 if (TemplateParameterLists.size() > 0 ||
17348 (SS.isNotEmpty() && TUK != TUK_Reference)) {
17349 TemplateParameterList *TemplateParams =
17351 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17352 TUK == TUK_Friend, isMemberSpecialization, Invalid);
17353
17354 // C++23 [dcl.type.elab] p2:
17355 // If an elaborated-type-specifier is the sole constituent of a
17356 // declaration, the declaration is ill-formed unless it is an explicit
17357 // specialization, an explicit instantiation or it has one of the
17358 // following forms: [...]
17359 // C++23 [dcl.enum] p1:
17360 // If the enum-head-name of an opaque-enum-declaration contains a
17361 // nested-name-specifier, the declaration shall be an explicit
17362 // specialization.
17363 //
17364 // FIXME: Class template partial specializations can be forward declared
17365 // per CWG2213, but the resolution failed to allow qualified forward
17366 // declarations. This is almost certainly unintentional, so we allow them.
17367 if (TUK == TUK_Declaration && SS.isNotEmpty() && !isMemberSpecialization)
17368 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17370
17371 if (TemplateParams) {
17372 if (Kind == TagTypeKind::Enum) {
17373 Diag(KWLoc, diag::err_enum_template);
17374 return true;
17375 }
17376
17377 if (TemplateParams->size() > 0) {
17378 // This is a declaration or definition of a class template (which may
17379 // be a member of another template).
17380
17381 if (Invalid)
17382 return true;
17383
17384 OwnedDecl = false;
17386 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17387 AS, ModulePrivateLoc,
17388 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17389 TemplateParameterLists.data(), SkipBody);
17390 return Result.get();
17391 } else {
17392 // The "template<>" header is extraneous.
17393 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17394 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17395 isMemberSpecialization = true;
17396 }
17397 }
17398
17399 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17400 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17401 return true;
17402 }
17403
17404 if (TUK == TUK_Friend && Kind == TagTypeKind::Enum) {
17405 // C++23 [dcl.type.elab]p4:
17406 // If an elaborated-type-specifier appears with the friend specifier as
17407 // an entire member-declaration, the member-declaration shall have one
17408 // of the following forms:
17409 // friend class-key nested-name-specifier(opt) identifier ;
17410 // friend class-key simple-template-id ;
17411 // friend class-key nested-name-specifier template(opt)
17412 // simple-template-id ;
17413 //
17414 // Since enum is not a class-key, so declarations like "friend enum E;"
17415 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17416 // invalid, most implementations accept so we issue a pedantic warning.
17417 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17418 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17419 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17420 Diag(KWLoc, diag::note_enum_friend)
17421 << (ScopedEnum + ScopedEnumUsesClassTag);
17422 }
17423
17424 // Figure out the underlying type if this a enum declaration. We need to do
17425 // this early, because it's needed to detect if this is an incompatible
17426 // redeclaration.
17427 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17428 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17429
17430 if (Kind == TagTypeKind::Enum) {
17431 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17432 // No underlying type explicitly specified, or we failed to parse the
17433 // type, default to int.
17434 EnumUnderlying = Context.IntTy.getTypePtr();
17435 } else if (UnderlyingType.get()) {
17436 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17437 // integral type; any cv-qualification is ignored.
17438 TypeSourceInfo *TI = nullptr;
17439 GetTypeFromParser(UnderlyingType.get(), &TI);
17440 EnumUnderlying = TI;
17441
17443 // Recover by falling back to int.
17444 EnumUnderlying = Context.IntTy.getTypePtr();
17445
17448 EnumUnderlying = Context.IntTy.getTypePtr();
17449
17450 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17451 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17452 // of 'int'. However, if this is an unfixed forward declaration, don't set
17453 // the underlying type unless the user enables -fms-compatibility. This
17454 // makes unfixed forward declared enums incomplete and is more conforming.
17455 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
17456 EnumUnderlying = Context.IntTy.getTypePtr();
17457 }
17458 }
17459
17460 DeclContext *SearchDC = CurContext;
17461 DeclContext *DC = CurContext;
17462 bool isStdBadAlloc = false;
17463 bool isStdAlignValT = false;
17464
17466 if (TUK == TUK_Friend || TUK == TUK_Reference)
17467 Redecl = RedeclarationKind::NotForRedeclaration;
17468
17469 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17470 /// implemented asks for structural equivalence checking, the returned decl
17471 /// here is passed back to the parser, allowing the tag body to be parsed.
17472 auto createTagFromNewDecl = [&]() -> TagDecl * {
17473 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17474 // If there is an identifier, use the location of the identifier as the
17475 // location of the decl, otherwise use the location of the struct/union
17476 // keyword.
17477 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17478 TagDecl *New = nullptr;
17479
17480 if (Kind == TagTypeKind::Enum) {
17481 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17482 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17483 // If this is an undefined enum, bail.
17484 if (TUK != TUK_Definition && !Invalid)
17485 return nullptr;
17486 if (EnumUnderlying) {
17487 EnumDecl *ED = cast<EnumDecl>(New);
17488 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17490 else
17491 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17492 QualType EnumTy = ED->getIntegerType();
17495 : EnumTy);
17496 }
17497 } else { // struct/union
17498 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17499 nullptr);
17500 }
17501
17502 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17503 // Add alignment attributes if necessary; these attributes are checked
17504 // when the ASTContext lays out the structure.
17505 //
17506 // It is important for implementing the correct semantics that this
17507 // happen here (in ActOnTag). The #pragma pack stack is
17508 // maintained as a result of parser callbacks which can occur at
17509 // many points during the parsing of a struct declaration (because
17510 // the #pragma tokens are effectively skipped over during the
17511 // parsing of the struct).
17512 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17515 }
17516 }
17518 return New;
17519 };
17520
17521 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17522 if (Name && SS.isNotEmpty()) {
17523 // We have a nested-name tag ('struct foo::bar').
17524
17525 // Check for invalid 'foo::'.
17526 if (SS.isInvalid()) {
17527 Name = nullptr;
17528 goto CreateNewDecl;
17529 }
17530
17531 // If this is a friend or a reference to a class in a dependent
17532 // context, don't try to make a decl for it.
17533 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17534 DC = computeDeclContext(SS, false);
17535 if (!DC) {
17536 IsDependent = true;
17537 return true;
17538 }
17539 } else {
17540 DC = computeDeclContext(SS, true);
17541 if (!DC) {
17542 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17543 << SS.getRange();
17544 return true;
17545 }
17546 }
17547
17548 if (RequireCompleteDeclContext(SS, DC))
17549 return true;
17550
17551 SearchDC = DC;
17552 // Look-up name inside 'foo::'.
17554
17555 if (Previous.isAmbiguous())
17556 return true;
17557
17558 if (Previous.empty()) {
17559 // Name lookup did not find anything. However, if the
17560 // nested-name-specifier refers to the current instantiation,
17561 // and that current instantiation has any dependent base
17562 // classes, we might find something at instantiation time: treat
17563 // this as a dependent elaborated-type-specifier.
17564 // But this only makes any sense for reference-like lookups.
17565 if (Previous.wasNotFoundInCurrentInstantiation() &&
17566 (TUK == TUK_Reference || TUK == TUK_Friend)) {
17567 IsDependent = true;
17568 return true;
17569 }
17570
17571 // A tag 'foo::bar' must already exist.
17572 Diag(NameLoc, diag::err_not_tag_in_scope)
17573 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17574 Name = nullptr;
17575 Invalid = true;
17576 goto CreateNewDecl;
17577 }
17578 } else if (Name) {
17579 // C++14 [class.mem]p14:
17580 // If T is the name of a class, then each of the following shall have a
17581 // name different from T:
17582 // -- every member of class T that is itself a type
17583 if (TUK != TUK_Reference && TUK != TUK_Friend &&
17584 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17585 return true;
17586
17587 // If this is a named struct, check to see if there was a previous forward
17588 // declaration or definition.
17589 // FIXME: We're looking into outer scopes here, even when we
17590 // shouldn't be. Doing so can result in ambiguities that we
17591 // shouldn't be diagnosing.
17592 LookupName(Previous, S);
17593
17594 // When declaring or defining a tag, ignore ambiguities introduced
17595 // by types using'ed into this scope.
17596 if (Previous.isAmbiguous() &&
17597 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
17598 LookupResult::Filter F = Previous.makeFilter();
17599 while (F.hasNext()) {
17600 NamedDecl *ND = F.next();
17601 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17602 SearchDC->getRedeclContext()))
17603 F.erase();
17604 }
17605 F.done();
17606 }
17607
17608 // C++11 [namespace.memdef]p3:
17609 // If the name in a friend declaration is neither qualified nor
17610 // a template-id and the declaration is a function or an
17611 // elaborated-type-specifier, the lookup to determine whether
17612 // the entity has been previously declared shall not consider
17613 // any scopes outside the innermost enclosing namespace.
17614 //
17615 // MSVC doesn't implement the above rule for types, so a friend tag
17616 // declaration may be a redeclaration of a type declared in an enclosing
17617 // scope. They do implement this rule for friend functions.
17618 //
17619 // Does it matter that this should be by scope instead of by
17620 // semantic context?
17621 if (!Previous.empty() && TUK == TUK_Friend) {
17622 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17623 LookupResult::Filter F = Previous.makeFilter();
17624 bool FriendSawTagOutsideEnclosingNamespace = false;
17625 while (F.hasNext()) {
17626 NamedDecl *ND = F.next();
17628 if (DC->isFileContext() &&
17629 !EnclosingNS->Encloses(ND->getDeclContext())) {
17630 if (getLangOpts().MSVCCompat)
17631 FriendSawTagOutsideEnclosingNamespace = true;
17632 else
17633 F.erase();
17634 }
17635 }
17636 F.done();
17637
17638 // Diagnose this MSVC extension in the easy case where lookup would have
17639 // unambiguously found something outside the enclosing namespace.
17640 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17641 NamedDecl *ND = Previous.getFoundDecl();
17642 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17643 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17644 }
17645 }
17646
17647 // Note: there used to be some attempt at recovery here.
17648 if (Previous.isAmbiguous())
17649 return true;
17650
17651 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
17652 // FIXME: This makes sure that we ignore the contexts associated
17653 // with C structs, unions, and enums when looking for a matching
17654 // tag declaration or definition. See the similar lookup tweak
17655 // in Sema::LookupName; is there a better way to deal with this?
17656 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17657 SearchDC = SearchDC->getParent();
17658 } else if (getLangOpts().CPlusPlus) {
17659 // Inside ObjCContainer want to keep it as a lexical decl context but go
17660 // past it (most often to TranslationUnit) to find the semantic decl
17661 // context.
17662 while (isa<ObjCContainerDecl>(SearchDC))
17663 SearchDC = SearchDC->getParent();
17664 }
17665 } else if (getLangOpts().CPlusPlus) {
17666 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17667 // TagDecl the same way as we skip it for named TagDecl.
17668 while (isa<ObjCContainerDecl>(SearchDC))
17669 SearchDC = SearchDC->getParent();
17670 }
17671
17672 if (Previous.isSingleResult() &&
17673 Previous.getFoundDecl()->isTemplateParameter()) {
17674 // Maybe we will complain about the shadowed template parameter.
17675 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17676 // Just pretend that we didn't see the previous declaration.
17677 Previous.clear();
17678 }
17679
17680 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17681 DC->Equals(getStdNamespace())) {
17682 if (Name->isStr("bad_alloc")) {
17683 // This is a declaration of or a reference to "std::bad_alloc".
17684 isStdBadAlloc = true;
17685
17686 // If std::bad_alloc has been implicitly declared (but made invisible to
17687 // name lookup), fill in this implicit declaration as the previous
17688 // declaration, so that the declarations get chained appropriately.
17689 if (Previous.empty() && StdBadAlloc)
17690 Previous.addDecl(getStdBadAlloc());
17691 } else if (Name->isStr("align_val_t")) {
17692 isStdAlignValT = true;
17693 if (Previous.empty() && StdAlignValT)
17694 Previous.addDecl(getStdAlignValT());
17695 }
17696 }
17697
17698 // If we didn't find a previous declaration, and this is a reference
17699 // (or friend reference), move to the correct scope. In C++, we
17700 // also need to do a redeclaration lookup there, just in case
17701 // there's a shadow friend decl.
17702 if (Name && Previous.empty() &&
17703 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17704 if (Invalid) goto CreateNewDecl;
17705 assert(SS.isEmpty());
17706
17707 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17708 // C++ [basic.scope.pdecl]p5:
17709 // -- for an elaborated-type-specifier of the form
17710 //
17711 // class-key identifier
17712 //
17713 // if the elaborated-type-specifier is used in the
17714 // decl-specifier-seq or parameter-declaration-clause of a
17715 // function defined in namespace scope, the identifier is
17716 // declared as a class-name in the namespace that contains
17717 // the declaration; otherwise, except as a friend
17718 // declaration, the identifier is declared in the smallest
17719 // non-class, non-function-prototype scope that contains the
17720 // declaration.
17721 //
17722 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17723 // C structs and unions.
17724 //
17725 // It is an error in C++ to declare (rather than define) an enum
17726 // type, including via an elaborated type specifier. We'll
17727 // diagnose that later; for now, declare the enum in the same
17728 // scope as we would have picked for any other tag type.
17729 //
17730 // GNU C also supports this behavior as part of its incomplete
17731 // enum types extension, while GNU C++ does not.
17732 //
17733 // Find the context where we'll be declaring the tag.
17734 // FIXME: We would like to maintain the current DeclContext as the
17735 // lexical context,
17736 SearchDC = getTagInjectionContext(SearchDC);
17737
17738 // Find the scope where we'll be declaring the tag.
17740 } else {
17741 assert(TUK == TUK_Friend);
17742 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17743
17744 // C++ [namespace.memdef]p3:
17745 // If a friend declaration in a non-local class first declares a
17746 // class or function, the friend class or function is a member of
17747 // the innermost enclosing namespace.
17748 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17749 : SearchDC->getEnclosingNamespaceContext();
17750 }
17751
17752 // In C++, we need to do a redeclaration lookup to properly
17753 // diagnose some problems.
17754 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17755 // hidden declaration so that we don't get ambiguity errors when using a
17756 // type declared by an elaborated-type-specifier. In C that is not correct
17757 // and we should instead merge compatible types found by lookup.
17758 if (getLangOpts().CPlusPlus) {
17759 // FIXME: This can perform qualified lookups into function contexts,
17760 // which are meaningless.
17761 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17762 LookupQualifiedName(Previous, SearchDC);
17763 } else {
17764 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17765 LookupName(Previous, S);
17766 }
17767 }
17768
17769 // If we have a known previous declaration to use, then use it.
17770 if (Previous.empty() && SkipBody && SkipBody->Previous)
17771 Previous.addDecl(SkipBody->Previous);
17772
17773 if (!Previous.empty()) {
17774 NamedDecl *PrevDecl = Previous.getFoundDecl();
17775 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17776
17777 // It's okay to have a tag decl in the same scope as a typedef
17778 // which hides a tag decl in the same scope. Finding this
17779 // with a redeclaration lookup can only actually happen in C++.
17780 //
17781 // This is also okay for elaborated-type-specifiers, which is
17782 // technically forbidden by the current standard but which is
17783 // okay according to the likely resolution of an open issue;
17784 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17785 if (getLangOpts().CPlusPlus) {
17786 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17787 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17788 TagDecl *Tag = TT->getDecl();
17789 if (Tag->getDeclName() == Name &&
17791 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17792 PrevDecl = Tag;
17793 Previous.clear();
17794 Previous.addDecl(Tag);
17795 Previous.resolveKind();
17796 }
17797 }
17798 }
17799 }
17800
17801 // If this is a redeclaration of a using shadow declaration, it must
17802 // declare a tag in the same context. In MSVC mode, we allow a
17803 // redefinition if either context is within the other.
17804 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17805 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17806 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17807 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17808 !(OldTag && isAcceptableTagRedeclContext(
17809 *this, OldTag->getDeclContext(), SearchDC))) {
17810 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17811 Diag(Shadow->getTargetDecl()->getLocation(),
17812 diag::note_using_decl_target);
17813 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17814 << 0;
17815 // Recover by ignoring the old declaration.
17816 Previous.clear();
17817 goto CreateNewDecl;
17818 }
17819 }
17820
17821 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17822 // If this is a use of a previous tag, or if the tag is already declared
17823 // in the same scope (so that the definition/declaration completes or
17824 // rementions the tag), reuse the decl.
17825 if (TUK == TUK_Reference || TUK == TUK_Friend ||
17826 isDeclInScope(DirectPrevDecl, SearchDC, S,
17827 SS.isNotEmpty() || isMemberSpecialization)) {
17828 // Make sure that this wasn't declared as an enum and now used as a
17829 // struct or something similar.
17830 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17831 TUK == TUK_Definition, KWLoc,
17832 Name)) {
17833 bool SafeToContinue =
17834 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17835 Kind != TagTypeKind::Enum);
17836 if (SafeToContinue)
17837 Diag(KWLoc, diag::err_use_with_wrong_tag)
17838 << Name
17840 PrevTagDecl->getKindName());
17841 else
17842 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17843 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17844
17845 if (SafeToContinue)
17846 Kind = PrevTagDecl->getTagKind();
17847 else {
17848 // Recover by making this an anonymous redefinition.
17849 Name = nullptr;
17850 Previous.clear();
17851 Invalid = true;
17852 }
17853 }
17854
17855 if (Kind == TagTypeKind::Enum &&
17856 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17857 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17858 if (TUK == TUK_Reference || TUK == TUK_Friend)
17859 return PrevTagDecl;
17860
17861 QualType EnumUnderlyingTy;
17862 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17863 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17864 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17865 EnumUnderlyingTy = QualType(T, 0);
17866
17867 // All conflicts with previous declarations are recovered by
17868 // returning the previous declaration, unless this is a definition,
17869 // in which case we want the caller to bail out.
17870 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17871 ScopedEnum, EnumUnderlyingTy,
17872 IsFixed, PrevEnum))
17873 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17874 }
17875
17876 // C++11 [class.mem]p1:
17877 // A member shall not be declared twice in the member-specification,
17878 // except that a nested class or member class template can be declared
17879 // and then later defined.
17880 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17881 S->isDeclScope(PrevDecl)) {
17882 Diag(NameLoc, diag::ext_member_redeclared);
17883 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17884 }
17885
17886 if (!Invalid) {
17887 // If this is a use, just return the declaration we found, unless
17888 // we have attributes.
17889 if (TUK == TUK_Reference || TUK == TUK_Friend) {
17890 if (!Attrs.empty()) {
17891 // FIXME: Diagnose these attributes. For now, we create a new
17892 // declaration to hold them.
17893 } else if (TUK == TUK_Reference &&
17894 (PrevTagDecl->getFriendObjectKind() ==
17896 PrevDecl->getOwningModule() != getCurrentModule()) &&
17897 SS.isEmpty()) {
17898 // This declaration is a reference to an existing entity, but
17899 // has different visibility from that entity: it either makes
17900 // a friend visible or it makes a type visible in a new module.
17901 // In either case, create a new declaration. We only do this if
17902 // the declaration would have meant the same thing if no prior
17903 // declaration were found, that is, if it was found in the same
17904 // scope where we would have injected a declaration.
17905 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17906 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17907 return PrevTagDecl;
17908 // This is in the injected scope, create a new declaration in
17909 // that scope.
17911 } else {
17912 return PrevTagDecl;
17913 }
17914 }
17915
17916 // Diagnose attempts to redefine a tag.
17917 if (TUK == TUK_Definition) {
17918 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17919 // If we're defining a specialization and the previous definition
17920 // is from an implicit instantiation, don't emit an error
17921 // here; we'll catch this in the general case below.
17922 bool IsExplicitSpecializationAfterInstantiation = false;
17923 if (isMemberSpecialization) {
17924 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17925 IsExplicitSpecializationAfterInstantiation =
17926 RD->getTemplateSpecializationKind() !=
17928 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17929 IsExplicitSpecializationAfterInstantiation =
17930 ED->getTemplateSpecializationKind() !=
17932 }
17933
17934 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17935 // not keep more that one definition around (merge them). However,
17936 // ensure the decl passes the structural compatibility check in
17937 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17938 NamedDecl *Hidden = nullptr;
17939 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17940 // There is a definition of this tag, but it is not visible. We
17941 // explicitly make use of C++'s one definition rule here, and
17942 // assume that this definition is identical to the hidden one
17943 // we already have. Make the existing definition visible and
17944 // use it in place of this one.
17945 if (!getLangOpts().CPlusPlus) {
17946 // Postpone making the old definition visible until after we
17947 // complete parsing the new one and do the structural
17948 // comparison.
17949 SkipBody->CheckSameAsPrevious = true;
17950 SkipBody->New = createTagFromNewDecl();
17951 SkipBody->Previous = Def;
17952 return Def;
17953 } else {
17954 SkipBody->ShouldSkip = true;
17955 SkipBody->Previous = Def;
17957 // Carry on and handle it like a normal definition. We'll
17958 // skip starting the definitiion later.
17959 }
17960 } else if (!IsExplicitSpecializationAfterInstantiation) {
17961 // A redeclaration in function prototype scope in C isn't
17962 // visible elsewhere, so merely issue a warning.
17963 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17964 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17965 else
17966 Diag(NameLoc, diag::err_redefinition) << Name;
17968 NameLoc.isValid() ? NameLoc : KWLoc);
17969 // If this is a redefinition, recover by making this
17970 // struct be anonymous, which will make any later
17971 // references get the previous definition.
17972 Name = nullptr;
17973 Previous.clear();
17974 Invalid = true;
17975 }
17976 } else {
17977 // If the type is currently being defined, complain
17978 // about a nested redefinition.
17979 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17980 if (TD->isBeingDefined()) {
17981 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17982 Diag(PrevTagDecl->getLocation(),
17983 diag::note_previous_definition);
17984 Name = nullptr;
17985 Previous.clear();
17986 Invalid = true;
17987 }
17988 }
17989
17990 // Okay, this is definition of a previously declared or referenced
17991 // tag. We're going to create a new Decl for it.
17992 }
17993
17994 // Okay, we're going to make a redeclaration. If this is some kind
17995 // of reference, make sure we build the redeclaration in the same DC
17996 // as the original, and ignore the current access specifier.
17997 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17998 SearchDC = PrevTagDecl->getDeclContext();
17999 AS = AS_none;
18000 }
18001 }
18002 // If we get here we have (another) forward declaration or we
18003 // have a definition. Just create a new decl.
18004
18005 } else {
18006 // If we get here, this is a definition of a new tag type in a nested
18007 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18008 // new decl/type. We set PrevDecl to NULL so that the entities
18009 // have distinct types.
18010 Previous.clear();
18011 }
18012 // If we get here, we're going to create a new Decl. If PrevDecl
18013 // is non-NULL, it's a definition of the tag declared by
18014 // PrevDecl. If it's NULL, we have a new definition.
18015
18016 // Otherwise, PrevDecl is not a tag, but was found with tag
18017 // lookup. This is only actually possible in C++, where a few
18018 // things like templates still live in the tag namespace.
18019 } else {
18020 // Use a better diagnostic if an elaborated-type-specifier
18021 // found the wrong kind of type on the first
18022 // (non-redeclaration) lookup.
18023 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
18024 !Previous.isForRedeclaration()) {
18025 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18026 Diag(NameLoc, diag::err_tag_reference_non_tag)
18027 << PrevDecl << NTK << llvm::to_underlying(Kind);
18028 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18029 Invalid = true;
18030
18031 // Otherwise, only diagnose if the declaration is in scope.
18032 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18033 SS.isNotEmpty() || isMemberSpecialization)) {
18034 // do nothing
18035
18036 // Diagnose implicit declarations introduced by elaborated types.
18037 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
18038 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18039 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18040 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18041 Invalid = true;
18042
18043 // Otherwise it's a declaration. Call out a particularly common
18044 // case here.
18045 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18046 unsigned Kind = 0;
18047 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18048 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18049 << Name << Kind << TND->getUnderlyingType();
18050 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18051 Invalid = true;
18052
18053 // Otherwise, diagnose.
18054 } else {
18055 // The tag name clashes with something else in the target scope,
18056 // issue an error and recover by making this tag be anonymous.
18057 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18058 notePreviousDefinition(PrevDecl, NameLoc);
18059 Name = nullptr;
18060 Invalid = true;
18061 }
18062
18063 // The existing declaration isn't relevant to us; we're in a
18064 // new scope, so clear out the previous declaration.
18065 Previous.clear();
18066 }
18067 }
18068
18069CreateNewDecl:
18070
18071 TagDecl *PrevDecl = nullptr;
18072 if (Previous.isSingleResult())
18073 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18074
18075 // If there is an identifier, use the location of the identifier as the
18076 // location of the decl, otherwise use the location of the struct/union
18077 // keyword.
18078 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18079
18080 // Otherwise, create a new declaration. If there is a previous
18081 // declaration of the same entity, the two will be linked via
18082 // PrevDecl.
18083 TagDecl *New;
18084
18085 if (Kind == TagTypeKind::Enum) {
18086 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18087 // enum X { A, B, C } D; D should chain to X.
18088 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18089 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18090 ScopedEnumUsesClassTag, IsFixed);
18091
18092 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18093 StdAlignValT = cast<EnumDecl>(New);
18094
18095 // If this is an undefined enum, warn.
18096 if (TUK != TUK_Definition && !Invalid) {
18097 TagDecl *Def;
18098 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
18099 // C++0x: 7.2p2: opaque-enum-declaration.
18100 // Conflicts are diagnosed above. Do nothing.
18101 }
18102 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18103 Diag(Loc, diag::ext_forward_ref_enum_def)
18104 << New;
18105 Diag(Def->getLocation(), diag::note_previous_definition);
18106 } else {
18107 unsigned DiagID = diag::ext_forward_ref_enum;
18108 if (getLangOpts().MSVCCompat)
18109 DiagID = diag::ext_ms_forward_ref_enum;
18110 else if (getLangOpts().CPlusPlus)
18111 DiagID = diag::err_forward_ref_enum;
18112 Diag(Loc, DiagID);
18113 }
18114 }
18115
18116 if (EnumUnderlying) {
18117 EnumDecl *ED = cast<EnumDecl>(New);
18118 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
18120 else
18121 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
18122 QualType EnumTy = ED->getIntegerType();
18125 : EnumTy);
18126 assert(ED->isComplete() && "enum with type should be complete");
18127 }
18128 } else {
18129 // struct/union/class
18130
18131 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18132 // struct X { int A; } D; D should chain to X.
18133 if (getLangOpts().CPlusPlus) {
18134 // FIXME: Look for a way to use RecordDecl for simple structs.
18135 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18136 cast_or_null<CXXRecordDecl>(PrevDecl));
18137
18138 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18139 StdBadAlloc = cast<CXXRecordDecl>(New);
18140 } else
18141 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18142 cast_or_null<RecordDecl>(PrevDecl));
18143 }
18144
18145 // Only C23 and later allow defining new types in 'offsetof()'.
18146 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus &&
18147 !getLangOpts().C23)
18148 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18149 << (OOK == OOK_Macro) << New->getSourceRange();
18150
18151 // C++11 [dcl.type]p3:
18152 // A type-specifier-seq shall not define a class or enumeration [...].
18153 if (!Invalid && getLangOpts().CPlusPlus &&
18154 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
18155 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18156 << Context.getTagDeclType(New);
18157 Invalid = true;
18158 }
18159
18160 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
18161 DC->getDeclKind() == Decl::Enum) {
18162 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18163 << Context.getTagDeclType(New);
18164 Invalid = true;
18165 }
18166
18167 // Maybe add qualifier info.
18168 if (SS.isNotEmpty()) {
18169 if (SS.isSet()) {
18170 // If this is either a declaration or a definition, check the
18171 // nested-name-specifier against the current context.
18172 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
18173 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18174 /*TemplateId=*/nullptr,
18175 isMemberSpecialization))
18176 Invalid = true;
18177
18179 if (TemplateParameterLists.size() > 0) {
18180 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18181 }
18182 }
18183 else
18184 Invalid = true;
18185 }
18186
18187 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18188 // Add alignment attributes if necessary; these attributes are checked when
18189 // the ASTContext lays out the structure.
18190 //
18191 // It is important for implementing the correct semantics that this
18192 // happen here (in ActOnTag). The #pragma pack stack is
18193 // maintained as a result of parser callbacks which can occur at
18194 // many points during the parsing of a struct declaration (because
18195 // the #pragma tokens are effectively skipped over during the
18196 // parsing of the struct).
18197 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18200 }
18201 }
18202
18203 if (ModulePrivateLoc.isValid()) {
18204 if (isMemberSpecialization)
18205 Diag(New->getLocation(), diag::err_module_private_specialization)
18206 << 2
18207 << FixItHint::CreateRemoval(ModulePrivateLoc);
18208 // __module_private__ does not apply to local classes. However, we only
18209 // diagnose this as an error when the declaration specifiers are
18210 // freestanding. Here, we just ignore the __module_private__.
18211 else if (!SearchDC->isFunctionOrMethod())
18212 New->setModulePrivate();
18213 }
18214
18215 // If this is a specialization of a member class (of a class template),
18216 // check the specialization.
18217 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18218 Invalid = true;
18219
18220 // If we're declaring or defining a tag in function prototype scope in C,
18221 // note that this type can only be used within the function and add it to
18222 // the list of decls to inject into the function definition scope.
18223 if ((Name || Kind == TagTypeKind::Enum) &&
18224 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18225 if (getLangOpts().CPlusPlus) {
18226 // C++ [dcl.fct]p6:
18227 // Types shall not be defined in return or parameter types.
18228 if (TUK == TUK_Definition && !IsTypeSpecifier) {
18229 Diag(Loc, diag::err_type_defined_in_param_type)
18230 << Name;
18231 Invalid = true;
18232 }
18233 } else if (!PrevDecl) {
18234 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
18235 }
18236 }
18237
18238 if (Invalid)
18239 New->setInvalidDecl();
18240
18241 // Set the lexical context. If the tag has a C++ scope specifier, the
18242 // lexical context will be different from the semantic context.
18244
18245 // Mark this as a friend decl if applicable.
18246 // In Microsoft mode, a friend declaration also acts as a forward
18247 // declaration so we always pass true to setObjectOfFriendDecl to make
18248 // the tag name visible.
18249 if (TUK == TUK_Friend)
18250 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18251
18252 // Set the access specifier.
18253 if (!Invalid && SearchDC->isRecord())
18254 SetMemberAccessSpecifier(New, PrevDecl, AS);
18255
18256 if (PrevDecl)
18257 CheckRedeclarationInModule(New, PrevDecl);
18258
18259 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
18260 New->startDefinition();
18261
18262 ProcessDeclAttributeList(S, New, Attrs);
18263 AddPragmaAttributes(S, New);
18264
18265 // If this has an identifier, add it to the scope stack.
18266 if (TUK == TUK_Friend) {
18267 // We might be replacing an existing declaration in the lookup tables;
18268 // if so, borrow its access specifier.
18269 if (PrevDecl)
18270 New->setAccess(PrevDecl->getAccess());
18271
18273 DC->makeDeclVisibleInContext(New);
18274 if (Name) // can be null along some error paths
18275 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18276 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18277 } else if (Name) {
18278 S = getNonFieldDeclScope(S);
18279 PushOnScopeChains(New, S, true);
18280 } else {
18281 CurContext->addDecl(New);
18282 }
18283
18284 // If this is the C FILE type, notify the AST context.
18285 if (IdentifierInfo *II = New->getIdentifier())
18286 if (!New->isInvalidDecl() &&
18288 II->isStr("FILE"))
18289 Context.setFILEDecl(New);
18290
18291 if (PrevDecl)
18292 mergeDeclAttributes(New, PrevDecl);
18293
18294 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18297 }
18298
18299 // If there's a #pragma GCC visibility in scope, set the visibility of this
18300 // record.
18302
18303 if (isMemberSpecialization && !New->isInvalidDecl())
18305
18306 OwnedDecl = true;
18307 // In C++, don't return an invalid declaration. We can't recover well from
18308 // the cases where we make the type anonymous.
18309 if (Invalid && getLangOpts().CPlusPlus) {
18310 if (New->isBeingDefined())
18311 if (auto RD = dyn_cast<RecordDecl>(New))
18312 RD->completeDefinition();
18313 return true;
18314 } else if (SkipBody && SkipBody->ShouldSkip) {
18315 return SkipBody->Previous;
18316 } else {
18317 return New;
18318 }
18319}
18320
18323 TagDecl *Tag = cast<TagDecl>(TagD);
18324
18325 // Enter the tag context.
18326 PushDeclContext(S, Tag);
18327
18329
18330 // If there's a #pragma GCC visibility in scope, set the visibility of this
18331 // record.
18333}
18334
18336 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18337 return false;
18338
18339 // Make the previous decl visible.
18341 return true;
18342}
18343
18345 assert(IDecl->getLexicalParent() == CurContext &&
18346 "The next DeclContext should be lexically contained in the current one.");
18347 CurContext = IDecl;
18348}
18349
18351 SourceLocation FinalLoc,
18352 bool IsFinalSpelledSealed,
18353 bool IsAbstract,
18354 SourceLocation LBraceLoc) {
18356 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18357
18358 FieldCollector->StartClass();
18359
18360 if (!Record->getIdentifier())
18361 return;
18362
18363 if (IsAbstract)
18364 Record->markAbstract();
18365
18366 if (FinalLoc.isValid()) {
18367 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18368 IsFinalSpelledSealed
18369 ? FinalAttr::Keyword_sealed
18370 : FinalAttr::Keyword_final));
18371 }
18372 // C++ [class]p2:
18373 // [...] The class-name is also inserted into the scope of the
18374 // class itself; this is known as the injected-class-name. For
18375 // purposes of access checking, the injected-class-name is treated
18376 // as if it were a public member name.
18377 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18378 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18379 Record->getLocation(), Record->getIdentifier(),
18380 /*PrevDecl=*/nullptr,
18381 /*DelayTypeCreation=*/true);
18382 Context.getTypeDeclType(InjectedClassName, Record);
18383 InjectedClassName->setImplicit();
18384 InjectedClassName->setAccess(AS_public);
18385 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18386 InjectedClassName->setDescribedClassTemplate(Template);
18387 PushOnScopeChains(InjectedClassName, S);
18388 assert(InjectedClassName->isInjectedClassName() &&
18389 "Broken injected-class-name");
18390}
18391
18393 SourceRange BraceRange) {
18395 TagDecl *Tag = cast<TagDecl>(TagD);
18396 Tag->setBraceRange(BraceRange);
18397
18398 // Make sure we "complete" the definition even it is invalid.
18399 if (Tag->isBeingDefined()) {
18400 assert(Tag->isInvalidDecl() && "We should already have completed it");
18401 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18402 RD->completeDefinition();
18403 }
18404
18405 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18406 FieldCollector->FinishClass();
18407 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18408 auto *Def = RD->getDefinition();
18409 assert(Def && "The record is expected to have a completed definition");
18410 unsigned NumInitMethods = 0;
18411 for (auto *Method : Def->methods()) {
18412 if (!Method->getIdentifier())
18413 continue;
18414 if (Method->getName() == "__init")
18415 NumInitMethods++;
18416 }
18417 if (NumInitMethods > 1 || !Def->hasInitMethod())
18418 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18419 }
18420 }
18421
18422 // Exit this scope of this tag's definition.
18424
18425 if (getCurLexicalContext()->isObjCContainer() &&
18426 Tag->getDeclContext()->isFileContext())
18428
18429 // Notify the consumer that we've defined a tag.
18430 if (!Tag->isInvalidDecl())
18432
18433 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18434 // from XLs and instead matches the XL #pragma pack(1) behavior.
18435 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18436 AlignPackStack.hasValue()) {
18437 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18438 // Only diagnose #pragma align(packed).
18439 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18440 return;
18441 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18442 if (!RD)
18443 return;
18444 // Only warn if there is at least 1 bitfield member.
18445 if (llvm::any_of(RD->fields(),
18446 [](const FieldDecl *FD) { return FD->isBitField(); }))
18447 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18448 }
18449}
18450
18452 // Exit this scope of this interface definition.
18454}
18455
18457 assert(ObjCCtx == CurContext && "Mismatch of container contexts");
18458 OriginalLexicalContext = ObjCCtx;
18460}
18461
18464 OriginalLexicalContext = nullptr;
18465}
18466
18469 TagDecl *Tag = cast<TagDecl>(TagD);
18470 Tag->setInvalidDecl();
18471
18472 // Make sure we "complete" the definition even it is invalid.
18473 if (Tag->isBeingDefined()) {
18474 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18475 RD->completeDefinition();
18476 }
18477
18478 // We're undoing ActOnTagStartDefinition here, not
18479 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18480 // the FieldCollector.
18481
18483}
18484
18485// Note that FieldName may be null for anonymous bitfields.
18487 const IdentifierInfo *FieldName,
18488 QualType FieldTy, bool IsMsStruct,
18489 Expr *BitWidth) {
18490 assert(BitWidth);
18491 if (BitWidth->containsErrors())
18492 return ExprError();
18493
18494 // C99 6.7.2.1p4 - verify the field type.
18495 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18496 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18497 // Handle incomplete and sizeless types with a specific error.
18498 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18499 diag::err_field_incomplete_or_sizeless))
18500 return ExprError();
18501 if (FieldName)
18502 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18503 << FieldName << FieldTy << BitWidth->getSourceRange();
18504 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18505 << FieldTy << BitWidth->getSourceRange();
18506 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18508 return ExprError();
18509
18510 // If the bit-width is type- or value-dependent, don't try to check
18511 // it now.
18512 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18513 return BitWidth;
18514
18515 llvm::APSInt Value;
18517 if (ICE.isInvalid())
18518 return ICE;
18519 BitWidth = ICE.get();
18520
18521 // Zero-width bitfield is ok for anonymous field.
18522 if (Value == 0 && FieldName)
18523 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18524 << FieldName << BitWidth->getSourceRange();
18525
18526 if (Value.isSigned() && Value.isNegative()) {
18527 if (FieldName)
18528 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18529 << FieldName << toString(Value, 10);
18530 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18531 << toString(Value, 10);
18532 }
18533
18534 // The size of the bit-field must not exceed our maximum permitted object
18535 // size.
18536 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18537 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18538 << !FieldName << FieldName << toString(Value, 10);
18539 }
18540
18541 if (!FieldTy->isDependentType()) {
18542 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18543 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18544 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18545
18546 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18547 // ABI.
18548 bool CStdConstraintViolation =
18549 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18550 bool MSBitfieldViolation =
18551 Value.ugt(TypeStorageSize) &&
18552 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18553 if (CStdConstraintViolation || MSBitfieldViolation) {
18554 unsigned DiagWidth =
18555 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18556 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18557 << (bool)FieldName << FieldName << toString(Value, 10)
18558 << !CStdConstraintViolation << DiagWidth;
18559 }
18560
18561 // Warn on types where the user might conceivably expect to get all
18562 // specified bits as value bits: that's all integral types other than
18563 // 'bool'.
18564 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18565 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18566 << FieldName << toString(Value, 10)
18567 << (unsigned)TypeWidth;
18568 }
18569 }
18570
18571 return BitWidth;
18572}
18573
18574/// ActOnField - Each field of a C struct/union is passed into this in order
18575/// to create a FieldDecl object for it.
18577 Declarator &D, Expr *BitfieldWidth) {
18578 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18579 D, BitfieldWidth,
18580 /*InitStyle=*/ICIS_NoInit, AS_public);
18581 return Res;
18582}
18583
18584/// HandleField - Analyze a field of a C struct or a C++ data member.
18585///
18587 SourceLocation DeclStart,
18588 Declarator &D, Expr *BitWidth,
18589 InClassInitStyle InitStyle,
18590 AccessSpecifier AS) {
18591 if (D.isDecompositionDeclarator()) {
18593 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18594 << Decomp.getSourceRange();
18595 return nullptr;
18596 }
18597
18598 const IdentifierInfo *II = D.getIdentifier();
18599 SourceLocation Loc = DeclStart;
18600 if (II) Loc = D.getIdentifierLoc();
18601
18603 QualType T = TInfo->getType();
18604 if (getLangOpts().CPlusPlus) {
18606
18609 D.setInvalidType();
18610 T = Context.IntTy;
18611 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18612 }
18613 }
18614
18616
18618 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18619 << getLangOpts().CPlusPlus17;
18622 diag::err_invalid_thread)
18624
18625 // Check to see if this name was declared as a member previously
18626 NamedDecl *PrevDecl = nullptr;
18627 LookupResult Previous(*this, II, Loc, LookupMemberName,
18628 RedeclarationKind::ForVisibleRedeclaration);
18629 LookupName(Previous, S);
18630 switch (Previous.getResultKind()) {
18633 PrevDecl = Previous.getAsSingle<NamedDecl>();
18634 break;
18635
18637 PrevDecl = Previous.getRepresentativeDecl();
18638 break;
18639
18643 break;
18644 }
18645 Previous.suppressDiagnostics();
18646
18647 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18648 // Maybe we will complain about the shadowed template parameter.
18650 // Just pretend that we didn't see the previous declaration.
18651 PrevDecl = nullptr;
18652 }
18653
18654 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18655 PrevDecl = nullptr;
18656
18657 bool Mutable
18659 SourceLocation TSSL = D.getBeginLoc();
18660 FieldDecl *NewFD
18661 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18662 TSSL, AS, PrevDecl, &D);
18663
18664 if (NewFD->isInvalidDecl())
18665 Record->setInvalidDecl();
18666
18668 NewFD->setModulePrivate();
18669
18670 if (NewFD->isInvalidDecl() && PrevDecl) {
18671 // Don't introduce NewFD into scope; there's already something
18672 // with the same name in the same scope.
18673 } else if (II) {
18674 PushOnScopeChains(NewFD, S);
18675 } else
18676 Record->addDecl(NewFD);
18677
18678 return NewFD;
18679}
18680
18681/// Build a new FieldDecl and check its well-formedness.
18682///
18683/// This routine builds a new FieldDecl given the fields name, type,
18684/// record, etc. \p PrevDecl should refer to any previous declaration
18685/// with the same name and in the same scope as the field to be
18686/// created.
18687///
18688/// \returns a new FieldDecl.
18689///
18690/// \todo The Declarator argument is a hack. It will be removed once
18692 TypeSourceInfo *TInfo,
18694 bool Mutable, Expr *BitWidth,
18695 InClassInitStyle InitStyle,
18696 SourceLocation TSSL,
18697 AccessSpecifier AS, NamedDecl *PrevDecl,
18698 Declarator *D) {
18699 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18700 bool InvalidDecl = false;
18701 if (D) InvalidDecl = D->isInvalidType();
18702
18703 // If we receive a broken type, recover by assuming 'int' and
18704 // marking this declaration as invalid.
18705 if (T.isNull() || T->containsErrors()) {
18706 InvalidDecl = true;
18707 T = Context.IntTy;
18708 }
18709
18711 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18712 if (RequireCompleteSizedType(Loc, EltTy,
18713 diag::err_field_incomplete_or_sizeless)) {
18714 // Fields of incomplete type force their record to be invalid.
18715 Record->setInvalidDecl();
18716 InvalidDecl = true;
18717 } else {
18718 NamedDecl *Def;
18719 EltTy->isIncompleteType(&Def);
18720 if (Def && Def->isInvalidDecl()) {
18721 Record->setInvalidDecl();
18722 InvalidDecl = true;
18723 }
18724 }
18725 }
18726
18727 // TR 18037 does not allow fields to be declared with address space
18728 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18730 Diag(Loc, diag::err_field_with_address_space);
18731 Record->setInvalidDecl();
18732 InvalidDecl = true;
18733 }
18734
18735 if (LangOpts.OpenCL) {
18736 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18737 // used as structure or union field: image, sampler, event or block types.
18738 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18739 T->isBlockPointerType()) {
18740 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18741 Record->setInvalidDecl();
18742 InvalidDecl = true;
18743 }
18744 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18745 // is enabled.
18746 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18747 "__cl_clang_bitfields", LangOpts)) {
18748 Diag(Loc, diag::err_opencl_bitfields);
18749 InvalidDecl = true;
18750 }
18751 }
18752
18753 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18754 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18755 T.hasQualifiers()) {
18756 InvalidDecl = true;
18757 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18758 }
18759
18760 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18761 // than a variably modified type.
18762 if (!InvalidDecl && T->isVariablyModifiedType()) {
18764 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18765 InvalidDecl = true;
18766 }
18767
18768 // Fields can not have abstract class types
18769 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18770 diag::err_abstract_type_in_decl,
18772 InvalidDecl = true;
18773
18774 if (InvalidDecl)
18775 BitWidth = nullptr;
18776 // If this is declared as a bit-field, check the bit-field.
18777 if (BitWidth) {
18778 BitWidth =
18779 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18780 if (!BitWidth) {
18781 InvalidDecl = true;
18782 BitWidth = nullptr;
18783 }
18784 }
18785
18786 // Check that 'mutable' is consistent with the type of the declaration.
18787 if (!InvalidDecl && Mutable) {
18788 unsigned DiagID = 0;
18789 if (T->isReferenceType())
18790 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18791 : diag::err_mutable_reference;
18792 else if (T.isConstQualified())
18793 DiagID = diag::err_mutable_const;
18794
18795 if (DiagID) {
18796 SourceLocation ErrLoc = Loc;
18797 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18798 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18799 Diag(ErrLoc, DiagID);
18800 if (DiagID != diag::ext_mutable_reference) {
18801 Mutable = false;
18802 InvalidDecl = true;
18803 }
18804 }
18805 }
18806
18807 // C++11 [class.union]p8 (DR1460):
18808 // At most one variant member of a union may have a
18809 // brace-or-equal-initializer.
18810 if (InitStyle != ICIS_NoInit)
18811 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18812
18813 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18814 BitWidth, Mutable, InitStyle);
18815 if (InvalidDecl)
18816 NewFD->setInvalidDecl();
18817
18818 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18819 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18820 Diag(Loc, diag::err_duplicate_member) << II;
18821 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18822 NewFD->setInvalidDecl();
18823 }
18824
18825 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18826 if (Record->isUnion()) {
18827 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18828 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18829 if (RDecl->getDefinition()) {
18830 // C++ [class.union]p1: An object of a class with a non-trivial
18831 // constructor, a non-trivial copy constructor, a non-trivial
18832 // destructor, or a non-trivial copy assignment operator
18833 // cannot be a member of a union, nor can an array of such
18834 // objects.
18835 if (CheckNontrivialField(NewFD))
18836 NewFD->setInvalidDecl();
18837 }
18838 }
18839
18840 // C++ [class.union]p1: If a union contains a member of reference type,
18841 // the program is ill-formed, except when compiling with MSVC extensions
18842 // enabled.
18843 if (EltTy->isReferenceType()) {
18844 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18845 diag::ext_union_member_of_reference_type :
18846 diag::err_union_member_of_reference_type)
18847 << NewFD->getDeclName() << EltTy;
18848 if (!getLangOpts().MicrosoftExt)
18849 NewFD->setInvalidDecl();
18850 }
18851 }
18852 }
18853
18854 // FIXME: We need to pass in the attributes given an AST
18855 // representation, not a parser representation.
18856 if (D) {
18857 // FIXME: The current scope is almost... but not entirely... correct here.
18858 ProcessDeclAttributes(getCurScope(), NewFD, *D);
18859
18860 if (NewFD->hasAttrs())
18862 }
18863
18864 // In auto-retain/release, infer strong retension for fields of
18865 // retainable type.
18866 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18867 NewFD->setInvalidDecl();
18868
18869 if (T.isObjCGCWeak())
18870 Diag(Loc, diag::warn_attribute_weak_on_field);
18871
18872 // PPC MMA non-pointer types are not allowed as field types.
18873 if (Context.getTargetInfo().getTriple().isPPC64() &&
18874 CheckPPCMMAType(T, NewFD->getLocation()))
18875 NewFD->setInvalidDecl();
18876
18877 NewFD->setAccess(AS);
18878 return NewFD;
18879}
18880
18882 assert(FD);
18883 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18884
18885 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18886 return false;
18887
18889 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18890 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18891 if (RDecl->getDefinition()) {
18892 // We check for copy constructors before constructors
18893 // because otherwise we'll never get complaints about
18894 // copy constructors.
18895
18897 // We're required to check for any non-trivial constructors. Since the
18898 // implicit default constructor is suppressed if there are any
18899 // user-declared constructors, we just need to check that there is a
18900 // trivial default constructor and a trivial copy constructor. (We don't
18901 // worry about move constructors here, since this is a C++98 check.)
18902 if (RDecl->hasNonTrivialCopyConstructor())
18904 else if (!RDecl->hasTrivialDefaultConstructor())
18906 else if (RDecl->hasNonTrivialCopyAssignment())
18908 else if (RDecl->hasNonTrivialDestructor())
18910
18911 if (member != CXXSpecialMemberKind::Invalid) {
18912 if (!getLangOpts().CPlusPlus11 &&
18913 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18914 // Objective-C++ ARC: it is an error to have a non-trivial field of
18915 // a union. However, system headers in Objective-C programs
18916 // occasionally have Objective-C lifetime objects within unions,
18917 // and rather than cause the program to fail, we make those
18918 // members unavailable.
18919 SourceLocation Loc = FD->getLocation();
18920 if (getSourceManager().isInSystemHeader(Loc)) {
18921 if (!FD->hasAttr<UnavailableAttr>())
18922 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18923 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18924 return false;
18925 }
18926 }
18927
18928 Diag(
18929 FD->getLocation(),
18931 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
18932 : diag::err_illegal_union_or_anon_struct_member)
18933 << FD->getParent()->isUnion() << FD->getDeclName()
18934 << llvm::to_underlying(member);
18935 DiagnoseNontrivial(RDecl, member);
18936 return !getLangOpts().CPlusPlus11;
18937 }
18938 }
18939 }
18940
18941 return false;
18942}
18943
18944/// TranslateIvarVisibility - Translate visibility from a token ID to an
18945/// AST enum value.
18948 switch (ivarVisibility) {
18949 default: llvm_unreachable("Unknown visitibility kind");
18950 case tok::objc_private: return ObjCIvarDecl::Private;
18951 case tok::objc_public: return ObjCIvarDecl::Public;
18952 case tok::objc_protected: return ObjCIvarDecl::Protected;
18953 case tok::objc_package: return ObjCIvarDecl::Package;
18954 }
18955}
18956
18957/// ActOnIvar - Each ivar field of an objective-c class is passed into this
18958/// in order to create an IvarDecl object for it.
18961
18962 const IdentifierInfo *II = D.getIdentifier();
18963 SourceLocation Loc = DeclStart;
18964 if (II) Loc = D.getIdentifierLoc();
18965
18966 // FIXME: Unnamed fields can be handled in various different ways, for
18967 // example, unnamed unions inject all members into the struct namespace!
18968
18970 QualType T = TInfo->getType();
18971
18972 if (BitWidth) {
18973 // 6.7.2.1p3, 6.7.2.1p4
18974 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
18975 if (!BitWidth)
18976 D.setInvalidType();
18977 } else {
18978 // Not a bitfield.
18979
18980 // validate II.
18981
18982 }
18983 if (T->isReferenceType()) {
18984 Diag(Loc, diag::err_ivar_reference_type);
18985 D.setInvalidType();
18986 }
18987 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18988 // than a variably modified type.
18989 else if (T->isVariablyModifiedType()) {
18991 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18992 D.setInvalidType();
18993 }
18994
18995 // Get the visibility (access control) for this ivar.
18997 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
18999 // Must set ivar's DeclContext to its enclosing interface.
19000 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
19001 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
19002 return nullptr;
19003 ObjCContainerDecl *EnclosingContext;
19004 if (ObjCImplementationDecl *IMPDecl =
19005 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19007 // Case of ivar declared in an implementation. Context is that of its class.
19008 EnclosingContext = IMPDecl->getClassInterface();
19009 assert(EnclosingContext && "Implementation has no class interface!");
19010 }
19011 else
19012 EnclosingContext = EnclosingDecl;
19013 } else {
19014 if (ObjCCategoryDecl *CDecl =
19015 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19016 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
19017 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
19018 return nullptr;
19019 }
19020 }
19021 EnclosingContext = EnclosingDecl;
19022 }
19023
19024 // Construct the decl.
19026 Context, EnclosingContext, DeclStart, Loc, II, T, TInfo, ac, BitWidth);
19027
19028 if (T->containsErrors())
19029 NewID->setInvalidDecl();
19030
19031 if (II) {
19032 NamedDecl *PrevDecl =
19034 RedeclarationKind::ForVisibleRedeclaration);
19035 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
19036 && !isa<TagDecl>(PrevDecl)) {
19037 Diag(Loc, diag::err_duplicate_member) << II;
19038 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19039 NewID->setInvalidDecl();
19040 }
19041 }
19042
19043 // Process attributes attached to the ivar.
19044 ProcessDeclAttributes(S, NewID, D);
19045
19046 if (D.isInvalidType())
19047 NewID->setInvalidDecl();
19048
19049 // In ARC, infer 'retaining' for ivars of retainable type.
19050 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
19051 NewID->setInvalidDecl();
19052
19054 NewID->setModulePrivate();
19055
19056 if (II) {
19057 // FIXME: When interfaces are DeclContexts, we'll need to add
19058 // these to the interface.
19059 S->AddDecl(NewID);
19060 IdResolver.AddDecl(NewID);
19061 }
19062
19064 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
19065 Diag(Loc, diag::warn_ivars_in_interface);
19066
19067 return NewID;
19068}
19069
19070/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
19071/// class and class extensions. For every class \@interface and class
19072/// extension \@interface, if the last ivar is a bitfield of any type,
19073/// then add an implicit `char :0` ivar to the end of that interface.
19075 SmallVectorImpl<Decl *> &AllIvarDecls) {
19076 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19077 return;
19078
19079 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19080 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19081
19082 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
19083 return;
19084 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19085 if (!ID) {
19086 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19087 if (!CD->IsClassExtension())
19088 return;
19089 }
19090 // No need to add this to end of @implementation.
19091 else
19092 return;
19093 }
19094 // All conditions are met. Add a new bitfield to the tail end of ivars.
19095 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19096 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19097
19098 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
19099 DeclLoc, DeclLoc, nullptr,
19102 DeclLoc),
19104 true);
19105 AllIvarDecls.push_back(Ivar);
19106}
19107
19108/// [class.dtor]p4:
19109/// At the end of the definition of a class, overload resolution is
19110/// performed among the prospective destructors declared in that class with
19111/// an empty argument list to select the destructor for the class, also
19112/// known as the selected destructor.
19113///
19114/// We do the overload resolution here, then mark the selected constructor in the AST.
19115/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19117 if (!Record->hasUserDeclaredDestructor()) {
19118 return;
19119 }
19120
19121 SourceLocation Loc = Record->getLocation();
19123
19124 for (auto *Decl : Record->decls()) {
19125 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19126 if (DD->isInvalidDecl())
19127 continue;
19128 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19129 OCS);
19130 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19131 }
19132 }
19133
19134 if (OCS.empty()) {
19135 return;
19136 }
19138 unsigned Msg = 0;
19139 OverloadCandidateDisplayKind DisplayKind;
19140
19141 switch (OCS.BestViableFunction(S, Loc, Best)) {
19142 case OR_Success:
19143 case OR_Deleted:
19144 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19145 break;
19146
19147 case OR_Ambiguous:
19148 Msg = diag::err_ambiguous_destructor;
19149 DisplayKind = OCD_AmbiguousCandidates;
19150 break;
19151
19153 Msg = diag::err_no_viable_destructor;
19154 DisplayKind = OCD_AllCandidates;
19155 break;
19156 }
19157
19158 if (Msg) {
19159 // OpenCL have got their own thing going with destructors. It's slightly broken,
19160 // but we allow it.
19161 if (!S.LangOpts.OpenCL) {
19162 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19163 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19164 Record->setInvalidDecl();
19165 }
19166 // It's a bit hacky: At this point we've raised an error but we want the
19167 // rest of the compiler to continue somehow working. However almost
19168 // everything we'll try to do with the class will depend on there being a
19169 // destructor. So let's pretend the first one is selected and hope for the
19170 // best.
19171 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19172 }
19173}
19174
19175/// [class.mem.special]p5
19176/// Two special member functions are of the same kind if:
19177/// - they are both default constructors,
19178/// - they are both copy or move constructors with the same first parameter
19179/// type, or
19180/// - they are both copy or move assignment operators with the same first
19181/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19183 CXXMethodDecl *M1,
19184 CXXMethodDecl *M2,
19186 // We don't want to compare templates to non-templates: See
19187 // https://github.com/llvm/llvm-project/issues/59206
19189 return bool(M1->getDescribedFunctionTemplate()) ==
19191 // FIXME: better resolve CWG
19192 // https://cplusplus.github.io/CWG/issues/2787.html
19193 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19194 M2->getNonObjectParameter(0)->getType()))
19195 return false;
19198 return false;
19199
19200 return true;
19201}
19202
19203/// [class.mem.special]p6:
19204/// An eligible special member function is a special member function for which:
19205/// - the function is not deleted,
19206/// - the associated constraints, if any, are satisfied, and
19207/// - no special member function of the same kind whose associated constraints
19208/// [CWG2595], if any, are satisfied is more constrained.
19212 SmallVector<bool, 4> SatisfactionStatus;
19213
19214 for (CXXMethodDecl *Method : Methods) {
19215 const Expr *Constraints = Method->getTrailingRequiresClause();
19216 if (!Constraints)
19217 SatisfactionStatus.push_back(true);
19218 else {
19219 ConstraintSatisfaction Satisfaction;
19220 if (S.CheckFunctionConstraints(Method, Satisfaction))
19221 SatisfactionStatus.push_back(false);
19222 else
19223 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19224 }
19225 }
19226
19227 for (size_t i = 0; i < Methods.size(); i++) {
19228 if (!SatisfactionStatus[i])
19229 continue;
19230 CXXMethodDecl *Method = Methods[i];
19231 CXXMethodDecl *OrigMethod = Method;
19232 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19233 OrigMethod = cast<CXXMethodDecl>(MF);
19234
19235 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
19236 bool AnotherMethodIsMoreConstrained = false;
19237 for (size_t j = 0; j < Methods.size(); j++) {
19238 if (i == j || !SatisfactionStatus[j])
19239 continue;
19240 CXXMethodDecl *OtherMethod = Methods[j];
19241 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19242 OtherMethod = cast<CXXMethodDecl>(MF);
19243
19244 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19245 CSM))
19246 continue;
19247
19248 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
19249 if (!OtherConstraints)
19250 continue;
19251 if (!Constraints) {
19252 AnotherMethodIsMoreConstrained = true;
19253 break;
19254 }
19255 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
19256 {Constraints},
19257 AnotherMethodIsMoreConstrained)) {
19258 // There was an error with the constraints comparison. Exit the loop
19259 // and don't consider this function eligible.
19260 AnotherMethodIsMoreConstrained = true;
19261 }
19262 if (AnotherMethodIsMoreConstrained)
19263 break;
19264 }
19265 // FIXME: Do not consider deleted methods as eligible after implementing
19266 // DR1734 and DR1496.
19267 if (!AnotherMethodIsMoreConstrained) {
19268 Method->setIneligibleOrNotSelected(false);
19269 Record->addedEligibleSpecialMemberFunction(Method,
19270 1 << llvm::to_underlying(CSM));
19271 }
19272 }
19273}
19274
19277 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19278 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19279 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19280 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19281 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19282
19283 for (auto *Decl : Record->decls()) {
19284 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19285 if (!MD) {
19286 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19287 if (FTD)
19288 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19289 }
19290 if (!MD)
19291 continue;
19292 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19293 if (CD->isInvalidDecl())
19294 continue;
19295 if (CD->isDefaultConstructor())
19296 DefaultConstructors.push_back(MD);
19297 else if (CD->isCopyConstructor())
19298 CopyConstructors.push_back(MD);
19299 else if (CD->isMoveConstructor())
19300 MoveConstructors.push_back(MD);
19301 } else if (MD->isCopyAssignmentOperator()) {
19302 CopyAssignmentOperators.push_back(MD);
19303 } else if (MD->isMoveAssignmentOperator()) {
19304 MoveAssignmentOperators.push_back(MD);
19305 }
19306 }
19307
19308 SetEligibleMethods(S, Record, DefaultConstructors,
19310 SetEligibleMethods(S, Record, CopyConstructors,
19312 SetEligibleMethods(S, Record, MoveConstructors,
19314 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19316 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19318}
19319
19320void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19321 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19322 SourceLocation RBrac,
19323 const ParsedAttributesView &Attrs) {
19324 assert(EnclosingDecl && "missing record or interface decl");
19325
19326 // If this is an Objective-C @implementation or category and we have
19327 // new fields here we should reset the layout of the interface since
19328 // it will now change.
19329 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19330 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19331 switch (DC->getKind()) {
19332 default: break;
19333 case Decl::ObjCCategory:
19334 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19335 break;
19336 case Decl::ObjCImplementation:
19337 Context.
19338 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19339 break;
19340 }
19341 }
19342
19343 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19344 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19345
19346 // Start counting up the number of named members; make sure to include
19347 // members of anonymous structs and unions in the total.
19348 unsigned NumNamedMembers = 0;
19349 if (Record) {
19350 for (const auto *I : Record->decls()) {
19351 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19352 if (IFD->getDeclName())
19353 ++NumNamedMembers;
19354 }
19355 }
19356
19357 // Verify that all the fields are okay.
19359
19360 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19361 i != end; ++i) {
19362 FieldDecl *FD = cast<FieldDecl>(*i);
19363
19364 // Get the type for the field.
19365 const Type *FDTy = FD->getType().getTypePtr();
19366
19367 if (!FD->isAnonymousStructOrUnion()) {
19368 // Remember all fields written by the user.
19369 RecFields.push_back(FD);
19370 }
19371
19372 // If the field is already invalid for some reason, don't emit more
19373 // diagnostics about it.
19374 if (FD->isInvalidDecl()) {
19375 EnclosingDecl->setInvalidDecl();
19376 continue;
19377 }
19378
19379 // C99 6.7.2.1p2:
19380 // A structure or union shall not contain a member with
19381 // incomplete or function type (hence, a structure shall not
19382 // contain an instance of itself, but may contain a pointer to
19383 // an instance of itself), except that the last member of a
19384 // structure with more than one named member may have incomplete
19385 // array type; such a structure (and any union containing,
19386 // possibly recursively, a member that is such a structure)
19387 // shall not be a member of a structure or an element of an
19388 // array.
19389 bool IsLastField = (i + 1 == Fields.end());
19390 if (FDTy->isFunctionType()) {
19391 // Field declared as a function.
19392 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19393 << FD->getDeclName();
19394 FD->setInvalidDecl();
19395 EnclosingDecl->setInvalidDecl();
19396 continue;
19397 } else if (FDTy->isIncompleteArrayType() &&
19398 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19399 if (Record) {
19400 // Flexible array member.
19401 // Microsoft and g++ is more permissive regarding flexible array.
19402 // It will accept flexible array in union and also
19403 // as the sole element of a struct/class.
19404 unsigned DiagID = 0;
19405 if (!Record->isUnion() && !IsLastField) {
19406 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19407 << FD->getDeclName() << FD->getType()
19408 << llvm::to_underlying(Record->getTagKind());
19409 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19410 FD->setInvalidDecl();
19411 EnclosingDecl->setInvalidDecl();
19412 continue;
19413 } else if (Record->isUnion())
19414 DiagID = getLangOpts().MicrosoftExt
19415 ? diag::ext_flexible_array_union_ms
19416 : diag::ext_flexible_array_union_gnu;
19417 else if (NumNamedMembers < 1)
19418 DiagID = getLangOpts().MicrosoftExt
19419 ? diag::ext_flexible_array_empty_aggregate_ms
19420 : diag::ext_flexible_array_empty_aggregate_gnu;
19421
19422 if (DiagID)
19423 Diag(FD->getLocation(), DiagID)
19424 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19425 // While the layout of types that contain virtual bases is not specified
19426 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19427 // virtual bases after the derived members. This would make a flexible
19428 // array member declared at the end of an object not adjacent to the end
19429 // of the type.
19430 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19431 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19432 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19433 if (!getLangOpts().C99)
19434 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19435 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19436
19437 // If the element type has a non-trivial destructor, we would not
19438 // implicitly destroy the elements, so disallow it for now.
19439 //
19440 // FIXME: GCC allows this. We should probably either implicitly delete
19441 // the destructor of the containing class, or just allow this.
19442 QualType BaseElem = Context.getBaseElementType(FD->getType());
19443 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19444 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19445 << FD->getDeclName() << FD->getType();
19446 FD->setInvalidDecl();
19447 EnclosingDecl->setInvalidDecl();
19448 continue;
19449 }
19450 // Okay, we have a legal flexible array member at the end of the struct.
19451 Record->setHasFlexibleArrayMember(true);
19452 } else {
19453 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19454 // unless they are followed by another ivar. That check is done
19455 // elsewhere, after synthesized ivars are known.
19456 }
19457 } else if (!FDTy->isDependentType() &&
19459 FD->getLocation(), FD->getType(),
19460 diag::err_field_incomplete_or_sizeless)) {
19461 // Incomplete type
19462 FD->setInvalidDecl();
19463 EnclosingDecl->setInvalidDecl();
19464 continue;
19465 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19466 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19467 // A type which contains a flexible array member is considered to be a
19468 // flexible array member.
19469 Record->setHasFlexibleArrayMember(true);
19470 if (!Record->isUnion()) {
19471 // If this is a struct/class and this is not the last element, reject
19472 // it. Note that GCC supports variable sized arrays in the middle of
19473 // structures.
19474 if (!IsLastField)
19475 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19476 << FD->getDeclName() << FD->getType();
19477 else {
19478 // We support flexible arrays at the end of structs in
19479 // other structs as an extension.
19480 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19481 << FD->getDeclName();
19482 }
19483 }
19484 }
19485 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19487 diag::err_abstract_type_in_decl,
19489 // Ivars can not have abstract class types
19490 FD->setInvalidDecl();
19491 }
19492 if (Record && FDTTy->getDecl()->hasObjectMember())
19493 Record->setHasObjectMember(true);
19494 if (Record && FDTTy->getDecl()->hasVolatileMember())
19495 Record->setHasVolatileMember(true);
19496 } else if (FDTy->isObjCObjectType()) {
19497 /// A field cannot be an Objective-c object
19498 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19501 FD->setType(T);
19502 } else if (Record && Record->isUnion() &&
19504 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19505 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19508 // For backward compatibility, fields of C unions declared in system
19509 // headers that have non-trivial ObjC ownership qualifications are marked
19510 // as unavailable unless the qualifier is explicit and __strong. This can
19511 // break ABI compatibility between programs compiled with ARC and MRR, but
19512 // is a better option than rejecting programs using those unions under
19513 // ARC.
19514 FD->addAttr(UnavailableAttr::CreateImplicit(
19515 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19516 FD->getLocation()));
19517 } else if (getLangOpts().ObjC &&
19518 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19519 !Record->hasObjectMember()) {
19520 if (FD->getType()->isObjCObjectPointerType() ||
19521 FD->getType().isObjCGCStrong())
19522 Record->setHasObjectMember(true);
19523 else if (Context.getAsArrayType(FD->getType())) {
19524 QualType BaseType = Context.getBaseElementType(FD->getType());
19525 if (BaseType->isRecordType() &&
19526 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19527 Record->setHasObjectMember(true);
19528 else if (BaseType->isObjCObjectPointerType() ||
19529 BaseType.isObjCGCStrong())
19530 Record->setHasObjectMember(true);
19531 }
19532 }
19533
19534 if (Record && !getLangOpts().CPlusPlus &&
19535 !shouldIgnoreForRecordTriviality(FD)) {
19536 QualType FT = FD->getType();
19538 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19540 Record->isUnion())
19541 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19542 }
19545 Record->setNonTrivialToPrimitiveCopy(true);
19546 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19547 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19548 }
19549 if (FT.isDestructedType()) {
19550 Record->setNonTrivialToPrimitiveDestroy(true);
19551 Record->setParamDestroyedInCallee(true);
19552 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19553 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19554 }
19555
19556 if (const auto *RT = FT->getAs<RecordType>()) {
19557 if (RT->getDecl()->getArgPassingRestrictions() ==
19559 Record->setArgPassingRestrictions(
19562 Record->setArgPassingRestrictions(
19564 }
19565
19566 if (Record && FD->getType().isVolatileQualified())
19567 Record->setHasVolatileMember(true);
19568 // Keep track of the number of named members.
19569 if (FD->getIdentifier())
19570 ++NumNamedMembers;
19571 }
19572
19573 // Okay, we successfully defined 'Record'.
19574 if (Record) {
19575 bool Completed = false;
19576 if (S) {
19577 Scope *Parent = S->getParent();
19578 if (Parent && Parent->isTypeAliasScope() &&
19579 Parent->isTemplateParamScope())
19580 Record->setInvalidDecl();
19581 }
19582
19583 if (CXXRecord) {
19584 if (!CXXRecord->isInvalidDecl()) {
19585 // Set access bits correctly on the directly-declared conversions.
19587 I = CXXRecord->conversion_begin(),
19588 E = CXXRecord->conversion_end(); I != E; ++I)
19589 I.setAccess((*I)->getAccess());
19590 }
19591
19592 // Add any implicitly-declared members to this class.
19594
19595 if (!CXXRecord->isDependentType()) {
19596 if (!CXXRecord->isInvalidDecl()) {
19597 // If we have virtual base classes, we may end up finding multiple
19598 // final overriders for a given virtual function. Check for this
19599 // problem now.
19600 if (CXXRecord->getNumVBases()) {
19601 CXXFinalOverriderMap FinalOverriders;
19602 CXXRecord->getFinalOverriders(FinalOverriders);
19603
19604 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19605 MEnd = FinalOverriders.end();
19606 M != MEnd; ++M) {
19607 for (OverridingMethods::iterator SO = M->second.begin(),
19608 SOEnd = M->second.end();
19609 SO != SOEnd; ++SO) {
19610 assert(SO->second.size() > 0 &&
19611 "Virtual function without overriding functions?");
19612 if (SO->second.size() == 1)
19613 continue;
19614
19615 // C++ [class.virtual]p2:
19616 // In a derived class, if a virtual member function of a base
19617 // class subobject has more than one final overrider the
19618 // program is ill-formed.
19619 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19620 << (const NamedDecl *)M->first << Record;
19621 Diag(M->first->getLocation(),
19622 diag::note_overridden_virtual_function);
19624 OM = SO->second.begin(),
19625 OMEnd = SO->second.end();
19626 OM != OMEnd; ++OM)
19627 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19628 << (const NamedDecl *)M->first << OM->Method->getParent();
19629
19630 Record->setInvalidDecl();
19631 }
19632 }
19633 CXXRecord->completeDefinition(&FinalOverriders);
19634 Completed = true;
19635 }
19636 }
19637 ComputeSelectedDestructor(*this, CXXRecord);
19639 }
19640 }
19641
19642 if (!Completed)
19643 Record->completeDefinition();
19644
19645 // Handle attributes before checking the layout.
19647
19648 // Check to see if a FieldDecl is a pointer to a function.
19649 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19650 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19651 if (!FD) {
19652 // Check whether this is a forward declaration that was inserted by
19653 // Clang. This happens when a non-forward declared / defined type is
19654 // used, e.g.:
19655 //
19656 // struct foo {
19657 // struct bar *(*f)();
19658 // struct bar *(*g)();
19659 // };
19660 //
19661 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19662 // incomplete definition.
19663 if (const auto *TD = dyn_cast<TagDecl>(D))
19664 return !TD->isCompleteDefinition();
19665 return false;
19666 }
19667 QualType FieldType = FD->getType().getDesugaredType(Context);
19668 if (isa<PointerType>(FieldType)) {
19669 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19670 return PointeeType.getDesugaredType(Context)->isFunctionType();
19671 }
19672 return false;
19673 };
19674
19675 // Maybe randomize the record's decls. We automatically randomize a record
19676 // of function pointers, unless it has the "no_randomize_layout" attribute.
19677 if (!getLangOpts().CPlusPlus &&
19678 (Record->hasAttr<RandomizeLayoutAttr>() ||
19679 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19680 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19681 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19682 !Record->isRandomized()) {
19683 SmallVector<Decl *, 32> NewDeclOrdering;
19685 NewDeclOrdering))
19686 Record->reorderDecls(NewDeclOrdering);
19687 }
19688
19689 // We may have deferred checking for a deleted destructor. Check now.
19690 if (CXXRecord) {
19691 auto *Dtor = CXXRecord->getDestructor();
19692 if (Dtor && Dtor->isImplicit() &&
19694 CXXRecord->setImplicitDestructorIsDeleted();
19695 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19696 }
19697 }
19698
19699 if (Record->hasAttrs()) {
19701
19702 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19703 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19704 IA->getRange(), IA->getBestCase(),
19705 IA->getInheritanceModel());
19706 }
19707
19708 // Check if the structure/union declaration is a type that can have zero
19709 // size in C. For C this is a language extension, for C++ it may cause
19710 // compatibility problems.
19711 bool CheckForZeroSize;
19712 if (!getLangOpts().CPlusPlus) {
19713 CheckForZeroSize = true;
19714 } else {
19715 // For C++ filter out types that cannot be referenced in C code.
19716 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19717 CheckForZeroSize =
19718 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19719 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19720 CXXRecord->isCLike();
19721 }
19722 if (CheckForZeroSize) {
19723 bool ZeroSize = true;
19724 bool IsEmpty = true;
19725 unsigned NonBitFields = 0;
19726 for (RecordDecl::field_iterator I = Record->field_begin(),
19727 E = Record->field_end();
19728 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19729 IsEmpty = false;
19730 if (I->isUnnamedBitField()) {
19731 if (!I->isZeroLengthBitField(Context))
19732 ZeroSize = false;
19733 } else {
19734 ++NonBitFields;
19735 QualType FieldType = I->getType();
19736 if (FieldType->isIncompleteType() ||
19737 !Context.getTypeSizeInChars(FieldType).isZero())
19738 ZeroSize = false;
19739 }
19740 }
19741
19742 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19743 // allowed in C++, but warn if its declaration is inside
19744 // extern "C" block.
19745 if (ZeroSize) {
19746 Diag(RecLoc, getLangOpts().CPlusPlus ?
19747 diag::warn_zero_size_struct_union_in_extern_c :
19748 diag::warn_zero_size_struct_union_compat)
19749 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19750 }
19751
19752 // Structs without named members are extension in C (C99 6.7.2.1p7),
19753 // but are accepted by GCC.
19754 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19755 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19756 diag::ext_no_named_members_in_struct_union)
19757 << Record->isUnion();
19758 }
19759 }
19760 } else {
19761 ObjCIvarDecl **ClsFields =
19762 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19763 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19764 ID->setEndOfDefinitionLoc(RBrac);
19765 // Add ivar's to class's DeclContext.
19766 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19767 ClsFields[i]->setLexicalDeclContext(ID);
19768 ID->addDecl(ClsFields[i]);
19769 }
19770 // Must enforce the rule that ivars in the base classes may not be
19771 // duplicates.
19772 if (ID->getSuperClass())
19773 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19774 } else if (ObjCImplementationDecl *IMPDecl =
19775 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19776 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19777 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19778 // Ivar declared in @implementation never belongs to the implementation.
19779 // Only it is in implementation's lexical context.
19780 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19781 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19782 IMPDecl->setIvarLBraceLoc(LBrac);
19783 IMPDecl->setIvarRBraceLoc(RBrac);
19784 } else if (ObjCCategoryDecl *CDecl =
19785 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19786 // case of ivars in class extension; all other cases have been
19787 // reported as errors elsewhere.
19788 // FIXME. Class extension does not have a LocEnd field.
19789 // CDecl->setLocEnd(RBrac);
19790 // Add ivar's to class extension's DeclContext.
19791 // Diagnose redeclaration of private ivars.
19792 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19793 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19794 if (IDecl) {
19795 if (const ObjCIvarDecl *ClsIvar =
19796 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19797 Diag(ClsFields[i]->getLocation(),
19798 diag::err_duplicate_ivar_declaration);
19799 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19800 continue;
19801 }
19802 for (const auto *Ext : IDecl->known_extensions()) {
19803 if (const ObjCIvarDecl *ClsExtIvar
19804 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19805 Diag(ClsFields[i]->getLocation(),
19806 diag::err_duplicate_ivar_declaration);
19807 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19808 continue;
19809 }
19810 }
19811 }
19812 ClsFields[i]->setLexicalDeclContext(CDecl);
19813 CDecl->addDecl(ClsFields[i]);
19814 }
19815 CDecl->setIvarLBraceLoc(LBrac);
19816 CDecl->setIvarRBraceLoc(RBrac);
19817 }
19818 }
19820}
19821
19822/// Determine whether the given integral value is representable within
19823/// the given type T.
19825 llvm::APSInt &Value,
19826 QualType T) {
19827 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19828 "Integral type required!");
19829 unsigned BitWidth = Context.getIntWidth(T);
19830
19831 if (Value.isUnsigned() || Value.isNonNegative()) {
19833 --BitWidth;
19834 return Value.getActiveBits() <= BitWidth;
19835 }
19836 return Value.getSignificantBits() <= BitWidth;
19837}
19838
19839// Given an integral type, return the next larger integral type
19840// (or a NULL type of no such type exists).
19842 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19843 // enum checking below.
19844 assert((T->isIntegralType(Context) ||
19845 T->isEnumeralType()) && "Integral type required!");
19846 const unsigned NumTypes = 4;
19847 QualType SignedIntegralTypes[NumTypes] = {
19848 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19849 };
19850 QualType UnsignedIntegralTypes[NumTypes] = {
19851 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19852 Context.UnsignedLongLongTy
19853 };
19854
19855 unsigned BitWidth = Context.getTypeSize(T);
19856 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19857 : UnsignedIntegralTypes;
19858 for (unsigned I = 0; I != NumTypes; ++I)
19859 if (Context.getTypeSize(Types[I]) > BitWidth)
19860 return Types[I];
19861
19862 return QualType();
19863}
19864
19866 EnumConstantDecl *LastEnumConst,
19867 SourceLocation IdLoc,
19869 Expr *Val) {
19870 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19871 llvm::APSInt EnumVal(IntWidth);
19872 QualType EltTy;
19873
19875 Val = nullptr;
19876
19877 if (Val)
19878 Val = DefaultLvalueConversion(Val).get();
19879
19880 if (Val) {
19881 if (Enum->isDependentType() || Val->isTypeDependent() ||
19882 Val->containsErrors())
19883 EltTy = Context.DependentTy;
19884 else {
19885 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19886 // underlying type, but do allow it in all other contexts.
19887 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19888 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19889 // constant-expression in the enumerator-definition shall be a converted
19890 // constant expression of the underlying type.
19891 EltTy = Enum->getIntegerType();
19892 ExprResult Converted =
19893 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19895 if (Converted.isInvalid())
19896 Val = nullptr;
19897 else
19898 Val = Converted.get();
19899 } else if (!Val->isValueDependent() &&
19900 !(Val =
19902 .get())) {
19903 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19904 } else {
19905 if (Enum->isComplete()) {
19906 EltTy = Enum->getIntegerType();
19907
19908 // In Obj-C and Microsoft mode, require the enumeration value to be
19909 // representable in the underlying type of the enumeration. In C++11,
19910 // we perform a non-narrowing conversion as part of converted constant
19911 // expression checking.
19912 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19914 .getTriple()
19915 .isWindowsMSVCEnvironment()) {
19916 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19917 } else {
19918 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19919 }
19920 }
19921
19922 // Cast to the underlying type.
19923 Val = ImpCastExprToType(Val, EltTy,
19924 EltTy->isBooleanType() ? CK_IntegralToBoolean
19925 : CK_IntegralCast)
19926 .get();
19927 } else if (getLangOpts().CPlusPlus) {
19928 // C++11 [dcl.enum]p5:
19929 // If the underlying type is not fixed, the type of each enumerator
19930 // is the type of its initializing value:
19931 // - If an initializer is specified for an enumerator, the
19932 // initializing value has the same type as the expression.
19933 EltTy = Val->getType();
19934 } else {
19935 // C99 6.7.2.2p2:
19936 // The expression that defines the value of an enumeration constant
19937 // shall be an integer constant expression that has a value
19938 // representable as an int.
19939
19940 // Complain if the value is not representable in an int.
19942 Diag(IdLoc, diag::ext_enum_value_not_int)
19943 << toString(EnumVal, 10) << Val->getSourceRange()
19944 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19945 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19946 // Force the type of the expression to 'int'.
19947 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19948 }
19949 EltTy = Val->getType();
19950 }
19951 }
19952 }
19953 }
19954
19955 if (!Val) {
19956 if (Enum->isDependentType())
19957 EltTy = Context.DependentTy;
19958 else if (!LastEnumConst) {
19959 // C++0x [dcl.enum]p5:
19960 // If the underlying type is not fixed, the type of each enumerator
19961 // is the type of its initializing value:
19962 // - If no initializer is specified for the first enumerator, the
19963 // initializing value has an unspecified integral type.
19964 //
19965 // GCC uses 'int' for its unspecified integral type, as does
19966 // C99 6.7.2.2p3.
19967 if (Enum->isFixed()) {
19968 EltTy = Enum->getIntegerType();
19969 }
19970 else {
19971 EltTy = Context.IntTy;
19972 }
19973 } else {
19974 // Assign the last value + 1.
19975 EnumVal = LastEnumConst->getInitVal();
19976 ++EnumVal;
19977 EltTy = LastEnumConst->getType();
19978
19979 // Check for overflow on increment.
19980 if (EnumVal < LastEnumConst->getInitVal()) {
19981 // C++0x [dcl.enum]p5:
19982 // If the underlying type is not fixed, the type of each enumerator
19983 // is the type of its initializing value:
19984 //
19985 // - Otherwise the type of the initializing value is the same as
19986 // the type of the initializing value of the preceding enumerator
19987 // unless the incremented value is not representable in that type,
19988 // in which case the type is an unspecified integral type
19989 // sufficient to contain the incremented value. If no such type
19990 // exists, the program is ill-formed.
19992 if (T.isNull() || Enum->isFixed()) {
19993 // There is no integral type larger enough to represent this
19994 // value. Complain, then allow the value to wrap around.
19995 EnumVal = LastEnumConst->getInitVal();
19996 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19997 ++EnumVal;
19998 if (Enum->isFixed())
19999 // When the underlying type is fixed, this is ill-formed.
20000 Diag(IdLoc, diag::err_enumerator_wrapped)
20001 << toString(EnumVal, 10)
20002 << EltTy;
20003 else
20004 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20005 << toString(EnumVal, 10);
20006 } else {
20007 EltTy = T;
20008 }
20009
20010 // Retrieve the last enumerator's value, extent that type to the
20011 // type that is supposed to be large enough to represent the incremented
20012 // value, then increment.
20013 EnumVal = LastEnumConst->getInitVal();
20014 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20015 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20016 ++EnumVal;
20017
20018 // If we're not in C++, diagnose the overflow of enumerator values,
20019 // which in C99 means that the enumerator value is not representable in
20020 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
20021 // permits enumerator values that are representable in some larger
20022 // integral type.
20023 if (!getLangOpts().CPlusPlus && !T.isNull())
20024 Diag(IdLoc, diag::warn_enum_value_overflow);
20025 } else if (!getLangOpts().CPlusPlus &&
20026 !EltTy->isDependentType() &&
20027 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
20028 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20029 Diag(IdLoc, diag::ext_enum_value_not_int)
20030 << toString(EnumVal, 10) << 1;
20031 }
20032 }
20033 }
20034
20035 if (!EltTy->isDependentType()) {
20036 // Make the enumerator value match the signedness and size of the
20037 // enumerator's type.
20038 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20039 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20040 }
20041
20042 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20043 Val, EnumVal);
20044}
20045
20047 SourceLocation IILoc) {
20048 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20050 return SkipBodyInfo();
20051
20052 // We have an anonymous enum definition. Look up the first enumerator to
20053 // determine if we should merge the definition with an existing one and
20054 // skip the body.
20055 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20057 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20058 if (!PrevECD)
20059 return SkipBodyInfo();
20060
20061 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20062 NamedDecl *Hidden;
20063 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20064 SkipBodyInfo Skip;
20065 Skip.Previous = Hidden;
20066 return Skip;
20067 }
20068
20069 return SkipBodyInfo();
20070}
20071
20072Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20074 const ParsedAttributesView &Attrs,
20075 SourceLocation EqualLoc, Expr *Val) {
20076 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20077 EnumConstantDecl *LastEnumConst =
20078 cast_or_null<EnumConstantDecl>(lastEnumConst);
20079
20080 // The scope passed in may not be a decl scope. Zip up the scope tree until
20081 // we find one that is.
20082 S = getNonFieldDeclScope(S);
20083
20084 // Verify that there isn't already something declared with this name in this
20085 // scope.
20086 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20087 RedeclarationKind::ForVisibleRedeclaration);
20088 LookupName(R, S);
20089 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20090
20091 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20092 // Maybe we will complain about the shadowed template parameter.
20093 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20094 // Just pretend that we didn't see the previous declaration.
20095 PrevDecl = nullptr;
20096 }
20097
20098 // C++ [class.mem]p15:
20099 // If T is the name of a class, then each of the following shall have a name
20100 // different from T:
20101 // - every enumerator of every member of class T that is an unscoped
20102 // enumerated type
20103 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
20105 DeclarationNameInfo(Id, IdLoc));
20106
20107 EnumConstantDecl *New =
20108 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20109 if (!New)
20110 return nullptr;
20111
20112 if (PrevDecl) {
20113 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20114 // Check for other kinds of shadowing not already handled.
20115 CheckShadow(New, PrevDecl, R);
20116 }
20117
20118 // When in C++, we may get a TagDecl with the same name; in this case the
20119 // enum constant will 'hide' the tag.
20120 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20121 "Received TagDecl when not in C++!");
20122 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20123 if (isa<EnumConstantDecl>(PrevDecl))
20124 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20125 else
20126 Diag(IdLoc, diag::err_redefinition) << Id;
20127 notePreviousDefinition(PrevDecl, IdLoc);
20128 return nullptr;
20129 }
20130 }
20131
20132 // Process attributes.
20133 ProcessDeclAttributeList(S, New, Attrs);
20134 AddPragmaAttributes(S, New);
20135 ProcessAPINotes(New);
20136
20137 // Register this decl in the current scope stack.
20138 New->setAccess(TheEnumDecl->getAccess());
20139 PushOnScopeChains(New, S);
20140
20142
20143 return New;
20144}
20145
20146// Returns true when the enum initial expression does not trigger the
20147// duplicate enum warning. A few common cases are exempted as follows:
20148// Element2 = Element1
20149// Element2 = Element1 + 1
20150// Element2 = Element1 - 1
20151// Where Element2 and Element1 are from the same enum.
20153 Expr *InitExpr = ECD->getInitExpr();
20154 if (!InitExpr)
20155 return true;
20156 InitExpr = InitExpr->IgnoreImpCasts();
20157
20158 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20159 if (!BO->isAdditiveOp())
20160 return true;
20161 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20162 if (!IL)
20163 return true;
20164 if (IL->getValue() != 1)
20165 return true;
20166
20167 InitExpr = BO->getLHS();
20168 }
20169
20170 // This checks if the elements are from the same enum.
20171 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20172 if (!DRE)
20173 return true;
20174
20175 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20176 if (!EnumConstant)
20177 return true;
20178
20179 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
20180 Enum)
20181 return true;
20182
20183 return false;
20184}
20185
20186// Emits a warning when an element is implicitly set a value that
20187// a previous element has already been set to.
20190 // Avoid anonymous enums
20191 if (!Enum->getIdentifier())
20192 return;
20193
20194 // Only check for small enums.
20195 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20196 return;
20197
20198 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20199 return;
20200
20201 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20202 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20203
20204 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20205
20206 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20207 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20208
20209 // Use int64_t as a key to avoid needing special handling for map keys.
20210 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20211 llvm::APSInt Val = D->getInitVal();
20212 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20213 };
20214
20215 DuplicatesVector DupVector;
20216 ValueToVectorMap EnumMap;
20217
20218 // Populate the EnumMap with all values represented by enum constants without
20219 // an initializer.
20220 for (auto *Element : Elements) {
20221 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20222
20223 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20224 // this constant. Skip this enum since it may be ill-formed.
20225 if (!ECD) {
20226 return;
20227 }
20228
20229 // Constants with initializers are handled in the next loop.
20230 if (ECD->getInitExpr())
20231 continue;
20232
20233 // Duplicate values are handled in the next loop.
20234 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20235 }
20236
20237 if (EnumMap.size() == 0)
20238 return;
20239
20240 // Create vectors for any values that has duplicates.
20241 for (auto *Element : Elements) {
20242 // The last loop returned if any constant was null.
20243 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
20244 if (!ValidDuplicateEnum(ECD, Enum))
20245 continue;
20246
20247 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20248 if (Iter == EnumMap.end())
20249 continue;
20250
20251 DeclOrVector& Entry = Iter->second;
20252 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
20253 // Ensure constants are different.
20254 if (D == ECD)
20255 continue;
20256
20257 // Create new vector and push values onto it.
20258 auto Vec = std::make_unique<ECDVector>();
20259 Vec->push_back(D);
20260 Vec->push_back(ECD);
20261
20262 // Update entry to point to the duplicates vector.
20263 Entry = Vec.get();
20264
20265 // Store the vector somewhere we can consult later for quick emission of
20266 // diagnostics.
20267 DupVector.emplace_back(std::move(Vec));
20268 continue;
20269 }
20270
20271 ECDVector *Vec = Entry.get<ECDVector*>();
20272 // Make sure constants are not added more than once.
20273 if (*Vec->begin() == ECD)
20274 continue;
20275
20276 Vec->push_back(ECD);
20277 }
20278
20279 // Emit diagnostics.
20280 for (const auto &Vec : DupVector) {
20281 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20282
20283 // Emit warning for one enum constant.
20284 auto *FirstECD = Vec->front();
20285 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20286 << FirstECD << toString(FirstECD->getInitVal(), 10)
20287 << FirstECD->getSourceRange();
20288
20289 // Emit one note for each of the remaining enum constants with
20290 // the same value.
20291 for (auto *ECD : llvm::drop_begin(*Vec))
20292 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20293 << ECD << toString(ECD->getInitVal(), 10)
20294 << ECD->getSourceRange();
20295 }
20296}
20297
20298bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20299 bool AllowMask) const {
20300 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20301 assert(ED->isCompleteDefinition() && "expected enum definition");
20302
20303 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
20304 llvm::APInt &FlagBits = R.first->second;
20305
20306 if (R.second) {
20307 for (auto *E : ED->enumerators()) {
20308 const auto &EVal = E->getInitVal();
20309 // Only single-bit enumerators introduce new flag values.
20310 if (EVal.isPowerOf2())
20311 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20312 }
20313 }
20314
20315 // A value is in a flag enum if either its bits are a subset of the enum's
20316 // flag bits (the first condition) or we are allowing masks and the same is
20317 // true of its complement (the second condition). When masks are allowed, we
20318 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20319 //
20320 // While it's true that any value could be used as a mask, the assumption is
20321 // that a mask will have all of the insignificant bits set. Anything else is
20322 // likely a logic error.
20323 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20324 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20325}
20326
20328 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20329 const ParsedAttributesView &Attrs) {
20330 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20332
20333 ProcessDeclAttributeList(S, Enum, Attrs);
20335
20336 if (Enum->isDependentType()) {
20337 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20338 EnumConstantDecl *ECD =
20339 cast_or_null<EnumConstantDecl>(Elements[i]);
20340 if (!ECD) continue;
20341
20342 ECD->setType(EnumType);
20343 }
20344
20345 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20346 return;
20347 }
20348
20349 // TODO: If the result value doesn't fit in an int, it must be a long or long
20350 // long value. ISO C does not support this, but GCC does as an extension,
20351 // emit a warning.
20352 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20353 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
20354 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
20355
20356 // Verify that all the values are okay, compute the size of the values, and
20357 // reverse the list.
20358 unsigned NumNegativeBits = 0;
20359 unsigned NumPositiveBits = 0;
20360
20361 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20362 EnumConstantDecl *ECD =
20363 cast_or_null<EnumConstantDecl>(Elements[i]);
20364 if (!ECD) continue; // Already issued a diagnostic.
20365
20366 const llvm::APSInt &InitVal = ECD->getInitVal();
20367
20368 // Keep track of the size of positive and negative values.
20369 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20370 // If the enumerator is zero that should still be counted as a positive
20371 // bit since we need a bit to store the value zero.
20372 unsigned ActiveBits = InitVal.getActiveBits();
20373 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
20374 } else {
20375 NumNegativeBits =
20376 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
20377 }
20378 }
20379
20380 // If we have an empty set of enumerators we still need one bit.
20381 // From [dcl.enum]p8
20382 // If the enumerator-list is empty, the values of the enumeration are as if
20383 // the enumeration had a single enumerator with value 0
20384 if (!NumPositiveBits && !NumNegativeBits)
20385 NumPositiveBits = 1;
20386
20387 // Figure out the type that should be used for this enum.
20388 QualType BestType;
20389 unsigned BestWidth;
20390
20391 // C++0x N3000 [conv.prom]p3:
20392 // An rvalue of an unscoped enumeration type whose underlying
20393 // type is not fixed can be converted to an rvalue of the first
20394 // of the following types that can represent all the values of
20395 // the enumeration: int, unsigned int, long int, unsigned long
20396 // int, long long int, or unsigned long long int.
20397 // C99 6.4.4.3p2:
20398 // An identifier declared as an enumeration constant has type int.
20399 // The C99 rule is modified by a gcc extension
20400 QualType BestPromotionType;
20401
20402 bool Packed = Enum->hasAttr<PackedAttr>();
20403 // -fshort-enums is the equivalent to specifying the packed attribute on all
20404 // enum definitions.
20405 if (LangOpts.ShortEnums)
20406 Packed = true;
20407
20408 // If the enum already has a type because it is fixed or dictated by the
20409 // target, promote that type instead of analyzing the enumerators.
20410 if (Enum->isComplete()) {
20411 BestType = Enum->getIntegerType();
20412 if (Context.isPromotableIntegerType(BestType))
20413 BestPromotionType = Context.getPromotedIntegerType(BestType);
20414 else
20415 BestPromotionType = BestType;
20416
20417 BestWidth = Context.getIntWidth(BestType);
20418 }
20419 else if (NumNegativeBits) {
20420 // If there is a negative value, figure out the smallest integer type (of
20421 // int/long/longlong) that fits.
20422 // If it's packed, check also if it fits a char or a short.
20423 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
20424 BestType = Context.SignedCharTy;
20425 BestWidth = CharWidth;
20426 } else if (Packed && NumNegativeBits <= ShortWidth &&
20427 NumPositiveBits < ShortWidth) {
20428 BestType = Context.ShortTy;
20429 BestWidth = ShortWidth;
20430 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
20431 BestType = Context.IntTy;
20432 BestWidth = IntWidth;
20433 } else {
20434 BestWidth = Context.getTargetInfo().getLongWidth();
20435
20436 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
20437 BestType = Context.LongTy;
20438 } else {
20439 BestWidth = Context.getTargetInfo().getLongLongWidth();
20440
20441 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
20442 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20443 BestType = Context.LongLongTy;
20444 }
20445 }
20446 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
20447 } else {
20448 // If there is no negative value, figure out the smallest type that fits
20449 // all of the enumerator values.
20450 // If it's packed, check also if it fits a char or a short.
20451 if (Packed && NumPositiveBits <= CharWidth) {
20452 BestType = Context.UnsignedCharTy;
20453 BestPromotionType = Context.IntTy;
20454 BestWidth = CharWidth;
20455 } else if (Packed && NumPositiveBits <= ShortWidth) {
20456 BestType = Context.UnsignedShortTy;
20457 BestPromotionType = Context.IntTy;
20458 BestWidth = ShortWidth;
20459 } else if (NumPositiveBits <= IntWidth) {
20460 BestType = Context.UnsignedIntTy;
20461 BestWidth = IntWidth;
20462 BestPromotionType
20463 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20465 } else if (NumPositiveBits <=
20466 (BestWidth = Context.getTargetInfo().getLongWidth())) {
20467 BestType = Context.UnsignedLongTy;
20468 BestPromotionType
20469 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20471 } else {
20472 BestWidth = Context.getTargetInfo().getLongLongWidth();
20473 if (NumPositiveBits > BestWidth) {
20474 // This can happen with bit-precise integer types, but those are not
20475 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
20476 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
20477 // a 128-bit integer, we should consider doing the same.
20478 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20479 }
20480 BestType = Context.UnsignedLongLongTy;
20481 BestPromotionType
20482 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20484 }
20485 }
20486
20487 // Loop over all of the enumerator constants, changing their types to match
20488 // the type of the enum if needed.
20489 for (auto *D : Elements) {
20490 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20491 if (!ECD) continue; // Already issued a diagnostic.
20492
20493 // Standard C says the enumerators have int type, but we allow, as an
20494 // extension, the enumerators to be larger than int size. If each
20495 // enumerator value fits in an int, type it as an int, otherwise type it the
20496 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20497 // that X has type 'int', not 'unsigned'.
20498
20499 // Determine whether the value fits into an int.
20500 llvm::APSInt InitVal = ECD->getInitVal();
20501
20502 // If it fits into an integer type, force it. Otherwise force it to match
20503 // the enum decl type.
20504 QualType NewTy;
20505 unsigned NewWidth;
20506 bool NewSign;
20507 if (!getLangOpts().CPlusPlus &&
20508 !Enum->isFixed() &&
20510 NewTy = Context.IntTy;
20511 NewWidth = IntWidth;
20512 NewSign = true;
20513 } else if (ECD->getType() == BestType) {
20514 // Already the right type!
20515 if (getLangOpts().CPlusPlus)
20516 // C++ [dcl.enum]p4: Following the closing brace of an
20517 // enum-specifier, each enumerator has the type of its
20518 // enumeration.
20519 ECD->setType(EnumType);
20520 continue;
20521 } else {
20522 NewTy = BestType;
20523 NewWidth = BestWidth;
20524 NewSign = BestType->isSignedIntegerOrEnumerationType();
20525 }
20526
20527 // Adjust the APSInt value.
20528 InitVal = InitVal.extOrTrunc(NewWidth);
20529 InitVal.setIsSigned(NewSign);
20530 ECD->setInitVal(Context, InitVal);
20531
20532 // Adjust the Expr initializer and type.
20533 if (ECD->getInitExpr() &&
20534 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20535 ECD->setInitExpr(ImplicitCastExpr::Create(
20536 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20537 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20538 if (getLangOpts().CPlusPlus)
20539 // C++ [dcl.enum]p4: Following the closing brace of an
20540 // enum-specifier, each enumerator has the type of its
20541 // enumeration.
20542 ECD->setType(EnumType);
20543 else
20544 ECD->setType(NewTy);
20545 }
20546
20547 Enum->completeDefinition(BestType, BestPromotionType,
20548 NumPositiveBits, NumNegativeBits);
20549
20550 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20551
20552 if (Enum->isClosedFlag()) {
20553 for (Decl *D : Elements) {
20554 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20555 if (!ECD) continue; // Already issued a diagnostic.
20556
20557 llvm::APSInt InitVal = ECD->getInitVal();
20558 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20559 !IsValueInFlagEnum(Enum, InitVal, true))
20560 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20561 << ECD << Enum;
20562 }
20563 }
20564
20565 // Now that the enum type is defined, ensure it's not been underaligned.
20566 if (Enum->hasAttrs())
20568}
20569
20571 SourceLocation StartLoc,
20572 SourceLocation EndLoc) {
20573 StringLiteral *AsmString = cast<StringLiteral>(expr);
20574
20576 AsmString, StartLoc,
20577 EndLoc);
20578 CurContext->addDecl(New);
20579 return New;
20580}
20581
20583 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20584 CurContext->addDecl(New);
20585 PushDeclContext(S, New);
20587 PushCompoundScope(false);
20588 return New;
20589}
20590
20592 D->setStmt(Statement);
20596}
20597
20599 IdentifierInfo* AliasName,
20600 SourceLocation PragmaLoc,
20601 SourceLocation NameLoc,
20602 SourceLocation AliasNameLoc) {
20603 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20605 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20607 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20608 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20609
20610 // If a declaration that:
20611 // 1) declares a function or a variable
20612 // 2) has external linkage
20613 // already exists, add a label attribute to it.
20614 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20615 if (isDeclExternC(PrevDecl))
20616 PrevDecl->addAttr(Attr);
20617 else
20618 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20619 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20620 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20621 } else
20622 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20623}
20624
20626 SourceLocation PragmaLoc,
20627 SourceLocation NameLoc) {
20628 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20629
20630 if (PrevDecl) {
20631 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20632 } else {
20633 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20634 }
20635}
20636
20638 IdentifierInfo* AliasName,
20639 SourceLocation PragmaLoc,
20640 SourceLocation NameLoc,
20641 SourceLocation AliasNameLoc) {
20642 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20644 WeakInfo W = WeakInfo(Name, NameLoc);
20645
20646 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20647 if (!PrevDecl->hasAttr<AliasAttr>())
20648 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20650 } else {
20651 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20652 }
20653}
20654
20656 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
20657}
20658
20660 bool Final) {
20661 assert(FD && "Expected non-null FunctionDecl");
20662
20663 // SYCL functions can be template, so we check if they have appropriate
20664 // attribute prior to checking if it is a template.
20665 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20667
20668 // Templates are emitted when they're instantiated.
20669 if (FD->isDependentContext())
20671
20672 // Check whether this function is an externally visible definition.
20673 auto IsEmittedForExternalSymbol = [this, FD]() {
20674 // We have to check the GVA linkage of the function's *definition* -- if we
20675 // only have a declaration, we don't know whether or not the function will
20676 // be emitted, because (say) the definition could include "inline".
20677 const FunctionDecl *Def = FD->getDefinition();
20678
20679 return Def && !isDiscardableGVALinkage(
20680 getASTContext().GetGVALinkageForFunction(Def));
20681 };
20682
20683 if (LangOpts.OpenMPIsTargetDevice) {
20684 // In OpenMP device mode we will not emit host only functions, or functions
20685 // we don't need due to their linkage.
20686 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20687 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20688 // DevTy may be changed later by
20689 // #pragma omp declare target to(*) device_type(*).
20690 // Therefore DevTy having no value does not imply host. The emission status
20691 // will be checked again at the end of compilation unit with Final = true.
20692 if (DevTy)
20693 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20695 // If we have an explicit value for the device type, or we are in a target
20696 // declare context, we need to emit all extern and used symbols.
20697 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20698 if (IsEmittedForExternalSymbol())
20700 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20701 // we'll omit it.
20702 if (Final)
20704 } else if (LangOpts.OpenMP > 45) {
20705 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20706 // function. In 5.0, no_host was introduced which might cause a function to
20707 // be ommitted.
20708 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20709 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20710 if (DevTy)
20711 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20713 }
20714
20715 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20717
20718 if (LangOpts.CUDA) {
20719 // When compiling for device, host functions are never emitted. Similarly,
20720 // when compiling for host, device and global functions are never emitted.
20721 // (Technically, we do emit a host-side stub for global functions, but this
20722 // doesn't count for our purposes here.)
20724 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20726 if (!LangOpts.CUDAIsDevice &&
20729
20730 if (IsEmittedForExternalSymbol())
20732 }
20733
20734 // Otherwise, the function is known-emitted if it's in our set of
20735 // known-emitted functions.
20737}
20738
20740 // Host-side references to a __global__ function refer to the stub, so the
20741 // function itself is never emitted and therefore should not be marked.
20742 // If we have host fn calls kernel fn calls host+device, the HD function
20743 // does not get instantiated on the host. We model this by omitting at the
20744 // call to the kernel from the callgraph. This ensures that, when compiling
20745 // for host, only HD functions actually called from the host get marked as
20746 // known-emitted.
20747 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20749}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
#define SM(sm)
Definition: Cuda.cpp:82
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
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:2226
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines helper utilities for supporting the HLSL runtime environment.
unsigned Iter
Definition: HTMLLogger.cpp:154
static const Decl * getCanonicalDecl(const Decl *D)
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition: MachO.h:27
llvm::MachO::Record Record
Definition: MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition: Mangle.cpp:58
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
Definition: Redeclaration.h:18
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:16041
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6975
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:147
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15547
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:11477
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:202
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:3445
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:3612
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:815
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:6662
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:1494
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:6700
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:2382
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:9301
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:3559
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2898
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
Definition: SemaDecl.cpp:8287
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:9650
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
Definition: SemaDecl.cpp:3343
void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
Definition: SemaDecl.cpp:7539
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
Definition: SemaDecl.cpp:8673
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
Definition: SemaDecl.cpp:11897
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:2787
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:4530
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
Definition: SemaDecl.cpp:12003
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15531
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
Definition: SemaDecl.cpp:11613
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:2090
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
Definition: SemaDecl.cpp:15144
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:562
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
Definition: SemaDecl.cpp:11486
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:7306
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:19824
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:20188
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
Definition: SemaDecl.cpp:5084
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:3026
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
Definition: SemaDecl.cpp:17092
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:3594
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7066
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:6039
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:4954
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:9337
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:9833
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
Definition: SemaDecl.cpp:16070
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:3501
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:8642
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2756
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
Definition: SemaDecl.cpp:9522
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
Definition: SemaDecl.cpp:3141
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:8312
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:17256
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:5369
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:8559
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
Definition: SemaDecl.cpp:1966
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
Definition: SemaDecl.cpp:9844
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:5449
OpenCLParamType
Definition: SemaDecl.cpp:9513
@ InvalidAddrSpacePtrKernelParam
Definition: SemaDecl.cpp:9517
@ ValidKernelParam
Definition: SemaDecl.cpp:9514
@ InvalidKernelParam
Definition: SemaDecl.cpp:9518
@ RecordKernelParam
Definition: SemaDecl.cpp:9519
@ PtrKernelParam
Definition: SemaDecl.cpp:9516
@ PtrPtrKernelParam
Definition: SemaDecl.cpp:9515
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:6148
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:19182
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:582
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:19116
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:7351
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:5533
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11406
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:9824
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
Definition: SemaDecl.cpp:3406
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:3538
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:17076
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
Definition: SemaDecl.cpp:2219
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:4420
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:9150
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
Definition: SemaDecl.cpp:6074
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:19209
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:830
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
Definition: SemaDecl.cpp:7378
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:8276
@ SDK_StructuredBinding
Definition: SemaDecl.cpp:8283
@ SDK_Field
Definition: SemaDecl.cpp:8280
@ SDK_Global
Definition: SemaDecl.cpp:8278
@ SDK_Local
Definition: SemaDecl.cpp:8277
@ SDK_Typedef
Definition: SemaDecl.cpp:8281
@ SDK_StaticMember
Definition: SemaDecl.cpp:8279
@ SDK_Using
Definition: SemaDecl.cpp:8282
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4900
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:3522
static ObjCIvarDecl::AccessControl TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)
TranslateIvarVisibility - Translate visibility from a token ID to an AST enum value.
Definition: SemaDecl.cpp:18947
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:9544
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:5547
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
Definition: SemaDecl.cpp:12626
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
Definition: SemaDecl.cpp:7431
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
Definition: SemaDecl.cpp:1823
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
Definition: SemaDecl.cpp:19275
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11235
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
Definition: SemaDecl.cpp:1812
static void filterNonConflictingPreviousTypedefDecls(Sema &S, 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:2505
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:3000
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:6584
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:14948
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
Definition: SemaDecl.cpp:7527
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:6021
static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Definition: SemaDecl.cpp:11502
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1877
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
Definition: SemaDecl.cpp:11185
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
Definition: SemaDecl.cpp:6936
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:5512
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:244
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:11644
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:8303
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:11452
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:7157
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11250
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:20152
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:19841
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:7337
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2775
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
Definition: SemaDecl.cpp:11066
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1839
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:17293
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for OpenMP constructs and clauses.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Definition: SourceCode.cpp:152
Defines the SourceManager interface.
C Language Family Type Representation.
const NestedNameSpecifier * Specifier
StateNode * Previous
std::string Label
__device__ int
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
Definition: SemaDecl.cpp:16028
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:16030
llvm::APInt getValue() const
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:72
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:57
virtual bool shouldSkipFunctionBody(Decl *D)
This callback is called for each function if the Parser was initialized with SkipFunctionBodies set t...
Definition: ASTConsumer.h:145
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:112
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
SourceManager & getSourceManager()
Definition: ASTContext.h:705
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2767
QualType getParenType(QualType NamedType) const
CanQualType LongTy
Definition: ASTContext.h:1100
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
ExternCContextDecl * getExternCContextDecl() const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2085
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:1871
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2574
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2590
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:1975
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:1897
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:1953
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:2773
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:1119
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:1590
IdentifierTable & Idents
Definition: ASTContext.h:644
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:646
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:775
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:496
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:2073
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:1987
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
Definition: ASTContext.h:1093
CanQualType IntTy
Definition: ASTContext.h:1100
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:2156
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType SignedCharTy
Definition: ASTContext.h:1100
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:697
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:2063
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2617
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:2340
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:1091
CanQualType UnsignedCharTy
Definition: ASTContext.h:1101
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
CanQualType UnknownAnyTy
Definition: ASTContext.h:1119
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1101
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:1568
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1420
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:2770
CanQualType ShortTy
Definition: ASTContext.h:1100
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1884
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:757
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:2179
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:1963
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:1100
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:2242
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2248
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2245
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2254
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2251
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:2371
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:3294
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1563
Expr * getSizeExpr() const
Definition: TypeLoc.h:1583
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1591
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1571
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3514
QualType getElementType() const
Definition: Type.h:3526
Attr - This represents one attribute.
Definition: Attr.h:42
attr::Kind getKind() const
Definition: Attr.h:88
bool isInherited() const
Definition: Attr.h:97
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition: Attr.h:102
SourceLocation getLocation() const
Definition: Attr.h:95
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:629
AttributeFactory & getFactory() const
Definition: ParsedAttr.h:725
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:5600
QualType getModifiedType() const
Definition: Type.h:5622
bool isCallingConv() const
Definition: Type.cpp:4064
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:5655
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5977
AutoTypeKeyword getKeyword() const
Definition: Type.h:6008
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4241
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:4295
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition: Expr.h:4283
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
Expr * getLHS() const
Definition: Expr.h:3889
Expr * getRHS() const
Definition: Expr.h:3891
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:3980
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4495
bool doesNotEscape() const
Definition: Decl.h:4646
This class is used for builtin types like 'int'.
Definition: Type.h:2977
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:209
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:262
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition: Builtins.h:222
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
bool isReturnsTwice(unsigned ID) const
Return true if we know this builtin can return twice.
Definition: Builtins.h:137
bool isConstWithoutErrnoAndExceptions(unsigned ID) const
Return true if this function has no side effects and doesn't read memory, except for possibly errno o...
Definition: Builtins.h:247
bool allowTypeMismatch(unsigned ID) const
Determines whether a declaration of this builtin should be recognized even if the type doesn't match ...
Definition: Builtins.h:202
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:111
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition: Builtins.h:167
bool isScanfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like scanf in its formatting rules and, if so, set the index to the...
Definition: Builtins.cpp:204
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:182
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:160
bool isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like printf in its formatting rules and, if so, set the index to th...
Definition: Builtins.cpp:199
bool isConstWithoutExceptions(unsigned ID) const
Definition: Builtins.h:251
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache",...
Definition: Builtins.h:174
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition: Builtins.h:116
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:127
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition: Builtins.h:122
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:194
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclCXX.h:195
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1540
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1683
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1603
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition: DeclCXX.cpp:2762
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:2723
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
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:2890
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal)
Definition: DeclCXX.cpp:2157
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
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:2857
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:2060
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:2455
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2509
bool isVirtual() const
Definition: DeclCXX.h:2115
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2576
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2488
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:2274
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2221
bool isConst() const
Definition: DeclCXX.h:2112
bool isStatic() const
Definition: DeclCXX.cpp:2186
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2466
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2156
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:1335
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1241
base_class_iterator bases_end()
Definition: DeclCXX.h:628
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1367
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1548
base_class_range bases()
Definition: DeclCXX.h:619
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1377
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1930
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:626
capture_const_range captures() const
Definition: DeclCXX.h:1101
bool hasDefinition() const
Definition: DeclCXX.h:571
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1897
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1063
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1901
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1289
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:209
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:235
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:214
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:83
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:212
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
bool isCallToStdMove() const
Definition: Expr.cpp:3510
Expr * getCallee()
Definition: Expr.h:2970
arg_range arguments()
Definition: Expr.h:3059
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CastKind getCastKind() const
Definition: Expr.h:3527
Expr * getSubExpr()
Definition: Expr.h:3533
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:4179
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:178
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:218
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3608
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2342
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isFileContext() const
Definition: DeclBase.h:2137
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1975
bool isObjCContainer() const
Definition: DeclBase.h:2105
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1264
bool isClosure() const
Definition: DeclBase.h:2099
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2082
bool isNamespace() const
Definition: DeclBase.h:2151
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1231
bool isTranslationUnit() const
Definition: DeclBase.h:2142
bool isRecord() const
Definition: DeclBase.h:2146
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1920
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1617
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1698
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1567
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1938
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1354
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1215
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1334
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2059
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1345
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:1260
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
ValueDecl * getDecl()
Definition: Expr.h:1328
Captures information about "declaration specifiers".
Definition: DeclSpec.h:246
bool isVirtualSpecified() const
Definition: DeclSpec.h:644
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:825
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:308
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:591
static const TST TST_typename
Definition: DeclSpec.h:305
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:641
void ClearStorageClassSpecs()
Definition: DeclSpec.h:511
bool isNoreturnSpecified() const
Definition: DeclSpec.h:657
TST getTypeSpecType() const
Definition: DeclSpec.h:533
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:506
SCS getStorageClassSpec() const
Definition: DeclSpec.h:497
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:856
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:571
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:570
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:705
static const TST TST_interface
Definition: DeclSpec.h:303
static const TST TST_typeofExpr
Definition: DeclSpec.h:307
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:612
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:704
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:658
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:501
static const TST TST_union
Definition: DeclSpec.h:301
SCS
storage-class-specifier
Definition: DeclSpec.h:250
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:650
static const TST TST_int
Definition: DeclSpec.h:284
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:826
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1494
ParsedType getRepAsType() const
Definition: DeclSpec.h:543
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:784
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:498
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:869
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:622
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:613
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:651
Expr * getRepAsExpr() const
Definition: DeclSpec.h:551
static const TST TST_enum
Definition: DeclSpec.h:300
static const TST TST_decltype
Definition: DeclSpec.h:310
static bool isDeclRep(TST T)
Definition: DeclSpec.h:465
bool isInlineSpecified() const
Definition: DeclSpec.h:633
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:614
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:309
static const TST TST_class
Definition: DeclSpec.h:304
void ClearConstexprSpec()
Definition: DeclSpec.h:837
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:320
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:507
Decl * getRepAsDecl() const
Definition: DeclSpec.h:547
static const TST TST_unspecified
Definition: DeclSpec.h:277
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:616
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:645
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:832
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:578
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:788
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:266
static const TST TST_error
Definition: DeclSpec.h:324
ExplicitSpecifier getExplicitSpecifier() const
Definition: DeclSpec.h:640
bool isTypeSpecOwned() const
Definition: DeclSpec.h:537
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:636
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:617
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:615
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:817
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:647
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:833
static const TST TST_typeofType
Definition: DeclSpec.h:306
static const TST TST_auto
Definition: DeclSpec.h:317
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:828
static const TST TST_struct
Definition: DeclSpec.h:302
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1051
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1066
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition: DeclBase.cpp:295
bool isInStdNamespace() const
Definition: DeclBase.cpp:403
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
T * getAttr() const
Definition: DeclBase.h:579
bool hasAttrs() const
Definition: DeclBase.h:524
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:526
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:754
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1141
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
Module * getOwningModuleForLinkage(bool IgnoreLinkage=false) const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1624
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:638
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:883
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1209
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
@ FOK_Declared
A friend of a previously-declared entity.
Definition: DeclBase.h:1208
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:262
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1074
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:555
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:833
bool isFromExplicitGlobalModule() const
Whether this declaration comes from explicit global module.
Definition: DeclBase.cpp:1105
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
void dropAttrs()
Definition: DeclBase.cpp:968
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition: DeclBase.h:210
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition: DeclBase.h:1170
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2739
bool isInvalidDecl() const
Definition: DeclBase.h:594
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1159
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:508
SourceLocation getLocation() const
Definition: DeclBase.h:445
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:820
void setImplicit(bool I=true)
Definition: DeclBase.h:600
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:614
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:530
DeclContext * getDeclContext()
Definition: DeclBase.h:454
attr_range attrs() const
Definition: DeclBase.h:541
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
bool hasOwningModule() const
Is this declaration owned by some module?
Definition: DeclBase.h:828
void dropAttr()
Definition: DeclBase.h:562
AttrVec & getAttrs()
Definition: DeclBase.h:530
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:336
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:583
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1225
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
Kind getKind() const
Definition: DeclBase.h:448
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 isEmpty() const
Evaluates true when this declaration name is empty.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:770
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:828
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:813
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2047
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2087
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1985
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:858
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:805
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1997
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:846
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2031
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1898
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2454
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2396
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2045
Expr * getAsmLabel() const
Definition: DeclSpec.h:2700
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition: DeclSpec.h:2739
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2681
void setRedeclaration(bool Val)
Definition: DeclSpec.h:2762
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2334
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2337
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:2082
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2631
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2711
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition: DeclSpec.h:2661
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2392
bool isRedeclaration() const
Definition: DeclSpec.h:2763
const ParsedAttributesView & getDeclarationAttributes() const
Definition: DeclSpec.h:2684
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition: DeclSpec.h:2066
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2081
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition: DeclSpec.cpp:436
bool isFunctionDefinition() const
Definition: DeclSpec.h:2735
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:2064
bool hasInitializer() const
Definition: DeclSpec.h:2744
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition: DeclSpec.h:2731
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2060
void takeAttributes(ParsedAttributes &attrs)
takeAttributes - Takes attributes from the given parsed-attributes set and add them to this declarato...
Definition: DeclSpec.h:2674
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2351
bool isInvalidType() const
Definition: DeclSpec.h:2712
bool isExplicitObjectMemberFunction()
Definition: DeclSpec.cpp:424
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2080
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition: DeclSpec.h:2324
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition: DeclSpec.h:2747
bool isStaticMember()
Returns true if this declares a static member.
Definition: DeclSpec.cpp:416
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2052
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2485
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2328
A decomposition declaration.
Definition: DeclCXX.h:4166
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3360
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1788
SourceRange getSourceRange() const
Definition: DeclSpec.h:1834
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1832
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5943
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:5964
bool isDeduced() const
Definition: Type.h:5965
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:931
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3298
llvm::APSInt getInitVal() const
Definition: Decl.h:3318
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5455
const Expr * getInitExpr() const
Definition: Decl.h:3316
Represents an enum.
Definition: Decl.h:3868
enumerator_range enumerators() const
Definition: Decl.h:4001
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4073
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:4037
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:4040
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4087
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4854
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4899
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4082
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4874
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:4023
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4028
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5571
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
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:3059
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:3055
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3039
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
isConstantInitializer - Returns true if this expression can be emitted to IR as a constant,...
Definition: Expr.cpp:3287
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
void applyChanges(FPOptionsOverride FPO)
Definition: LangOptions.h:1031
bool isFPConstrained() const
Definition: LangOptions.h:843
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
Definition: LangOptions.h:1025
Represents a member of a struct/union/class.
Definition: Decl.h:3058
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3149
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4562
bool isZeroLengthBitField(const ASTContext &Ctx) const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition: Decl.cpp:4599
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3271
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:4547
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5588
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
Represents a function declaration or definition.
Definition: Decl.h:1971
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2600
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2707
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2439
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4054
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3603
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4047
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4042
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3255
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2284
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2612
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2591
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3873
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3632
param_iterator param_end()
Definition: Decl.h:2697
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2831
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2606
QualType getReturnType() const
Definition: Decl.h:2755
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2684
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3576
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2352
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2340
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3488
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4162
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2411
void setWillHaveBody(bool V=true)
Definition: Decl.h:2597
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2406
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4172
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3617
param_iterator param_begin()
Definition: Decl.h:2696
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2733
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2296
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2503
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3314
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4106
@ TK_MemberSpecialization
Definition: Decl.h:1983
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2798
bool isStatic() const
Definition: Decl.h:2839
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4374
void setTrivial(bool IT)
Definition: Decl.h:2341
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3993
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2433
bool isDeletedAsWritten() const
Definition: Decl.h:2507
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition: Decl.h:2428
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2323
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3492
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2327
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2391
bool isImmediateEscalating() const
Definition: Decl.cpp:3268
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2319
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2590
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2252
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3306
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2826
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:3366
bool param_empty() const
Definition: Decl.h:2695
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:2161
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3180
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2190
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3572
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2348
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2384
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4397
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2843
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:3987
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2436
void setDefaulted(bool D=true)
Definition: Decl.h:2349
bool isConsteval() const
Definition: Decl.h:2445
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:2772
void setBody(Stmt *B)
Definition: Decl.cpp:3248
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3506
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3126
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition: Decl.h:2422
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4014
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2183
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3156
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2398
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:3203
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2809
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3558
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2596
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4652
unsigned getNumParams() const
Definition: Type.h:4885
QualType getParamType(unsigned i) const
Definition: Type.h:4887
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:4917
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5008
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4896
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4892
ArrayRef< QualType > param_types() const
Definition: Type.h:5040
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
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.
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:467
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:523
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Definition: DeclTemplate.h:537
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4363
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4478
CallingConv getCC() const
Definition: Type.h:4425
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4444
unsigned getRegParm() const
Definition: Type.h:4418
bool getNoCallerSavedRegs() const
Definition: Type.h:4414
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4437
bool getHasRegParm() const
Definition: Type.h:4416
bool getNoReturn() const
Definition: Type.h:4411
bool getProducesResult() const
Definition: Type.h:4412
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:4458
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:4472
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4252
ExtInfo getExtInfo() const
Definition: Type.h:4581
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3470
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4539
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4535
unsigned getRegParmType() const
Definition: Type.h:4572
CallingConv getCallConv() const
Definition: Type.h:4580
QualType getReturnType() const
Definition: Type.h:4569
bool getCmseNSCallAttr() const
Definition: Type.h:4579
@ SME_PStateSMEnabledMask
Definition: Type.h:4513
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:3655
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
Represents a C array with an unspecified size.
Definition: Type.h:3699
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3342
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5483
void setInherited(bool I)
Definition: Attr.h:154
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2506
Describes an C or C++ initializer list.
Definition: Expr.h:4847
child_range children()
Definition: Expr.h:5039
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:8591
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
Describes an entity that is being initialized.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:977
Represents the declaration of a label.
Definition: Decl.h:499
bool isResolvedMSAsmLabel() const
Definition: Decl.h:534
LabelStmt * getStmt() const
Definition: Decl.h:523
bool isMSAsmLabel() const
Definition: Decl.h:533
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:278
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:625
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:753
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:658
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:496
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:553
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
Definition: LangOptions.h:664
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:535
void push_back(const T &LocalValue)
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition: Lexer.cpp:1358
Represents a linkage specification.
Definition: DeclCXX.h:2934
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2920
void InstantiatedLocal(const Decl *D, Decl *Inst)
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:673
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:719
bool hasNext() const
Definition: Lookup.h:704
NamedDecl * next()
Definition: Lookup.h:708
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:556
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:662
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:747
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:566
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:668
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:573
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:632
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:3172
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
Expr * getBase() const
Definition: Expr.h:3249
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3456
Describes a module or submodule.
Definition: Module.h:105
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:111
Module * Parent
The parent of this module.
Definition: Module.h:154
bool isPrivateModule() const
Definition: Module.h:210
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition: Module.h:591
bool isModuleImplementation() const
Is this a module implementation.
Definition: Module.h:607
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition: Module.h:630
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:596
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:244
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:185
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:665
@ ClassId_NSObject
Definition: NSAPI.h:30
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Decl.cpp:1072
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1082
Visibility getVisibility() const
Determines the visibility of this entity.
Definition: Decl.h:419
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition: Decl.h:454
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:404
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
bool declarationReplaces(const NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition: Decl.cpp:1850
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:686
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1927
bool isExternallyVisible() const
Definition: Decl.h:408
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition: Decl.cpp:1119
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:372
Represent a C++ namespace.
Definition: Decl.h:547
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:605
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.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
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:2326
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2772
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition: DeclObjC.cpp:81
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2594
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1541
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1760
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
Definition: DeclObjC.cpp:1833
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
param_const_iterator param_end() const
Definition: DeclObjC.h:358
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
bool isOptional() const
Definition: DeclObjC.h:505
ParmVarDecl *const * param_iterator
Definition: DeclObjC.h:350
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:82
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:1168
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:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
MapType::iterator iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
Expr ** getExprs()
Definition: Expr.h:5664
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5653
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1203
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1216
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1199
Sugar for parentheses used when specifying types.
Definition: Type.h:3109
Represents a parameter to a function.
Definition: Decl.h:1761
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1821
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1825
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1794
QualType getOriginalType() const
Definition: Decl.cpp:2924
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:2915
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:126
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:826
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:906
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:946
AttributePool & getPool() const
Definition: ParsedAttr.h:952
PipeType - OpenCL20.
Definition: Type.h:7204
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1282
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1307
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3135
QualType getPointeeType() const
Definition: Type.h:3145
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:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7439
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7433
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:7502
@ DK_nontrivial_c_struct
Definition: Type.h:1523
PrimitiveDefaultInitializeKind
Definition: Type.h:1451
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2810
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:75
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:1007
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:2858
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7355
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7481
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:7496
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7395
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
QualType getCanonicalType() const
Definition: Type.h:7407
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7449
std::optional< NonConstantStorageReason > isNonConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Determine whether instances of this type can be placed in immutable storage.
Definition: Type.cpp:116
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition: Type.cpp:2842
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1427
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7428
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1530
bool isCanonical() const
Definition: Type.h:7412
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:1436
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2561
NonConstantStorageReason
Definition: Type.h:1024
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: Type.h:1481
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: Type.h:1486
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:7490
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7295
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7302
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4272
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:340
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:336
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:353
bool hasConst() const
Definition: Type.h:443
void removeConst()
Definition: Type.h:445
void addConst()
Definition: Type.h:446
ObjCLifetime getObjCLifetime() const
Definition: Type.h:531
bool empty() const
Definition: Type.h:633
Represents a struct/union/class.
Definition: Decl.h:4169
bool hasObjectMember() const
Definition: Decl.h:4229
field_range fields() const
Definition: Decl.h:4375
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5017
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5037
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5083
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4360
field_iterator field_begin() const
Definition: Decl.cpp:5071
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5545
RecordDecl * getDecl() const
Definition: Type.h:5555
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:6909
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:866
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
redecl_iterator redecls_end() const
Definition: Redeclarable.h:303
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
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:223
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3376
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3019
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:3067
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:378
void RemoveDecl(Decl *D)
Definition: Scope.h:350
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:381
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:578
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:267
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
void checkAllowedInitializer(VarDecl *VD)
Definition: SemaCUDA.cpp:658
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
Definition: SemaCUDA.cpp:1061
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
void maybeAddHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition: SemaCUDA.cpp:740
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
Definition: SemaCUDA.cpp:1005
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition: SemaCUDA.cpp:805
void CheckEntryPoint(FunctionDecl *FD)
Definition: SemaHLSL.cpp:130
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition: SemaHLSL.cpp:48
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, HLSLShaderAttr::ShaderType ShaderType)
Definition: SemaHLSL.cpp:63
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition: SemaHLSL.cpp:96
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.
bool IsAlignAttr() const
Definition: Sema.h:1262
Mode getAlignMode() const
Definition: Sema.h:1264
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2544
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:937
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:949
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition: Sema.h:2759
static NameClassification VarTemplate(TemplateName Name)
Definition: Sema.h:2769
static NameClassification Unknown()
Definition: Sema.h:2739
static NameClassification OverloadSet(ExprResult E)
Definition: Sema.h:2743
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition: Sema.h:2787
static NameClassification FunctionTemplate(TemplateName Name)
Definition: Sema.h:2775
static NameClassification NonType(NamedDecl *D)
Definition: Sema.h:2749
static NameClassification Concept(TemplateName Name)
Definition: Sema.h:2781
static NameClassification UndeclaredNonType()
Definition: Sema.h:2755
static NameClassification TypeTemplate(TemplateName Name)
Definition: Sema.h:2763
static NameClassification Error()
Definition: Sema.h:2737
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9508
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9538
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
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)
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:14401
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:11101
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6794
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6827
void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl)
Definition: SemaDecl.cpp:18344
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9787
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:698
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:2583
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
Definition: SemaType.cpp:9290
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:6745
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New)
Definition: SemaDecl.cpp:2544
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9871
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old)
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
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:1583
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:15291
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:6365
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:4638
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:7372
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7376
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:7395
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:7411
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:7408
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7384
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:7379
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6763
void ActOnPopScope(SourceLocation Loc, Scope *S)
Definition: SemaDecl.cpp:2235
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5402
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:16012
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:13044
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:40
NonTrivialCUnionContext
Definition: Sema.h:2998
@ NTCUC_CopyInit
Definition: Sema.h:3008
@ NTCUC_AutoVar
Definition: Sema.h:3006
@ NTCUC_DefaultInitializedObject
Definition: Sema.h:3004
@ NTCUC_FunctionReturn
Definition: Sema.h:3002
@ NTCUC_FunctionParam
Definition: Sema.h:3000
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:3663
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:6232
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
Definition: SemaLookup.cpp:992
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
Definition: SemaExpr.cpp:3110
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:18467
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
SemaOpenMP & OpenMP()
Definition: Sema.h:1013
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
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.
Definition: SemaExpr.cpp:3037
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:6199
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:825
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:18392
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition: Sema.h:3505
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:2618
PragmaClangSection PragmaClangRodataSection
Definition: Sema.h:1188
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:16553
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:4792
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:15168
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:12187
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:1109
SemaCUDA & CUDA()
Definition: Sema.h:998
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:17673
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.
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
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:1478
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:2245
Preprocessor & getPreprocessor() const
Definition: Sema.h:526
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:7025
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1419
PragmaStack< StringLiteral * > CodeSegStack
Definition: Sema.h:1413
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:1177
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckForFunctionMarkedFinal - Checks whether a virtual member function overrides a virtual member fun...
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:6360
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:17458
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:4906
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:12466
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:16769
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:2154
@ 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:18486
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:18586
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:14776
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:1454
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15654
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:1499
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3530
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:646
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1689
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:20570
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15278
ASTContext & Context
Definition: Sema.h:858
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14798
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5898
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:524
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20591
void * SkippedDefinitionContext
Definition: Sema.h:3246
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:918
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
Definition: SemaDecl.cpp:5411
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:5016
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:66
@ AllowFold
Definition: Sema.h:5792
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1521
PragmaStack< bool > StrictGuardStackCheckStack
Definition: Sema.h:1416
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:2626
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:2440
ASTContext & getASTContext() const
Definition: Sema.h:527
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:16084
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
Definition: SemaDecl.cpp:1754
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:18099
PragmaStack< StringLiteral * > ConstSegStack
Definition: Sema.h:1412
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:645
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:684
SmallVector< VarDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition: Sema.h:2636
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3344
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:4861
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9662
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20739
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:775
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:5568
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1504
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:17127
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:9137
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:9267
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:6476
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:693
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:4443
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2126
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:1267
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:167
ObjCInterfaceDecl * getObjCInterfaceDecl(const IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection=false)
Look for an Objective-C class in the translation unit.
Definition: SemaDecl.cpp:2325
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition: Sema.h:3392
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:17020
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition: Sema.h:522
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2144
void PopCompoundScope()
Definition: Sema.cpp:2283
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:20046
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition: Sema.h:10809
@ UPPC_EnumeratorValue
The enumerator value.
Definition: Sema.h:10812
@ UPPC_Initializer
An initializer.
Definition: Sema.h:10824
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:10818
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:10797
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:10836
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition: Sema.h:10821
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:10800
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition: Sema.h:10803
const LangOptions & getLangOpts() const
Definition: Sema.h:520
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:1452
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition: Sema.h:2643
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1411
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:6717
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:6755
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1626
Preprocessor & PP
Definition: Sema.h:857
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:8340
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:1916
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
const LangOptions & LangOpts
Definition: Sema.h:856
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2360
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition: Sema.h:11738
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15497
SemaHLSL & HLSL()
Definition: Sema.h:1003
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1883
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:12046
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:18691
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:1189
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *RetExpr, const AutoType *AT)
Deduce the return type for a function from a returned expression, per C++1y [dcl.spec....
Definition: SemaStmt.cpp:3864
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:204
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:20311
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.
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
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:1221
PragmaStack< AlignPackInfo > AlignPackStack
Definition: Sema.h:1401
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:15970
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:5188
PragmaStack< StringLiteral * > BSSSegStack
Definition: Sema.h:1411
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition: Sema.h:702
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:9761
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:8350
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:879
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:17098
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1398
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8492
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 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...
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void AddCFAuditedAttribute(Decl *D)
AddCFAuditedAttribute - Check whether we're currently within '#pragma clang arc_cf_code_audited' and,...
Definition: SemaAttr.cpp:863
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:12645
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:20072
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:892
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2278
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:15030
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Definition: SemaDecl.cpp:2399
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:2374
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:20625
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:18881
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:5185
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1231
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:18350
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:10732
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:9010
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:651
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:3432
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11732
StringLiteral * CurInitSeg
Last section used with #pragma init_seg.
Definition: Sema.h:1451
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20659
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:7739
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:9032
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:15600
void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init)
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:18335
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15527
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:996
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:15070
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5904
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
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:15364
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:8534
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1309
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4804
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
Definition: SemaDecl.cpp:15933
ObjCContainerDecl * getObjCDeclContext() const
Definition: SemaDecl.cpp:20655
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition: Sema.h:2640
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9398
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:15994
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:11121
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10484
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3161
@ NTK_Typedef
Definition: Sema.h:3166
@ NTK_NonUnion
Definition: Sema.h:3164
@ NTK_TypeAlias
Definition: Sema.h:3167
@ NTK_NonClass
Definition: Sema.h:3163
@ NTK_NonEnum
Definition: Sema.h:3165
@ NTK_NonStruct
Definition: Sema.h:3162
@ NTK_TemplateTemplateArgument
Definition: Sema.h:3170
@ NTK_TypeAliasTemplate
Definition: Sema.h:3169
@ NTK_Template
Definition: Sema.h:3168
void ActOnObjCContainerFinishDefinition()
Definition: SemaDecl.cpp:18451
SourceManager & getSourceManager() const
Definition: Sema.h:525
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams)
Handle a friend type declaration.
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_bits attribute.
Definition: Sema.h:2593
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:4361
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:20327
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:1363
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:11293
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:18321
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:1190
@ NTCUK_Destruct
Definition: Sema.h:3028
@ NTCUK_Init
Definition: Sema.h:3027
@ NTCUK_Copy
Definition: Sema.h:3029
PragmaClangSection PragmaClangDataSection
Definition: Sema.h:1187
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20505
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:16022
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:14020
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:1248
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:20598
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:5020
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:227
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:20582
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8374
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".
void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx)
Definition: SemaDecl.cpp:18462
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:7604
@ CTK_ErrorRecovery
Definition: Sema.h:7605
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14430
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14953
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2301
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:4567
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:4814
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:592
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
@ CCEK_Enumerator
Enumerator value with fixed underlying type.
Definition: Sema.h:8028
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
Definition: SemaDecl.cpp:19074
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3194
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:1946
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition: Sema.h:2614
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:290
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:19865
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12680
ASTConsumer & Consumer
Definition: Sema.h:859
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:3424
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:7934
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:7926
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:7930
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:5192
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2103
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:897
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1622
@ FirstDecl
Parsing the first decl in a TU.
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
Definition: SemaDecl.cpp:16691
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:6981
@ 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:3346
@ AMK_None
Don't merge availability attributes at all.
Definition: Sema.h:3348
@ AMK_Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition: Sema.h:3354
@ AMK_ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition: Sema.h:3357
@ AMK_OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition: Sema.h:3360
@ AMK_Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition: Sema.h:3351
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:15074
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:6122
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14739
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:17321
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:4886
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:78
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9276
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:15449
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:830
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1356
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:21155
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19320
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:1200
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:11154
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:2633
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:18177
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6438
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1328
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:861
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
Definition: SemaDecl.cpp:5854
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
Definition: SemaDecl.cpp:16079
DiagnosticsEngine & Diags
Definition: Sema.h:860
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:521
FPOptions CurFPFeatures
Definition: Sema.h:854
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:16075
NamespaceDecl * getStdNamespace() const
QualType AdjustParameterTypeForObjCAutoRefCount(QualType T, SourceLocation NameLoc, TypeSourceInfo *TSInfo)
Definition: SemaDecl.cpp:15333
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:6780
PragmaStack< StringLiteral * > DataSegStack
Definition: Sema.h:1410
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:650
@ TUK_Definition
Definition: Sema.h:3184
@ TUK_Declaration
Definition: Sema.h:3183
@ TUK_Friend
Definition: Sema.h:3185
@ TUK_Reference
Definition: Sema.h:3182
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7398
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:15107
@ TPC_FriendFunctionTemplate
Definition: Sema.h:9009
@ TPC_ClassTemplateMember
Definition: Sema.h:9007
@ TPC_FunctionTemplate
Definition: Sema.h:9006
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:9010
@ TPC_VarTemplate
Definition: Sema.h:9005
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:6867
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:16538
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2121
void PopDeclContext()
Definition: SemaDecl.cpp:1335
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:4826
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:1605
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:9270
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:14062
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:13226
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:1588
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:16963
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition: Sema.cpp:2343
OffsetOfKind
Definition: Sema.h:3188
@ OOK_Outside
Definition: Sema.h:3190
@ OOK_Macro
Definition: Sema.h:3195
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13502
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:18576
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
Definition: SemaDecl.cpp:4397
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:14347
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:280
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:2608
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1899
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:21454
PragmaClangSection PragmaClangBSSSection
Definition: Sema.h:1186
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6166
@ AbstractVariableType
Definition: Sema.h:4587
@ AbstractReturnType
Definition: Sema.h:4585
@ AbstractFieldType
Definition: Sema.h:4588
@ AbstractIvarType
Definition: Sema.h:4589
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)
Definition: SemaDecl.cpp:1728
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:6480
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:1257
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:8364
SwiftNameAttr * mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:20637
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:8705
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
Decl * ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitWidth, tok::ObjCKeywordKind visibility)
ActOnIvar - Each ivar field of an objective-c class is passed into this in order to create an IvarDec...
Definition: SemaDecl.cpp:18959
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
Definition: SemaDecl.cpp:1342
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:13192
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.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:3222
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:2589
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
Definition: SemaAttr.cpp:1184
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:15959
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:13478
IdentifierResolver IdResolver
Definition: Sema.h:2537
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:20298
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2292
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:700
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:15307
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:6446
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:2880
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6153
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:17039
void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx)
Invoked when we must temporarily exit the objective-c container scope for parsing/looking-up C constr...
Definition: SemaDecl.cpp:18456
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:218
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=std::nullopt)
Definition: SemaDecl.cpp:7566
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:6733
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:1284
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
child_range children()
Definition: Stmt.cpp:287
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition: Expr.h:1926
StringRef getString() const
Definition: Expr.h:1850
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3585
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3860
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3708
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3683
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3669
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3688
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3813
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4739
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4730
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4722
bool isUnion() const
Definition: Decl.h:3791
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4785
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4822
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3809
void setFreeStanding(bool isFreeStanding=true)
True if this tag is free standing, e.g. "struct foo;".
Definition: Decl.h:3726
TagKind getTagKind() const
Definition: Decl.h:3780
void setBraceRange(SourceRange R)
Definition: Decl.h:3665
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:213
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1497
unsigned getShortWidth() const
Return the size of 'signed short' and 'unsigned short' for this target, in bits.
Definition: TargetInfo.h:496
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1235
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:504
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
Definition: TargetInfo.h:1776
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:514
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1540
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1548
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1483
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1306
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1372
unsigned getCharWidth() const
Definition: TargetInfo.h:491
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:538
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:509
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
Definition: TargetInfo.h:1462
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1273
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1451
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:629
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6085
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4194
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:4458
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5603
void setStmt(Stmt *S)
Definition: Decl.cpp:5623
Represents a declaration of a type.
Definition: Decl.h:3391
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3416
const Type * getTypeForDecl() const
Definition: Decl.h:3415
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition: TypeLoc.h:338
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1225
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:206
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceLocation getTemplateKeywordLoc() const
Get the SourceLocation of the template keyword (if any).
Definition: TypeLoc.cpp:746
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7326
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:7337
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6348
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3121
The base class of the type hierarchy.
Definition: Type.h:1813
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:2454
bool isStructureType() const
Definition: Type.cpp:628
bool isDecltypeType() const
Definition: Type.h:7795
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isDependentSizedArrayType() const
Definition: Type.h:7694
bool isBlockPointerType() const
Definition: Type.h:7616
bool isVoidType() const
Definition: Type.h:7901
bool isBooleanType() const
Definition: Type.h:8029
bool isFunctionReferenceType() const
Definition: Type.h:7649
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2155
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8076
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:729
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2880
bool isIncompleteArrayType() const
Definition: Type.h:7682
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8195
bool isDependentAddressSpaceType() const
Definition: Type.h:7736
bool isConstantArrayType() const
Definition: Type.h:7678
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8056
bool isVoidPointerType() const
Definition: Type.cpp:654
bool isArrayType() const
Definition: Type.h:7674
bool isFunctionPointerType() const
Definition: Type.h:7642
bool isPointerType() const
Definition: Type.h:7608
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2460
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8186
bool isReferenceType() const
Definition: Type.h:7620
bool isEnumeralType() const
Definition: Type.h:7706
bool isScalarType() const
Definition: Type.h:8000
bool isVariableArrayType() const
Definition: Type.h:7686
bool isClkEventT() const
Definition: Type.h:7813
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2046
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8016
bool isImageType() const
Definition: Type.h:7825
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2754
bool isPipeType() const
Definition: Type.h:7832
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2657
bool isBitIntType() const
Definition: Type.h:7836
bool isOpenCLSpecificType() const
Definition: Type.h:7861
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2649
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2326
bool isHalfType() const
Definition: Type.h:7905
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:1999
const RecordType * getAsStructureType() const
Definition: Type.cpp:710
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2444
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2643
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8069
bool isAtomicType() const
Definition: Type.h:7753
bool isFunctionProtoType() const
Definition: Type.h:2490
bool isObjCIdType() const
Definition: Type.h:7773
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2667
bool isObjCObjectType() const
Definition: Type.h:7744
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4882
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8035
bool isEventT() const
Definition: Type.h:7809
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4825
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:8136
bool isFunctionType() const
Definition: Type.h:7604
bool isObjCObjectPointerType() const
Definition: Type.h:7740
bool isMemberFunctionPointerType() const
Definition: Type.h:7660
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2474
bool isFloatingType() const
Definition: Type.cpp:2237
bool isAnyPointerType() const
Definition: Type.h:7612
TypeClass getTypeClass() const
Definition: Type.h:2300
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:2004
bool isSamplerT() const
Definition: Type.h:7805
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8119
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:604
bool isNullPtrType() const
Definition: Type.h:7934
bool isRecordType() const
Definition: Type.h:7702
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4610
bool isUnionType() const
Definition: Type.cpp:660
bool isFunctionNoProtoType() const
Definition: Type.h:2489
bool isReserveIDT() const
Definition: Type.h:7821
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:1878
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2456
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1874
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3535
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5505
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3433
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3483
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:3499
QualType getUnderlyingType() const
Definition: Decl.h:3488
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3495
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5514
TypedefNameDecl * getDecl() const
Definition: Type.h:5213
QualType desugar() const
Definition: Type.cpp:3813
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:2183
Expr * getSubExpr() const
Definition: Expr.h:2228
Opcode getOpcode() const
Definition: Expr.h:2223
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:2283
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1024
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1233
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1082
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1106
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1076
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
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:3320
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3384
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3113
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5373
Represents a variable declaration or definition.
Definition: Decl.h:918
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2787
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2148
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1505
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1549
TLSKind getTLSKind() const
Definition: Decl.cpp:2165
bool hasInit() const
Definition: Decl.cpp:2395
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1432
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2257
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2187
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:2438
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2254
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1558
bool isCXXCondDecl() const
Definition: Decl.h:1595
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:929
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition: Decl.h:932
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:926
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2160
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1577
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1270
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1213
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2363
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2463
void setInlineSpecified()
Definition: Decl.h:1538
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1195
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1329
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1160
bool checkForConstantInitialization(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the initializer of this variable to determine whether it's a constant initializer.
Definition: Decl.cpp:2637
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1531
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1164
const Expr * getInit() const
Definition: Decl.h:1355
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1204
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1171
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2423
void setConstexpr(bool IC)
Definition: Decl.h:1552
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:941
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:944
void setInit(Expr *I)
Definition: Decl.cpp:2454
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2342
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1285
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1282
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1288
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2792
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2242
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1240
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1155
void setImplicitlyInline()
Definition: Decl.h:1543
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1456
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1572
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2683
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1249
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:2756
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition: Decl.h:1466
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2663
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:3743
Expr * getSizeExpr() const
Definition: Type.h:3762
Captures information about a #pragma weak directive.
Definition: Weak.h:25
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
bool isVariableCapture() const
Definition: ScopeInfo.h:650
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:739
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:729
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:749
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1093
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:731
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition: ScopeInfo.h:141
void addByrefBlockVar(VarDecl *VD)
Definition: ScopeInfo.h:498
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition: ScopeInfo.h:150
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition: ScopeInfo.h:167
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition: ScopeInfo.h:145
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition: ScopeInfo.h:158
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:878
ParmVarDecl * ExplicitObjectParameter
Definition: ScopeInfo.h:875
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition: ScopeInfo.h:948
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:865
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:873
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:890
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
Definition: Randstruct.cpp:175
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition: TokenKinds.h:41
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:36
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:1881
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:209
@ GNUMode
Definition: LangStandard.h:63
@ OpenCL
Definition: LangStandard.h:65
@ 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:28
CUDAFunctionTarget
Definition: Cuda.h:131
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:268
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:269
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:44
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:245
@ SC_Auto
Definition: Specifiers.h:253
@ SC_PrivateExtern
Definition: Specifiers.h:250
@ SC_Extern
Definition: Specifiers.h:248
@ SC_Register
Definition: Specifiers.h:254
@ SC_Static
Definition: Specifiers.h:249
@ SC_None
Definition: Specifiers.h:247
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:232
@ TSCS_thread_local
C++11 thread_local.
Definition: Specifiers.h:238
@ TSCS_unspecified
Definition: Specifiers.h:233
@ TSCS__Thread_local
C11 _Thread_local.
Definition: Specifiers.h:241
@ TSCS___thread
GNU __thread.
Definition: Specifiers.h:235
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:54
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:304
TagTypeKind
The kind of a tag type.
Definition: Type.h:6295
@ 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:109
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
ExprResult ExprError()
Definition: Ownership.h:264
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1542
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
@ TU_Complete
The translation unit is a complete translation unit.
Definition: LangOptions.h:1038
int hasAttribute(AttributeCommonInfo::Syntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:31
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:431
@ 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:132
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:1950
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:373
@ 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:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_C
Definition: Specifiers.h:276
@ CC_X86StdCall
Definition: Specifiers.h:277
@ 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.
ReservedIdentifierStatus
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:34
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
@ AS_public
Definition: Specifiers.h:121
@ AS_protected
Definition: Specifiers.h:122
@ AS_none
Definition: Specifiers.h:124
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
#define bool
Definition: stdbool.h:20
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:1424
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition: DeclSpec.h:1575
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1399
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1358
const IdentifierInfo * Ident
Definition: DeclSpec.h:1330
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1247
enum clang::DeclaratorChunk::@221 Kind
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1659
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:161
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1640
FunctionTypeInfo Fun
Definition: DeclSpec.h:1638
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1683
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:4731
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:4750
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:56
std::vector< std::string > Features
Definition: TargetInfo.h:57
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
SourceLocation PragmaLocation
Definition: Sema.h:1183
ValueType CurrentValue
Definition: Sema.h:1386
bool CheckSameAsPrevious
Definition: Sema.h:359
NamedDecl * Previous
Definition: Sema.h:360
NamedDecl * New
Definition: Sema.h:361
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.