clang 20.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
36#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41#include "clang/Sema/DeclSpec.h"
44#include "clang/Sema/Lookup.h"
46#include "clang/Sema/Scope.h"
48#include "clang/Sema/SemaARM.h"
49#include "clang/Sema/SemaCUDA.h"
50#include "clang/Sema/SemaHLSL.h"
52#include "clang/Sema/SemaObjC.h"
54#include "clang/Sema/SemaPPC.h"
56#include "clang/Sema/SemaSYCL.h"
58#include "clang/Sema/SemaWasm.h"
59#include "clang/Sema/Template.h"
60#include "llvm/ADT/STLForwardCompat.h"
61#include "llvm/ADT/SmallString.h"
62#include "llvm/ADT/StringExtras.h"
63#include "llvm/TargetParser/Triple.h"
64#include <algorithm>
65#include <cstring>
66#include <optional>
67#include <unordered_map>
68
69using namespace clang;
70using namespace sema;
71
73 if (OwnedType) {
74 Decl *Group[2] = { OwnedType, Ptr };
76 }
77
79}
80
81namespace {
82
83class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
84 public:
85 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
86 bool AllowTemplates = false,
87 bool AllowNonTemplates = true)
88 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
89 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
90 WantExpressionKeywords = false;
91 WantCXXNamedCasts = false;
92 WantRemainingKeywords = false;
93 }
94
95 bool ValidateCandidate(const TypoCorrection &candidate) override {
96 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
97 if (!AllowInvalidDecl && ND->isInvalidDecl())
98 return false;
99
100 if (getAsTypeTemplateDecl(ND))
101 return AllowTemplates;
102
103 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
104 if (!IsType)
105 return false;
106
107 if (AllowNonTemplates)
108 return true;
109
110 // An injected-class-name of a class template (specialization) is valid
111 // as a template or as a non-template.
112 if (AllowTemplates) {
113 auto *RD = dyn_cast<CXXRecordDecl>(ND);
114 if (!RD || !RD->isInjectedClassName())
115 return false;
116 RD = cast<CXXRecordDecl>(RD->getDeclContext());
117 return RD->getDescribedClassTemplate() ||
118 isa<ClassTemplateSpecializationDecl>(RD);
119 }
120
121 return false;
122 }
123
124 return !WantClassName && candidate.isKeyword();
125 }
126
127 std::unique_ptr<CorrectionCandidateCallback> clone() override {
128 return std::make_unique<TypeNameValidatorCCC>(*this);
129 }
130
131 private:
132 bool AllowInvalidDecl;
133 bool WantClassName;
134 bool AllowTemplates;
135 bool AllowNonTemplates;
136};
137
138} // end anonymous namespace
139
140namespace {
141enum class UnqualifiedTypeNameLookupResult {
142 NotFound,
143 FoundNonType,
144 FoundType
145};
146} // end anonymous namespace
147
148/// Tries to perform unqualified lookup of the type decls in bases for
149/// dependent class.
150/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
151/// type decl, \a FoundType if only type decls are found.
152static UnqualifiedTypeNameLookupResult
154 SourceLocation NameLoc,
155 const CXXRecordDecl *RD) {
156 if (!RD->hasDefinition())
157 return UnqualifiedTypeNameLookupResult::NotFound;
158 // Look for type decls in base classes.
159 UnqualifiedTypeNameLookupResult FoundTypeDecl =
160 UnqualifiedTypeNameLookupResult::NotFound;
161 for (const auto &Base : RD->bases()) {
162 const CXXRecordDecl *BaseRD = nullptr;
163 if (auto *BaseTT = Base.getType()->getAs<TagType>())
164 BaseRD = BaseTT->getAsCXXRecordDecl();
165 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
166 // Look for type decls in dependent base classes that have known primary
167 // templates.
168 if (!TST || !TST->isDependentType())
169 continue;
170 auto *TD = TST->getTemplateName().getAsTemplateDecl();
171 if (!TD)
172 continue;
173 if (auto *BasePrimaryTemplate =
174 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
175 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
176 BaseRD = BasePrimaryTemplate;
177 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
179 CTD->findPartialSpecialization(Base.getType()))
180 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
181 BaseRD = PS;
182 }
183 }
184 }
185 if (BaseRD) {
186 for (NamedDecl *ND : BaseRD->lookup(&II)) {
187 if (!isa<TypeDecl>(ND))
188 return UnqualifiedTypeNameLookupResult::FoundNonType;
189 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190 }
191 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
192 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
193 case UnqualifiedTypeNameLookupResult::FoundNonType:
194 return UnqualifiedTypeNameLookupResult::FoundNonType;
195 case UnqualifiedTypeNameLookupResult::FoundType:
196 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
197 break;
198 case UnqualifiedTypeNameLookupResult::NotFound:
199 break;
200 }
201 }
202 }
203 }
204
205 return FoundTypeDecl;
206}
207
209 const IdentifierInfo &II,
210 SourceLocation NameLoc) {
211 // Lookup in the parent class template context, if any.
212 const CXXRecordDecl *RD = nullptr;
213 UnqualifiedTypeNameLookupResult FoundTypeDecl =
214 UnqualifiedTypeNameLookupResult::NotFound;
215 for (DeclContext *DC = S.CurContext;
216 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
217 DC = DC->getParent()) {
218 // Look for type decls in dependent base classes that have known primary
219 // templates.
220 RD = dyn_cast<CXXRecordDecl>(DC);
221 if (RD && RD->getDescribedClassTemplate())
222 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
223 }
224 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
225 return nullptr;
226
227 // We found some types in dependent base classes. Recover as if the user
228 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
229 // lookup during template instantiation.
230 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
231
232 ASTContext &Context = S.Context;
233 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
234 cast<Type>(Context.getRecordType(RD)));
235 QualType T =
237
238 CXXScopeSpec SS;
239 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
240
241 TypeLocBuilder Builder;
242 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
243 DepTL.setNameLoc(NameLoc);
245 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
246 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
247}
248
249/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
251 SourceLocation NameLoc,
252 bool WantNontrivialTypeSourceInfo = true) {
253 switch (T->getTypeClass()) {
254 case Type::DeducedTemplateSpecialization:
255 case Type::Enum:
256 case Type::InjectedClassName:
257 case Type::Record:
258 case Type::Typedef:
259 case Type::UnresolvedUsing:
260 case Type::Using:
261 break;
262 // These can never be qualified so an ElaboratedType node
263 // would carry no additional meaning.
264 case Type::ObjCInterface:
265 case Type::ObjCTypeParam:
266 case Type::TemplateTypeParm:
267 return ParsedType::make(T);
268 default:
269 llvm_unreachable("Unexpected Type Class");
270 }
271
272 if (!SS || SS->isEmpty())
274 ElaboratedTypeKeyword::None, nullptr, T, nullptr));
275
277 if (!WantNontrivialTypeSourceInfo)
278 return ParsedType::make(ElTy);
279
280 TypeLocBuilder Builder;
281 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
282 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
285 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
286}
287
289 Scope *S, CXXScopeSpec *SS, bool isClassName,
290 bool HasTrailingDot, ParsedType ObjectTypePtr,
291 bool IsCtorOrDtorName,
292 bool WantNontrivialTypeSourceInfo,
293 bool IsClassTemplateDeductionContext,
294 ImplicitTypenameContext AllowImplicitTypename,
295 IdentifierInfo **CorrectedII) {
296 // FIXME: Consider allowing this outside C++1z mode as an extension.
297 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
298 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
299 !isClassName && !HasTrailingDot;
300
301 // Determine where we will perform name lookup.
302 DeclContext *LookupCtx = nullptr;
303 if (ObjectTypePtr) {
304 QualType ObjectType = ObjectTypePtr.get();
305 if (ObjectType->isRecordType())
306 LookupCtx = computeDeclContext(ObjectType);
307 } else if (SS && SS->isNotEmpty()) {
308 LookupCtx = computeDeclContext(*SS, false);
309
310 if (!LookupCtx) {
311 if (isDependentScopeSpecifier(*SS)) {
312 // C++ [temp.res]p3:
313 // A qualified-id that refers to a type and in which the
314 // nested-name-specifier depends on a template-parameter (14.6.2)
315 // shall be prefixed by the keyword typename to indicate that the
316 // qualified-id denotes a type, forming an
317 // elaborated-type-specifier (7.1.5.3).
318 //
319 // We therefore do not perform any name lookup if the result would
320 // refer to a member of an unknown specialization.
321 // In C++2a, in several contexts a 'typename' is not required. Also
322 // allow this as an extension.
323 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
324 !isClassName && !IsCtorOrDtorName)
325 return nullptr;
326 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
327 if (IsImplicitTypename) {
328 SourceLocation QualifiedLoc = SS->getRange().getBegin();
330 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
331 else
332 Diag(QualifiedLoc, diag::ext_implicit_typename)
333 << SS->getScopeRep() << II.getName()
334 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
335 }
336
337 // We know from the grammar that this name refers to a type,
338 // so build a dependent node to describe the type.
339 if (WantNontrivialTypeSourceInfo)
340 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
341 (ImplicitTypenameContext)IsImplicitTypename)
342 .get();
343
346 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
348 SourceLocation(), QualifierLoc, II, NameLoc);
349 return ParsedType::make(T);
350 }
351
352 return nullptr;
353 }
354
355 if (!LookupCtx->isDependentContext() &&
356 RequireCompleteDeclContext(*SS, LookupCtx))
357 return nullptr;
358 }
359
360 // In the case where we know that the identifier is a class name, we know that
361 // it is a type declaration (struct, class, union or enum) so we can use tag
362 // name lookup.
363 //
364 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
365 // the component name of the type-name or simple-template-id is type-only.
366 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
367 LookupResult Result(*this, &II, NameLoc, Kind);
368 if (LookupCtx) {
369 // Perform "qualified" name lookup into the declaration context we
370 // computed, which is either the type of the base of a member access
371 // expression or the declaration context associated with a prior
372 // nested-name-specifier.
373 LookupQualifiedName(Result, LookupCtx);
374
375 if (ObjectTypePtr && Result.empty()) {
376 // C++ [basic.lookup.classref]p3:
377 // If the unqualified-id is ~type-name, the type-name is looked up
378 // in the context of the entire postfix-expression. If the type T of
379 // the object expression is of a class type C, the type-name is also
380 // looked up in the scope of class C. At least one of the lookups shall
381 // find a name that refers to (possibly cv-qualified) T.
382 LookupName(Result, S);
383 }
384 } else {
385 // Perform unqualified name lookup.
386 LookupName(Result, S);
387
388 // For unqualified lookup in a class template in MSVC mode, look into
389 // dependent base classes where the primary class template is known.
390 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
391 if (ParsedType TypeInBase =
392 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
393 return TypeInBase;
394 }
395 }
396
397 NamedDecl *IIDecl = nullptr;
398 UsingShadowDecl *FoundUsingShadow = nullptr;
399 switch (Result.getResultKind()) {
401 if (CorrectedII) {
402 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
403 AllowDeducedTemplate);
404 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
405 S, SS, CCC, CTK_ErrorRecovery);
406 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
407 TemplateTy Template;
408 bool MemberOfUnknownSpecialization;
410 TemplateName.setIdentifier(NewII, NameLoc);
412 CXXScopeSpec NewSS, *NewSSPtr = SS;
413 if (SS && NNS) {
414 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
415 NewSSPtr = &NewSS;
416 }
417 if (Correction && (NNS || NewII != &II) &&
418 // Ignore a correction to a template type as the to-be-corrected
419 // identifier is not a template (typo correction for template names
420 // is handled elsewhere).
421 !(getLangOpts().CPlusPlus && NewSSPtr &&
422 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
423 Template, MemberOfUnknownSpecialization))) {
424 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
425 isClassName, HasTrailingDot, ObjectTypePtr,
426 IsCtorOrDtorName,
427 WantNontrivialTypeSourceInfo,
428 IsClassTemplateDeductionContext);
429 if (Ty) {
430 diagnoseTypo(Correction,
431 PDiag(diag::err_unknown_type_or_class_name_suggest)
432 << Result.getLookupName() << isClassName);
433 if (SS && NNS)
434 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
435 *CorrectedII = NewII;
436 return Ty;
437 }
438 }
439 }
440 Result.suppressDiagnostics();
441 return nullptr;
443 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
445 SS->getScopeRep(), &II);
446 TypeLocBuilder TLB;
450 TL.setNameLoc(NameLoc);
452 }
453 [[fallthrough]];
456 Result.suppressDiagnostics();
457 return nullptr;
458
460 // Recover from type-hiding ambiguities by hiding the type. We'll
461 // do the lookup again when looking for an object, and we can
462 // diagnose the error then. If we don't do this, then the error
463 // about hiding the type will be immediately followed by an error
464 // that only makes sense if the identifier was treated like a type.
465 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
466 Result.suppressDiagnostics();
467 return nullptr;
468 }
469
470 // Look to see if we have a type anywhere in the list of results.
471 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
472 Res != ResEnd; ++Res) {
473 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
474 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
475 RealRes) ||
476 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
477 if (!IIDecl ||
478 // Make the selection of the recovery decl deterministic.
479 RealRes->getLocation() < IIDecl->getLocation()) {
480 IIDecl = RealRes;
481 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
482 }
483 }
484 }
485
486 if (!IIDecl) {
487 // None of the entities we found is a type, so there is no way
488 // to even assume that the result is a type. In this case, don't
489 // complain about the ambiguity. The parser will either try to
490 // perform this lookup again (e.g., as an object name), which
491 // will produce the ambiguity, or will complain that it expected
492 // a type name.
493 Result.suppressDiagnostics();
494 return nullptr;
495 }
496
497 // We found a type within the ambiguous lookup; diagnose the
498 // ambiguity and then return that type. This might be the right
499 // answer, or it might not be, but it suppresses any attempt to
500 // perform the name lookup again.
501 break;
502
504 IIDecl = Result.getFoundDecl();
505 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
506 break;
507 }
508
509 assert(IIDecl && "Didn't find decl");
510
511 QualType T;
512 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
513 // C++ [class.qual]p2: A lookup that would find the injected-class-name
514 // instead names the constructors of the class, except when naming a class.
515 // This is ill-formed when we're not actually forming a ctor or dtor name.
516 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
517 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
518 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
519 FoundRD->isInjectedClassName() &&
520 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
521 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
522 << &II << /*Type*/1;
523
524 DiagnoseUseOfDecl(IIDecl, NameLoc);
525
527 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
528 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
529 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
530 if (!HasTrailingDot)
532 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
533 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
534 (void)DiagnoseUseOfDecl(UD, NameLoc);
535 // Recover with 'int'
537 } else if (AllowDeducedTemplate) {
538 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
539 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
541 SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false,
542 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
544 false);
545 // Don't wrap in a further UsingType.
546 FoundUsingShadow = nullptr;
547 }
548 }
549
550 if (T.isNull()) {
551 // If it's not plausibly a type, suppress diagnostics.
552 Result.suppressDiagnostics();
553 return nullptr;
554 }
555
556 if (FoundUsingShadow)
557 T = Context.getUsingType(FoundUsingShadow, T);
558
559 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
560}
561
562// Builds a fake NNS for the given decl context.
563static NestedNameSpecifier *
565 for (;; DC = DC->getLookupParent()) {
566 DC = DC->getPrimaryContext();
567 auto *ND = dyn_cast<NamespaceDecl>(DC);
568 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
569 return NestedNameSpecifier::Create(Context, nullptr, ND);
570 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
571 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
572 RD->getTypeForDecl());
573 else if (isa<TranslationUnitDecl>(DC))
575 }
576 llvm_unreachable("something isn't in TU scope?");
577}
578
579/// Find the parent class with dependent bases of the innermost enclosing method
580/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
581/// up allowing unqualified dependent type names at class-level, which MSVC
582/// correctly rejects.
583static const CXXRecordDecl *
585 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
586 DC = DC->getPrimaryContext();
587 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
588 if (MD->getParent()->hasAnyDependentBases())
589 return MD->getParent();
590 }
591 return nullptr;
592}
593
595 SourceLocation NameLoc,
596 bool IsTemplateTypeArg) {
597 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
598
599 NestedNameSpecifier *NNS = nullptr;
600 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
601 // If we weren't able to parse a default template argument, delay lookup
602 // until instantiation time by making a non-dependent DependentTypeName. We
603 // pretend we saw a NestedNameSpecifier referring to the current scope, and
604 // lookup is retried.
605 // FIXME: This hurts our diagnostic quality, since we get errors like "no
606 // type named 'Foo' in 'current_namespace'" when the user didn't write any
607 // name specifiers.
609 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
610 } else if (const CXXRecordDecl *RD =
612 // Build a DependentNameType that will perform lookup into RD at
613 // instantiation time.
614 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
615 RD->getTypeForDecl());
616
617 // Diagnose that this identifier was undeclared, and retry the lookup during
618 // template instantiation.
619 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
620 << RD;
621 } else {
622 // This is not a situation that we should recover from.
623 return ParsedType();
624 }
625
626 QualType T =
628
629 // Build type location information. We synthesized the qualifier, so we have
630 // to build a fake NestedNameSpecifierLoc.
631 NestedNameSpecifierLocBuilder NNSLocBuilder;
632 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
633 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
634
635 TypeLocBuilder Builder;
636 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
637 DepTL.setNameLoc(NameLoc);
639 DepTL.setQualifierLoc(QualifierLoc);
640 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
641}
642
644 // Do a tag name lookup in this scope.
645 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
646 LookupName(R, S, false);
649 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
650 switch (TD->getTagKind()) {
656 return DeclSpec::TST_union;
658 return DeclSpec::TST_class;
660 return DeclSpec::TST_enum;
661 }
662 }
663
665}
666
668 if (CurContext->isRecord()) {
670 return true;
671
672 const Type *Ty = SS->getScopeRep()->getAsType();
673
674 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
675 for (const auto &Base : RD->bases())
676 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
677 return true;
678 return S->isFunctionPrototypeScope();
679 }
680 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
681}
682
684 SourceLocation IILoc,
685 Scope *S,
686 CXXScopeSpec *SS,
687 ParsedType &SuggestedType,
688 bool IsTemplateName) {
689 // Don't report typename errors for editor placeholders.
690 if (II->isEditorPlaceholder())
691 return;
692 // We don't have anything to suggest (yet).
693 SuggestedType = nullptr;
694
695 // There may have been a typo in the name of the type. Look up typo
696 // results, in case we have something that we can suggest.
697 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
698 /*AllowTemplates=*/IsTemplateName,
699 /*AllowNonTemplates=*/!IsTemplateName);
700 if (TypoCorrection Corrected =
702 CCC, CTK_ErrorRecovery)) {
703 // FIXME: Support error recovery for the template-name case.
704 bool CanRecover = !IsTemplateName;
705 if (Corrected.isKeyword()) {
706 // We corrected to a keyword.
707 diagnoseTypo(Corrected,
708 PDiag(IsTemplateName ? diag::err_no_template_suggest
709 : diag::err_unknown_typename_suggest)
710 << II);
711 II = Corrected.getCorrectionAsIdentifierInfo();
712 } else {
713 // We found a similarly-named type or interface; suggest that.
714 if (!SS || !SS->isSet()) {
715 diagnoseTypo(Corrected,
716 PDiag(IsTemplateName ? diag::err_no_template_suggest
717 : diag::err_unknown_typename_suggest)
718 << II, CanRecover);
719 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
720 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
721 bool DroppedSpecifier =
722 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
723 diagnoseTypo(Corrected,
724 PDiag(IsTemplateName
725 ? diag::err_no_member_template_suggest
726 : diag::err_unknown_nested_typename_suggest)
727 << II << DC << DroppedSpecifier << SS->getRange(),
728 CanRecover);
729 } else {
730 llvm_unreachable("could not have corrected a typo here");
731 }
732
733 if (!CanRecover)
734 return;
735
736 CXXScopeSpec tmpSS;
737 if (Corrected.getCorrectionSpecifier())
738 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
739 SourceRange(IILoc));
740 // FIXME: Support class template argument deduction here.
741 SuggestedType =
742 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
743 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
744 /*IsCtorOrDtorName=*/false,
745 /*WantNontrivialTypeSourceInfo=*/true);
746 }
747 return;
748 }
749
750 if (getLangOpts().CPlusPlus && !IsTemplateName) {
751 // See if II is a class template that the user forgot to pass arguments to.
752 UnqualifiedId Name;
753 Name.setIdentifier(II, IILoc);
754 CXXScopeSpec EmptySS;
755 TemplateTy TemplateResult;
756 bool MemberOfUnknownSpecialization;
757 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
758 Name, nullptr, true, TemplateResult,
759 MemberOfUnknownSpecialization) == TNK_Type_template) {
760 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
761 return;
762 }
763 }
764
765 // FIXME: Should we move the logic that tries to recover from a missing tag
766 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
767
768 if (!SS || (!SS->isSet() && !SS->isInvalid()))
769 Diag(IILoc, IsTemplateName ? diag::err_no_template
770 : diag::err_unknown_typename)
771 << II;
772 else if (DeclContext *DC = computeDeclContext(*SS, false))
773 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
774 : diag::err_typename_nested_not_found)
775 << II << DC << SS->getRange();
776 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
777 SuggestedType =
778 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
779 } else if (isDependentScopeSpecifier(*SS)) {
780 unsigned DiagID = diag::err_typename_missing;
781 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
782 DiagID = diag::ext_typename_missing;
783
784 Diag(SS->getRange().getBegin(), DiagID)
785 << SS->getScopeRep() << II->getName()
786 << SourceRange(SS->getRange().getBegin(), IILoc)
787 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
788 SuggestedType = ActOnTypenameType(S, SourceLocation(),
789 *SS, *II, IILoc).get();
790 } else {
791 assert(SS && SS->isInvalid() &&
792 "Invalid scope specifier has already been diagnosed");
793 }
794}
795
796/// Determine whether the given result set contains either a type name
797/// or
798static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
799 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
800 NextToken.is(tok::less);
801
802 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
803 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
804 return true;
805
806 if (CheckTemplate && isa<TemplateDecl>(*I))
807 return true;
808 }
809
810 return false;
811}
812
814 Scope *S, CXXScopeSpec &SS,
815 IdentifierInfo *&Name,
816 SourceLocation NameLoc) {
817 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
818 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
819 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
820 StringRef FixItTagName;
821 switch (Tag->getTagKind()) {
823 FixItTagName = "class ";
824 break;
825
827 FixItTagName = "enum ";
828 break;
829
831 FixItTagName = "struct ";
832 break;
833
835 FixItTagName = "__interface ";
836 break;
837
839 FixItTagName = "union ";
840 break;
841 }
842
843 StringRef TagName = FixItTagName.drop_back();
844 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
845 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
846 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
847
848 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
849 I != IEnd; ++I)
850 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
851 << Name << TagName;
852
853 // Replace lookup results with just the tag decl.
855 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
856 return true;
857 }
858
859 return false;
860}
861
863 IdentifierInfo *&Name,
864 SourceLocation NameLoc,
865 const Token &NextToken,
867 DeclarationNameInfo NameInfo(Name, NameLoc);
868 ObjCMethodDecl *CurMethod = getCurMethodDecl();
869
870 assert(NextToken.isNot(tok::coloncolon) &&
871 "parse nested name specifiers before calling ClassifyName");
872 if (getLangOpts().CPlusPlus && SS.isSet() &&
873 isCurrentClassName(*Name, S, &SS)) {
874 // Per [class.qual]p2, this names the constructors of SS, not the
875 // injected-class-name. We don't have a classification for that.
876 // There's not much point caching this result, since the parser
877 // will reject it later.
879 }
880
881 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
882 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
883 /*AllowBuiltinCreation=*/!CurMethod);
884
885 if (SS.isInvalid())
887
888 // For unqualified lookup in a class template in MSVC mode, look into
889 // dependent base classes where the primary class template is known.
890 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
891 if (ParsedType TypeInBase =
892 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
893 return TypeInBase;
894 }
895
896 // Perform lookup for Objective-C instance variables (including automatically
897 // synthesized instance variables), if we're in an Objective-C method.
898 // FIXME: This lookup really, really needs to be folded in to the normal
899 // unqualified lookup mechanism.
900 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
901 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
902 if (Ivar.isInvalid())
904 if (Ivar.isUsable())
905 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
906
907 // We defer builtin creation until after ivar lookup inside ObjC methods.
908 if (Result.empty())
910 }
911
912 bool SecondTry = false;
913 bool IsFilteredTemplateName = false;
914
915Corrected:
916 switch (Result.getResultKind()) {
918 // If an unqualified-id is followed by a '(', then we have a function
919 // call.
920 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
921 // In C++, this is an ADL-only call.
922 // FIXME: Reference?
925
926 // C90 6.3.2.2:
927 // If the expression that precedes the parenthesized argument list in a
928 // function call consists solely of an identifier, and if no
929 // declaration is visible for this identifier, the identifier is
930 // implicitly declared exactly as if, in the innermost block containing
931 // the function call, the declaration
932 //
933 // extern int identifier ();
934 //
935 // appeared.
936 //
937 // We also allow this in C99 as an extension. However, this is not
938 // allowed in all language modes as functions without prototypes may not
939 // be supported.
940 if (getLangOpts().implicitFunctionsAllowed()) {
941 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
943 }
944 }
945
946 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
947 // In C++20 onwards, this could be an ADL-only call to a function
948 // template, and we're required to assume that this is a template name.
949 //
950 // FIXME: Find a way to still do typo correction in this case.
951 TemplateName Template =
954 }
955
956 // In C, we first see whether there is a tag type by the same name, in
957 // which case it's likely that the user just forgot to write "enum",
958 // "struct", or "union".
959 if (!getLangOpts().CPlusPlus && !SecondTry &&
960 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
961 break;
962 }
963
964 // Perform typo correction to determine if there is another name that is
965 // close to this name.
966 if (!SecondTry && CCC) {
967 SecondTry = true;
968 if (TypoCorrection Corrected =
969 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
970 &SS, *CCC, CTK_ErrorRecovery)) {
971 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
972 unsigned QualifiedDiag = diag::err_no_member_suggest;
973
974 NamedDecl *FirstDecl = Corrected.getFoundDecl();
975 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
976 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
977 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
978 UnqualifiedDiag = diag::err_no_template_suggest;
979 QualifiedDiag = diag::err_no_member_template_suggest;
980 } else if (UnderlyingFirstDecl &&
981 (isa<TypeDecl>(UnderlyingFirstDecl) ||
982 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
983 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
984 UnqualifiedDiag = diag::err_unknown_typename_suggest;
985 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
986 }
987
988 if (SS.isEmpty()) {
989 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
990 } else {// FIXME: is this even reachable? Test it.
991 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
992 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
993 Name->getName() == CorrectedStr;
994 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
995 << Name << computeDeclContext(SS, false)
996 << DroppedSpecifier << SS.getRange());
997 }
998
999 // Update the name, so that the caller has the new name.
1000 Name = Corrected.getCorrectionAsIdentifierInfo();
1001
1002 // Typo correction corrected to a keyword.
1003 if (Corrected.isKeyword())
1004 return Name;
1005
1006 // Also update the LookupResult...
1007 // FIXME: This should probably go away at some point
1008 Result.clear();
1009 Result.setLookupName(Corrected.getCorrection());
1010 if (FirstDecl)
1011 Result.addDecl(FirstDecl);
1012
1013 // If we found an Objective-C instance variable, let
1014 // LookupInObjCMethod build the appropriate expression to
1015 // reference the ivar.
1016 // FIXME: This is a gross hack.
1017 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1018 DeclResult R =
1019 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1020 if (R.isInvalid())
1022 if (R.isUsable())
1023 return NameClassification::NonType(Ivar);
1024 }
1025
1026 goto Corrected;
1027 }
1028 }
1029
1030 // We failed to correct; just fall through and let the parser deal with it.
1031 Result.suppressDiagnostics();
1033
1035 // We performed name lookup into the current instantiation, and there were
1036 // dependent bases, so we treat this result the same way as any other
1037 // dependent nested-name-specifier.
1038
1039 // C++ [temp.res]p2:
1040 // A name used in a template declaration or definition and that is
1041 // dependent on a template-parameter is assumed not to name a type
1042 // unless the applicable name lookup finds a type name or the name is
1043 // qualified by the keyword typename.
1044 //
1045 // FIXME: If the next token is '<', we might want to ask the parser to
1046 // perform some heroics to see if we actually have a
1047 // template-argument-list, which would indicate a missing 'template'
1048 // keyword here.
1050 }
1051
1055 break;
1056
1058 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1059 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1060 /*AllowDependent=*/false)) {
1061 // C++ [temp.local]p3:
1062 // A lookup that finds an injected-class-name (10.2) can result in an
1063 // ambiguity in certain cases (for example, if it is found in more than
1064 // one base class). If all of the injected-class-names that are found
1065 // refer to specializations of the same class template, and if the name
1066 // is followed by a template-argument-list, the reference refers to the
1067 // class template itself and not a specialization thereof, and is not
1068 // ambiguous.
1069 //
1070 // This filtering can make an ambiguous result into an unambiguous one,
1071 // so try again after filtering out template names.
1073 if (!Result.isAmbiguous()) {
1074 IsFilteredTemplateName = true;
1075 break;
1076 }
1077 }
1078
1079 // Diagnose the ambiguity and return an error.
1081 }
1082
1083 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1084 (IsFilteredTemplateName ||
1086 Result, /*AllowFunctionTemplates=*/true,
1087 /*AllowDependent=*/false,
1088 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1090 // C++ [temp.names]p3:
1091 // After name lookup (3.4) finds that a name is a template-name or that
1092 // an operator-function-id or a literal- operator-id refers to a set of
1093 // overloaded functions any member of which is a function template if
1094 // this is followed by a <, the < is always taken as the delimiter of a
1095 // template-argument-list and never as the less-than operator.
1096 // C++2a [temp.names]p2:
1097 // A name is also considered to refer to a template if it is an
1098 // unqualified-id followed by a < and name lookup finds either one
1099 // or more functions or finds nothing.
1100 if (!IsFilteredTemplateName)
1102
1103 bool IsFunctionTemplate;
1104 bool IsVarTemplate;
1105 TemplateName Template;
1106 if (Result.end() - Result.begin() > 1) {
1107 IsFunctionTemplate = true;
1108 Template = Context.getOverloadedTemplateName(Result.begin(),
1109 Result.end());
1110 } else if (!Result.empty()) {
1111 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1112 *Result.begin(), /*AllowFunctionTemplates=*/true,
1113 /*AllowDependent=*/false));
1114 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1115 IsVarTemplate = isa<VarTemplateDecl>(TD);
1116
1117 UsingShadowDecl *FoundUsingShadow =
1118 dyn_cast<UsingShadowDecl>(*Result.begin());
1119 assert(!FoundUsingShadow ||
1120 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1122 SS.getScopeRep(),
1123 /*TemplateKeyword=*/false,
1124 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1125 } else {
1126 // All results were non-template functions. This is a function template
1127 // name.
1128 IsFunctionTemplate = true;
1129 Template = Context.getAssumedTemplateName(NameInfo.getName());
1130 }
1131
1132 if (IsFunctionTemplate) {
1133 // Function templates always go through overload resolution, at which
1134 // point we'll perform the various checks (e.g., accessibility) we need
1135 // to based on which function we selected.
1136 Result.suppressDiagnostics();
1137
1138 return NameClassification::FunctionTemplate(Template);
1139 }
1140
1141 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1143 }
1144
1145 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1147 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1148 T = Context.getUsingType(USD, T);
1149 return buildNamedType(*this, &SS, T, NameLoc);
1150 };
1151
1152 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1153 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1154 DiagnoseUseOfDecl(Type, NameLoc);
1155 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1156 return BuildTypeFor(Type, *Result.begin());
1157 }
1158
1159 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1160 if (!Class) {
1161 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1162 if (ObjCCompatibleAliasDecl *Alias =
1163 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1164 Class = Alias->getClassInterface();
1165 }
1166
1167 if (Class) {
1168 DiagnoseUseOfDecl(Class, NameLoc);
1169
1170 if (NextToken.is(tok::period)) {
1171 // Interface. <something> is parsed as a property reference expression.
1172 // Just return "unknown" as a fall-through for now.
1173 Result.suppressDiagnostics();
1175 }
1176
1178 return ParsedType::make(T);
1179 }
1180
1181 if (isa<ConceptDecl>(FirstDecl)) {
1182 // We want to preserve the UsingShadowDecl for concepts.
1183 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1186 TemplateName(cast<TemplateDecl>(FirstDecl)));
1187 }
1188
1189 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1190 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1192 }
1193
1194 // We can have a type template here if we're classifying a template argument.
1195 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1196 !isa<VarTemplateDecl>(FirstDecl))
1198 TemplateName(cast<TemplateDecl>(FirstDecl)));
1199
1200 // Check for a tag type hidden by a non-type decl in a few cases where it
1201 // seems likely a type is wanted instead of the non-type that was found.
1202 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1203 if ((NextToken.is(tok::identifier) ||
1204 (NextIsOp &&
1205 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1206 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1207 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1208 DiagnoseUseOfDecl(Type, NameLoc);
1209 return BuildTypeFor(Type, *Result.begin());
1210 }
1211
1212 // If we already know which single declaration is referenced, just annotate
1213 // that declaration directly. Defer resolving even non-overloaded class
1214 // member accesses, as we need to defer certain access checks until we know
1215 // the context.
1216 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1217 if (Result.isSingleResult() && !ADL &&
1218 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1219 return NameClassification::NonType(Result.getRepresentativeDecl());
1220
1221 // Otherwise, this is an overload set that we will need to resolve later.
1222 Result.suppressDiagnostics();
1224 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1225 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1226 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1227}
1228
1231 SourceLocation NameLoc) {
1232 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1233 CXXScopeSpec SS;
1234 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1235 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1236}
1237
1240 IdentifierInfo *Name,
1241 SourceLocation NameLoc,
1242 bool IsAddressOfOperand) {
1243 DeclarationNameInfo NameInfo(Name, NameLoc);
1244 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1245 NameInfo, IsAddressOfOperand,
1246 /*TemplateArgs=*/nullptr);
1247}
1248
1251 SourceLocation NameLoc,
1252 const Token &NextToken) {
1253 if (getCurMethodDecl() && SS.isEmpty())
1254 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1255 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1256
1257 // Reconstruct the lookup result.
1258 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1259 Result.addDecl(Found);
1260 Result.resolveKind();
1261
1262 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1263 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1264}
1265
1267 // For an implicit class member access, transform the result into a member
1268 // access expression if necessary.
1269 auto *ULE = cast<UnresolvedLookupExpr>(E);
1270 if ((*ULE->decls_begin())->isCXXClassMember()) {
1271 CXXScopeSpec SS;
1272 SS.Adopt(ULE->getQualifierLoc());
1273
1274 // Reconstruct the lookup result.
1275 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1277 Result.setNamingClass(ULE->getNamingClass());
1278 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1279 Result.addDecl(*I, I.getAccess());
1280 Result.resolveKind();
1282 nullptr, S);
1283 }
1284
1285 // Otherwise, this is already in the form we needed, and no further checks
1286 // are necessary.
1287 return ULE;
1288}
1289
1292 auto *TD = Name.getAsTemplateDecl();
1293 if (!TD)
1295 if (isa<ClassTemplateDecl>(TD))
1297 if (isa<FunctionTemplateDecl>(TD))
1299 if (isa<VarTemplateDecl>(TD))
1301 if (isa<TypeAliasTemplateDecl>(TD))
1303 if (isa<TemplateTemplateParmDecl>(TD))
1305 if (isa<ConceptDecl>(TD))
1308}
1309
1311 assert(DC->getLexicalParent() == CurContext &&
1312 "The next DeclContext should be lexically contained in the current one.");
1313 CurContext = DC;
1314 S->setEntity(DC);
1315}
1316
1318 assert(CurContext && "DeclContext imbalance!");
1319
1321 assert(CurContext && "Popped translation unit!");
1322}
1323
1325 Decl *D) {
1326 // Unlike PushDeclContext, the context to which we return is not necessarily
1327 // the containing DC of TD, because the new context will be some pre-existing
1328 // TagDecl definition instead of a fresh one.
1329 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1330 CurContext = cast<TagDecl>(D)->getDefinition();
1331 assert(CurContext && "skipping definition of undefined tag");
1332 // Start lookups from the parent of the current context; we don't want to look
1333 // into the pre-existing complete definition.
1334 S->setEntity(CurContext->getLookupParent());
1335 return Result;
1336}
1337
1339 CurContext = static_cast<decltype(CurContext)>(Context);
1340}
1341
1343 // C++0x [basic.lookup.unqual]p13:
1344 // A name used in the definition of a static data member of class
1345 // X (after the qualified-id of the static member) is looked up as
1346 // if the name was used in a member function of X.
1347 // C++0x [basic.lookup.unqual]p14:
1348 // If a variable member of a namespace is defined outside of the
1349 // scope of its namespace then any name used in the definition of
1350 // the variable member (after the declarator-id) is looked up as
1351 // if the definition of the variable member occurred in its
1352 // namespace.
1353 // Both of these imply that we should push a scope whose context
1354 // is the semantic context of the declaration. We can't use
1355 // PushDeclContext here because that context is not necessarily
1356 // lexically contained in the current context. Fortunately,
1357 // the containing scope should have the appropriate information.
1358
1359 assert(!S->getEntity() && "scope already has entity");
1360
1361#ifndef NDEBUG
1362 Scope *Ancestor = S->getParent();
1363 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1364 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1365#endif
1366
1367 CurContext = DC;
1368 S->setEntity(DC);
1369
1370 if (S->getParent()->isTemplateParamScope()) {
1371 // Also set the corresponding entities for all immediately-enclosing
1372 // template parameter scopes.
1373 EnterTemplatedContext(S->getParent(), DC);
1374 }
1375}
1376
1378 assert(S->getEntity() == CurContext && "Context imbalance!");
1379
1380 // Switch back to the lexical context. The safety of this is
1381 // enforced by an assert in EnterDeclaratorContext.
1382 Scope *Ancestor = S->getParent();
1383 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1384 CurContext = Ancestor->getEntity();
1385
1386 // We don't need to do anything with the scope, which is going to
1387 // disappear.
1388}
1389
1391 assert(S->isTemplateParamScope() &&
1392 "expected to be initializing a template parameter scope");
1393
1394 // C++20 [temp.local]p7:
1395 // In the definition of a member of a class template that appears outside
1396 // of the class template definition, the name of a member of the class
1397 // template hides the name of a template-parameter of any enclosing class
1398 // templates (but not a template-parameter of the member if the member is a
1399 // class or function template).
1400 // C++20 [temp.local]p9:
1401 // In the definition of a class template or in the definition of a member
1402 // of such a template that appears outside of the template definition, for
1403 // each non-dependent base class (13.8.2.1), if the name of the base class
1404 // or the name of a member of the base class is the same as the name of a
1405 // template-parameter, the base class name or member name hides the
1406 // template-parameter name (6.4.10).
1407 //
1408 // This means that a template parameter scope should be searched immediately
1409 // after searching the DeclContext for which it is a template parameter
1410 // scope. For example, for
1411 // template<typename T> template<typename U> template<typename V>
1412 // void N::A<T>::B<U>::f(...)
1413 // we search V then B<U> (and base classes) then U then A<T> (and base
1414 // classes) then T then N then ::.
1415 unsigned ScopeDepth = getTemplateDepth(S);
1416 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1417 DeclContext *SearchDCAfterScope = DC;
1418 for (; DC; DC = DC->getLookupParent()) {
1419 if (const TemplateParameterList *TPL =
1420 cast<Decl>(DC)->getDescribedTemplateParams()) {
1421 unsigned DCDepth = TPL->getDepth() + 1;
1422 if (DCDepth > ScopeDepth)
1423 continue;
1424 if (ScopeDepth == DCDepth)
1425 SearchDCAfterScope = DC = DC->getLookupParent();
1426 break;
1427 }
1428 }
1429 S->setLookupEntity(SearchDCAfterScope);
1430 }
1431}
1432
1434 // We assume that the caller has already called
1435 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1436 FunctionDecl *FD = D->getAsFunction();
1437 if (!FD)
1438 return;
1439
1440 // Same implementation as PushDeclContext, but enters the context
1441 // from the lexical parent, rather than the top-level class.
1442 assert(CurContext == FD->getLexicalParent() &&
1443 "The next DeclContext should be lexically contained in the current one.");
1444 CurContext = FD;
1445 S->setEntity(CurContext);
1446
1447 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1448 ParmVarDecl *Param = FD->getParamDecl(P);
1449 // If the parameter has an identifier, then add it to the scope
1450 if (Param->getIdentifier()) {
1451 S->AddDecl(Param);
1452 IdResolver.AddDecl(Param);
1453 }
1454 }
1455}
1456
1458 // Same implementation as PopDeclContext, but returns to the lexical parent,
1459 // rather than the top-level class.
1460 assert(CurContext && "DeclContext imbalance!");
1462 assert(CurContext && "Popped translation unit!");
1463}
1464
1465/// Determine whether overloading is allowed for a new function
1466/// declaration considering prior declarations of the same name.
1467///
1468/// This routine determines whether overloading is possible, not
1469/// whether a new declaration actually overloads a previous one.
1470/// It will return true in C++ (where overloads are always permitted)
1471/// or, as a C extension, when either the new declaration or a
1472/// previous one is declared with the 'overloadable' attribute.
1474 ASTContext &Context,
1475 const FunctionDecl *New) {
1476 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1477 return true;
1478
1479 // Multiversion function declarations are not overloads in the
1480 // usual sense of that term, but lookup will report that an
1481 // overload set was found if more than one multiversion function
1482 // declaration is present for the same name. It is therefore
1483 // inadequate to assume that some prior declaration(s) had
1484 // the overloadable attribute; checking is required. Since one
1485 // declaration is permitted to omit the attribute, it is necessary
1486 // to check at least two; hence the 'any_of' check below. Note that
1487 // the overloadable attribute is implicitly added to declarations
1488 // that were required to have it but did not.
1489 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1490 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1491 return ND->hasAttr<OverloadableAttr>();
1492 });
1493 } else if (Previous.getResultKind() == LookupResult::Found)
1494 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1495
1496 return false;
1497}
1498
1499void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1500 // Move up the scope chain until we find the nearest enclosing
1501 // non-transparent context. The declaration will be introduced into this
1502 // scope.
1503 while (S->getEntity() && S->getEntity()->isTransparentContext())
1504 S = S->getParent();
1505
1506 // Add scoped declarations into their context, so that they can be
1507 // found later. Declarations without a context won't be inserted
1508 // into any context.
1509 if (AddToContext)
1511
1512 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1513 // are function-local declarations.
1514 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1515 return;
1516
1517 // Template instantiations should also not be pushed into scope.
1518 if (isa<FunctionDecl>(D) &&
1519 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1520 return;
1521
1522 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1523 S->AddDecl(D);
1524 return;
1525 }
1526 // If this replaces anything in the current scope,
1527 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1528 IEnd = IdResolver.end();
1529 for (; I != IEnd; ++I) {
1530 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1531 S->RemoveDecl(*I);
1533
1534 // Should only need to replace one decl.
1535 break;
1536 }
1537 }
1538
1539 S->AddDecl(D);
1540
1541 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1542 // Implicitly-generated labels may end up getting generated in an order that
1543 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1544 // the label at the appropriate place in the identifier chain.
1545 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1546 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1547 if (IDC == CurContext) {
1548 if (!S->isDeclScope(*I))
1549 continue;
1550 } else if (IDC->Encloses(CurContext))
1551 break;
1552 }
1553
1555 } else {
1557 }
1559}
1560
1562 bool AllowInlineNamespace) const {
1563 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1564}
1565
1567 DeclContext *TargetDC = DC->getPrimaryContext();
1568 do {
1569 if (DeclContext *ScopeDC = S->getEntity())
1570 if (ScopeDC->getPrimaryContext() == TargetDC)
1571 return S;
1572 } while ((S = S->getParent()));
1573
1574 return nullptr;
1575}
1576
1578 DeclContext*,
1579 ASTContext&);
1580
1582 bool ConsiderLinkage,
1583 bool AllowInlineNamespace) {
1585 while (F.hasNext()) {
1586 NamedDecl *D = F.next();
1587
1588 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1589 continue;
1590
1591 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1592 continue;
1593
1594 F.erase();
1595 }
1596
1597 F.done();
1598}
1599
1601 // [module.interface]p7:
1602 // A declaration is attached to a module as follows:
1603 // - If the declaration is a non-dependent friend declaration that nominates a
1604 // function with a declarator-id that is a qualified-id or template-id or that
1605 // nominates a class other than with an elaborated-type-specifier with neither
1606 // a nested-name-specifier nor a simple-template-id, it is attached to the
1607 // module to which the friend is attached ([basic.link]).
1608 if (New->getFriendObjectKind() &&
1612 return false;
1613 }
1614
1615 Module *NewM = New->getOwningModule();
1616 Module *OldM = Old->getOwningModule();
1617
1618 if (NewM && NewM->isPrivateModule())
1619 NewM = NewM->Parent;
1620 if (OldM && OldM->isPrivateModule())
1621 OldM = OldM->Parent;
1622
1623 if (NewM == OldM)
1624 return false;
1625
1626 if (NewM && OldM) {
1627 // A module implementation unit has visibility of the decls in its
1628 // implicitly imported interface.
1629 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1630 return false;
1631
1632 // Partitions are part of the module, but a partition could import another
1633 // module, so verify that the PMIs agree.
1634 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1635 getASTContext().isInSameModule(NewM, OldM))
1636 return false;
1637 }
1638
1639 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1640 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1641 if (NewIsModuleInterface || OldIsModuleInterface) {
1642 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1643 // if a declaration of D [...] appears in the purview of a module, all
1644 // other such declarations shall appear in the purview of the same module
1645 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1646 << New
1647 << NewIsModuleInterface
1648 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1649 << OldIsModuleInterface
1650 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1651 Diag(Old->getLocation(), diag::note_previous_declaration);
1652 New->setInvalidDecl();
1653 return true;
1654 }
1655
1656 return false;
1657}
1658
1660 // [module.interface]p1:
1661 // An export-declaration shall inhabit a namespace scope.
1662 //
1663 // So it is meaningless to talk about redeclaration which is not at namespace
1664 // scope.
1665 if (!New->getLexicalDeclContext()
1667 ->isFileContext() ||
1668 !Old->getLexicalDeclContext()
1670 ->isFileContext())
1671 return false;
1672
1673 bool IsNewExported = New->isInExportDeclContext();
1674 bool IsOldExported = Old->isInExportDeclContext();
1675
1676 // It should be irrevelant if both of them are not exported.
1677 if (!IsNewExported && !IsOldExported)
1678 return false;
1679
1680 if (IsOldExported)
1681 return false;
1682
1683 // If the Old declaration are not attached to named modules
1684 // and the New declaration are attached to global module.
1685 // It should be fine to allow the export since it doesn't change
1686 // the linkage of declarations. See
1687 // https://github.com/llvm/llvm-project/issues/98583 for details.
1688 if (!Old->isInNamedModule() && New->getOwningModule() &&
1690 return false;
1691
1692 assert(IsNewExported);
1693
1694 auto Lk = Old->getFormalLinkage();
1695 int S = 0;
1696 if (Lk == Linkage::Internal)
1697 S = 1;
1698 else if (Lk == Linkage::Module)
1699 S = 2;
1700 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1701 Diag(Old->getLocation(), diag::note_previous_declaration);
1702 return true;
1703}
1704
1707 return true;
1708
1709 if (CheckRedeclarationExported(New, Old))
1710 return true;
1711
1712 return false;
1713}
1714
1716 const NamedDecl *Old) const {
1717 assert(getASTContext().isSameEntity(New, Old) &&
1718 "New and Old are not the same definition, we should diagnostic it "
1719 "immediately instead of checking it.");
1720 assert(const_cast<Sema *>(this)->isReachable(New) &&
1721 const_cast<Sema *>(this)->isReachable(Old) &&
1722 "We shouldn't see unreachable definitions here.");
1723
1724 Module *NewM = New->getOwningModule();
1725 Module *OldM = Old->getOwningModule();
1726
1727 // We only checks for named modules here. The header like modules is skipped.
1728 // FIXME: This is not right if we import the header like modules in the module
1729 // purview.
1730 //
1731 // For example, assuming "header.h" provides definition for `D`.
1732 // ```C++
1733 // //--- M.cppm
1734 // export module M;
1735 // import "header.h"; // or #include "header.h" but import it by clang modules
1736 // actually.
1737 //
1738 // //--- Use.cpp
1739 // import M;
1740 // import "header.h"; // or uses clang modules.
1741 // ```
1742 //
1743 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1744 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1745 // reject it. But the current implementation couldn't detect the case since we
1746 // don't record the information about the importee modules.
1747 //
1748 // But this might not be painful in practice. Since the design of C++20 Named
1749 // Modules suggests us to use headers in global module fragment instead of
1750 // module purview.
1751 if (NewM && NewM->isHeaderLikeModule())
1752 NewM = nullptr;
1753 if (OldM && OldM->isHeaderLikeModule())
1754 OldM = nullptr;
1755
1756 if (!NewM && !OldM)
1757 return true;
1758
1759 // [basic.def.odr]p14.3
1760 // Each such definition shall not be attached to a named module
1761 // ([module.unit]).
1762 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1763 return true;
1764
1765 // Then New and Old lives in the same TU if their share one same module unit.
1766 if (NewM)
1767 NewM = NewM->getTopLevelModule();
1768 if (OldM)
1769 OldM = OldM->getTopLevelModule();
1770 return OldM == NewM;
1771}
1772
1774 if (D->getDeclContext()->isFileContext())
1775 return false;
1776
1777 return isa<UsingShadowDecl>(D) ||
1778 isa<UnresolvedUsingTypenameDecl>(D) ||
1779 isa<UnresolvedUsingValueDecl>(D);
1780}
1781
1782/// Removes using shadow declarations not at class scope from the lookup
1783/// results.
1786 while (F.hasNext())
1788 F.erase();
1789
1790 F.done();
1791}
1792
1793/// Check for this common pattern:
1794/// @code
1795/// class S {
1796/// S(const S&); // DO NOT IMPLEMENT
1797/// void operator=(const S&); // DO NOT IMPLEMENT
1798/// };
1799/// @endcode
1801 // FIXME: Should check for private access too but access is set after we get
1802 // the decl here.
1803 if (D->doesThisDeclarationHaveABody())
1804 return false;
1805
1806 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1807 return CD->isCopyConstructor();
1808 return D->isCopyAssignmentOperator();
1809}
1810
1811bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1812 const DeclContext *DC = D->getDeclContext();
1813 while (!DC->isTranslationUnit()) {
1814 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1815 if (!RD->hasNameForLinkage())
1816 return true;
1817 }
1818 DC = DC->getParent();
1819 }
1820
1821 return !D->isExternallyVisible();
1822}
1823
1824// FIXME: This needs to be refactored; some other isInMainFile users want
1825// these semantics.
1826static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1828 return false;
1829 return S.SourceMgr.isInMainFile(Loc);
1830}
1831
1833 assert(D);
1834
1835 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1836 return false;
1837
1838 // Ignore all entities declared within templates, and out-of-line definitions
1839 // of members of class templates.
1842 return false;
1843
1844 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1845 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1846 return false;
1847 // A non-out-of-line declaration of a member specialization was implicitly
1848 // instantiated; it's the out-of-line declaration that we're interested in.
1849 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1850 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1851 return false;
1852
1853 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1854 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1855 return false;
1856 } else {
1857 // 'static inline' functions are defined in headers; don't warn.
1858 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1859 return false;
1860 }
1861
1862 if (FD->doesThisDeclarationHaveABody() &&
1864 return false;
1865 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1866 // Constants and utility variables are defined in headers with internal
1867 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1868 // like "inline".)
1869 if (!isMainFileLoc(*this, VD->getLocation()))
1870 return false;
1871
1872 if (Context.DeclMustBeEmitted(VD))
1873 return false;
1874
1875 if (VD->isStaticDataMember() &&
1876 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1877 return false;
1878 if (VD->isStaticDataMember() &&
1879 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1880 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1881 return false;
1882
1883 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1884 return false;
1885 } else {
1886 return false;
1887 }
1888
1889 // Only warn for unused decls internal to the translation unit.
1890 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1891 // for inline functions defined in the main source file, for instance.
1892 return mightHaveNonExternalLinkage(D);
1893}
1894
1896 if (!D)
1897 return;
1898
1899 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1900 const FunctionDecl *First = FD->getFirstDecl();
1902 return; // First should already be in the vector.
1903 }
1904
1905 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1906 const VarDecl *First = VD->getFirstDecl();
1908 return; // First should already be in the vector.
1909 }
1910
1913}
1914
1915static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1916 const NamedDecl *D) {
1917 if (D->isInvalidDecl())
1918 return false;
1919
1920 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1921 // For a decomposition declaration, warn if none of the bindings are
1922 // referenced, instead of if the variable itself is referenced (which
1923 // it is, by the bindings' expressions).
1924 bool IsAllPlaceholders = true;
1925 for (const auto *BD : DD->bindings()) {
1926 if (BD->isReferenced() || BD->hasAttr<UnusedAttr>())
1927 return false;
1928 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1929 }
1930 if (IsAllPlaceholders)
1931 return false;
1932 } else if (!D->getDeclName()) {
1933 return false;
1934 } else if (D->isReferenced() || D->isUsed()) {
1935 return false;
1936 }
1937
1938 if (D->isPlaceholderVar(LangOpts))
1939 return false;
1940
1941 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1942 D->hasAttr<CleanupAttr>())
1943 return false;
1944
1945 if (isa<LabelDecl>(D))
1946 return true;
1947
1948 // Except for labels, we only care about unused decls that are local to
1949 // functions.
1950 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1951 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1952 // For dependent types, the diagnostic is deferred.
1953 WithinFunction =
1954 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1955 if (!WithinFunction)
1956 return false;
1957
1958 if (isa<TypedefNameDecl>(D))
1959 return true;
1960
1961 // White-list anything that isn't a local variable.
1962 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1963 return false;
1964
1965 // Types of valid local variables should be complete, so this should succeed.
1966 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1967
1968 const Expr *Init = VD->getInit();
1969 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
1970 Init = Cleanups->getSubExpr();
1971
1972 const auto *Ty = VD->getType().getTypePtr();
1973
1974 // Only look at the outermost level of typedef.
1975 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1976 // Allow anything marked with __attribute__((unused)).
1977 if (TT->getDecl()->hasAttr<UnusedAttr>())
1978 return false;
1979 }
1980
1981 // Warn for reference variables whose initializtion performs lifetime
1982 // extension.
1983 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
1984 MTE && MTE->getExtendingDecl()) {
1985 Ty = VD->getType().getNonReferenceType().getTypePtr();
1986 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1987 }
1988
1989 // If we failed to complete the type for some reason, or if the type is
1990 // dependent, don't diagnose the variable.
1991 if (Ty->isIncompleteType() || Ty->isDependentType())
1992 return false;
1993
1994 // Look at the element type to ensure that the warning behaviour is
1995 // consistent for both scalars and arrays.
1996 Ty = Ty->getBaseElementTypeUnsafe();
1997
1998 if (const TagType *TT = Ty->getAs<TagType>()) {
1999 const TagDecl *Tag = TT->getDecl();
2000 if (Tag->hasAttr<UnusedAttr>())
2001 return false;
2002
2003 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2004 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2005 return false;
2006
2007 if (Init) {
2008 const auto *Construct =
2009 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2010 if (Construct && !Construct->isElidable()) {
2011 const CXXConstructorDecl *CD = Construct->getConstructor();
2012 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2013 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2014 return false;
2015 }
2016
2017 // Suppress the warning if we don't know how this is constructed, and
2018 // it could possibly be non-trivial constructor.
2019 if (Init->isTypeDependent()) {
2020 for (const CXXConstructorDecl *Ctor : RD->ctors())
2021 if (!Ctor->isTrivial())
2022 return false;
2023 }
2024
2025 // Suppress the warning if the constructor is unresolved because
2026 // its arguments are dependent.
2027 if (isa<CXXUnresolvedConstructExpr>(Init))
2028 return false;
2029 }
2030 }
2031 }
2032
2033 // TODO: __attribute__((unused)) templates?
2034 }
2035
2036 return true;
2037}
2038
2040 FixItHint &Hint) {
2041 if (isa<LabelDecl>(D)) {
2043 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2044 /*SkipTrailingWhitespaceAndNewline=*/false);
2045 if (AfterColon.isInvalid())
2046 return;
2049 }
2050}
2051
2054 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2055}
2056
2058 DiagReceiverTy DiagReceiver) {
2059 if (D->getTypeForDecl()->isDependentType())
2060 return;
2061
2062 for (auto *TmpD : D->decls()) {
2063 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2064 DiagnoseUnusedDecl(T, DiagReceiver);
2065 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2066 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2067 }
2068}
2069
2072 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2073}
2074
2077 return;
2078
2079 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2080 // typedefs can be referenced later on, so the diagnostics are emitted
2081 // at end-of-translation-unit.
2083 return;
2084 }
2085
2086 FixItHint Hint;
2088
2089 unsigned DiagID;
2090 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2091 DiagID = diag::warn_unused_exception_param;
2092 else if (isa<LabelDecl>(D))
2093 DiagID = diag::warn_unused_label;
2094 else
2095 DiagID = diag::warn_unused_variable;
2096
2097 SourceLocation DiagLoc = D->getLocation();
2098 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2099}
2100
2102 DiagReceiverTy DiagReceiver) {
2103 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2104 // it's not really unused.
2105 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2106 return;
2107
2108 // In C++, `_` variables behave as if they were maybe_unused
2109 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2110 return;
2111
2112 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2113
2114 if (Ty->isReferenceType() || Ty->isDependentType())
2115 return;
2116
2117 if (const TagType *TT = Ty->getAs<TagType>()) {
2118 const TagDecl *Tag = TT->getDecl();
2119 if (Tag->hasAttr<UnusedAttr>())
2120 return;
2121 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2122 // mimic gcc's behavior.
2123 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2124 RD && !RD->hasAttr<WarnUnusedAttr>())
2125 return;
2126 }
2127
2128 // Don't warn about __block Objective-C pointer variables, as they might
2129 // be assigned in the block but not used elsewhere for the purpose of lifetime
2130 // extension.
2131 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2132 return;
2133
2134 // Don't warn about Objective-C pointer variables with precise lifetime
2135 // semantics; they can be used to ensure ARC releases the object at a known
2136 // time, which may mean assignment but no other references.
2137 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2138 return;
2139
2140 auto iter = RefsMinusAssignments.find(VD);
2141 if (iter == RefsMinusAssignments.end())
2142 return;
2143
2144 assert(iter->getSecond() >= 0 &&
2145 "Found a negative number of references to a VarDecl");
2146 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2147 // Assume the given VarDecl is "used" if its ref count stored in
2148 // `RefMinusAssignments` is positive, with one exception.
2149 //
2150 // For a C++ variable whose decl (with initializer) entirely consist the
2151 // condition expression of a if/while/for construct,
2152 // Clang creates a DeclRefExpr for the condition expression rather than a
2153 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2154 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2155 // used in the body of the if/while/for construct.
2156 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2157 if (!UnusedCXXCondDecl)
2158 return;
2159 }
2160
2161 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2162 : diag::warn_unused_but_set_variable;
2163 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2164}
2165
2167 Sema::DiagReceiverTy DiagReceiver) {
2168 // Verify that we have no forward references left. If so, there was a goto
2169 // or address of a label taken, but no definition of it. Label fwd
2170 // definitions are indicated with a null substmt which is also not a resolved
2171 // MS inline assembly label name.
2172 bool Diagnose = false;
2173 if (L->isMSAsmLabel())
2174 Diagnose = !L->isResolvedMSAsmLabel();
2175 else
2176 Diagnose = L->getStmt() == nullptr;
2177 if (Diagnose)
2178 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2179 << L);
2180}
2181
2183 S->applyNRVO();
2184
2185 if (S->decl_empty()) return;
2186 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2187 "Scope shouldn't contain decls!");
2188
2189 /// We visit the decls in non-deterministic order, but we want diagnostics
2190 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2191 /// and sort the diagnostics before emitting them, after we visited all decls.
2192 struct LocAndDiag {
2194 std::optional<SourceLocation> PreviousDeclLoc;
2196 };
2198 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2199 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2200 };
2201 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2202 SourceLocation PreviousDeclLoc,
2203 PartialDiagnostic PD) {
2204 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2205 };
2206
2207 for (auto *TmpD : S->decls()) {
2208 assert(TmpD && "This decl didn't get pushed??");
2209
2210 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2211 NamedDecl *D = cast<NamedDecl>(TmpD);
2212
2213 // Diagnose unused variables in this scope.
2214 if (!S->hasUnrecoverableErrorOccurred()) {
2215 DiagnoseUnusedDecl(D, addDiag);
2216 if (const auto *RD = dyn_cast<RecordDecl>(D))
2217 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2218 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2219 DiagnoseUnusedButSetDecl(VD, addDiag);
2220 RefsMinusAssignments.erase(VD);
2221 }
2222 }
2223
2224 if (!D->getDeclName()) continue;
2225
2226 // If this was a forward reference to a label, verify it was defined.
2227 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2228 CheckPoppedLabel(LD, *this, addDiag);
2229
2230 // Partial translation units that are created in incremental processing must
2231 // not clean up the IdResolver because PTUs should take into account the
2232 // declarations that came from previous PTUs.
2236
2237 // Warn on it if we are shadowing a declaration.
2238 auto ShadowI = ShadowingDecls.find(D);
2239 if (ShadowI != ShadowingDecls.end()) {
2240 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2241 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2242 PDiag(diag::warn_ctor_parm_shadows_field)
2243 << D << FD << FD->getParent());
2244 }
2245 ShadowingDecls.erase(ShadowI);
2246 }
2247 }
2248
2249 llvm::sort(DeclDiags,
2250 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2251 // The particular order for diagnostics is not important, as long
2252 // as the order is deterministic. Using the raw location is going
2253 // to generally be in source order unless there are macro
2254 // expansions involved.
2255 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2256 });
2257 for (const LocAndDiag &D : DeclDiags) {
2258 Diag(D.Loc, D.PD);
2259 if (D.PreviousDeclLoc)
2260 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2261 }
2262}
2263
2265 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2266 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2267 (S->isClassScope() && !getLangOpts().CPlusPlus))
2268 S = S->getParent();
2269 return S;
2270}
2271
2272static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2274 switch (Error) {
2276 return "";
2278 return BuiltinInfo.getHeaderName(ID);
2280 return "stdio.h";
2282 return "setjmp.h";
2284 return "ucontext.h";
2285 }
2286 llvm_unreachable("unhandled error kind");
2287}
2288
2290 unsigned ID, SourceLocation Loc) {
2292
2293 if (getLangOpts().CPlusPlus) {
2296 CLinkageDecl->setImplicit();
2297 Parent->addDecl(CLinkageDecl);
2298 Parent = CLinkageDecl;
2299 }
2300
2303 assert(getLangOpts().CPlusPlus20 &&
2304 "consteval builtins should only be available in C++20 mode");
2305 ConstexprKind = ConstexprSpecKind::Consteval;
2306 }
2307
2309 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2310 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2311 Type->isFunctionProtoType(), ConstexprKind);
2312 New->setImplicit();
2313 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2314
2315 // Create Decl objects for each parameter, adding them to the
2316 // FunctionDecl.
2317 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2319 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2321 Context, New, SourceLocation(), SourceLocation(), nullptr,
2322 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2323 parm->setScopeInfo(0, i);
2324 Params.push_back(parm);
2325 }
2326 New->setParams(Params);
2327 }
2328
2330 return New;
2331}
2332
2334 Scope *S, bool ForRedeclaration,
2337
2339 QualType R = Context.GetBuiltinType(ID, Error);
2340 if (Error) {
2341 if (!ForRedeclaration)
2342 return nullptr;
2343
2344 // If we have a builtin without an associated type we should not emit a
2345 // warning when we were not able to find a type for it.
2346 if (Error == ASTContext::GE_Missing_type ||
2348 return nullptr;
2349
2350 // If we could not find a type for setjmp it is because the jmp_buf type was
2351 // not defined prior to the setjmp declaration.
2352 if (Error == ASTContext::GE_Missing_setjmp) {
2353 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2355 return nullptr;
2356 }
2357
2358 // Generally, we emit a warning that the declaration requires the
2359 // appropriate header.
2360 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2361 << getHeaderName(Context.BuiltinInfo, ID, Error)
2363 return nullptr;
2364 }
2365
2366 if (!ForRedeclaration &&
2369 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2370 : diag::ext_implicit_lib_function_decl)
2371 << Context.BuiltinInfo.getName(ID) << R;
2372 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2373 Diag(Loc, diag::note_include_header_or_declare)
2374 << Header << Context.BuiltinInfo.getName(ID);
2375 }
2376
2377 if (R.isNull())
2378 return nullptr;
2379
2380 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2382
2383 // TUScope is the translation-unit scope to insert this function into.
2384 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2385 // relate Scopes to DeclContexts, and probably eliminate CurContext
2386 // entirely, but we're not there yet.
2387 DeclContext *SavedContext = CurContext;
2388 CurContext = New->getDeclContext();
2390 CurContext = SavedContext;
2391 return New;
2392}
2393
2394/// Typedef declarations don't have linkage, but they still denote the same
2395/// entity if their types are the same.
2396/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2397/// isSameEntity.
2398static void
2401 // This is only interesting when modules are enabled.
2402 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2403 return;
2404
2405 // Empty sets are uninteresting.
2406 if (Previous.empty())
2407 return;
2408
2409 LookupResult::Filter Filter = Previous.makeFilter();
2410 while (Filter.hasNext()) {
2411 NamedDecl *Old = Filter.next();
2412
2413 // Non-hidden declarations are never ignored.
2414 if (S.isVisible(Old))
2415 continue;
2416
2417 // Declarations of the same entity are not ignored, even if they have
2418 // different linkages.
2419 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2420 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2421 Decl->getUnderlyingType()))
2422 continue;
2423
2424 // If both declarations give a tag declaration a typedef name for linkage
2425 // purposes, then they declare the same entity.
2426 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2427 Decl->getAnonDeclWithTypedefName())
2428 continue;
2429 }
2430
2431 Filter.erase();
2432 }
2433
2434 Filter.done();
2435}
2436
2438 QualType OldType;
2439 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2440 OldType = OldTypedef->getUnderlyingType();
2441 else
2442 OldType = Context.getTypeDeclType(Old);
2443 QualType NewType = New->getUnderlyingType();
2444
2445 if (NewType->isVariablyModifiedType()) {
2446 // Must not redefine a typedef with a variably-modified type.
2447 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2448 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2449 << Kind << NewType;
2450 if (Old->getLocation().isValid())
2452 New->setInvalidDecl();
2453 return true;
2454 }
2455
2456 if (OldType != NewType &&
2457 !OldType->isDependentType() &&
2458 !NewType->isDependentType() &&
2459 !Context.hasSameType(OldType, NewType)) {
2460 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2461 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2462 << Kind << NewType << OldType;
2463 if (Old->getLocation().isValid())
2465 New->setInvalidDecl();
2466 return true;
2467 }
2468 return false;
2469}
2470
2472 LookupResult &OldDecls) {
2473 // If the new decl is known invalid already, don't bother doing any
2474 // merging checks.
2475 if (New->isInvalidDecl()) return;
2476
2477 // Allow multiple definitions for ObjC built-in typedefs.
2478 // FIXME: Verify the underlying types are equivalent!
2479 if (getLangOpts().ObjC) {
2480 const IdentifierInfo *TypeID = New->getIdentifier();
2481 switch (TypeID->getLength()) {
2482 default: break;
2483 case 2:
2484 {
2485 if (!TypeID->isStr("id"))
2486 break;
2487 QualType T = New->getUnderlyingType();
2488 if (!T->isPointerType())
2489 break;
2490 if (!T->isVoidPointerType()) {
2492 if (!PT->isStructureType())
2493 break;
2494 }
2496 // Install the built-in type for 'id', ignoring the current definition.
2498 return;
2499 }
2500 case 5:
2501 if (!TypeID->isStr("Class"))
2502 break;
2504 // Install the built-in type for 'Class', ignoring the current definition.
2506 return;
2507 case 3:
2508 if (!TypeID->isStr("SEL"))
2509 break;
2511 // Install the built-in type for 'SEL', ignoring the current definition.
2513 return;
2514 }
2515 // Fall through - the typedef name was not a builtin type.
2516 }
2517
2518 // Verify the old decl was also a type.
2519 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2520 if (!Old) {
2521 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2522 << New->getDeclName();
2523
2524 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2525 if (OldD->getLocation().isValid())
2526 notePreviousDefinition(OldD, New->getLocation());
2527
2528 return New->setInvalidDecl();
2529 }
2530
2531 // If the old declaration is invalid, just give up here.
2532 if (Old->isInvalidDecl())
2533 return New->setInvalidDecl();
2534
2535 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2536 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2537 auto *NewTag = New->getAnonDeclWithTypedefName();
2538 NamedDecl *Hidden = nullptr;
2539 if (OldTag && NewTag &&
2540 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2541 !hasVisibleDefinition(OldTag, &Hidden)) {
2542 // There is a definition of this tag, but it is not visible. Use it
2543 // instead of our tag.
2544 New->setTypeForDecl(OldTD->getTypeForDecl());
2545 if (OldTD->isModed())
2546 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2547 OldTD->getUnderlyingType());
2548 else
2549 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2550
2551 // Make the old tag definition visible.
2553
2554 // If this was an unscoped enumeration, yank all of its enumerators
2555 // out of the scope.
2556 if (isa<EnumDecl>(NewTag)) {
2557 Scope *EnumScope = getNonFieldDeclScope(S);
2558 for (auto *D : NewTag->decls()) {
2559 auto *ED = cast<EnumConstantDecl>(D);
2560 assert(EnumScope->isDeclScope(ED));
2561 EnumScope->RemoveDecl(ED);
2563 ED->getLexicalDeclContext()->removeDecl(ED);
2564 }
2565 }
2566 }
2567 }
2568
2569 // If the typedef types are not identical, reject them in all languages and
2570 // with any extensions enabled.
2571 if (isIncompatibleTypedef(Old, New))
2572 return;
2573
2574 // The types match. Link up the redeclaration chain and merge attributes if
2575 // the old declaration was a typedef.
2576 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2577 New->setPreviousDecl(Typedef);
2578 mergeDeclAttributes(New, Old);
2579 }
2580
2581 if (getLangOpts().MicrosoftExt)
2582 return;
2583
2584 if (getLangOpts().CPlusPlus) {
2585 // C++ [dcl.typedef]p2:
2586 // In a given non-class scope, a typedef specifier can be used to
2587 // redefine the name of any type declared in that scope to refer
2588 // to the type to which it already refers.
2589 if (!isa<CXXRecordDecl>(CurContext))
2590 return;
2591
2592 // C++0x [dcl.typedef]p4:
2593 // In a given class scope, a typedef specifier can be used to redefine
2594 // any class-name declared in that scope that is not also a typedef-name
2595 // to refer to the type to which it already refers.
2596 //
2597 // This wording came in via DR424, which was a correction to the
2598 // wording in DR56, which accidentally banned code like:
2599 //
2600 // struct S {
2601 // typedef struct A { } A;
2602 // };
2603 //
2604 // in the C++03 standard. We implement the C++0x semantics, which
2605 // allow the above but disallow
2606 //
2607 // struct S {
2608 // typedef int I;
2609 // typedef int I;
2610 // };
2611 //
2612 // since that was the intent of DR56.
2613 if (!isa<TypedefNameDecl>(Old))
2614 return;
2615
2616 Diag(New->getLocation(), diag::err_redefinition)
2617 << New->getDeclName();
2619 return New->setInvalidDecl();
2620 }
2621
2622 // Modules always permit redefinition of typedefs, as does C11.
2623 if (getLangOpts().Modules || getLangOpts().C11)
2624 return;
2625
2626 // If we have a redefinition of a typedef in C, emit a warning. This warning
2627 // is normally mapped to an error, but can be controlled with
2628 // -Wtypedef-redefinition. If either the original or the redefinition is
2629 // in a system header, don't emit this for compatibility with GCC.
2630 if (getDiagnostics().getSuppressSystemWarnings() &&
2631 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2632 (Old->isImplicit() ||
2635 return;
2636
2637 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2638 << New->getDeclName();
2640}
2641
2642/// DeclhasAttr - returns true if decl Declaration already has the target
2643/// attribute.
2644static bool DeclHasAttr(const Decl *D, const Attr *A) {
2645 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2646 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2647 for (const auto *i : D->attrs())
2648 if (i->getKind() == A->getKind()) {
2649 if (Ann) {
2650 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2651 return true;
2652 continue;
2653 }
2654 // FIXME: Don't hardcode this check
2655 if (OA && isa<OwnershipAttr>(i))
2656 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2657 return true;
2658 }
2659
2660 return false;
2661}
2662
2664 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2665 return VD->isThisDeclarationADefinition();
2666 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2667 return TD->isCompleteDefinition() || TD->isBeingDefined();
2668 return true;
2669}
2670
2671/// Merge alignment attributes from \p Old to \p New, taking into account the
2672/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2673///
2674/// \return \c true if any attributes were added to \p New.
2675static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2676 // Look for alignas attributes on Old, and pick out whichever attribute
2677 // specifies the strictest alignment requirement.
2678 AlignedAttr *OldAlignasAttr = nullptr;
2679 AlignedAttr *OldStrictestAlignAttr = nullptr;
2680 unsigned OldAlign = 0;
2681 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2682 // FIXME: We have no way of representing inherited dependent alignments
2683 // in a case like:
2684 // template<int A, int B> struct alignas(A) X;
2685 // template<int A, int B> struct alignas(B) X {};
2686 // For now, we just ignore any alignas attributes which are not on the
2687 // definition in such a case.
2688 if (I->isAlignmentDependent())
2689 return false;
2690
2691 if (I->isAlignas())
2692 OldAlignasAttr = I;
2693
2694 unsigned Align = I->getAlignment(S.Context);
2695 if (Align > OldAlign) {
2696 OldAlign = Align;
2697 OldStrictestAlignAttr = I;
2698 }
2699 }
2700
2701 // Look for alignas attributes on New.
2702 AlignedAttr *NewAlignasAttr = nullptr;
2703 unsigned NewAlign = 0;
2704 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2705 if (I->isAlignmentDependent())
2706 return false;
2707
2708 if (I->isAlignas())
2709 NewAlignasAttr = I;
2710
2711 unsigned Align = I->getAlignment(S.Context);
2712 if (Align > NewAlign)
2713 NewAlign = Align;
2714 }
2715
2716 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2717 // Both declarations have 'alignas' attributes. We require them to match.
2718 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2719 // fall short. (If two declarations both have alignas, they must both match
2720 // every definition, and so must match each other if there is a definition.)
2721
2722 // If either declaration only contains 'alignas(0)' specifiers, then it
2723 // specifies the natural alignment for the type.
2724 if (OldAlign == 0 || NewAlign == 0) {
2725 QualType Ty;
2726 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2727 Ty = VD->getType();
2728 else
2729 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2730
2731 if (OldAlign == 0)
2732 OldAlign = S.Context.getTypeAlign(Ty);
2733 if (NewAlign == 0)
2734 NewAlign = S.Context.getTypeAlign(Ty);
2735 }
2736
2737 if (OldAlign != NewAlign) {
2738 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2741 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2742 }
2743 }
2744
2745 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2746 // C++11 [dcl.align]p6:
2747 // if any declaration of an entity has an alignment-specifier,
2748 // every defining declaration of that entity shall specify an
2749 // equivalent alignment.
2750 // C11 6.7.5/7:
2751 // If the definition of an object does not have an alignment
2752 // specifier, any other declaration of that object shall also
2753 // have no alignment specifier.
2754 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2755 << OldAlignasAttr;
2756 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2757 << OldAlignasAttr;
2758 }
2759
2760 bool AnyAdded = false;
2761
2762 // Ensure we have an attribute representing the strictest alignment.
2763 if (OldAlign > NewAlign) {
2764 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2765 Clone->setInherited(true);
2766 New->addAttr(Clone);
2767 AnyAdded = true;
2768 }
2769
2770 // Ensure we have an alignas attribute if the old declaration had one.
2771 if (OldAlignasAttr && !NewAlignasAttr &&
2772 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2773 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2774 Clone->setInherited(true);
2775 New->addAttr(Clone);
2776 AnyAdded = true;
2777 }
2778
2779 return AnyAdded;
2780}
2781
2782#define WANT_DECL_MERGE_LOGIC
2783#include "clang/Sema/AttrParsedAttrImpl.inc"
2784#undef WANT_DECL_MERGE_LOGIC
2785
2787 const InheritableAttr *Attr,
2789 // Diagnose any mutual exclusions between the attribute that we want to add
2790 // and attributes that already exist on the declaration.
2791 if (!DiagnoseMutualExclusions(S, D, Attr))
2792 return false;
2793
2794 // This function copies an attribute Attr from a previous declaration to the
2795 // new declaration D if the new declaration doesn't itself have that attribute
2796 // yet or if that attribute allows duplicates.
2797 // If you're adding a new attribute that requires logic different from
2798 // "use explicit attribute on decl if present, else use attribute from
2799 // previous decl", for example if the attribute needs to be consistent
2800 // between redeclarations, you need to call a custom merge function here.
2801 InheritableAttr *NewAttr = nullptr;
2802 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2803 NewAttr = S.mergeAvailabilityAttr(
2804 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2805 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2806 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2807 AA->getPriority(), AA->getEnvironment());
2808 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2809 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2810 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2811 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2812 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2813 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2814 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2815 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2816 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2817 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2818 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2819 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2820 FA->getFirstArg());
2821 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2822 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2823 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2824 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2825 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2826 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2827 IA->getInheritanceModel());
2828 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2829 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2830 &S.Context.Idents.get(AA->getSpelling()));
2831 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2832 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2833 isa<CUDAGlobalAttr>(Attr))) {
2834 // CUDA target attributes are part of function signature for
2835 // overloading purposes and must not be merged.
2836 return false;
2837 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2838 NewAttr = S.mergeMinSizeAttr(D, *MA);
2839 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2840 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2841 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2842 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2843 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2844 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2845 else if (isa<AlignedAttr>(Attr))
2846 // AlignedAttrs are handled separately, because we need to handle all
2847 // such attributes on a declaration at the same time.
2848 NewAttr = nullptr;
2849 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2850 (AMK == Sema::AMK_Override ||
2853 NewAttr = nullptr;
2854 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2855 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2856 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2857 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2858 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2859 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2860 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2861 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2862 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2863 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2864 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2865 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2866 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2867 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2868 NT->getZ());
2869 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2870 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2871 WS->getPreferred(),
2872 WS->getSpelledArgsCount());
2873 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2874 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2875 else if (isa<SuppressAttr>(Attr))
2876 // Do nothing. Each redeclaration should be suppressed separately.
2877 NewAttr = nullptr;
2878 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2879 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2880
2881 if (NewAttr) {
2882 NewAttr->setInherited(true);
2883 D->addAttr(NewAttr);
2884 if (isa<MSInheritanceAttr>(NewAttr))
2885 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2886 return true;
2887 }
2888
2889 return false;
2890}
2891
2892static const NamedDecl *getDefinition(const Decl *D) {
2893 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2894 return TD->getDefinition();
2895 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2896 const VarDecl *Def = VD->getDefinition();
2897 if (Def)
2898 return Def;
2899 return VD->getActingDefinition();
2900 }
2901 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2902 const FunctionDecl *Def = nullptr;
2903 if (FD->isDefined(Def, true))
2904 return Def;
2905 }
2906 return nullptr;
2907}
2908
2909static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2910 for (const auto *Attribute : D->attrs())
2911 if (Attribute->getKind() == Kind)
2912 return true;
2913 return false;
2914}
2915
2916/// checkNewAttributesAfterDef - If we already have a definition, check that
2917/// there are no new attributes in this declaration.
2918static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2919 if (!New->hasAttrs())
2920 return;
2921
2922 const NamedDecl *Def = getDefinition(Old);
2923 if (!Def || Def == New)
2924 return;
2925
2926 AttrVec &NewAttributes = New->getAttrs();
2927 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2928 Attr *NewAttribute = NewAttributes[I];
2929
2930 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2931 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2932 SkipBodyInfo SkipBody;
2933 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2934
2935 // If we're skipping this definition, drop the "alias" attribute.
2936 if (SkipBody.ShouldSkip) {
2937 NewAttributes.erase(NewAttributes.begin() + I);
2938 --E;
2939 continue;
2940 }
2941 } else {
2942 VarDecl *VD = cast<VarDecl>(New);
2943 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2945 ? diag::err_alias_after_tentative
2946 : diag::err_redefinition;
2947 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2948 if (Diag == diag::err_redefinition)
2949 S.notePreviousDefinition(Def, VD->getLocation());
2950 else
2951 S.Diag(Def->getLocation(), diag::note_previous_definition);
2952 VD->setInvalidDecl();
2953 }
2954 ++I;
2955 continue;
2956 }
2957
2958 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2959 // Tentative definitions are only interesting for the alias check above.
2960 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2961 ++I;
2962 continue;
2963 }
2964 }
2965
2966 if (hasAttribute(Def, NewAttribute->getKind())) {
2967 ++I;
2968 continue; // regular attr merging will take care of validating this.
2969 }
2970
2971 if (isa<C11NoReturnAttr>(NewAttribute)) {
2972 // C's _Noreturn is allowed to be added to a function after it is defined.
2973 ++I;
2974 continue;
2975 } else if (isa<UuidAttr>(NewAttribute)) {
2976 // msvc will allow a subsequent definition to add an uuid to a class
2977 ++I;
2978 continue;
2979 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2980 if (AA->isAlignas()) {
2981 // C++11 [dcl.align]p6:
2982 // if any declaration of an entity has an alignment-specifier,
2983 // every defining declaration of that entity shall specify an
2984 // equivalent alignment.
2985 // C11 6.7.5/7:
2986 // If the definition of an object does not have an alignment
2987 // specifier, any other declaration of that object shall also
2988 // have no alignment specifier.
2989 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2990 << AA;
2991 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2992 << AA;
2993 NewAttributes.erase(NewAttributes.begin() + I);
2994 --E;
2995 continue;
2996 }
2997 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2998 // If there is a C definition followed by a redeclaration with this
2999 // attribute then there are two different definitions. In C++, prefer the
3000 // standard diagnostics.
3001 if (!S.getLangOpts().CPlusPlus) {
3002 S.Diag(NewAttribute->getLocation(),
3003 diag::err_loader_uninitialized_redeclaration);
3004 S.Diag(Def->getLocation(), diag::note_previous_definition);
3005 NewAttributes.erase(NewAttributes.begin() + I);
3006 --E;
3007 continue;
3008 }
3009 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3010 cast<VarDecl>(New)->isInline() &&
3011 !cast<VarDecl>(New)->isInlineSpecified()) {
3012 // Don't warn about applying selectany to implicitly inline variables.
3013 // Older compilers and language modes would require the use of selectany
3014 // to make such variables inline, and it would have no effect if we
3015 // honored it.
3016 ++I;
3017 continue;
3018 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3019 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3020 // declarations after definitions.
3021 ++I;
3022 continue;
3023 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3024 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3025 // error since the definition will have already been created without
3026 // the semantic effects of the attribute having been applied.
3027 S.Diag(NewAttribute->getLocation(),
3028 diag::err_sycl_entry_point_after_definition);
3029 S.Diag(Def->getLocation(), diag::note_previous_definition);
3030 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3031 ++I;
3032 continue;
3033 }
3034
3035 S.Diag(NewAttribute->getLocation(),
3036 diag::warn_attribute_precede_definition);
3037 S.Diag(Def->getLocation(), diag::note_previous_definition);
3038 NewAttributes.erase(NewAttributes.begin() + I);
3039 --E;
3040 }
3041}
3042
3043static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3044 const ConstInitAttr *CIAttr,
3045 bool AttrBeforeInit) {
3046 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3047
3048 // Figure out a good way to write this specifier on the old declaration.
3049 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3050 // enough of the attribute list spelling information to extract that without
3051 // heroics.
3052 std::string SuitableSpelling;
3053 if (S.getLangOpts().CPlusPlus20)
3054 SuitableSpelling = std::string(
3055 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3056 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3057 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3058 InsertLoc, {tok::l_square, tok::l_square,
3059 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3060 S.PP.getIdentifierInfo("require_constant_initialization"),
3061 tok::r_square, tok::r_square}));
3062 if (SuitableSpelling.empty())
3063 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3064 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3065 S.PP.getIdentifierInfo("require_constant_initialization"),
3066 tok::r_paren, tok::r_paren}));
3067 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3068 SuitableSpelling = "constinit";
3069 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3070 SuitableSpelling = "[[clang::require_constant_initialization]]";
3071 if (SuitableSpelling.empty())
3072 SuitableSpelling = "__attribute__((require_constant_initialization))";
3073 SuitableSpelling += " ";
3074
3075 if (AttrBeforeInit) {
3076 // extern constinit int a;
3077 // int a = 0; // error (missing 'constinit'), accepted as extension
3078 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3079 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3080 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3081 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3082 } else {
3083 // int a = 0;
3084 // constinit extern int a; // error (missing 'constinit')
3085 S.Diag(CIAttr->getLocation(),
3086 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3087 : diag::warn_require_const_init_added_too_late)
3088 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3089 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3090 << CIAttr->isConstinit()
3091 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3092 }
3093}
3094
3097 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3098 UsedAttr *NewAttr = OldAttr->clone(Context);
3099 NewAttr->setInherited(true);
3100 New->addAttr(NewAttr);
3101 }
3102 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3103 RetainAttr *NewAttr = OldAttr->clone(Context);
3104 NewAttr->setInherited(true);
3105 New->addAttr(NewAttr);
3106 }
3107
3108 if (!Old->hasAttrs() && !New->hasAttrs())
3109 return;
3110
3111 // [dcl.constinit]p1:
3112 // If the [constinit] specifier is applied to any declaration of a
3113 // variable, it shall be applied to the initializing declaration.
3114 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3115 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3116 if (bool(OldConstInit) != bool(NewConstInit)) {
3117 const auto *OldVD = cast<VarDecl>(Old);
3118 auto *NewVD = cast<VarDecl>(New);
3119
3120 // Find the initializing declaration. Note that we might not have linked
3121 // the new declaration into the redeclaration chain yet.
3122 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3123 if (!InitDecl &&
3124 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3125 InitDecl = NewVD;
3126
3127 if (InitDecl == NewVD) {
3128 // This is the initializing declaration. If it would inherit 'constinit',
3129 // that's ill-formed. (Note that we do not apply this to the attribute
3130 // form).
3131 if (OldConstInit && OldConstInit->isConstinit())
3132 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3133 /*AttrBeforeInit=*/true);
3134 } else if (NewConstInit) {
3135 // This is the first time we've been told that this declaration should
3136 // have a constant initializer. If we already saw the initializing
3137 // declaration, this is too late.
3138 if (InitDecl && InitDecl != NewVD) {
3139 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3140 /*AttrBeforeInit=*/false);
3141 NewVD->dropAttr<ConstInitAttr>();
3142 }
3143 }
3144 }
3145
3146 // Attributes declared post-definition are currently ignored.
3147 checkNewAttributesAfterDef(*this, New, Old);
3148
3149 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3150 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3151 if (!OldA->isEquivalent(NewA)) {
3152 // This redeclaration changes __asm__ label.
3153 Diag(New->getLocation(), diag::err_different_asm_label);
3154 Diag(OldA->getLocation(), diag::note_previous_declaration);
3155 }
3156 } else if (Old->isUsed()) {
3157 // This redeclaration adds an __asm__ label to a declaration that has
3158 // already been ODR-used.
3159 Diag(New->getLocation(), diag::err_late_asm_label_name)
3160 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3161 }
3162 }
3163
3164 // Re-declaration cannot add abi_tag's.
3165 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3166 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3167 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3168 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3169 Diag(NewAbiTagAttr->getLocation(),
3170 diag::err_new_abi_tag_on_redeclaration)
3171 << NewTag;
3172 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3173 }
3174 }
3175 } else {
3176 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3177 Diag(Old->getLocation(), diag::note_previous_declaration);
3178 }
3179 }
3180
3181 // This redeclaration adds a section attribute.
3182 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3183 if (auto *VD = dyn_cast<VarDecl>(New)) {
3184 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3185 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3186 Diag(Old->getLocation(), diag::note_previous_declaration);
3187 }
3188 }
3189 }
3190
3191 // Redeclaration adds code-seg attribute.
3192 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3193 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3194 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3195 Diag(New->getLocation(), diag::warn_mismatched_section)
3196 << 0 /*codeseg*/;
3197 Diag(Old->getLocation(), diag::note_previous_declaration);
3198 }
3199
3200 if (!Old->hasAttrs())
3201 return;
3202
3203 bool foundAny = New->hasAttrs();
3204
3205 // Ensure that any moving of objects within the allocated map is done before
3206 // we process them.
3207 if (!foundAny) New->setAttrs(AttrVec());
3208
3209 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3210 // Ignore deprecated/unavailable/availability attributes if requested.
3212 if (isa<DeprecatedAttr>(I) ||
3213 isa<UnavailableAttr>(I) ||
3214 isa<AvailabilityAttr>(I)) {
3215 switch (AMK) {
3216 case AMK_None:
3217 continue;
3218
3219 case AMK_Redeclaration:
3220 case AMK_Override:
3223 LocalAMK = AMK;
3224 break;
3225 }
3226 }
3227
3228 // Already handled.
3229 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3230 continue;
3231
3232 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3233 foundAny = true;
3234 }
3235
3236 if (mergeAlignedAttrs(*this, New, Old))
3237 foundAny = true;
3238
3239 if (!foundAny) New->dropAttrs();
3240}
3241
3242// Returns the number of added attributes.
3243template <class T>
3244static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3245 Sema &S) {
3246 unsigned found = 0;
3247 for (const auto *I : From->specific_attrs<T>()) {
3248 if (!DeclHasAttr(To, I)) {
3249 T *newAttr = cast<T>(I->clone(S.Context));
3250 newAttr->setInherited(true);
3251 To->addAttr(newAttr);
3252 ++found;
3253 }
3254 }
3255 return found;
3256}
3257
3258template <class F>
3259static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3260 F &&propagator) {
3261 if (!From->hasAttrs()) {
3262 return;
3263 }
3264
3265 bool foundAny = To->hasAttrs();
3266
3267 // Ensure that any moving of objects within the allocated map is
3268 // done before we process them.
3269 if (!foundAny)
3270 To->setAttrs(AttrVec());
3271
3272 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3273
3274 if (!foundAny)
3275 To->dropAttrs();
3276}
3277
3278/// mergeParamDeclAttributes - Copy attributes from the old parameter
3279/// to the new one.
3281 const ParmVarDecl *oldDecl,
3282 Sema &S) {
3283 // C++11 [dcl.attr.depend]p2:
3284 // The first declaration of a function shall specify the
3285 // carries_dependency attribute for its declarator-id if any declaration
3286 // of the function specifies the carries_dependency attribute.
3287 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3288 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3289 S.Diag(CDA->getLocation(),
3290 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3291 // Find the first declaration of the parameter.
3292 // FIXME: Should we build redeclaration chains for function parameters?
3293 const FunctionDecl *FirstFD =
3294 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3295 const ParmVarDecl *FirstVD =
3296 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3297 S.Diag(FirstVD->getLocation(),
3298 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3299 }
3300
3302 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3303 unsigned found = 0;
3304 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3305 // Propagate the lifetimebound attribute from parameters to the
3306 // most recent declaration. Note that this doesn't include the implicit
3307 // 'this' parameter, as the attribute is applied to the function type in
3308 // that case.
3309 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3310 return found;
3311 });
3312}
3313
3315 const ASTContext &Ctx) {
3316
3317 auto NoSizeInfo = [&Ctx](QualType Ty) {
3318 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3319 return true;
3320 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3321 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3322 return false;
3323 };
3324
3325 // `type[]` is equivalent to `type *` and `type[*]`.
3326 if (NoSizeInfo(Old) && NoSizeInfo(New))
3327 return true;
3328
3329 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3330 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3331 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3332 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3333 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3334 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3335 return false;
3336 return true;
3337 }
3338
3339 // Only compare size, ignore Size modifiers and CVR.
3340 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3341 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3342 Ctx.getAsConstantArrayType(New)->getSize();
3343 }
3344
3345 // Don't try to compare dependent sized array
3347 return true;
3348 }
3349
3350 return Old == New;
3351}
3352
3353static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3354 const ParmVarDecl *OldParam,
3355 Sema &S) {
3356 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3357 if (auto Newnullability = NewParam->getType()->getNullability()) {
3358 if (*Oldnullability != *Newnullability) {
3359 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3361 *Newnullability,
3363 != 0))
3365 *Oldnullability,
3367 != 0));
3368 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3369 }
3370 } else {
3371 QualType NewT = NewParam->getType();
3372 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3373 NewParam->setType(NewT);
3374 }
3375 }
3376 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3377 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3378 if (OldParamDT && NewParamDT &&
3379 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3380 QualType OldParamOT = OldParamDT->getOriginalType();
3381 QualType NewParamOT = NewParamDT->getOriginalType();
3382 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3383 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3384 << NewParam << NewParamOT;
3385 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3386 << OldParamOT;
3387 }
3388 }
3389}
3390
3391namespace {
3392
3393/// Used in MergeFunctionDecl to keep track of function parameters in
3394/// C.
3395struct GNUCompatibleParamWarning {
3396 ParmVarDecl *OldParm;
3397 ParmVarDecl *NewParm;
3398 QualType PromotedType;
3399};
3400
3401} // end anonymous namespace
3402
3403// Determine whether the previous declaration was a definition, implicit
3404// declaration, or a declaration.
3405template <typename T>
3406static std::pair<diag::kind, SourceLocation>
3407getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3408 diag::kind PrevDiag;
3409 SourceLocation OldLocation = Old->getLocation();
3410 if (Old->isThisDeclarationADefinition())
3411 PrevDiag = diag::note_previous_definition;
3412 else if (Old->isImplicit()) {
3413 PrevDiag = diag::note_previous_implicit_declaration;
3414 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3415 if (FD->getBuiltinID())
3416 PrevDiag = diag::note_previous_builtin_declaration;
3417 }
3418 if (OldLocation.isInvalid())
3419 OldLocation = New->getLocation();
3420 } else
3421 PrevDiag = diag::note_previous_declaration;
3422 return std::make_pair(PrevDiag, OldLocation);
3423}
3424
3425/// canRedefineFunction - checks if a function can be redefined. Currently,
3426/// only extern inline functions can be redefined, and even then only in
3427/// GNU89 mode.
3428static bool canRedefineFunction(const FunctionDecl *FD,
3429 const LangOptions& LangOpts) {
3430 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3431 !LangOpts.CPlusPlus &&
3432 FD->isInlineSpecified() &&
3433 FD->getStorageClass() == SC_Extern);
3434}
3435
3437 const AttributedType *AT = T->getAs<AttributedType>();
3438 while (AT && !AT->isCallingConv())
3439 AT = AT->getModifiedType()->getAs<AttributedType>();
3440 return AT;
3441}
3442
3443template <typename T>
3444static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3445 const DeclContext *DC = Old->getDeclContext();
3446 if (DC->isRecord())
3447 return false;
3448
3449 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3450 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3451 return true;
3452 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3453 return true;
3454 return false;
3455}
3456
3457template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3458static bool isExternC(VarTemplateDecl *) { return false; }
3459static bool isExternC(FunctionTemplateDecl *) { return false; }
3460
3461/// Check whether a redeclaration of an entity introduced by a
3462/// using-declaration is valid, given that we know it's not an overload
3463/// (nor a hidden tag declaration).
3464template<typename ExpectedDecl>
3466 ExpectedDecl *New) {
3467 // C++11 [basic.scope.declarative]p4:
3468 // Given a set of declarations in a single declarative region, each of
3469 // which specifies the same unqualified name,
3470 // -- they shall all refer to the same entity, or all refer to functions
3471 // and function templates; or
3472 // -- exactly one declaration shall declare a class name or enumeration
3473 // name that is not a typedef name and the other declarations shall all
3474 // refer to the same variable or enumerator, or all refer to functions
3475 // and function templates; in this case the class name or enumeration
3476 // name is hidden (3.3.10).
3477
3478 // C++11 [namespace.udecl]p14:
3479 // If a function declaration in namespace scope or block scope has the
3480 // same name and the same parameter-type-list as a function introduced
3481 // by a using-declaration, and the declarations do not declare the same
3482 // function, the program is ill-formed.
3483
3484 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3485 if (Old &&
3486 !Old->getDeclContext()->getRedeclContext()->Equals(
3487 New->getDeclContext()->getRedeclContext()) &&
3488 !(isExternC(Old) && isExternC(New)))
3489 Old = nullptr;
3490
3491 if (!Old) {
3492 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3493 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3494 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3495 return true;
3496 }
3497 return false;
3498}
3499
3501 const FunctionDecl *B) {
3502 assert(A->getNumParams() == B->getNumParams());
3503
3504 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3505 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3506 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3507 if (AttrA == AttrB)
3508 return true;
3509 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3510 AttrA->isDynamic() == AttrB->isDynamic();
3511 };
3512
3513 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3514}
3515
3516/// If necessary, adjust the semantic declaration context for a qualified
3517/// declaration to name the correct inline namespace within the qualifier.
3519 DeclaratorDecl *OldD) {
3520 // The only case where we need to update the DeclContext is when
3521 // redeclaration lookup for a qualified name finds a declaration
3522 // in an inline namespace within the context named by the qualifier:
3523 //
3524 // inline namespace N { int f(); }
3525 // int ::f(); // Sema DC needs adjusting from :: to N::.
3526 //
3527 // For unqualified declarations, the semantic context *can* change
3528 // along the redeclaration chain (for local extern declarations,
3529 // extern "C" declarations, and friend declarations in particular).
3530 if (!NewD->getQualifier())
3531 return;
3532
3533 // NewD is probably already in the right context.
3534 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3535 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3536 if (NamedDC->Equals(SemaDC))
3537 return;
3538
3539 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3540 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3541 "unexpected context for redeclaration");
3542
3543 auto *LexDC = NewD->getLexicalDeclContext();
3544 auto FixSemaDC = [=](NamedDecl *D) {
3545 if (!D)
3546 return;
3547 D->setDeclContext(SemaDC);
3548 D->setLexicalDeclContext(LexDC);
3549 };
3550
3551 FixSemaDC(NewD);
3552 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3553 FixSemaDC(FD->getDescribedFunctionTemplate());
3554 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3555 FixSemaDC(VD->getDescribedVarTemplate());
3556}
3557
3559 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3560 // Verify the old decl was also a function.
3561 FunctionDecl *Old = OldD->getAsFunction();
3562 if (!Old) {
3563 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3564 if (New->getFriendObjectKind()) {
3565 Diag(New->getLocation(), diag::err_using_decl_friend);
3566 Diag(Shadow->getTargetDecl()->getLocation(),
3567 diag::note_using_decl_target);
3568 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3569 << 0;
3570 return true;
3571 }
3572
3573 // Check whether the two declarations might declare the same function or
3574 // function template.
3575 if (FunctionTemplateDecl *NewTemplate =
3577 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3578 NewTemplate))
3579 return true;
3580 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3581 ->getAsFunction();
3582 } else {
3583 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3584 return true;
3585 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3586 }
3587 } else {
3588 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3589 << New->getDeclName();
3590 notePreviousDefinition(OldD, New->getLocation());
3591 return true;
3592 }
3593 }
3594
3595 // If the old declaration was found in an inline namespace and the new
3596 // declaration was qualified, update the DeclContext to match.
3598
3599 // If the old declaration is invalid, just give up here.
3600 if (Old->isInvalidDecl())
3601 return true;
3602
3603 // Disallow redeclaration of some builtins.
3604 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3605 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3606 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3607 << Old << Old->getType();
3608 return true;
3609 }
3610
3611 diag::kind PrevDiag;
3612 SourceLocation OldLocation;
3613 std::tie(PrevDiag, OldLocation) =
3615
3616 // Don't complain about this if we're in GNU89 mode and the old function
3617 // is an extern inline function.
3618 // Don't complain about specializations. They are not supposed to have
3619 // storage classes.
3620 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3621 New->getStorageClass() == SC_Static &&
3622 Old->hasExternalFormalLinkage() &&
3625 if (getLangOpts().MicrosoftExt) {
3626 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3627 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3628 } else {
3629 Diag(New->getLocation(), diag::err_static_non_static) << New;
3630 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3631 return true;
3632 }
3633 }
3634
3635 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3636 if (!Old->hasAttr<InternalLinkageAttr>()) {
3637 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3638 << ILA;
3639 Diag(Old->getLocation(), diag::note_previous_declaration);
3640 New->dropAttr<InternalLinkageAttr>();
3641 }
3642
3643 if (auto *EA = New->getAttr<ErrorAttr>()) {
3644 if (!Old->hasAttr<ErrorAttr>()) {
3645 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3646 Diag(Old->getLocation(), diag::note_previous_declaration);
3647 New->dropAttr<ErrorAttr>();
3648 }
3649 }
3650
3651 if (CheckRedeclarationInModule(New, Old))
3652 return true;
3653
3654 if (!getLangOpts().CPlusPlus) {
3655 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3656 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3657 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3658 << New << OldOvl;
3659
3660 // Try our best to find a decl that actually has the overloadable
3661 // attribute for the note. In most cases (e.g. programs with only one
3662 // broken declaration/definition), this won't matter.
3663 //
3664 // FIXME: We could do this if we juggled some extra state in
3665 // OverloadableAttr, rather than just removing it.
3666 const Decl *DiagOld = Old;
3667 if (OldOvl) {
3668 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3669 const auto *A = D->getAttr<OverloadableAttr>();
3670 return A && !A->isImplicit();
3671 });
3672 // If we've implicitly added *all* of the overloadable attrs to this
3673 // chain, emitting a "previous redecl" note is pointless.
3674 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3675 }
3676
3677 if (DiagOld)
3678 Diag(DiagOld->getLocation(),
3679 diag::note_attribute_overloadable_prev_overload)
3680 << OldOvl;
3681
3682 if (OldOvl)
3683 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3684 else
3685 New->dropAttr<OverloadableAttr>();
3686 }
3687 }
3688
3689 // It is not permitted to redeclare an SME function with different SME
3690 // attributes.
3691 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3692 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3693 << New->getType() << Old->getType();
3694 Diag(OldLocation, diag::note_previous_declaration);
3695 return true;
3696 }
3697
3698 // If a function is first declared with a calling convention, but is later
3699 // declared or defined without one, all following decls assume the calling
3700 // convention of the first.
3701 //
3702 // It's OK if a function is first declared without a calling convention,
3703 // but is later declared or defined with the default calling convention.
3704 //
3705 // To test if either decl has an explicit calling convention, we look for
3706 // AttributedType sugar nodes on the type as written. If they are missing or
3707 // were canonicalized away, we assume the calling convention was implicit.
3708 //
3709 // Note also that we DO NOT return at this point, because we still have
3710 // other tests to run.
3711 QualType OldQType = Context.getCanonicalType(Old->getType());
3712 QualType NewQType = Context.getCanonicalType(New->getType());
3713 const FunctionType *OldType = cast<FunctionType>(OldQType);
3714 const FunctionType *NewType = cast<FunctionType>(NewQType);
3715 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3716 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3717 bool RequiresAdjustment = false;
3718
3719 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3721 const FunctionType *FT =
3722 First->getType().getCanonicalType()->castAs<FunctionType>();
3724 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3725 if (!NewCCExplicit) {
3726 // Inherit the CC from the previous declaration if it was specified
3727 // there but not here.
3728 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3729 RequiresAdjustment = true;
3730 } else if (Old->getBuiltinID()) {
3731 // Builtin attribute isn't propagated to the new one yet at this point,
3732 // so we check if the old one is a builtin.
3733
3734 // Calling Conventions on a Builtin aren't really useful and setting a
3735 // default calling convention and cdecl'ing some builtin redeclarations is
3736 // common, so warn and ignore the calling convention on the redeclaration.
3737 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3738 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3740 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3741 RequiresAdjustment = true;
3742 } else {
3743 // Calling conventions aren't compatible, so complain.
3744 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3745 Diag(New->getLocation(), diag::err_cconv_change)
3746 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3747 << !FirstCCExplicit
3748 << (!FirstCCExplicit ? "" :
3750
3751 // Put the note on the first decl, since it is the one that matters.
3752 Diag(First->getLocation(), diag::note_previous_declaration);
3753 return true;
3754 }
3755 }
3756
3757 // FIXME: diagnose the other way around?
3758 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3759 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3760 RequiresAdjustment = true;
3761 }
3762
3763 // Merge regparm attribute.
3764 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3765 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3766 if (NewTypeInfo.getHasRegParm()) {
3767 Diag(New->getLocation(), diag::err_regparm_mismatch)
3768 << NewType->getRegParmType()
3769 << OldType->getRegParmType();
3770 Diag(OldLocation, diag::note_previous_declaration);
3771 return true;
3772 }
3773
3774 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3775 RequiresAdjustment = true;
3776 }
3777
3778 // Merge ns_returns_retained attribute.
3779 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3780 if (NewTypeInfo.getProducesResult()) {
3781 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3782 << "'ns_returns_retained'";
3783 Diag(OldLocation, diag::note_previous_declaration);
3784 return true;
3785 }
3786
3787 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3788 RequiresAdjustment = true;
3789 }
3790
3791 if (OldTypeInfo.getNoCallerSavedRegs() !=
3792 NewTypeInfo.getNoCallerSavedRegs()) {
3793 if (NewTypeInfo.getNoCallerSavedRegs()) {
3794 AnyX86NoCallerSavedRegistersAttr *Attr =
3795 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3796 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3797 Diag(OldLocation, diag::note_previous_declaration);
3798 return true;
3799 }
3800
3801 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3802 RequiresAdjustment = true;
3803 }
3804
3805 if (RequiresAdjustment) {
3808 New->setType(QualType(AdjustedType, 0));
3809 NewQType = Context.getCanonicalType(New->getType());
3810 }
3811
3812 // If this redeclaration makes the function inline, we may need to add it to
3813 // UndefinedButUsed.
3814 if (!Old->isInlined() && New->isInlined() &&
3815 !New->hasAttr<GNUInlineAttr>() &&
3816 !getLangOpts().GNUInline &&
3817 Old->isUsed(false) &&
3818 !Old->isDefined() && !New->isThisDeclarationADefinition())
3819 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3820 SourceLocation()));
3821
3822 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3823 // about it.
3824 if (New->hasAttr<GNUInlineAttr>() &&
3825 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3826 UndefinedButUsed.erase(Old->getCanonicalDecl());
3827 }
3828
3829 // If pass_object_size params don't match up perfectly, this isn't a valid
3830 // redeclaration.
3831 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3833 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3834 << New->getDeclName();
3835 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3836 return true;
3837 }
3838
3839 QualType OldQTypeForComparison = OldQType;
3841 const auto OldFX = Old->getFunctionEffects();
3842 const auto NewFX = New->getFunctionEffects();
3843 if (OldFX != NewFX) {
3844 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3845 for (const auto &Diff : Diffs) {
3846 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3847 Diag(New->getLocation(),
3848 diag::warn_mismatched_func_effect_redeclaration)
3849 << Diff.effectName();
3850 Diag(Old->getLocation(), diag::note_previous_declaration);
3851 }
3852 }
3853 // Following a warning, we could skip merging effects from the previous
3854 // declaration, but that would trigger an additional "conflicting types"
3855 // error.
3856 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3858 FunctionEffectSet MergedFX =
3859 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3860 if (!MergeErrs.empty())
3862 Old->getLocation());
3863
3864 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3865 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3866 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
3867 NewFPT->getParamTypes(), EPI);
3868
3869 New->setType(ModQT);
3870 NewQType = New->getType();
3871
3872 // Revise OldQTForComparison to include the merged effects,
3873 // so as not to fail due to differences later.
3874 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3875 EPI = OldFPT->getExtProtoInfo();
3876 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3877 OldQTypeForComparison = Context.getFunctionType(
3878 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
3879 }
3880 if (OldFX.empty()) {
3881 // A redeclaration may add the attribute to a previously seen function
3882 // body which needs to be verified.
3883 maybeAddDeclWithEffects(Old, MergedFX);
3884 }
3885 }
3886 }
3887 }
3888
3889 if (getLangOpts().CPlusPlus) {
3890 OldQType = Context.getCanonicalType(Old->getType());
3891 NewQType = Context.getCanonicalType(New->getType());
3892
3893 // Go back to the type source info to compare the declared return types,
3894 // per C++1y [dcl.type.auto]p13:
3895 // Redeclarations or specializations of a function or function template
3896 // with a declared return type that uses a placeholder type shall also
3897 // use that placeholder, not a deduced type.
3898 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3899 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3900 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3901 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3902 OldDeclaredReturnType)) {
3903 QualType ResQT;
3904 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3905 OldDeclaredReturnType->isObjCObjectPointerType())
3906 // FIXME: This does the wrong thing for a deduced return type.
3907 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3908 if (ResQT.isNull()) {
3909 if (New->isCXXClassMember() && New->isOutOfLine())
3910 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3911 << New << New->getReturnTypeSourceRange();
3912 else if (Old->isExternC() && New->isExternC() &&
3913 !Old->hasAttr<OverloadableAttr>() &&
3914 !New->hasAttr<OverloadableAttr>())
3915 Diag(New->getLocation(), diag::err_conflicting_types) << New;
3916 else
3917 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3918 << New->getReturnTypeSourceRange();
3919 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3920 << Old->getReturnTypeSourceRange();
3921 return true;
3922 }
3923 else
3924 NewQType = ResQT;
3925 }
3926
3927 QualType OldReturnType = OldType->getReturnType();
3928 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3929 if (OldReturnType != NewReturnType) {
3930 // If this function has a deduced return type and has already been
3931 // defined, copy the deduced value from the old declaration.
3932 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3933 if (OldAT && OldAT->isDeduced()) {
3934 QualType DT = OldAT->getDeducedType();
3935 if (DT.isNull()) {
3937 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3938 } else {
3939 New->setType(SubstAutoType(New->getType(), DT));
3940 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3941 }
3942 }
3943 }
3944
3945 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3946 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3947 if (OldMethod && NewMethod) {
3948 // Preserve triviality.
3949 NewMethod->setTrivial(OldMethod->isTrivial());
3950
3951 // MSVC allows explicit template specialization at class scope:
3952 // 2 CXXMethodDecls referring to the same function will be injected.
3953 // We don't want a redeclaration error.
3954 bool IsClassScopeExplicitSpecialization =
3955 OldMethod->isFunctionTemplateSpecialization() &&
3957 bool isFriend = NewMethod->getFriendObjectKind();
3958
3959 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3960 !IsClassScopeExplicitSpecialization) {
3961 // -- Member function declarations with the same name and the
3962 // same parameter types cannot be overloaded if any of them
3963 // is a static member function declaration.
3964 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3965 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3966 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3967 return true;
3968 }
3969
3970 // C++ [class.mem]p1:
3971 // [...] A member shall not be declared twice in the
3972 // member-specification, except that a nested class or member
3973 // class template can be declared and then later defined.
3974 if (!inTemplateInstantiation()) {
3975 unsigned NewDiag;
3976 if (isa<CXXConstructorDecl>(OldMethod))
3977 NewDiag = diag::err_constructor_redeclared;
3978 else if (isa<CXXDestructorDecl>(NewMethod))
3979 NewDiag = diag::err_destructor_redeclared;
3980 else if (isa<CXXConversionDecl>(NewMethod))
3981 NewDiag = diag::err_conv_function_redeclared;
3982 else
3983 NewDiag = diag::err_member_redeclared;
3984
3985 Diag(New->getLocation(), NewDiag);
3986 } else {
3987 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3988 << New << New->getType();
3989 }
3990 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3991 return true;
3992
3993 // Complain if this is an explicit declaration of a special
3994 // member that was initially declared implicitly.
3995 //
3996 // As an exception, it's okay to befriend such methods in order
3997 // to permit the implicit constructor/destructor/operator calls.
3998 } else if (OldMethod->isImplicit()) {
3999 if (isFriend) {
4000 NewMethod->setImplicit();
4001 } else {
4002 Diag(NewMethod->getLocation(),
4003 diag::err_definition_of_implicitly_declared_member)
4004 << New << llvm::to_underlying(getSpecialMember(OldMethod));
4005 return true;
4006 }
4007 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4008 Diag(NewMethod->getLocation(),
4009 diag::err_definition_of_explicitly_defaulted_member)
4010 << llvm::to_underlying(getSpecialMember(OldMethod));
4011 return true;
4012 }
4013 }
4014
4015 // C++1z [over.load]p2
4016 // Certain function declarations cannot be overloaded:
4017 // -- Function declarations that differ only in the return type,
4018 // the exception specification, or both cannot be overloaded.
4019
4020 // Check the exception specifications match. This may recompute the type of
4021 // both Old and New if it resolved exception specifications, so grab the
4022 // types again after this. Because this updates the type, we do this before
4023 // any of the other checks below, which may update the "de facto" NewQType
4024 // but do not necessarily update the type of New.
4025 if (CheckEquivalentExceptionSpec(Old, New))
4026 return true;
4027
4028 // C++11 [dcl.attr.noreturn]p1:
4029 // The first declaration of a function shall specify the noreturn
4030 // attribute if any declaration of that function specifies the noreturn
4031 // attribute.
4032 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4033 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4034 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4035 << NRA;
4036 Diag(Old->getLocation(), diag::note_previous_declaration);
4037 }
4038
4039 // C++11 [dcl.attr.depend]p2:
4040 // The first declaration of a function shall specify the
4041 // carries_dependency attribute for its declarator-id if any declaration
4042 // of the function specifies the carries_dependency attribute.
4043 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4044 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4045 Diag(CDA->getLocation(),
4046 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4047 Diag(Old->getFirstDecl()->getLocation(),
4048 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4049 }
4050
4051 // (C++98 8.3.5p3):
4052 // All declarations for a function shall agree exactly in both the
4053 // return type and the parameter-type-list.
4054 // We also want to respect all the extended bits except noreturn.
4055
4056 // noreturn should now match unless the old type info didn't have it.
4057 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4058 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4059 const FunctionType *OldTypeForComparison
4060 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4061 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4062 assert(OldQTypeForComparison.isCanonical());
4063 }
4064
4065 if (haveIncompatibleLanguageLinkages(Old, New)) {
4066 // As a special case, retain the language linkage from previous
4067 // declarations of a friend function as an extension.
4068 //
4069 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4070 // and is useful because there's otherwise no way to specify language
4071 // linkage within class scope.
4072 //
4073 // Check cautiously as the friend object kind isn't yet complete.
4074 if (New->getFriendObjectKind() != Decl::FOK_None) {
4075 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4076 Diag(OldLocation, PrevDiag);
4077 } else {
4078 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4079 Diag(OldLocation, PrevDiag);
4080 return true;
4081 }
4082 }
4083
4084 // HLSL check parameters for matching ABI specifications.
4085 if (getLangOpts().HLSL) {
4086 if (HLSL().CheckCompatibleParameterABI(New, Old))
4087 return true;
4088
4089 // If no errors are generated when checking parameter ABIs we can check if
4090 // the two declarations have the same type ignoring the ABIs and if so,
4091 // the declarations can be merged. This case for merging is only valid in
4092 // HLSL because there are no valid cases of merging mismatched parameter
4093 // ABIs except the HLSL implicit in and explicit in.
4094 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4095 NewQType))
4096 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4097 // Fall through for conflicting redeclarations and redefinitions.
4098 }
4099
4100 // If the function types are compatible, merge the declarations. Ignore the
4101 // exception specifier because it was already checked above in
4102 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4103 // about incompatible types under -fms-compatibility.
4104 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4105 NewQType))
4106 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4107
4108 // If the types are imprecise (due to dependent constructs in friends or
4109 // local extern declarations), it's OK if they differ. We'll check again
4110 // during instantiation.
4111 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4112 return false;
4113
4114 // Fall through for conflicting redeclarations and redefinitions.
4115 }
4116
4117 // C: Function types need to be compatible, not identical. This handles
4118 // duplicate function decls like "void f(int); void f(enum X);" properly.
4119 if (!getLangOpts().CPlusPlus) {
4120 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4121 // type is specified by a function definition that contains a (possibly
4122 // empty) identifier list, both shall agree in the number of parameters
4123 // and the type of each parameter shall be compatible with the type that
4124 // results from the application of default argument promotions to the
4125 // type of the corresponding identifier. ...
4126 // This cannot be handled by ASTContext::typesAreCompatible() because that
4127 // doesn't know whether the function type is for a definition or not when
4128 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4129 // we need to cover here is that the number of arguments agree as the
4130 // default argument promotion rules were already checked by
4131 // ASTContext::typesAreCompatible().
4132 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4133 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4134 if (Old->hasInheritedPrototype())
4135 Old = Old->getCanonicalDecl();
4136 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4137 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4138 return true;
4139 }
4140
4141 // If we are merging two functions where only one of them has a prototype,
4142 // we may have enough information to decide to issue a diagnostic that the
4143 // function without a prototype will change behavior in C23. This handles
4144 // cases like:
4145 // void i(); void i(int j);
4146 // void i(int j); void i();
4147 // void i(); void i(int j) {}
4148 // See ActOnFinishFunctionBody() for other cases of the behavior change
4149 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4150 // type without a prototype.
4151 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4152 !New->isImplicit() && !Old->isImplicit()) {
4153 const FunctionDecl *WithProto, *WithoutProto;
4154 if (New->hasWrittenPrototype()) {
4155 WithProto = New;
4156 WithoutProto = Old;
4157 } else {
4158 WithProto = Old;
4159 WithoutProto = New;
4160 }
4161
4162 if (WithProto->getNumParams() != 0) {
4163 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4164 // The one without the prototype will be changing behavior in C23, so
4165 // warn about that one so long as it's a user-visible declaration.
4166 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4167 if (WithoutProto == New)
4168 IsWithoutProtoADef = NewDeclIsDefn;
4169 else
4170 IsWithProtoADef = NewDeclIsDefn;
4171 Diag(WithoutProto->getLocation(),
4172 diag::warn_non_prototype_changes_behavior)
4173 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4174 << (WithoutProto == Old) << IsWithProtoADef;
4175
4176 // The reason the one without the prototype will be changing behavior
4177 // is because of the one with the prototype, so note that so long as
4178 // it's a user-visible declaration. There is one exception to this:
4179 // when the new declaration is a definition without a prototype, the
4180 // old declaration with a prototype is not the cause of the issue,
4181 // and that does not need to be noted because the one with a
4182 // prototype will not change behavior in C23.
4183 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4184 !IsWithoutProtoADef)
4185 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4186 }
4187 }
4188 }
4189
4190 if (Context.typesAreCompatible(OldQType, NewQType)) {
4191 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4192 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4193 const FunctionProtoType *OldProto = nullptr;
4194 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4195 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4196 // The old declaration provided a function prototype, but the
4197 // new declaration does not. Merge in the prototype.
4198 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4199 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4200 OldProto->getParamTypes(),
4201 OldProto->getExtProtoInfo());
4202 New->setType(NewQType);
4204
4205 // Synthesize parameters with the same types.
4207 for (const auto &ParamType : OldProto->param_types()) {
4209 Context, New, SourceLocation(), SourceLocation(), nullptr,
4210 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4211 Param->setScopeInfo(0, Params.size());
4212 Param->setImplicit();
4213 Params.push_back(Param);
4214 }
4215
4216 New->setParams(Params);
4217 }
4218
4219 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4220 }
4221 }
4222
4223 // Check if the function types are compatible when pointer size address
4224 // spaces are ignored.
4225 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4226 return false;
4227
4228 // GNU C permits a K&R definition to follow a prototype declaration
4229 // if the declared types of the parameters in the K&R definition
4230 // match the types in the prototype declaration, even when the
4231 // promoted types of the parameters from the K&R definition differ
4232 // from the types in the prototype. GCC then keeps the types from
4233 // the prototype.
4234 //
4235 // If a variadic prototype is followed by a non-variadic K&R definition,
4236 // the K&R definition becomes variadic. This is sort of an edge case, but
4237 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4238 // C99 6.9.1p8.
4239 if (!getLangOpts().CPlusPlus &&
4240 Old->hasPrototype() && !New->hasPrototype() &&
4241 New->getType()->getAs<FunctionProtoType>() &&
4242 Old->getNumParams() == New->getNumParams()) {
4245 const FunctionProtoType *OldProto
4246 = Old->getType()->getAs<FunctionProtoType>();
4247 const FunctionProtoType *NewProto
4248 = New->getType()->getAs<FunctionProtoType>();
4249
4250 // Determine whether this is the GNU C extension.
4251 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4252 NewProto->getReturnType());
4253 bool LooseCompatible = !MergedReturn.isNull();
4254 for (unsigned Idx = 0, End = Old->getNumParams();
4255 LooseCompatible && Idx != End; ++Idx) {
4256 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4257 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4258 if (Context.typesAreCompatible(OldParm->getType(),
4259 NewProto->getParamType(Idx))) {
4260 ArgTypes.push_back(NewParm->getType());
4261 } else if (Context.typesAreCompatible(OldParm->getType(),
4262 NewParm->getType(),
4263 /*CompareUnqualified=*/true)) {
4264 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4265 NewProto->getParamType(Idx) };
4266 Warnings.push_back(Warn);
4267 ArgTypes.push_back(NewParm->getType());
4268 } else
4269 LooseCompatible = false;
4270 }
4271
4272 if (LooseCompatible) {
4273 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4274 Diag(Warnings[Warn].NewParm->getLocation(),
4275 diag::ext_param_promoted_not_compatible_with_prototype)
4276 << Warnings[Warn].PromotedType
4277 << Warnings[Warn].OldParm->getType();
4278 if (Warnings[Warn].OldParm->getLocation().isValid())
4279 Diag(Warnings[Warn].OldParm->getLocation(),
4280 diag::note_previous_declaration);
4281 }
4282
4283 if (MergeTypeWithOld)
4284 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4285 OldProto->getExtProtoInfo()));
4286 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4287 }
4288
4289 // Fall through to diagnose conflicting types.
4290 }
4291
4292 // A function that has already been declared has been redeclared or
4293 // defined with a different type; show an appropriate diagnostic.
4294
4295 // If the previous declaration was an implicitly-generated builtin
4296 // declaration, then at the very least we should use a specialized note.
4297 unsigned BuiltinID;
4298 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4299 // If it's actually a library-defined builtin function like 'malloc'
4300 // or 'printf', just warn about the incompatible redeclaration.
4302 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4303 Diag(OldLocation, diag::note_previous_builtin_declaration)
4304 << Old << Old->getType();
4305 return false;
4306 }
4307
4308 PrevDiag = diag::note_previous_builtin_declaration;
4309 }
4310
4311 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4312 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4313 return true;
4314}
4315
4317 Scope *S, bool MergeTypeWithOld) {
4318 // Merge the attributes
4319 mergeDeclAttributes(New, Old);
4320
4321 // Merge "pure" flag.
4322 if (Old->isPureVirtual())
4323 New->setIsPureVirtual();
4324
4325 // Merge "used" flag.
4326 if (Old->getMostRecentDecl()->isUsed(false))
4327 New->setIsUsed();
4328
4329 // Merge attributes from the parameters. These can mismatch with K&R
4330 // declarations.
4331 if (New->getNumParams() == Old->getNumParams())
4332 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4333 ParmVarDecl *NewParam = New->getParamDecl(i);
4334 ParmVarDecl *OldParam = Old->getParamDecl(i);
4335 mergeParamDeclAttributes(NewParam, OldParam, *this);
4336 mergeParamDeclTypes(NewParam, OldParam, *this);
4337 }
4338
4339 if (getLangOpts().CPlusPlus)
4340 return MergeCXXFunctionDecl(New, Old, S);
4341
4342 // Merge the function types so the we get the composite types for the return
4343 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4344 // was visible.
4345 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4346 if (!Merged.isNull() && MergeTypeWithOld)
4347 New->setType(Merged);
4348
4349 return false;
4350}
4351
4353 ObjCMethodDecl *oldMethod) {
4354 // Merge the attributes, including deprecated/unavailable
4355 AvailabilityMergeKind MergeKind =
4356 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4359 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4360 : AMK_Override;
4361
4362 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4363
4364 // Merge attributes from the parameters.
4366 oe = oldMethod->param_end();
4368 ni = newMethod->param_begin(), ne = newMethod->param_end();
4369 ni != ne && oi != oe; ++ni, ++oi)
4370 mergeParamDeclAttributes(*ni, *oi, *this);
4371
4372 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4373}
4374
4376 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4377
4379 ? diag::err_redefinition_different_type
4380 : diag::err_redeclaration_different_type)
4381 << New->getDeclName() << New->getType() << Old->getType();
4382
4383 diag::kind PrevDiag;
4384 SourceLocation OldLocation;
4385 std::tie(PrevDiag, OldLocation)
4387 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4388 New->setInvalidDecl();
4389}
4390
4392 bool MergeTypeWithOld) {
4393 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4394 return;
4395
4396 QualType MergedT;
4397 if (getLangOpts().CPlusPlus) {
4398 if (New->getType()->isUndeducedType()) {
4399 // We don't know what the new type is until the initializer is attached.
4400 return;
4401 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4402 // These could still be something that needs exception specs checked.
4403 return MergeVarDeclExceptionSpecs(New, Old);
4404 }
4405 // C++ [basic.link]p10:
4406 // [...] the types specified by all declarations referring to a given
4407 // object or function shall be identical, except that declarations for an
4408 // array object can specify array types that differ by the presence or
4409 // absence of a major array bound (8.3.4).
4410 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4411 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4412 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4413
4414 // We are merging a variable declaration New into Old. If it has an array
4415 // bound, and that bound differs from Old's bound, we should diagnose the
4416 // mismatch.
4417 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4418 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4419 PrevVD = PrevVD->getPreviousDecl()) {
4420 QualType PrevVDTy = PrevVD->getType();
4421 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4422 continue;
4423
4424 if (!Context.hasSameType(New->getType(), PrevVDTy))
4425 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4426 }
4427 }
4428
4429 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4430 if (Context.hasSameType(OldArray->getElementType(),
4431 NewArray->getElementType()))
4432 MergedT = New->getType();
4433 }
4434 // FIXME: Check visibility. New is hidden but has a complete type. If New
4435 // has no array bound, it should not inherit one from Old, if Old is not
4436 // visible.
4437 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4438 if (Context.hasSameType(OldArray->getElementType(),
4439 NewArray->getElementType()))
4440 MergedT = Old->getType();
4441 }
4442 }
4443 else if (New->getType()->isObjCObjectPointerType() &&
4444 Old->getType()->isObjCObjectPointerType()) {
4445 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4446 Old->getType());
4447 }
4448 } else {
4449 // C 6.2.7p2:
4450 // All declarations that refer to the same object or function shall have
4451 // compatible type.
4452 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4453 }
4454 if (MergedT.isNull()) {
4455 // It's OK if we couldn't merge types if either type is dependent, for a
4456 // block-scope variable. In other cases (static data members of class
4457 // templates, variable templates, ...), we require the types to be
4458 // equivalent.
4459 // FIXME: The C++ standard doesn't say anything about this.
4460 if ((New->getType()->isDependentType() ||
4461 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4462 // If the old type was dependent, we can't merge with it, so the new type
4463 // becomes dependent for now. We'll reproduce the original type when we
4464 // instantiate the TypeSourceInfo for the variable.
4465 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4467 return;
4468 }
4469 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4470 }
4471
4472 // Don't actually update the type on the new declaration if the old
4473 // declaration was an extern declaration in a different scope.
4474 if (MergeTypeWithOld)
4475 New->setType(MergedT);
4476}
4477
4478static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4480 // C11 6.2.7p4:
4481 // For an identifier with internal or external linkage declared
4482 // in a scope in which a prior declaration of that identifier is
4483 // visible, if the prior declaration specifies internal or
4484 // external linkage, the type of the identifier at the later
4485 // declaration becomes the composite type.
4486 //
4487 // If the variable isn't visible, we do not merge with its type.
4488 if (Previous.isShadowed())
4489 return false;
4490
4491 if (S.getLangOpts().CPlusPlus) {
4492 // C++11 [dcl.array]p3:
4493 // If there is a preceding declaration of the entity in the same
4494 // scope in which the bound was specified, an omitted array bound
4495 // is taken to be the same as in that earlier declaration.
4496 return NewVD->isPreviousDeclInSameBlockScope() ||
4499 } else {
4500 // If the old declaration was function-local, don't merge with its
4501 // type unless we're in the same function.
4502 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4503 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4504 }
4505}
4506
4508 // If the new decl is already invalid, don't do any other checking.
4509 if (New->isInvalidDecl())
4510 return;
4511
4512 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4513 return;
4514
4515 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4516
4517 // Verify the old decl was also a variable or variable template.
4518 VarDecl *Old = nullptr;
4519 VarTemplateDecl *OldTemplate = nullptr;
4520 if (Previous.isSingleResult()) {
4521 if (NewTemplate) {
4522 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4523 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4524
4525 if (auto *Shadow =
4526 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4527 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4528 return New->setInvalidDecl();
4529 } else {
4530 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4531
4532 if (auto *Shadow =
4533 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4534 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4535 return New->setInvalidDecl();
4536 }
4537 }
4538 if (!Old) {
4539 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4540 << New->getDeclName();
4541 notePreviousDefinition(Previous.getRepresentativeDecl(),
4542 New->getLocation());
4543 return New->setInvalidDecl();
4544 }
4545
4546 // If the old declaration was found in an inline namespace and the new
4547 // declaration was qualified, update the DeclContext to match.
4549
4550 // Ensure the template parameters are compatible.
4551 if (NewTemplate &&
4553 OldTemplate->getTemplateParameters(),
4554 /*Complain=*/true, TPL_TemplateMatch))
4555 return New->setInvalidDecl();
4556
4557 // C++ [class.mem]p1:
4558 // A member shall not be declared twice in the member-specification [...]
4559 //
4560 // Here, we need only consider static data members.
4561 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4562 Diag(New->getLocation(), diag::err_duplicate_member)
4563 << New->getIdentifier();
4564 Diag(Old->getLocation(), diag::note_previous_declaration);
4565 New->setInvalidDecl();
4566 }
4567
4568 mergeDeclAttributes(New, Old);
4569 // Warn if an already-defined variable is made a weak_import in a subsequent
4570 // declaration
4571 if (New->hasAttr<WeakImportAttr>())
4572 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4573 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4574 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4575 Diag(D->getLocation(), diag::note_previous_definition);
4576 // Remove weak_import attribute on new declaration.
4577 New->dropAttr<WeakImportAttr>();
4578 break;
4579 }
4580 }
4581
4582 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4583 if (!Old->hasAttr<InternalLinkageAttr>()) {
4584 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4585 << ILA;
4586 Diag(Old->getLocation(), diag::note_previous_declaration);
4587 New->dropAttr<InternalLinkageAttr>();
4588 }
4589
4590 // Merge the types.
4591 VarDecl *MostRecent = Old->getMostRecentDecl();
4592 if (MostRecent != Old) {
4593 MergeVarDeclTypes(New, MostRecent,
4594 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4595 if (New->isInvalidDecl())
4596 return;
4597 }
4598
4599 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4600 if (New->isInvalidDecl())
4601 return;
4602
4603 diag::kind PrevDiag;
4604 SourceLocation OldLocation;
4605 std::tie(PrevDiag, OldLocation) =
4607
4608 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4609 if (New->getStorageClass() == SC_Static &&
4610 !New->isStaticDataMember() &&
4611 Old->hasExternalFormalLinkage()) {
4612 if (getLangOpts().MicrosoftExt) {
4613 Diag(New->getLocation(), diag::ext_static_non_static)
4614 << New->getDeclName();
4615 Diag(OldLocation, PrevDiag);
4616 } else {
4617 Diag(New->getLocation(), diag::err_static_non_static)
4618 << New->getDeclName();
4619 Diag(OldLocation, PrevDiag);
4620 return New->setInvalidDecl();
4621 }
4622 }
4623 // C99 6.2.2p4:
4624 // For an identifier declared with the storage-class specifier
4625 // extern in a scope in which a prior declaration of that
4626 // identifier is visible,23) if the prior declaration specifies
4627 // internal or external linkage, the linkage of the identifier at
4628 // the later declaration is the same as the linkage specified at
4629 // the prior declaration. If no prior declaration is visible, or
4630 // if the prior declaration specifies no linkage, then the
4631 // identifier has external linkage.
4632 if (New->hasExternalStorage() && Old->hasLinkage())
4633 /* Okay */;
4634 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4635 !New->isStaticDataMember() &&
4637 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4638 Diag(OldLocation, PrevDiag);
4639 return New->setInvalidDecl();
4640 }
4641
4642 // Check if extern is followed by non-extern and vice-versa.
4643 if (New->hasExternalStorage() &&
4644 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4645 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4646 Diag(OldLocation, PrevDiag);
4647 return New->setInvalidDecl();
4648 }
4649 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4650 !New->hasExternalStorage()) {
4651 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4652 Diag(OldLocation, PrevDiag);
4653 return New->setInvalidDecl();
4654 }
4655
4656 if (CheckRedeclarationInModule(New, Old))
4657 return;
4658
4659 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4660
4661 // FIXME: The test for external storage here seems wrong? We still
4662 // need to check for mismatches.
4663 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4664 // Don't complain about out-of-line definitions of static members.
4665 !(Old->getLexicalDeclContext()->isRecord() &&
4666 !New->getLexicalDeclContext()->isRecord())) {
4667 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4668 Diag(OldLocation, PrevDiag);
4669 return New->setInvalidDecl();
4670 }
4671
4672 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4673 if (VarDecl *Def = Old->getDefinition()) {
4674 // C++1z [dcl.fcn.spec]p4:
4675 // If the definition of a variable appears in a translation unit before
4676 // its first declaration as inline, the program is ill-formed.
4677 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4678 Diag(Def->getLocation(), diag::note_previous_definition);
4679 }
4680 }
4681
4682 // If this redeclaration makes the variable inline, we may need to add it to
4683 // UndefinedButUsed.
4684 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4686 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4687 SourceLocation()));
4688
4689 if (New->getTLSKind() != Old->getTLSKind()) {
4690 if (!Old->getTLSKind()) {
4691 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4692 Diag(OldLocation, PrevDiag);
4693 } else if (!New->getTLSKind()) {
4694 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4695 Diag(OldLocation, PrevDiag);
4696 } else {
4697 // Do not allow redeclaration to change the variable between requiring
4698 // static and dynamic initialization.
4699 // FIXME: GCC allows this, but uses the TLS keyword on the first
4700 // declaration to determine the kind. Do we need to be compatible here?
4701 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4702 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4703 Diag(OldLocation, PrevDiag);
4704 }
4705 }
4706
4707 // C++ doesn't have tentative definitions, so go right ahead and check here.
4708 if (getLangOpts().CPlusPlus) {
4709 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4710 Old->getCanonicalDecl()->isConstexpr()) {
4711 // This definition won't be a definition any more once it's been merged.
4712 Diag(New->getLocation(),
4713 diag::warn_deprecated_redundant_constexpr_static_def);
4715 VarDecl *Def = Old->getDefinition();
4716 if (Def && checkVarDeclRedefinition(Def, New))
4717 return;
4718 }
4719 }
4720
4721 if (haveIncompatibleLanguageLinkages(Old, New)) {
4722 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4723 Diag(OldLocation, PrevDiag);
4724 New->setInvalidDecl();
4725 return;
4726 }
4727
4728 // Merge "used" flag.
4729 if (Old->getMostRecentDecl()->isUsed(false))
4730 New->setIsUsed();
4731
4732 // Keep a chain of previous declarations.
4733 New->setPreviousDecl(Old);
4734 if (NewTemplate)
4735 NewTemplate->setPreviousDecl(OldTemplate);
4736
4737 // Inherit access appropriately.
4738 New->setAccess(Old->getAccess());
4739 if (NewTemplate)
4740 NewTemplate->setAccess(New->getAccess());
4741
4742 if (Old->isInline())
4743 New->setImplicitlyInline();
4744}
4745
4747 SourceManager &SrcMgr = getSourceManager();
4748 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4749 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4750 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4751 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4752 auto &HSI = PP.getHeaderSearchInfo();
4753 StringRef HdrFilename =
4754 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4755
4756 auto noteFromModuleOrInclude = [&](Module *Mod,
4757 SourceLocation IncLoc) -> bool {
4758 // Redefinition errors with modules are common with non modular mapped
4759 // headers, example: a non-modular header H in module A that also gets
4760 // included directly in a TU. Pointing twice to the same header/definition
4761 // is confusing, try to get better diagnostics when modules is on.
4762 if (IncLoc.isValid()) {
4763 if (Mod) {
4764 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4765 << HdrFilename.str() << Mod->getFullModuleName();
4766 if (!Mod->DefinitionLoc.isInvalid())
4767 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4768 << Mod->getFullModuleName();
4769 } else {
4770 Diag(IncLoc, diag::note_redefinition_include_same_file)
4771 << HdrFilename.str();
4772 }
4773 return true;
4774 }
4775
4776 return false;
4777 };
4778
4779 // Is it the same file and same offset? Provide more information on why
4780 // this leads to a redefinition error.
4781 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4782 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4783 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4784 bool EmittedDiag =
4785 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4786 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4787
4788 // If the header has no guards, emit a note suggesting one.
4789 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4790 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4791
4792 if (EmittedDiag)
4793 return;
4794 }
4795
4796 // Redefinition coming from different files or couldn't do better above.
4797 if (Old->getLocation().isValid())
4798 Diag(Old->getLocation(), diag::note_previous_definition);
4799}
4800
4802 if (!hasVisibleDefinition(Old) &&
4803 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4804 isa<VarTemplateSpecializationDecl>(New) ||
4807 // The previous definition is hidden, and multiple definitions are
4808 // permitted (in separate TUs). Demote this to a declaration.
4810
4811 // Make the canonical definition visible.
4812 if (auto *OldTD = Old->getDescribedVarTemplate())
4815 return false;
4816 } else {
4817 Diag(New->getLocation(), diag::err_redefinition) << New;
4819 New->setInvalidDecl();
4820 return true;
4821 }
4822}
4823
4825 DeclSpec &DS,
4826 const ParsedAttributesView &DeclAttrs,
4827 RecordDecl *&AnonRecord) {
4829 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4830}
4831
4832// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4833// disambiguate entities defined in different scopes.
4834// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4835// compatibility.
4836// We will pick our mangling number depending on which version of MSVC is being
4837// targeted.
4838static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4840 ? S->getMSCurManglingNumber()
4841 : S->getMSLastManglingNumber();
4842}
4843
4844void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4845 if (!Context.getLangOpts().CPlusPlus)
4846 return;
4847
4848 if (isa<CXXRecordDecl>(Tag->getParent())) {
4849 // If this tag is the direct child of a class, number it if
4850 // it is anonymous.
4851 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4852 return;
4854 Context.getManglingNumberContext(Tag->getParent());
4856 Tag, MCtx.getManglingNumber(
4857 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4858 return;
4859 }
4860
4861 // If this tag isn't a direct child of a class, number it if it is local.
4863 Decl *ManglingContextDecl;
4864 std::tie(MCtx, ManglingContextDecl) =
4865 getCurrentMangleNumberContext(Tag->getDeclContext());
4866 if (MCtx) {
4868 Tag, MCtx->getManglingNumber(
4869 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4870 }
4871}
4872
4873namespace {
4874struct NonCLikeKind {
4875 enum {
4876 None,
4877 BaseClass,
4878 DefaultMemberInit,
4879 Lambda,
4880 Friend,
4881 OtherMember,
4882 Invalid,
4883 } Kind = None;
4885
4886 explicit operator bool() { return Kind != None; }
4887};
4888}
4889
4890/// Determine whether a class is C-like, according to the rules of C++
4891/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4892static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4893 if (RD->isInvalidDecl())
4894 return {NonCLikeKind::Invalid, {}};
4895
4896 // C++ [dcl.typedef]p9: [P1766R1]
4897 // An unnamed class with a typedef name for linkage purposes shall not
4898 //
4899 // -- have any base classes
4900 if (RD->getNumBases())
4901 return {NonCLikeKind::BaseClass,
4903 RD->bases_end()[-1].getEndLoc())};
4904 bool Invalid = false;
4905 for (Decl *D : RD->decls()) {
4906 // Don't complain about things we already diagnosed.
4907 if (D->isInvalidDecl()) {
4908 Invalid = true;
4909 continue;
4910 }
4911
4912 // -- have any [...] default member initializers
4913 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4914 if (FD->hasInClassInitializer()) {
4915 auto *Init = FD->getInClassInitializer();
4916 return {NonCLikeKind::DefaultMemberInit,
4917 Init ? Init->getSourceRange() : D->getSourceRange()};
4918 }
4919 continue;
4920 }
4921
4922 // FIXME: We don't allow friend declarations. This violates the wording of
4923 // P1766, but not the intent.
4924 if (isa<FriendDecl>(D))
4925 return {NonCLikeKind::Friend, D->getSourceRange()};
4926
4927 // -- declare any members other than non-static data members, member
4928 // enumerations, or member classes,
4929 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4930 isa<EnumDecl>(D))
4931 continue;
4932 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4933 if (!MemberRD) {
4934 if (D->isImplicit())
4935 continue;
4936 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4937 }
4938
4939 // -- contain a lambda-expression,
4940 if (MemberRD->isLambda())
4941 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4942
4943 // and all member classes shall also satisfy these requirements
4944 // (recursively).
4945 if (MemberRD->isThisDeclarationADefinition()) {
4946 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4947 return Kind;
4948 }
4949 }
4950
4951 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4952}
4953
4955 TypedefNameDecl *NewTD) {
4956 if (TagFromDeclSpec->isInvalidDecl())
4957 return;
4958
4959 // Do nothing if the tag already has a name for linkage purposes.
4960 if (TagFromDeclSpec->hasNameForLinkage())
4961 return;
4962
4963 // A well-formed anonymous tag must always be a TagUseKind::Definition.
4964 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4965
4966 // The type must match the tag exactly; no qualifiers allowed.
4968 Context.getTagDeclType(TagFromDeclSpec))) {
4969 if (getLangOpts().CPlusPlus)
4970 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4971 return;
4972 }
4973
4974 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4975 // An unnamed class with a typedef name for linkage purposes shall [be
4976 // C-like].
4977 //
4978 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4979 // shouldn't happen, but there are constructs that the language rule doesn't
4980 // disallow for which we can't reasonably avoid computing linkage early.
4981 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4982 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4983 : NonCLikeKind();
4984 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4985 if (NonCLike || ChangesLinkage) {
4986 if (NonCLike.Kind == NonCLikeKind::Invalid)
4987 return;
4988
4989 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4990 if (ChangesLinkage) {
4991 // If the linkage changes, we can't accept this as an extension.
4992 if (NonCLike.Kind == NonCLikeKind::None)
4993 DiagID = diag::err_typedef_changes_linkage;
4994 else
4995 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4996 }
4997
4998 SourceLocation FixitLoc =
4999 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5000 llvm::SmallString<40> TextToInsert;
5001 TextToInsert += ' ';
5002 TextToInsert += NewTD->getIdentifier()->getName();
5003
5004 Diag(FixitLoc, DiagID)
5005 << isa<TypeAliasDecl>(NewTD)
5006 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5007 if (NonCLike.Kind != NonCLikeKind::None) {
5008 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5009 << NonCLike.Kind - 1 << NonCLike.Range;
5010 }
5011 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5012 << NewTD << isa<TypeAliasDecl>(NewTD);
5013
5014 if (ChangesLinkage)
5015 return;
5016 }
5017
5018 // Otherwise, set this as the anon-decl typedef for the tag.
5019 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5020
5021 // Now that we have a name for the tag, process API notes again.
5022 ProcessAPINotes(TagFromDeclSpec);
5023}
5024
5025static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5027 switch (T) {
5029 return 0;
5031 return 1;
5033 return 2;
5035 return 3;
5036 case DeclSpec::TST_enum:
5037 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5038 if (ED->isScopedUsingClassTag())
5039 return 5;
5040 if (ED->isScoped())
5041 return 6;
5042 }
5043 return 4;
5044 default:
5045 llvm_unreachable("unexpected type specifier");
5046 }
5047}
5048
5050 DeclSpec &DS,
5051 const ParsedAttributesView &DeclAttrs,
5052 MultiTemplateParamsArg TemplateParams,
5053 bool IsExplicitInstantiation,
5054 RecordDecl *&AnonRecord,
5055 SourceLocation EllipsisLoc) {
5056 Decl *TagD = nullptr;
5057 TagDecl *Tag = nullptr;
5063 TagD = DS.getRepAsDecl();
5064
5065 if (!TagD) // We probably had an error
5066 return nullptr;
5067
5068 // Note that the above type specs guarantee that the
5069 // type rep is a Decl, whereas in many of the others
5070 // it's a Type.
5071 if (isa<TagDecl>(TagD))
5072 Tag = cast<TagDecl>(TagD);
5073 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5074 Tag = CTD->getTemplatedDecl();
5075 }
5076
5077 if (Tag) {
5078 handleTagNumbering(Tag, S);
5079 Tag->setFreeStanding();
5080 if (Tag->isInvalidDecl())
5081 return Tag;
5082 }
5083
5084 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5085 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5086 // or incomplete types shall not be restrict-qualified."
5087 if (TypeQuals & DeclSpec::TQ_restrict)
5089 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5090 << DS.getSourceRange();
5091 }
5092
5093 if (DS.isInlineSpecified())
5094 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5095 << getLangOpts().CPlusPlus17;
5096
5097 if (DS.hasConstexprSpecifier()) {
5098 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5099 // and definitions of functions and variables.
5100 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5101 // the declaration of a function or function template
5102 if (Tag)
5103 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5105 << static_cast<int>(DS.getConstexprSpecifier());
5106 else if (getLangOpts().C23)
5107 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5108 else
5109 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5110 << static_cast<int>(DS.getConstexprSpecifier());
5111 // Don't emit warnings after this error.
5112 return TagD;
5113 }
5114
5116
5117 if (DS.isFriendSpecified()) {
5118 // If we're dealing with a decl but not a TagDecl, assume that
5119 // whatever routines created it handled the friendship aspect.
5120 if (TagD && !Tag)
5121 return nullptr;
5122 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5123 }
5124
5125 assert(EllipsisLoc.isInvalid() &&
5126 "Friend ellipsis but not friend-specified?");
5127
5128 // Track whether this decl-specifier declares anything.
5129 bool DeclaresAnything = true;
5130
5131 // Handle anonymous struct definitions.
5132 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5133 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5135 if (getLangOpts().CPlusPlus ||
5136 Record->getDeclContext()->isRecord()) {
5137 // If CurContext is a DeclContext that can contain statements,
5138 // RecursiveASTVisitor won't visit the decls that
5139 // BuildAnonymousStructOrUnion() will put into CurContext.
5140 // Also store them here so that they can be part of the
5141 // DeclStmt that gets created in this case.
5142 // FIXME: Also return the IndirectFieldDecls created by
5143 // BuildAnonymousStructOr union, for the same reason?
5145 AnonRecord = Record;
5146 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5148 }
5149
5150 DeclaresAnything = false;
5151 }
5152 }
5153
5154 // C11 6.7.2.1p2:
5155 // A struct-declaration that does not declare an anonymous structure or
5156 // anonymous union shall contain a struct-declarator-list.
5157 //
5158 // This rule also existed in C89 and C99; the grammar for struct-declaration
5159 // did not permit a struct-declaration without a struct-declarator-list.
5162 // Check for Microsoft C extension: anonymous struct/union member.
5163 // Handle 2 kinds of anonymous struct/union:
5164 // struct STRUCT;
5165 // union UNION;
5166 // and
5167 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5168 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5169 if ((Tag && Tag->getDeclName()) ||
5171 RecordDecl *Record = nullptr;
5172 if (Tag)
5173 Record = dyn_cast<RecordDecl>(Tag);
5174 else if (const RecordType *RT =
5176 Record = RT->getDecl();
5177 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5178 Record = UT->getDecl();
5179
5180 if (Record && getLangOpts().MicrosoftExt) {
5181 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5182 << Record->isUnion() << DS.getSourceRange();
5184 }
5185
5186 DeclaresAnything = false;
5187 }
5188 }
5189
5190 // Skip all the checks below if we have a type error.
5192 (TagD && TagD->isInvalidDecl()))
5193 return TagD;
5194
5195 if (getLangOpts().CPlusPlus &&
5197 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5198 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5199 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5200 DeclaresAnything = false;
5201
5202 if (!DS.isMissingDeclaratorOk()) {
5203 // Customize diagnostic for a typedef missing a name.
5205 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5206 << DS.getSourceRange();
5207 else
5208 DeclaresAnything = false;
5209 }
5210
5211 if (DS.isModulePrivateSpecified() &&
5212 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5213 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5214 << llvm::to_underlying(Tag->getTagKind())
5216
5218
5219 // C 6.7/2:
5220 // A declaration [...] shall declare at least a declarator [...], a tag,
5221 // or the members of an enumeration.
5222 // C++ [dcl.dcl]p3:
5223 // [If there are no declarators], and except for the declaration of an
5224 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5225 // names into the program, or shall redeclare a name introduced by a
5226 // previous declaration.
5227 if (!DeclaresAnything) {
5228 // In C, we allow this as a (popular) extension / bug. Don't bother
5229 // producing further diagnostics for redundant qualifiers after this.
5230 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5231 ? diag::err_no_declarators
5232 : diag::ext_no_declarators)
5233 << DS.getSourceRange();
5234 return TagD;
5235 }
5236
5237 // C++ [dcl.stc]p1:
5238 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5239 // init-declarator-list of the declaration shall not be empty.
5240 // C++ [dcl.fct.spec]p1:
5241 // If a cv-qualifier appears in a decl-specifier-seq, the
5242 // init-declarator-list of the declaration shall not be empty.
5243 //
5244 // Spurious qualifiers here appear to be valid in C.
5245 unsigned DiagID = diag::warn_standalone_specifier;
5246 if (getLangOpts().CPlusPlus)
5247 DiagID = diag::ext_standalone_specifier;
5248
5249 // Note that a linkage-specification sets a storage class, but
5250 // 'extern "C" struct foo;' is actually valid and not theoretically
5251 // useless.
5252 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5253 if (SCS == DeclSpec::SCS_mutable)
5254 // Since mutable is not a viable storage class specifier in C, there is
5255 // no reason to treat it as an extension. Instead, diagnose as an error.
5256 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5257 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5258 Diag(DS.getStorageClassSpecLoc(), DiagID)
5260 }
5261
5265 if (DS.getTypeQualifiers()) {
5267 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5269 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5270 // Restrict is covered above.
5272 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5274 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5275 }
5276
5277 // Warn about ignored type attributes, for example:
5278 // __attribute__((aligned)) struct A;
5279 // Attributes should be placed after tag to apply to type declaration.
5280 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5281 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5282 if (TypeSpecType == DeclSpec::TST_class ||
5283 TypeSpecType == DeclSpec::TST_struct ||
5284 TypeSpecType == DeclSpec::TST_interface ||
5285 TypeSpecType == DeclSpec::TST_union ||
5286 TypeSpecType == DeclSpec::TST_enum) {
5287
5288 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5289 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5290 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5291 DiagnosticId = diag::warn_attribute_ignored;
5292 else if (AL.isRegularKeywordAttribute())
5293 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5294 else
5295 DiagnosticId = diag::warn_declspec_attribute_ignored;
5296 Diag(AL.getLoc(), DiagnosticId)
5297 << AL << GetDiagnosticTypeSpecifierID(DS);
5298 };
5299
5300 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5301 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5302 }
5303 }
5304
5305 return TagD;
5306}
5307
5308/// We are trying to inject an anonymous member into the given scope;
5309/// check if there's an existing declaration that can't be overloaded.
5310///
5311/// \return true if this is a forbidden redeclaration
5312static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5313 DeclContext *Owner,
5314 DeclarationName Name,
5315 SourceLocation NameLoc, bool IsUnion,
5316 StorageClass SC) {
5317 LookupResult R(SemaRef, Name, NameLoc,
5320 RedeclarationKind::ForVisibleRedeclaration);
5321 if (!SemaRef.LookupName(R, S)) return false;
5322
5323 // Pick a representative declaration.
5325 assert(PrevDecl && "Expected a non-null Decl");
5326
5327 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5328 return false;
5329
5330 if (SC == StorageClass::SC_None &&
5331 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5332 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5333 if (!Owner->isRecord())
5334 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5335 return false;
5336 }
5337
5338 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5339 << IsUnion << Name;
5340 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5341
5342 return true;
5343}
5344
5346 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5348}
5349
5351 if (!getLangOpts().CPlusPlus)
5352 return;
5353
5354 // This function can be parsed before we have validated the
5355 // structure as an anonymous struct
5356 if (Record->isAnonymousStructOrUnion())
5357 return;
5358
5359 const NamedDecl *First = 0;
5360 for (const Decl *D : Record->decls()) {
5361 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5362 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5363 continue;
5364 if (!First)
5365 First = ND;
5366 else
5368 }
5369}
5370
5371/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5372/// anonymous struct or union AnonRecord into the owning context Owner
5373/// and scope S. This routine will be invoked just after we realize
5374/// that an unnamed union or struct is actually an anonymous union or
5375/// struct, e.g.,
5376///
5377/// @code
5378/// union {
5379/// int i;
5380/// float f;
5381/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5382/// // f into the surrounding scope.x
5383/// @endcode
5384///
5385/// This routine is recursive, injecting the names of nested anonymous
5386/// structs/unions into the owning context and scope as well.
5387static bool
5389 RecordDecl *AnonRecord, AccessSpecifier AS,
5390 StorageClass SC,
5391 SmallVectorImpl<NamedDecl *> &Chaining) {
5392 bool Invalid = false;
5393
5394 // Look every FieldDecl and IndirectFieldDecl with a name.
5395 for (auto *D : AnonRecord->decls()) {
5396 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5397 cast<NamedDecl>(D)->getDeclName()) {
5398 ValueDecl *VD = cast<ValueDecl>(D);
5399 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5400 VD->getLocation(), AnonRecord->isUnion(),
5401 SC)) {
5402 // C++ [class.union]p2:
5403 // The names of the members of an anonymous union shall be
5404 // distinct from the names of any other entity in the
5405 // scope in which the anonymous union is declared.
5406 Invalid = true;
5407 } else {
5408 // C++ [class.union]p2:
5409 // For the purpose of name lookup, after the anonymous union
5410 // definition, the members of the anonymous union are
5411 // considered to have been defined in the scope in which the
5412 // anonymous union is declared.
5413 unsigned OldChainingSize = Chaining.size();
5414 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5415 Chaining.append(IF->chain_begin(), IF->chain_end());
5416 else
5417 Chaining.push_back(VD);
5418
5419 assert(Chaining.size() >= 2);
5420 NamedDecl **NamedChain =
5421 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5422 for (unsigned i = 0; i < Chaining.size(); i++)
5423 NamedChain[i] = Chaining[i];
5424
5426 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5427 VD->getType(), {NamedChain, Chaining.size()});
5428
5429 for (const auto *Attr : VD->attrs())
5430 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5431
5432 IndirectField->setAccess(AS);
5433 IndirectField->setImplicit();
5434 SemaRef.PushOnScopeChains(IndirectField, S);
5435
5436 // That includes picking up the appropriate access specifier.
5437 if (AS != AS_none) IndirectField->setAccess(AS);
5438
5439 Chaining.resize(OldChainingSize);
5440 }
5441 }
5442 }
5443
5444 return Invalid;
5445}
5446
5447/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5448/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5449/// illegal input values are mapped to SC_None.
5450static StorageClass
5452 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5453 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5454 "Parser allowed 'typedef' as storage class VarDecl.");
5455 switch (StorageClassSpec) {
5458 if (DS.isExternInLinkageSpec())
5459 return SC_None;
5460 return SC_Extern;
5461 case DeclSpec::SCS_static: return SC_Static;
5462 case DeclSpec::SCS_auto: return SC_Auto;
5465 // Illegal SCSs map to None: error reporting is up to the caller.
5466 case DeclSpec::SCS_mutable: // Fall through.
5467 case DeclSpec::SCS_typedef: return SC_None;
5468 }
5469 llvm_unreachable("unknown storage class specifier");
5470}
5471
5473 assert(Record->hasInClassInitializer());
5474
5475 for (const auto *I : Record->decls()) {
5476 const auto *FD = dyn_cast<FieldDecl>(I);
5477 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5478 FD = IFD->getAnonField();
5479 if (FD && FD->hasInClassInitializer())
5480 return FD->getLocation();
5481 }
5482
5483 llvm_unreachable("couldn't find in-class initializer");
5484}
5485
5487 SourceLocation DefaultInitLoc) {
5488 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5489 return;
5490
5491 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5492 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5493}
5494
5496 CXXRecordDecl *AnonUnion) {
5497 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5498 return;
5499
5501}
5502
5504 AccessSpecifier AS,
5506 const PrintingPolicy &Policy) {
5507 DeclContext *Owner = Record->getDeclContext();
5508
5509 // Diagnose whether this anonymous struct/union is an extension.
5510 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5511 Diag(Record->getLocation(), diag::ext_anonymous_union);
5512 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5513 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5514 else if (!Record->isUnion() && !getLangOpts().C11)
5515 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5516
5517 // C and C++ require different kinds of checks for anonymous
5518 // structs/unions.
5519 bool Invalid = false;
5520 if (getLangOpts().CPlusPlus) {
5521 const char *PrevSpec = nullptr;
5522 if (Record->isUnion()) {
5523 // C++ [class.union]p6:
5524 // C++17 [class.union.anon]p2:
5525 // Anonymous unions declared in a named namespace or in the
5526 // global namespace shall be declared static.
5527 unsigned DiagID;
5528 DeclContext *OwnerScope = Owner->getRedeclContext();
5530 (OwnerScope->isTranslationUnit() ||
5531 (OwnerScope->isNamespace() &&
5532 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5533 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5534 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5535
5536 // Recover by adding 'static'.
5538 PrevSpec, DiagID, Policy);
5539 }
5540 // C++ [class.union]p6:
5541 // A storage class is not allowed in a declaration of an
5542 // anonymous union in a class scope.
5544 isa<RecordDecl>(Owner)) {
5546 diag::err_anonymous_union_with_storage_spec)
5548
5549 // Recover by removing the storage specifier.
5552 PrevSpec, DiagID, Context.getPrintingPolicy());
5553 }
5554 }
5555
5556 // Ignore const/volatile/restrict qualifiers.
5557 if (DS.getTypeQualifiers()) {
5559 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5560 << Record->isUnion() << "const"
5564 diag::ext_anonymous_struct_union_qualified)
5565 << Record->isUnion() << "volatile"
5569 diag::ext_anonymous_struct_union_qualified)
5570 << Record->isUnion() << "restrict"
5574 diag::ext_anonymous_struct_union_qualified)
5575 << Record->isUnion() << "_Atomic"
5579 diag::ext_anonymous_struct_union_qualified)
5580 << Record->isUnion() << "__unaligned"
5582
5584 }
5585
5586 // C++ [class.union]p2:
5587 // The member-specification of an anonymous union shall only
5588 // define non-static data members. [Note: nested types and
5589 // functions cannot be declared within an anonymous union. ]
5590 for (auto *Mem : Record->decls()) {
5591 // Ignore invalid declarations; we already diagnosed them.
5592 if (Mem->isInvalidDecl())
5593 continue;
5594
5595 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5596 // C++ [class.union]p3:
5597 // An anonymous union shall not have private or protected
5598 // members (clause 11).
5599 assert(FD->getAccess() != AS_none);
5600 if (FD->getAccess() != AS_public) {
5601 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5602 << Record->isUnion() << (FD->getAccess() == AS_protected);
5603 Invalid = true;
5604 }
5605
5606 // C++ [class.union]p1
5607 // An object of a class with a non-trivial constructor, a non-trivial
5608 // copy constructor, a non-trivial destructor, or a non-trivial copy
5609 // assignment operator cannot be a member of a union, nor can an
5610 // array of such objects.
5611 if (CheckNontrivialField(FD))
5612 Invalid = true;
5613 } else if (Mem->isImplicit()) {
5614 // Any implicit members are fine.
5615 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5616 // This is a type that showed up in an
5617 // elaborated-type-specifier inside the anonymous struct or
5618 // union, but which actually declares a type outside of the
5619 // anonymous struct or union. It's okay.
5620 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5621 if (!MemRecord->isAnonymousStructOrUnion() &&
5622 MemRecord->getDeclName()) {
5623 // Visual C++ allows type definition in anonymous struct or union.
5624 if (getLangOpts().MicrosoftExt)
5625 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5626 << Record->isUnion();
5627 else {
5628 // This is a nested type declaration.
5629 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5630 << Record->isUnion();
5631 Invalid = true;
5632 }
5633 } else {
5634 // This is an anonymous type definition within another anonymous type.
5635 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5636 // not part of standard C++.
5637 Diag(MemRecord->getLocation(),
5638 diag::ext_anonymous_record_with_anonymous_type)
5639 << Record->isUnion();
5640 }
5641 } else if (isa<AccessSpecDecl>(Mem)) {
5642 // Any access specifier is fine.
5643 } else if (isa<StaticAssertDecl>(Mem)) {
5644 // In C++1z, static_assert declarations are also fine.
5645 } else {
5646 // We have something that isn't a non-static data
5647 // member. Complain about it.
5648 unsigned DK = diag::err_anonymous_record_bad_member;
5649 if (isa<TypeDecl>(Mem))
5650 DK = diag::err_anonymous_record_with_type;
5651 else if (isa<FunctionDecl>(Mem))
5652 DK = diag::err_anonymous_record_with_function;
5653 else if (isa<VarDecl>(Mem))
5654 DK = diag::err_anonymous_record_with_static;
5655
5656 // Visual C++ allows type definition in anonymous struct or union.
5657 if (getLangOpts().MicrosoftExt &&
5658 DK == diag::err_anonymous_record_with_type)
5659 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5660 << Record->isUnion();
5661 else {
5662 Diag(Mem->getLocation(), DK) << Record->isUnion();
5663 Invalid = true;
5664 }
5665 }
5666 }
5667
5668 // C++11 [class.union]p8 (DR1460):
5669 // At most one variant member of a union may have a
5670 // brace-or-equal-initializer.
5671 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5672 Owner->isRecord())
5673 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5674 cast<CXXRecordDecl>(Record));
5675 }
5676
5677 if (!Record->isUnion() && !Owner->isRecord()) {
5678 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5679 << getLangOpts().CPlusPlus;
5680 Invalid = true;
5681 }
5682
5683 // C++ [dcl.dcl]p3:
5684 // [If there are no declarators], and except for the declaration of an
5685 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5686 // names into the program
5687 // C++ [class.mem]p2:
5688 // each such member-declaration shall either declare at least one member
5689 // name of the class or declare at least one unnamed bit-field
5690 //
5691 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5692 if (getLangOpts().CPlusPlus && Record->field_empty())
5693 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5694
5695 // Mock up a declarator.
5699 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5700
5701 // Create a declaration for this anonymous struct/union.
5702 NamedDecl *Anon = nullptr;
5703 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5704 Anon = FieldDecl::Create(
5705 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5706 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5707 /*BitWidth=*/nullptr, /*Mutable=*/false,
5708 /*InitStyle=*/ICIS_NoInit);
5709 Anon->setAccess(AS);
5710 ProcessDeclAttributes(S, Anon, Dc);
5711
5712 if (getLangOpts().CPlusPlus)
5713 FieldCollector->Add(cast<FieldDecl>(Anon));
5714 } else {
5715 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5716 if (SCSpec == DeclSpec::SCS_mutable) {
5717 // mutable can only appear on non-static class members, so it's always
5718 // an error here
5719 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5720 Invalid = true;
5721 SC = SC_None;
5722 }
5723
5724 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5725 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5726 Context.getTypeDeclType(Record), TInfo, SC);
5727 if (Invalid)
5728 Anon->setInvalidDecl();
5729
5730 ProcessDeclAttributes(S, Anon, Dc);
5731
5732 // Default-initialize the implicit variable. This initialization will be
5733 // trivial in almost all cases, except if a union member has an in-class
5734 // initializer:
5735 // union { int n = 0; };
5737 }
5738 Anon->setImplicit();
5739
5740 // Mark this as an anonymous struct/union type.
5741 Record->setAnonymousStructOrUnion(true);
5742
5743 // Add the anonymous struct/union object to the current
5744 // context. We'll be referencing this object when we refer to one of
5745 // its members.
5746 Owner->addDecl(Anon);
5747
5748 // Inject the members of the anonymous struct/union into the owning
5749 // context and into the identifier resolver chain for name lookup
5750 // purposes.
5752 Chain.push_back(Anon);
5753
5754 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5755 Chain))
5756 Invalid = true;
5757
5758 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5759 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5761 Decl *ManglingContextDecl;
5762 std::tie(MCtx, ManglingContextDecl) =
5763 getCurrentMangleNumberContext(NewVD->getDeclContext());
5764 if (MCtx) {
5766 NewVD, MCtx->getManglingNumber(
5767 NewVD, getMSManglingNumber(getLangOpts(), S)));
5769 }
5770 }
5771 }
5772
5773 if (Invalid)
5774 Anon->setInvalidDecl();
5775
5776 return Anon;
5777}
5778
5780 RecordDecl *Record) {
5781 assert(Record && "expected a record!");
5782
5783 // Mock up a declarator.
5786 assert(TInfo && "couldn't build declarator info for anonymous struct");
5787
5788 auto *ParentDecl = cast<RecordDecl>(CurContext);
5790
5791 // Create a declaration for this anonymous struct.
5792 NamedDecl *Anon =
5793 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5794 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5795 /*BitWidth=*/nullptr, /*Mutable=*/false,
5796 /*InitStyle=*/ICIS_NoInit);
5797 Anon->setImplicit();
5798
5799 // Add the anonymous struct object to the current context.
5800 CurContext->addDecl(Anon);
5801
5802 // Inject the members of the anonymous struct into the current
5803 // context and into the identifier resolver chain for name lookup
5804 // purposes.
5806 Chain.push_back(Anon);
5807
5808 RecordDecl *RecordDef = Record->getDefinition();
5809 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5810 diag::err_field_incomplete_or_sizeless) ||
5812 *this, S, CurContext, RecordDef, AS_none,
5814 Anon->setInvalidDecl();
5815 ParentDecl->setInvalidDecl();
5816 }
5817
5818 return Anon;
5819}
5820
5822 return GetNameFromUnqualifiedId(D.getName());
5823}
5824
5827 DeclarationNameInfo NameInfo;
5828 NameInfo.setLoc(Name.StartLocation);
5829
5830 switch (Name.getKind()) {
5831
5834 NameInfo.setName(Name.Identifier);
5835 return NameInfo;
5836
5838 // C++ [temp.deduct.guide]p3:
5839 // The simple-template-id shall name a class template specialization.
5840 // The template-name shall be the same identifier as the template-name
5841 // of the simple-template-id.
5842 // These together intend to imply that the template-name shall name a
5843 // class template.
5844 // FIXME: template<typename T> struct X {};
5845 // template<typename T> using Y = X<T>;
5846 // Y(int) -> Y<int>;
5847 // satisfies these rules but does not name a class template.
5848 TemplateName TN = Name.TemplateName.get().get();
5849 auto *Template = TN.getAsTemplateDecl();
5850 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5851 Diag(Name.StartLocation,
5852 diag::err_deduction_guide_name_not_class_template)
5854 if (Template)
5855 NoteTemplateLocation(*Template);
5856 return DeclarationNameInfo();
5857 }
5858
5859 NameInfo.setName(
5861 return NameInfo;
5862 }
5863
5866 Name.OperatorFunctionId.Operator));
5868 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5869 return NameInfo;
5870
5873 Name.Identifier));
5874 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5875 return NameInfo;
5876
5878 TypeSourceInfo *TInfo;
5879 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5880 if (Ty.isNull())
5881 return DeclarationNameInfo();
5884 NameInfo.setNamedTypeInfo(TInfo);
5885 return NameInfo;
5886 }
5887
5889 TypeSourceInfo *TInfo;
5890 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5891 if (Ty.isNull())
5892 return DeclarationNameInfo();
5895 NameInfo.setNamedTypeInfo(TInfo);
5896 return NameInfo;
5897 }
5898
5900 // In well-formed code, we can only have a constructor
5901 // template-id that refers to the current context, so go there
5902 // to find the actual type being constructed.
5903 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5904 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5905 return DeclarationNameInfo();
5906
5907 // Determine the type of the class being constructed.
5908 QualType CurClassType = Context.getTypeDeclType(CurClass);
5909
5910 // FIXME: Check two things: that the template-id names the same type as
5911 // CurClassType, and that the template-id does not occur when the name
5912 // was qualified.
5913
5915 Context.getCanonicalType(CurClassType)));
5916 // FIXME: should we retrieve TypeSourceInfo?
5917 NameInfo.setNamedTypeInfo(nullptr);
5918 return NameInfo;
5919 }
5920
5922 TypeSourceInfo *TInfo;
5923 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5924 if (Ty.isNull())
5925 return DeclarationNameInfo();
5928 NameInfo.setNamedTypeInfo(TInfo);
5929 return NameInfo;
5930 }
5931
5933 TemplateName TName = Name.TemplateId->Template.get();
5934 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5935 return Context.getNameForTemplate(TName, TNameLoc);
5936 }
5937
5938 } // switch (Name.getKind())
5939
5940 llvm_unreachable("Unknown name kind");
5941}
5942
5944 do {
5945 if (Ty->isPointerOrReferenceType())
5946 Ty = Ty->getPointeeType();
5947 else if (Ty->isArrayType())
5949 else
5950 return Ty.withoutLocalFastQualifiers();
5951 } while (true);
5952}
5953
5954/// hasSimilarParameters - Determine whether the C++ functions Declaration
5955/// and Definition have "nearly" matching parameters. This heuristic is
5956/// used to improve diagnostics in the case where an out-of-line function
5957/// definition doesn't match any declaration within the class or namespace.
5958/// Also sets Params to the list of indices to the parameters that differ
5959/// between the declaration and the definition. If hasSimilarParameters
5960/// returns true and Params is empty, then all of the parameters match.
5964 SmallVectorImpl<unsigned> &Params) {
5965 Params.clear();
5966 if (Declaration->param_size() != Definition->param_size())
5967 return false;
5968 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5969 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5970 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5971
5972 // The parameter types are identical
5973 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5974 continue;
5975
5976 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5977 QualType DefParamBaseTy = getCoreType(DefParamTy);
5978 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5979 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5980
5981 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5982 (DeclTyName && DeclTyName == DefTyName))
5983 Params.push_back(Idx);
5984 else // The two parameters aren't even close
5985 return false;
5986 }
5987
5988 return true;
5989}
5990
5991/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5992/// declarator needs to be rebuilt in the current instantiation.
5993/// Any bits of declarator which appear before the name are valid for
5994/// consideration here. That's specifically the type in the decl spec
5995/// and the base type in any member-pointer chunks.
5997 DeclarationName Name) {
5998 // The types we specifically need to rebuild are:
5999 // - typenames, typeofs, and decltypes
6000 // - types which will become injected class names
6001 // Of course, we also need to rebuild any type referencing such a
6002 // type. It's safest to just say "dependent", but we call out a
6003 // few cases here.
6004
6005 DeclSpec &DS = D.getMutableDeclSpec();
6006 switch (DS.getTypeSpecType()) {
6010#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6011#include "clang/Basic/TransformTypeTraits.def"
6012 case DeclSpec::TST_atomic: {
6013 // Grab the type from the parser.
6014 TypeSourceInfo *TSI = nullptr;
6015 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6016 if (T.isNull() || !T->isInstantiationDependentType()) break;
6017
6018 // Make sure there's a type source info. This isn't really much
6019 // of a waste; most dependent types should have type source info
6020 // attached already.
6021 if (!TSI)
6023
6024 // Rebuild the type in the current instantiation.
6025 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6026 if (!TSI) return true;
6027
6028 // Store the new type back in the decl spec.
6029 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6030 DS.UpdateTypeRep(LocType);
6031 break;
6032 }
6033
6037 Expr *E = DS.getRepAsExpr();
6039 if (Result.isInvalid()) return true;
6040 DS.UpdateExprRep(Result.get());
6041 break;
6042 }
6043
6044 default:
6045 // Nothing to do for these decl specs.
6046 break;
6047 }
6048
6049 // It doesn't matter what order we do this in.
6050 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6051 DeclaratorChunk &Chunk = D.getTypeObject(I);
6052
6053 // The only type information in the declarator which can come
6054 // before the declaration name is the base type of a member
6055 // pointer.
6057 continue;
6058
6059 // Rebuild the scope specifier in-place.
6060 CXXScopeSpec &SS = Chunk.Mem.Scope();
6062 return true;
6063 }
6064
6065 return false;
6066}
6067
6068/// Returns true if the declaration is declared in a system header or from a
6069/// system macro.
6071 return SM.isInSystemHeader(D->getLocation()) ||
6072 SM.isInSystemMacro(D->getLocation());
6073}
6074
6076 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6077 // of system decl.
6078 if (D->getPreviousDecl() || D->isImplicit())
6079 return;
6080 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6083 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6084 << D << static_cast<int>(Status);
6085 }
6086}
6087
6089 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6090
6091 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6092 // declaration only if the `bind_to_declaration` extension is set.
6094 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6095 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6096 llvm::omp::TraitProperty::
6097 implementation_extension_bind_to_declaration))
6099 S, D, MultiTemplateParamsArg(), Bases);
6100
6102
6104 Dcl && Dcl->getDeclContext()->isFileContext())
6106
6107 if (!Bases.empty())
6109 Bases);
6110
6111 return Dcl;
6112}
6113
6115 DeclarationNameInfo NameInfo) {
6116 DeclarationName Name = NameInfo.getName();
6117
6118 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6119 while (Record && Record->isAnonymousStructOrUnion())
6120 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6121 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6122 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6123 return true;
6124 }
6125
6126 return false;
6127}
6128
6130 DeclarationName Name,
6132 TemplateIdAnnotation *TemplateId,
6133 bool IsMemberSpecialization) {
6134 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6135 "without nested-name-specifier");
6136 DeclContext *Cur = CurContext;
6137 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6138 Cur = Cur->getParent();
6139
6140 // If the user provided a superfluous scope specifier that refers back to the
6141 // class in which the entity is already declared, diagnose and ignore it.
6142 //
6143 // class X {
6144 // void X::f();
6145 // };
6146 //
6147 // Note, it was once ill-formed to give redundant qualification in all
6148 // contexts, but that rule was removed by DR482.
6149 if (Cur->Equals(DC)) {
6150 if (Cur->isRecord()) {
6151 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6152 : diag::err_member_extra_qualification)
6153 << Name << FixItHint::CreateRemoval(SS.getRange());
6154 SS.clear();
6155 } else {
6156 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6157 }
6158 return false;
6159 }
6160
6161 // Check whether the qualifying scope encloses the scope of the original
6162 // declaration. For a template-id, we perform the checks in
6163 // CheckTemplateSpecializationScope.
6164 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6165 if (Cur->isRecord())
6166 Diag(Loc, diag::err_member_qualification)
6167 << Name << SS.getRange();
6168 else if (isa<TranslationUnitDecl>(DC))
6169 Diag(Loc, diag::err_invalid_declarator_global_scope)
6170 << Name << SS.getRange();
6171 else if (isa<FunctionDecl>(Cur))
6172 Diag(Loc, diag::err_invalid_declarator_in_function)
6173 << Name << SS.getRange();
6174 else if (isa<BlockDecl>(Cur))
6175 Diag(Loc, diag::err_invalid_declarator_in_block)
6176 << Name << SS.getRange();
6177 else if (isa<ExportDecl>(Cur)) {
6178 if (!isa<NamespaceDecl>(DC))
6179 Diag(Loc, diag::err_export_non_namespace_scope_name)
6180 << Name << SS.getRange();
6181 else
6182 // The cases that DC is not NamespaceDecl should be handled in
6183 // CheckRedeclarationExported.
6184 return false;
6185 } else
6186 Diag(Loc, diag::err_invalid_declarator_scope)
6187 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6188
6189 return true;
6190 }
6191
6192 if (Cur->isRecord()) {
6193 // Cannot qualify members within a class.
6194 Diag(Loc, diag::err_member_qualification)
6195 << Name << SS.getRange();
6196 SS.clear();
6197
6198 // C++ constructors and destructors with incorrect scopes can break
6199 // our AST invariants by having the wrong underlying types. If
6200 // that's the case, then drop this declaration entirely.
6201 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6202 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6203 !Context.hasSameType(Name.getCXXNameType(),
6204 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6205 return true;
6206
6207 return false;
6208 }
6209
6210 // C++23 [temp.names]p5:
6211 // The keyword template shall not appear immediately after a declarative
6212 // nested-name-specifier.
6213 //
6214 // First check the template-id (if any), and then check each component of the
6215 // nested-name-specifier in reverse order.
6216 //
6217 // FIXME: nested-name-specifiers in friend declarations are declarative,
6218 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6219 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6220 Diag(Loc, diag::ext_template_after_declarative_nns)
6222
6224 do {
6225 if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6227 Diag(Loc, diag::ext_template_after_declarative_nns)
6229 SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6230
6231 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6232 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6233 // C++23 [expr.prim.id.qual]p3:
6234 // [...] If a nested-name-specifier N is declarative and has a
6235 // simple-template-id with a template argument list A that involves a
6236 // template parameter, let T be the template nominated by N without A.
6237 // T shall be a class template.
6238 if (TST->isDependentType() && TST->isTypeAlias())
6239 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6240 << SpecLoc.getLocalSourceRange();
6241 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6242 // C++23 [expr.prim.id.qual]p2:
6243 // [...] A declarative nested-name-specifier shall not have a
6244 // computed-type-specifier.
6245 //
6246 // CWG2858 changed this from 'decltype-specifier' to
6247 // 'computed-type-specifier'.
6248 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6249 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6250 }
6251 }
6252 } while ((SpecLoc = SpecLoc.getPrefix()));
6253
6254 return false;
6255}
6256
6258 MultiTemplateParamsArg TemplateParamLists) {
6259 // TODO: consider using NameInfo for diagnostic.
6261 DeclarationName Name = NameInfo.getName();
6262
6263 // All of these full declarators require an identifier. If it doesn't have
6264 // one, the ParsedFreeStandingDeclSpec action should be used.
6265 if (D.isDecompositionDeclarator()) {
6266 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6267 } else if (!Name) {
6268 if (!D.isInvalidType()) // Reject this if we think it is valid.
6269 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6270 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6271 return nullptr;
6273 return nullptr;
6274
6275 DeclContext *DC = CurContext;
6276 if (D.getCXXScopeSpec().isInvalid())
6277 D.setInvalidType();
6278 else if (D.getCXXScopeSpec().isSet()) {
6279 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6281 return nullptr;
6282
6283 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6284 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6285 if (!DC || isa<EnumDecl>(DC)) {
6286 // If we could not compute the declaration context, it's because the
6287 // declaration context is dependent but does not refer to a class,
6288 // class template, or class template partial specialization. Complain
6289 // and return early, to avoid the coming semantic disaster.
6290 Diag(D.getIdentifierLoc(),
6291 diag::err_template_qualified_declarator_no_match)
6292 << D.getCXXScopeSpec().getScopeRep()
6293 << D.getCXXScopeSpec().getRange();
6294 return nullptr;
6295 }
6296 bool IsDependentContext = DC->isDependentContext();
6297
6298 if (!IsDependentContext &&
6299 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6300 return nullptr;
6301
6302 // If a class is incomplete, do not parse entities inside it.
6303 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6304 Diag(D.getIdentifierLoc(),
6305 diag::err_member_def_undefined_record)
6306 << Name << DC << D.getCXXScopeSpec().getRange();
6307 return nullptr;
6308 }
6309 if (!D.getDeclSpec().isFriendSpecified()) {
6310 TemplateIdAnnotation *TemplateId =
6312 ? D.getName().TemplateId
6313 : nullptr;
6314 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name,
6315 D.getIdentifierLoc(), TemplateId,
6316 /*IsMemberSpecialization=*/false)) {
6317 if (DC->isRecord())
6318 return nullptr;
6319
6320 D.setInvalidType();
6321 }
6322 }
6323
6324 // Check whether we need to rebuild the type of the given
6325 // declaration in the current instantiation.
6326 if (EnteringContext && IsDependentContext &&
6327 TemplateParamLists.size() != 0) {
6328 ContextRAII SavedContext(*this, DC);
6330 D.setInvalidType();
6331 }
6332 }
6333
6335 QualType R = TInfo->getType();
6336
6337 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6339 D.setInvalidType();
6340
6341 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6343
6344 // See if this is a redefinition of a variable in the same scope.
6345 if (!D.getCXXScopeSpec().isSet()) {
6346 bool IsLinkageLookup = false;
6347 bool CreateBuiltins = false;
6348
6349 // If the declaration we're planning to build will be a function
6350 // or object with linkage, then look for another declaration with
6351 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6352 //
6353 // If the declaration we're planning to build will be declared with
6354 // external linkage in the translation unit, create any builtin with
6355 // the same name.
6356 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6357 /* Do nothing*/;
6358 else if (CurContext->isFunctionOrMethod() &&
6359 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6360 R->isFunctionType())) {
6361 IsLinkageLookup = true;
6362 CreateBuiltins =
6365 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6366 CreateBuiltins = true;
6367
6368 if (IsLinkageLookup) {
6370 Previous.setRedeclarationKind(
6371 RedeclarationKind::ForExternalRedeclaration);
6372 }
6373
6374 LookupName(Previous, S, CreateBuiltins);
6375 } else { // Something like "int foo::x;"
6377
6378 // C++ [dcl.meaning]p1:
6379 // When the declarator-id is qualified, the declaration shall refer to a
6380 // previously declared member of the class or namespace to which the
6381 // qualifier refers (or, in the case of a namespace, of an element of the
6382 // inline namespace set of that namespace (7.3.1)) or to a specialization
6383 // thereof; [...]
6384 //
6385 // Note that we already checked the context above, and that we do not have
6386 // enough information to make sure that Previous contains the declaration
6387 // we want to match. For example, given:
6388 //
6389 // class X {
6390 // void f();
6391 // void f(float);
6392 // };
6393 //
6394 // void X::f(int) { } // ill-formed
6395 //
6396 // In this case, Previous will point to the overload set
6397 // containing the two f's declared in X, but neither of them
6398 // matches.
6399
6401 }
6402
6403 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6404 TPD && TPD->isTemplateParameter()) {
6405 // Older versions of clang allowed the names of function/variable templates
6406 // to shadow the names of their template parameters. For the compatibility
6407 // purposes we detect such cases and issue a default-to-error warning that
6408 // can be disabled with -Wno-strict-primary-template-shadow.
6409 if (!D.isInvalidType()) {
6410 bool AllowForCompatibility = false;
6411 if (Scope *DeclParent = S->getDeclParent();
6412 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6413 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6414 TemplateParamParent->isDeclScope(TPD);
6415 }
6416 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
6417 AllowForCompatibility);
6418 }
6419
6420 // Just pretend that we didn't see the previous declaration.
6421 Previous.clear();
6422 }
6423
6424 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6425 // Forget that the previous declaration is the injected-class-name.
6426 Previous.clear();
6427
6428 // In C++, the previous declaration we find might be a tag type
6429 // (class or enum). In this case, the new declaration will hide the
6430 // tag type. Note that this applies to functions, function templates, and
6431 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6432 if (Previous.isSingleTagDecl() &&
6433 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6434 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6435 Previous.clear();
6436
6437 // Check that there are no default arguments other than in the parameters
6438 // of a function declaration (C++ only).
6439 if (getLangOpts().CPlusPlus)
6441
6442 /// Get the innermost enclosing declaration scope.
6443 S = S->getDeclParent();
6444
6445 NamedDecl *New;
6446
6447 bool AddToScope = true;
6448 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6449 if (TemplateParamLists.size()) {
6450 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6451 return nullptr;
6452 }
6453
6454 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6455 } else if (R->isFunctionType()) {
6456 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6457 TemplateParamLists,
6458 AddToScope);
6459 } else {
6460 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6461 AddToScope);
6462 }
6463
6464 if (!New)
6465 return nullptr;
6466
6467 // If this has an identifier and is not a function template specialization,
6468 // add it to the scope stack.
6469 if (New->getDeclName() && AddToScope)
6470 PushOnScopeChains(New, S);
6471
6472 if (OpenMP().isInOpenMPDeclareTargetContext())
6474
6475 return New;
6476}
6477
6478/// Helper method to turn variable array types into constant array
6479/// types in certain situations which would otherwise be errors (for
6480/// GCC compatibility).
6482 ASTContext &Context,
6483 bool &SizeIsNegative,
6484 llvm::APSInt &Oversized) {
6485 // This method tries to turn a variable array into a constant
6486 // array even when the size isn't an ICE. This is necessary
6487 // for compatibility with code that depends on gcc's buggy
6488 // constant expression folding, like struct {char x[(int)(char*)2];}
6489 SizeIsNegative = false;
6490 Oversized = 0;
6491
6492 if (T->isDependentType())
6493 return QualType();
6494
6496 const Type *Ty = Qs.strip(T);
6497
6498 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6499 QualType Pointee = PTy->getPointeeType();
6500 QualType FixedType =
6501 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6502 Oversized);
6503 if (FixedType.isNull()) return FixedType;
6504 FixedType = Context.getPointerType(FixedType);
6505 return Qs.apply(Context, FixedType);
6506 }
6507 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6508 QualType Inner = PTy->getInnerType();
6509 QualType FixedType =
6510 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6511 Oversized);
6512 if (FixedType.isNull()) return FixedType;
6513 FixedType = Context.getParenType(FixedType);
6514 return Qs.apply(Context, FixedType);
6515 }
6516
6517 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6518 if (!VLATy)
6519 return QualType();
6520
6521 QualType ElemTy = VLATy->getElementType();
6522 if (ElemTy->isVariablyModifiedType()) {
6523 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6524 SizeIsNegative, Oversized);
6525 if (ElemTy.isNull())
6526 return QualType();
6527 }
6528
6530 if (!VLATy->getSizeExpr() ||
6531 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6532 return QualType();
6533
6534 llvm::APSInt Res = Result.Val.getInt();
6535
6536 // Check whether the array size is negative.
6537 if (Res.isSigned() && Res.isNegative()) {
6538 SizeIsNegative = true;
6539 return QualType();
6540 }
6541
6542 // Check whether the array is too large to be addressed.
6543 unsigned ActiveSizeBits =
6544 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6545 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6546 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6547 : Res.getActiveBits();
6548 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6549 Oversized = Res;
6550 return QualType();
6551 }
6552
6553 QualType FoldedArrayType = Context.getConstantArrayType(
6554 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6555 return Qs.apply(Context, FoldedArrayType);
6556}
6557
6558static void
6560 SrcTL = SrcTL.getUnqualifiedLoc();
6561 DstTL = DstTL.getUnqualifiedLoc();
6562 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6563 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6564 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6565 DstPTL.getPointeeLoc());
6566 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6567 return;
6568 }
6569 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6570 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6571 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6572 DstPTL.getInnerLoc());
6573 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6574 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6575 return;
6576 }
6577 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6578 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6579 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6580 TypeLoc DstElemTL = DstATL.getElementLoc();
6581 if (VariableArrayTypeLoc SrcElemATL =
6582 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6583 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6584 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6585 } else {
6586 DstElemTL.initializeFullCopy(SrcElemTL);
6587 }
6588 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6589 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6590 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6591}
6592
6593/// Helper method to turn variable array types into constant array
6594/// types in certain situations which would otherwise be errors (for
6595/// GCC compatibility).
6596static TypeSourceInfo*
6598 ASTContext &Context,
6599 bool &SizeIsNegative,
6600 llvm::APSInt &Oversized) {
6601 QualType FixedTy
6602 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6603 SizeIsNegative, Oversized);
6604 if (FixedTy.isNull())
6605 return nullptr;
6606 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6608 FixedTInfo->getTypeLoc());
6609 return FixedTInfo;
6610}
6611
6614 unsigned FailedFoldDiagID) {
6615 bool SizeIsNegative;
6616 llvm::APSInt Oversized;
6618 TInfo, Context, SizeIsNegative, Oversized);
6619 if (FixedTInfo) {
6620 Diag(Loc, diag::ext_vla_folded_to_constant);
6621 TInfo = FixedTInfo;
6622 T = FixedTInfo->getType();
6623 return true;
6624 }
6625
6626 if (SizeIsNegative)
6627 Diag(Loc, diag::err_typecheck_negative_array_size);
6628 else if (Oversized.getBoolValue())
6629 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6630 else if (FailedFoldDiagID)
6631 Diag(Loc, FailedFoldDiagID);
6632 return false;
6633}
6634
6635void
6637 if (!getLangOpts().CPlusPlus &&
6639 // Don't need to track declarations in the TU in C.
6640 return;
6641
6642 // Note that we have a locally-scoped external with this name.
6644}
6645
6647 // FIXME: We can have multiple results via __attribute__((overloadable)).
6649 return Result.empty() ? nullptr : *Result.begin();
6650}
6651
6653 // FIXME: We should probably indicate the identifier in question to avoid
6654 // confusion for constructs like "virtual int a(), b;"
6655 if (DS.isVirtualSpecified())
6657 diag::err_virtual_non_function);
6658
6659 if (DS.hasExplicitSpecifier())
6661 diag::err_explicit_non_function);
6662
6663 if (DS.isNoreturnSpecified())
6665 diag::err_noreturn_non_function);
6666}
6667
6668NamedDecl*
6671 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6672 if (D.getCXXScopeSpec().isSet()) {
6673 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6674 << D.getCXXScopeSpec().getRange();
6675 D.setInvalidType();
6676 // Pretend we didn't see the scope specifier.
6677 DC = CurContext;
6678 Previous.clear();
6679 }
6680
6681 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6682
6683 if (D.getDeclSpec().isInlineSpecified())
6684 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6685 << getLangOpts().CPlusPlus17;
6686 if (D.getDeclSpec().hasConstexprSpecifier())
6687 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6688 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6689
6690 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6692 Diag(D.getName().StartLocation,
6693 diag::err_deduction_guide_invalid_specifier)
6694 << "typedef";
6695 else
6696 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6697 << D.getName().getSourceRange();
6698 return nullptr;
6699 }
6700
6701 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6702 if (!NewTD) return nullptr;
6703
6704 // Handle attributes prior to checking for duplicates in MergeVarDecl
6705 ProcessDeclAttributes(S, NewTD, D);
6706
6708
6709 bool Redeclaration = D.isRedeclaration();
6710 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6711 D.setRedeclaration(Redeclaration);
6712 return ND;
6713}
6714
6715void
6717 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6718 // then it shall have block scope.
6719 // Note that variably modified types must be fixed before merging the decl so
6720 // that redeclarations will match.
6721 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6722 QualType T = TInfo->getType();
6723 if (T->isVariablyModifiedType()) {
6725
6726 if (S->getFnParent() == nullptr) {
6727 bool SizeIsNegative;
6728 llvm::APSInt Oversized;
6729 TypeSourceInfo *FixedTInfo =
6731 SizeIsNegative,
6732 Oversized);
6733 if (FixedTInfo) {
6734 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6735 NewTD->setTypeSourceInfo(FixedTInfo);
6736 } else {
6737 if (SizeIsNegative)
6738 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6739 else if (T->isVariableArrayType())
6740 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6741 else if (Oversized.getBoolValue())
6742 Diag(NewTD->getLocation(), diag::err_array_too_large)
6743 << toString(Oversized, 10);
6744 else
6745 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6746 NewTD->setInvalidDecl();
6747 }
6748 }
6749 }
6750}
6751
6752NamedDecl*
6754 LookupResult &Previous, bool &Redeclaration) {
6755
6756 // Find the shadowed declaration before filtering for scope.
6757 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6758
6759 // Merge the decl with the existing one if appropriate. If the decl is
6760 // in an outer scope, it isn't the same thing.
6761 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6762 /*AllowInlineNamespace*/false);
6764 if (!Previous.empty()) {
6765 Redeclaration = true;
6766 MergeTypedefNameDecl(S, NewTD, Previous);
6767 } else {
6769 }
6770
6771 if (ShadowedDecl && !Redeclaration)
6772 CheckShadow(NewTD, ShadowedDecl, Previous);
6773
6774 // If this is the C FILE type, notify the AST context.
6775 if (IdentifierInfo *II = NewTD->getIdentifier())
6776 if (!NewTD->isInvalidDecl() &&
6778 switch (II->getNotableIdentifierID()) {
6779 case tok::NotableIdentifierKind::FILE:
6780 Context.setFILEDecl(NewTD);
6781 break;
6782 case tok::NotableIdentifierKind::jmp_buf:
6783 Context.setjmp_bufDecl(NewTD);
6784 break;
6785 case tok::NotableIdentifierKind::sigjmp_buf:
6787 break;
6788 case tok::NotableIdentifierKind::ucontext_t:
6790 break;
6791 case tok::NotableIdentifierKind::float_t:
6792 case tok::NotableIdentifierKind::double_t:
6793 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6794 break;
6795 default:
6796 break;
6797 }
6798 }
6799
6800 return NewTD;
6801}
6802
6803/// Determines whether the given declaration is an out-of-scope
6804/// previous declaration.
6805///
6806/// This routine should be invoked when name lookup has found a
6807/// previous declaration (PrevDecl) that is not in the scope where a
6808/// new declaration by the same name is being introduced. If the new
6809/// declaration occurs in a local scope, previous declarations with
6810/// linkage may still be considered previous declarations (C99
6811/// 6.2.2p4-5, C++ [basic.link]p6).
6812///
6813/// \param PrevDecl the previous declaration found by name
6814/// lookup
6815///
6816/// \param DC the context in which the new declaration is being
6817/// declared.
6818///
6819/// \returns true if PrevDecl is an out-of-scope previous declaration
6820/// for a new delcaration with the same name.
6821static bool
6823 ASTContext &Context) {
6824 if (!PrevDecl)
6825 return false;
6826
6827 if (!PrevDecl->hasLinkage())
6828 return false;
6829
6830 if (Context.getLangOpts().CPlusPlus) {
6831 // C++ [basic.link]p6:
6832 // If there is a visible declaration of an entity with linkage
6833 // having the same name and type, ignoring entities declared
6834 // outside the innermost enclosing namespace scope, the block
6835 // scope declaration declares that same entity and receives the
6836 // linkage of the previous declaration.
6837 DeclContext *OuterContext = DC->getRedeclContext();
6838 if (!OuterContext->isFunctionOrMethod())
6839 // This rule only applies to block-scope declarations.
6840 return false;
6841
6842 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6843 if (PrevOuterContext->isRecord())
6844 // We found a member function: ignore it.
6845 return false;
6846
6847 // Find the innermost enclosing namespace for the new and
6848 // previous declarations.
6849 OuterContext = OuterContext->getEnclosingNamespaceContext();
6850 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6851
6852 // The previous declaration is in a different namespace, so it
6853 // isn't the same function.
6854 if (!OuterContext->Equals(PrevOuterContext))
6855 return false;
6856 }
6857
6858 return true;
6859}
6860
6862 CXXScopeSpec &SS = D.getCXXScopeSpec();
6863 if (!SS.isSet()) return;
6865}
6866
6868 if (Decl->getType().hasAddressSpace())
6869 return;
6870 if (Decl->getType()->isDependentType())
6871 return;
6872 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6873 QualType Type = Var->getType();
6874 if (Type->isSamplerT() || Type->isVoidType())
6875 return;
6877 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6878 // __opencl_c_program_scope_global_variables feature, the address space
6879 // for a variable at program scope or a static or extern variable inside
6880 // a function are inferred to be __global.
6881 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6882 Var->hasGlobalStorage())
6883 ImplAS = LangAS::opencl_global;
6884 // If the original type from a decayed type is an array type and that array
6885 // type has no address space yet, deduce it now.
6886 if (auto DT = dyn_cast<DecayedType>(Type)) {
6887 auto OrigTy = DT->getOriginalType();
6888 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6889 // Add the address space to the original array type and then propagate
6890 // that to the element type through `getAsArrayType`.
6891 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6892 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6893 // Re-generate the decayed type.
6894 Type = Context.getDecayedType(OrigTy);
6895 }
6896 }
6898 // Apply any qualifiers (including address space) from the array type to
6899 // the element type. This implements C99 6.7.3p8: "If the specification of
6900 // an array type includes any type qualifiers, the element type is so
6901 // qualified, not the array type."
6902 if (Type->isArrayType())
6904 Decl->setType(Type);
6905 }
6906}
6907
6908static void checkWeakAttr(Sema &S, NamedDecl &ND) {
6909 // 'weak' only applies to declarations with external linkage.
6910 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6911 if (!ND.isExternallyVisible()) {
6912 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6913 ND.dropAttr<WeakAttr>();
6914 }
6915 }
6916}
6917
6918static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
6919 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6920 if (ND.isExternallyVisible()) {
6921 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6922 ND.dropAttrs<WeakRefAttr, AliasAttr>();
6923 }
6924 }
6925}
6926
6927static void checkAliasAttr(Sema &S, NamedDecl &ND) {
6928 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6929 if (VD->hasInit()) {
6930 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6931 assert(VD->isThisDeclarationADefinition() &&
6932 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6933 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6934 VD->dropAttr<AliasAttr>();
6935 }
6936 }
6937 }
6938}
6939
6940static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
6941 // 'selectany' only applies to externally visible variable declarations.
6942 // It does not apply to functions.
6943 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6944 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6945 S.Diag(Attr->getLocation(),
6946 diag::err_attribute_selectany_non_extern_data);
6947 ND.dropAttr<SelectAnyAttr>();
6948 }
6949 }
6950}
6951
6953 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
6954 if (!ND.isExternallyVisible())
6955 S.Diag(Attr->getLocation(),
6956 diag::warn_attribute_hybrid_patchable_non_extern);
6957 }
6958}
6959
6961 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6962 auto *VD = dyn_cast<VarDecl>(&ND);
6963 bool IsAnonymousNS = false;
6964 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6965 if (VD) {
6966 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6967 while (NS && !IsAnonymousNS) {
6968 IsAnonymousNS = NS->isAnonymousNamespace();
6969 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6970 }
6971 }
6972 // dll attributes require external linkage. Static locals may have external
6973 // linkage but still cannot be explicitly imported or exported.
6974 // In Microsoft mode, a variable defined in anonymous namespace must have
6975 // external linkage in order to be exported.
6976 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6977 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6978 (!AnonNSInMicrosoftMode &&
6979 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6980 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6981 << &ND << Attr;
6982 ND.setInvalidDecl();
6983 }
6984 }
6985}
6986
6988 // Check the attributes on the function type and function params, if any.
6989 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6990 FD = FD->getMostRecentDecl();
6991 // Don't declare this variable in the second operand of the for-statement;
6992 // GCC miscompiles that by ending its lifetime before evaluating the
6993 // third operand. See gcc.gnu.org/PR86769.
6995 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6996 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6997 TL = ATL.getModifiedLoc()) {
6998 // The [[lifetimebound]] attribute can be applied to the implicit object
6999 // parameter of a non-static member function (other than a ctor or dtor)
7000 // by applying it to the function type.
7001 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7002 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7003 int NoImplicitObjectError = -1;
7004 if (!MD)
7005 NoImplicitObjectError = 0;
7006 else if (MD->isStatic())
7007 NoImplicitObjectError = 1;
7008 else if (MD->isExplicitObjectMemberFunction())
7009 NoImplicitObjectError = 2;
7010 if (NoImplicitObjectError != -1) {
7011 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7012 << NoImplicitObjectError << A->getRange();
7013 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7014 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7015 << isa<CXXDestructorDecl>(MD) << A->getRange();
7016 } else if (MD->getReturnType()->isVoidType()) {
7017 S.Diag(
7018 MD->getLocation(),
7019 diag::
7020 err_lifetimebound_implicit_object_parameter_void_return_type);
7021 }
7022 }
7023 }
7024
7025 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7026 const ParmVarDecl *P = FD->getParamDecl(I);
7027
7028 // The [[lifetimebound]] attribute can be applied to a function parameter
7029 // only if the function returns a value.
7030 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7031 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7032 S.Diag(A->getLocation(),
7033 diag::err_lifetimebound_parameter_void_return_type);
7034 }
7035 }
7036 }
7037 }
7038}
7039
7041 // Ensure that an auto decl is deduced otherwise the checks below might cache
7042 // the wrong linkage.
7043 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7044
7045 checkWeakAttr(S, ND);
7046 checkWeakRefAttr(S, ND);
7047 checkAliasAttr(S, ND);
7048 checkSelectAnyAttr(S, ND);
7050 checkInheritableAttr(S, ND);
7052}
7053
7055 NamedDecl *NewDecl,
7056 bool IsSpecialization,
7057 bool IsDefinition) {
7058 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7059 return;
7060
7061 bool IsTemplate = false;
7062 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7063 OldDecl = OldTD->getTemplatedDecl();
7064 IsTemplate = true;
7065 if (!IsSpecialization)
7066 IsDefinition = false;
7067 }
7068 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7069 NewDecl = NewTD->getTemplatedDecl();
7070 IsTemplate = true;
7071 }
7072
7073 if (!OldDecl || !NewDecl)
7074 return;
7075
7076 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7077 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7078 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7079 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7080
7081 // dllimport and dllexport are inheritable attributes so we have to exclude
7082 // inherited attribute instances.
7083 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7084 (NewExportAttr && !NewExportAttr->isInherited());
7085
7086 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7087 // the only exception being explicit specializations.
7088 // Implicitly generated declarations are also excluded for now because there
7089 // is no other way to switch these to use dllimport or dllexport.
7090 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7091
7092 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7093 // Allow with a warning for free functions and global variables.
7094 bool JustWarn = false;
7095 if (!OldDecl->isCXXClassMember()) {
7096 auto *VD = dyn_cast<VarDecl>(OldDecl);
7097 if (VD && !VD->getDescribedVarTemplate())
7098 JustWarn = true;
7099 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7100 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7101 JustWarn = true;
7102 }
7103
7104 // We cannot change a declaration that's been used because IR has already
7105 // been emitted. Dllimported functions will still work though (modulo
7106 // address equality) as they can use the thunk.
7107 if (OldDecl->isUsed())
7108 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7109 JustWarn = false;
7110
7111 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7112 : diag::err_attribute_dll_redeclaration;
7113 S.Diag(NewDecl->getLocation(), DiagID)
7114 << NewDecl
7115 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7116 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7117 if (!JustWarn) {
7118 NewDecl->setInvalidDecl();
7119 return;
7120 }
7121 }
7122
7123 // A redeclaration is not allowed to drop a dllimport attribute, the only
7124 // exceptions being inline function definitions (except for function
7125 // templates), local extern declarations, qualified friend declarations or
7126 // special MSVC extension: in the last case, the declaration is treated as if
7127 // it were marked dllexport.
7128 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7129 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7130 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7131 // Ignore static data because out-of-line definitions are diagnosed
7132 // separately.
7133 IsStaticDataMember = VD->isStaticDataMember();
7134 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7136 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7137 IsInline = FD->isInlined();
7138 IsQualifiedFriend = FD->getQualifier() &&
7139 FD->getFriendObjectKind() == Decl::FOK_Declared;
7140 }
7141
7142 if (OldImportAttr && !HasNewAttr &&
7143 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7144 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7145 if (IsMicrosoftABI && IsDefinition) {
7146 if (IsSpecialization) {
7147 S.Diag(
7148 NewDecl->getLocation(),
7149 diag::err_attribute_dllimport_function_specialization_definition);
7150 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7151 NewDecl->dropAttr<DLLImportAttr>();
7152 } else {
7153 S.Diag(NewDecl->getLocation(),
7154 diag::warn_redeclaration_without_import_attribute)
7155 << NewDecl;
7156 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7157 NewDecl->dropAttr<DLLImportAttr>();
7158 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7159 S.Context, NewImportAttr->getRange()));
7160 }
7161 } else if (IsMicrosoftABI && IsSpecialization) {
7162 assert(!IsDefinition);
7163 // MSVC allows this. Keep the inherited attribute.
7164 } else {
7165 S.Diag(NewDecl->getLocation(),
7166 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7167 << NewDecl << OldImportAttr;
7168 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7169 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7170 OldDecl->dropAttr<DLLImportAttr>();
7171 NewDecl->dropAttr<DLLImportAttr>();
7172 }
7173 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7174 // In MinGW, seeing a function declared inline drops the dllimport
7175 // attribute.
7176 OldDecl->dropAttr<DLLImportAttr>();
7177 NewDecl->dropAttr<DLLImportAttr>();
7178 S.Diag(NewDecl->getLocation(),
7179 diag::warn_dllimport_dropped_from_inline_function)
7180 << NewDecl << OldImportAttr;
7181 }
7182
7183 // A specialization of a class template member function is processed here
7184 // since it's a redeclaration. If the parent class is dllexport, the
7185 // specialization inherits that attribute. This doesn't happen automatically
7186 // since the parent class isn't instantiated until later.
7187 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7188 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7189 !NewImportAttr && !NewExportAttr) {
7190 if (const DLLExportAttr *ParentExportAttr =
7191 MD->getParent()->getAttr<DLLExportAttr>()) {
7192 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7193 NewAttr->setInherited(true);
7194 NewDecl->addAttr(NewAttr);
7195 }
7196 }
7197 }
7198}
7199
7200/// Given that we are within the definition of the given function,
7201/// will that definition behave like C99's 'inline', where the
7202/// definition is discarded except for optimization purposes?
7204 // Try to avoid calling GetGVALinkageForFunction.
7205
7206 // All cases of this require the 'inline' keyword.
7207 if (!FD->isInlined()) return false;
7208
7209 // This is only possible in C++ with the gnu_inline attribute.
7210 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7211 return false;
7212
7213 // Okay, go ahead and call the relatively-more-expensive function.
7215}
7216
7217/// Determine whether a variable is extern "C" prior to attaching
7218/// an initializer. We can't just call isExternC() here, because that
7219/// will also compute and cache whether the declaration is externally
7220/// visible, which might change when we attach the initializer.
7221///
7222/// This can only be used if the declaration is known to not be a
7223/// redeclaration of an internal linkage declaration.
7224///
7225/// For instance:
7226///
7227/// auto x = []{};
7228///
7229/// Attaching the initializer here makes this declaration not externally
7230/// visible, because its type has internal linkage.
7231///
7232/// FIXME: This is a hack.
7233template<typename T>
7234static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7235 if (S.getLangOpts().CPlusPlus) {
7236 // In C++, the overloadable attribute negates the effects of extern "C".
7237 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7238 return false;
7239
7240 // So do CUDA's host/device attributes.
7241 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7242 D->template hasAttr<CUDAHostAttr>()))
7243 return false;
7244 }
7245 return D->isExternC();
7246}
7247
7248static bool shouldConsiderLinkage(const VarDecl *VD) {
7249 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7250 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7251 isa<OMPDeclareMapperDecl>(DC))
7252 return VD->hasExternalStorage();
7253 if (DC->isFileContext())
7254 return true;
7255 if (DC->isRecord())
7256 return false;
7257 if (DC->getDeclKind() == Decl::HLSLBuffer)
7258 return false;
7259
7260 if (isa<RequiresExprBodyDecl>(DC))
7261 return false;
7262 llvm_unreachable("Unexpected context");
7263}
7264
7265static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7266 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7267 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7268 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7269 return true;
7270 if (DC->isRecord())
7271 return false;
7272 llvm_unreachable("Unexpected context");
7273}
7274
7275static bool hasParsedAttr(Scope *S, const Declarator &PD,
7276 ParsedAttr::Kind Kind) {
7277 // Check decl attributes on the DeclSpec.
7278 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7279 return true;
7280
7281 // Walk the declarator structure, checking decl attributes that were in a type
7282 // position to the decl itself.
7283 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7284 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7285 return true;
7286 }
7287
7288 // Finally, check attributes on the decl itself.
7289 return PD.getAttributes().hasAttribute(Kind) ||
7291}
7292
7294 if (!DC->isFunctionOrMethod())
7295 return false;
7296
7297 // If this is a local extern function or variable declared within a function
7298 // template, don't add it into the enclosing namespace scope until it is
7299 // instantiated; it might have a dependent type right now.
7300 if (DC->isDependentContext())
7301 return true;
7302
7303 // C++11 [basic.link]p7:
7304 // When a block scope declaration of an entity with linkage is not found to
7305 // refer to some other declaration, then that entity is a member of the
7306 // innermost enclosing namespace.
7307 //
7308 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7309 // semantically-enclosing namespace, not a lexically-enclosing one.
7310 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7311 DC = DC->getParent();
7312 return true;
7313}
7314
7315/// Returns true if given declaration has external C language linkage.
7316static bool isDeclExternC(const Decl *D) {
7317 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7318 return FD->isExternC();
7319 if (const auto *VD = dyn_cast<VarDecl>(D))
7320 return VD->isExternC();
7321
7322 llvm_unreachable("Unknown type of decl!");
7323}
7324
7325/// Returns true if there hasn't been any invalid type diagnosed.
7326static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7327 DeclContext *DC = NewVD->getDeclContext();
7328 QualType R = NewVD->getType();
7329
7330 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7331 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7332 // argument.
7333 if (R->isImageType() || R->isPipeType()) {
7334 Se.Diag(NewVD->getLocation(),
7335 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7336 << R;
7337 NewVD->setInvalidDecl();
7338 return false;
7339 }
7340
7341 // OpenCL v1.2 s6.9.r:
7342 // The event type cannot be used to declare a program scope variable.
7343 // OpenCL v2.0 s6.9.q:
7344 // The clk_event_t and reserve_id_t types cannot be declared in program
7345 // scope.
7346 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7347 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7348 Se.Diag(NewVD->getLocation(),
7349 diag::err_invalid_type_for_program_scope_var)
7350 << R;
7351 NewVD->setInvalidDecl();
7352 return false;
7353 }
7354 }
7355
7356 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7357 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7358 Se.getLangOpts())) {
7359 QualType NR = R.getCanonicalType();
7360 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7361 NR->isReferenceType()) {
7364 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7365 << NR->isReferenceType();
7366 NewVD->setInvalidDecl();
7367 return false;
7368 }
7369 NR = NR->getPointeeType();
7370 }
7371 }
7372
7373 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7374 Se.getLangOpts())) {
7375 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7376 // half array type (unless the cl_khr_fp16 extension is enabled).
7377 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7378 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7379 NewVD->setInvalidDecl();
7380 return false;
7381 }
7382 }
7383
7384 // OpenCL v1.2 s6.9.r:
7385 // The event type cannot be used with the __local, __constant and __global
7386 // address space qualifiers.
7387 if (R->isEventT()) {
7389 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7390 NewVD->setInvalidDecl();
7391 return false;
7392 }
7393 }
7394
7395 if (R->isSamplerT()) {
7396 // OpenCL v1.2 s6.9.b p4:
7397 // The sampler type cannot be used with the __local and __global address
7398 // space qualifiers.
7401 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7402 NewVD->setInvalidDecl();
7403 }
7404
7405 // OpenCL v1.2 s6.12.14.1:
7406 // A global sampler must be declared with either the constant address
7407 // space qualifier or with the const qualifier.
7408 if (DC->isTranslationUnit() &&
7410 R.isConstQualified())) {
7411 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7412 NewVD->setInvalidDecl();
7413 }
7414 if (NewVD->isInvalidDecl())
7415 return false;
7416 }
7417
7418 return true;
7419}
7420
7421template <typename AttrTy>
7422static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7423 const TypedefNameDecl *TND = TT->getDecl();
7424 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7425 AttrTy *Clone = Attribute->clone(S.Context);
7426 Clone->setInherited(true);
7427 D->addAttr(Clone);
7428 }
7429}
7430
7431// This function emits warning and a corresponding note based on the
7432// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7433// declarations of an annotated type must be const qualified.
7435 QualType VarType = VD->getType().getCanonicalType();
7436
7437 // Ignore local declarations (for now) and those with const qualification.
7438 // TODO: Local variables should not be allowed if their type declaration has
7439 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7440 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7441 return;
7442
7443 if (VarType->isArrayType()) {
7444 // Retrieve element type for array declarations.
7445 VarType = S.getASTContext().getBaseElementType(VarType);
7446 }
7447
7448 const RecordDecl *RD = VarType->getAsRecordDecl();
7449
7450 // Check if the record declaration is present and if it has any attributes.
7451 if (RD == nullptr)
7452 return;
7453
7454 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7455 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7456 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7457 return;
7458 }
7459}
7460
7461// Checks if VD is declared at global scope or with C language linkage.
7462static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7463 return Name.getAsIdentifierInfo() &&
7464 Name.getAsIdentifierInfo()->isStr("main") &&
7465 !VD->getDescribedVarTemplate() &&
7467 VD->isExternC());
7468}
7469
7471 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7472 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7473 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7474 QualType R = TInfo->getType();
7476
7477 IdentifierInfo *II = Name.getAsIdentifierInfo();
7478 bool IsPlaceholderVariable = false;
7479
7480 if (D.isDecompositionDeclarator()) {
7481 // Take the name of the first declarator as our name for diagnostic
7482 // purposes.
7483 auto &Decomp = D.getDecompositionDeclarator();
7484 if (!Decomp.bindings().empty()) {
7485 II = Decomp.bindings()[0].Name;
7486 Name = II;
7487 }
7488 } else if (!II) {
7489 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7490 return nullptr;
7491 }
7492
7493
7494 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7496
7497 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7498 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7499 IsPlaceholderVariable = true;
7500 if (!Previous.empty()) {
7501 NamedDecl *PrevDecl = *Previous.begin();
7502 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7503 DC->getRedeclContext());
7504 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7505 DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7506 }
7507 }
7508
7509 // dllimport globals without explicit storage class are treated as extern. We
7510 // have to change the storage class this early to get the right DeclContext.
7511 if (SC == SC_None && !DC->isRecord() &&
7512 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7513 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7514 SC = SC_Extern;
7515
7516 DeclContext *OriginalDC = DC;
7517 bool IsLocalExternDecl = SC == SC_Extern &&
7519
7520 if (SCSpec == DeclSpec::SCS_mutable) {
7521 // mutable can only appear on non-static class members, so it's always
7522 // an error here
7523 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7524 D.setInvalidType();
7525 SC = SC_None;
7526 }
7527
7528 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7529 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7530 D.getDeclSpec().getStorageClassSpecLoc())) {
7531 // In C++11, the 'register' storage class specifier is deprecated.
7532 // Suppress the warning in system macros, it's used in macros in some
7533 // popular C system headers, such as in glibc's htonl() macro.
7534 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7535 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7536 : diag::warn_deprecated_register)
7537 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7538 }
7539
7540 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7541
7542 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7543 // C99 6.9p2: The storage-class specifiers auto and register shall not
7544 // appear in the declaration specifiers in an external declaration.
7545 // Global Register+Asm is a GNU extension we support.
7546 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7547 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7548 D.setInvalidType();
7549 }
7550 }
7551
7552 // If this variable has a VLA type and an initializer, try to
7553 // fold to a constant-sized type. This is otherwise invalid.
7554 if (D.hasInitializer() && R->isVariableArrayType())
7555 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7556 /*DiagID=*/0);
7557
7558 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7559 const AutoType *AT = TL.getTypePtr();
7560 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7561 }
7562
7563 bool IsMemberSpecialization = false;
7564 bool IsVariableTemplateSpecialization = false;
7565 bool IsPartialSpecialization = false;
7566 bool IsVariableTemplate = false;
7567 VarDecl *NewVD = nullptr;
7568 VarTemplateDecl *NewTemplate = nullptr;
7569 TemplateParameterList *TemplateParams = nullptr;
7570 if (!getLangOpts().CPlusPlus) {
7571 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7572 II, R, TInfo, SC);
7573
7574 if (R->getContainedDeducedType())
7575 ParsingInitForAutoVars.insert(NewVD);
7576
7577 if (D.isInvalidType())
7578 NewVD->setInvalidDecl();
7579
7581 NewVD->hasLocalStorage())
7582 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7584 } else {
7585 bool Invalid = false;
7586 // Match up the template parameter lists with the scope specifier, then
7587 // determine whether we have a template or a template specialization.
7589 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7590 D.getCXXScopeSpec(),
7592 ? D.getName().TemplateId
7593 : nullptr,
7594 TemplateParamLists,
7595 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7596
7597 if (TemplateParams) {
7598 if (DC->isDependentContext()) {
7599 ContextRAII SavedContext(*this, DC);
7601 Invalid = true;
7602 }
7603
7604 if (!TemplateParams->size() &&
7606 // There is an extraneous 'template<>' for this variable. Complain
7607 // about it, but allow the declaration of the variable.
7608 Diag(TemplateParams->getTemplateLoc(),
7609 diag::err_template_variable_noparams)
7610 << II
7611 << SourceRange(TemplateParams->getTemplateLoc(),
7612 TemplateParams->getRAngleLoc());
7613 TemplateParams = nullptr;
7614 } else {
7615 // Check that we can declare a template here.
7616 if (CheckTemplateDeclScope(S, TemplateParams))
7617 return nullptr;
7618
7619 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7620 // This is an explicit specialization or a partial specialization.
7621 IsVariableTemplateSpecialization = true;
7622 IsPartialSpecialization = TemplateParams->size() > 0;
7623 } else { // if (TemplateParams->size() > 0)
7624 // This is a template declaration.
7625 IsVariableTemplate = true;
7626
7627 // Only C++1y supports variable templates (N3651).
7628 Diag(D.getIdentifierLoc(),
7630 ? diag::warn_cxx11_compat_variable_template
7631 : diag::ext_variable_template);
7632 }
7633 }
7634 } else {
7635 // Check that we can declare a member specialization here.
7636 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7637 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7638 return nullptr;
7639 assert((Invalid ||
7640 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7641 "should have a 'template<>' for this decl");
7642 }
7643
7644 bool IsExplicitSpecialization =
7645 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7646
7647 // C++ [temp.expl.spec]p2:
7648 // The declaration in an explicit-specialization shall not be an
7649 // export-declaration. An explicit specialization shall not use a
7650 // storage-class-specifier other than thread_local.
7651 //
7652 // We use the storage-class-specifier from DeclSpec because we may have
7653 // added implicit 'extern' for declarations with __declspec(dllimport)!
7654 if (SCSpec != DeclSpec::SCS_unspecified &&
7655 (IsExplicitSpecialization || IsMemberSpecialization)) {
7656 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7657 diag::ext_explicit_specialization_storage_class)
7658 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7659 }
7660
7661 if (CurContext->isRecord()) {
7662 if (SC == SC_Static) {
7663 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7664 // Walk up the enclosing DeclContexts to check for any that are
7665 // incompatible with static data members.
7666 const DeclContext *FunctionOrMethod = nullptr;
7667 const CXXRecordDecl *AnonStruct = nullptr;
7668 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7669 if (Ctxt->isFunctionOrMethod()) {
7670 FunctionOrMethod = Ctxt;
7671 break;
7672 }
7673 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7674 if (ParentDecl && !ParentDecl->getDeclName()) {
7675 AnonStruct = ParentDecl;
7676 break;
7677 }
7678 }
7679 if (FunctionOrMethod) {
7680 // C++ [class.static.data]p5: A local class shall not have static
7681 // data members.
7682 Diag(D.getIdentifierLoc(),
7683 diag::err_static_data_member_not_allowed_in_local_class)
7684 << Name << RD->getDeclName()
7685 << llvm::to_underlying(RD->getTagKind());
7686 } else if (AnonStruct) {
7687 // C++ [class.static.data]p4: Unnamed classes and classes contained
7688 // directly or indirectly within unnamed classes shall not contain
7689 // static data members.
7690 Diag(D.getIdentifierLoc(),
7691 diag::err_static_data_member_not_allowed_in_anon_struct)
7692 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7693 Invalid = true;
7694 } else if (RD->isUnion()) {
7695 // C++98 [class.union]p1: If a union contains a static data member,
7696 // the program is ill-formed. C++11 drops this restriction.
7697 Diag(D.getIdentifierLoc(),
7699 ? diag::warn_cxx98_compat_static_data_member_in_union
7700 : diag::ext_static_data_member_in_union)
7701 << Name;
7702 }
7703 }
7704 } else if (IsVariableTemplate || IsPartialSpecialization) {
7705 // There is no such thing as a member field template.
7706 Diag(D.getIdentifierLoc(), diag::err_template_member)
7707 << II << TemplateParams->getSourceRange();
7708 // Recover by pretending this is a static data member template.
7709 SC = SC_Static;
7710 }
7711 } else if (DC->isRecord()) {
7712 // This is an out-of-line definition of a static data member.
7713 switch (SC) {
7714 case SC_None:
7715 break;
7716 case SC_Static:
7717 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7718 diag::err_static_out_of_line)
7720 D.getDeclSpec().getStorageClassSpecLoc());
7721 break;
7722 case SC_Auto:
7723 case SC_Register:
7724 case SC_Extern:
7725 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7726 // to names of variables declared in a block or to function parameters.
7727 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7728 // of class members
7729
7730 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7731 diag::err_storage_class_for_static_member)
7733 D.getDeclSpec().getStorageClassSpecLoc());
7734 break;
7735 case SC_PrivateExtern:
7736 llvm_unreachable("C storage class in c++!");
7737 }
7738 }
7739
7740 if (IsVariableTemplateSpecialization) {
7741 SourceLocation TemplateKWLoc =
7742 TemplateParamLists.size() > 0
7743 ? TemplateParamLists[0]->getTemplateLoc()
7744 : SourceLocation();
7746 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7748 if (Res.isInvalid())
7749 return nullptr;
7750 NewVD = cast<VarDecl>(Res.get());
7751 AddToScope = false;
7752 } else if (D.isDecompositionDeclarator()) {
7754 D.getIdentifierLoc(), R, TInfo, SC,
7755 Bindings);
7756 } else
7757 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7758 D.getIdentifierLoc(), II, R, TInfo, SC);
7759
7760 // If this is supposed to be a variable template, create it as such.
7761 if (IsVariableTemplate) {
7762 NewTemplate =
7763 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7764 TemplateParams, NewVD);
7765 NewVD->setDescribedVarTemplate(NewTemplate);
7766 }
7767
7768 // If this decl has an auto type in need of deduction, make a note of the
7769 // Decl so we can diagnose uses of it in its own initializer.
7770 if (R->getContainedDeducedType())
7771 ParsingInitForAutoVars.insert(NewVD);
7772
7773 if (D.isInvalidType() || Invalid) {
7774 NewVD->setInvalidDecl();
7775 if (NewTemplate)
7776 NewTemplate->setInvalidDecl();
7777 }
7778
7779 SetNestedNameSpecifier(*this, NewVD, D);
7780
7781 // If we have any template parameter lists that don't directly belong to
7782 // the variable (matching the scope specifier), store them.
7783 // An explicit variable template specialization does not own any template
7784 // parameter lists.
7785 unsigned VDTemplateParamLists =
7786 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7787 if (TemplateParamLists.size() > VDTemplateParamLists)
7789 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7790 }
7791
7792 if (D.getDeclSpec().isInlineSpecified()) {
7793 if (!getLangOpts().CPlusPlus) {
7794 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7795 << 0;
7796 } else if (CurContext->isFunctionOrMethod()) {
7797 // 'inline' is not allowed on block scope variable declaration.
7798 Diag(D.getDeclSpec().getInlineSpecLoc(),
7799 diag::err_inline_declaration_block_scope) << Name
7800 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7801 } else {
7802 Diag(D.getDeclSpec().getInlineSpecLoc(),
7803 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7804 : diag::ext_inline_variable);
7805 NewVD->setInlineSpecified();
7806 }
7807 }
7808
7809 // Set the lexical context. If the declarator has a C++ scope specifier, the
7810 // lexical context will be different from the semantic context.
7812 if (NewTemplate)
7813 NewTemplate->setLexicalDeclContext(CurContext);
7814
7815 if (IsLocalExternDecl) {
7816 if (D.isDecompositionDeclarator())
7817 for (auto *B : Bindings)
7818 B->setLocalExternDecl();
7819 else
7820 NewVD->setLocalExternDecl();
7821 }
7822
7823 bool EmitTLSUnsupportedError = false;
7824 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7825 // C++11 [dcl.stc]p4:
7826 // When thread_local is applied to a variable of block scope the
7827 // storage-class-specifier static is implied if it does not appear
7828 // explicitly.
7829 // Core issue: 'static' is not implied if the variable is declared
7830 // 'extern'.
7831 if (NewVD->hasLocalStorage() &&
7832 (SCSpec != DeclSpec::SCS_unspecified ||
7834 !DC->isFunctionOrMethod()))
7835 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7836 diag::err_thread_non_global)
7838 else if (!Context.getTargetInfo().isTLSSupported()) {
7839 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7840 getLangOpts().SYCLIsDevice) {
7841 // Postpone error emission until we've collected attributes required to
7842 // figure out whether it's a host or device variable and whether the
7843 // error should be ignored.
7844 EmitTLSUnsupportedError = true;
7845 // We still need to mark the variable as TLS so it shows up in AST with
7846 // proper storage class for other tools to use even if we're not going
7847 // to emit any code for it.
7848 NewVD->setTSCSpec(TSCS);
7849 } else
7850 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7851 diag::err_thread_unsupported);
7852 } else
7853 NewVD->setTSCSpec(TSCS);
7854 }
7855
7856 switch (D.getDeclSpec().getConstexprSpecifier()) {
7858 break;
7859
7861 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7862 diag::err_constexpr_wrong_decl_kind)
7863 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7864 [[fallthrough]];
7865
7867 NewVD->setConstexpr(true);
7868 // C++1z [dcl.spec.constexpr]p1:
7869 // A static data member declared with the constexpr specifier is
7870 // implicitly an inline variable.
7871 if (NewVD->isStaticDataMember() &&
7872 (getLangOpts().CPlusPlus17 ||
7874 NewVD->setImplicitlyInline();
7875 break;
7876
7878 if (!NewVD->hasGlobalStorage())
7879 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7880 diag::err_constinit_local_variable);
7881 else
7882 NewVD->addAttr(
7883 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7884 ConstInitAttr::Keyword_constinit));
7885 break;
7886 }
7887
7888 // C99 6.7.4p3
7889 // An inline definition of a function with external linkage shall
7890 // not contain a definition of a modifiable object with static or
7891 // thread storage duration...
7892 // We only apply this when the function is required to be defined
7893 // elsewhere, i.e. when the function is not 'extern inline'. Note
7894 // that a local variable with thread storage duration still has to
7895 // be marked 'static'. Also note that it's possible to get these
7896 // semantics in C++ using __attribute__((gnu_inline)).
7897 if (SC == SC_Static && S->getFnParent() != nullptr &&
7898 !NewVD->getType().isConstQualified()) {
7900 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7901 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7902 diag::warn_static_local_in_extern_inline);
7904 }
7905 }
7906
7907 if (D.getDeclSpec().isModulePrivateSpecified()) {
7908 if (IsVariableTemplateSpecialization)
7909 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7910 << (IsPartialSpecialization ? 1 : 0)
7912 D.getDeclSpec().getModulePrivateSpecLoc());
7913 else if (IsMemberSpecialization)
7914 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7915 << 2
7916 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7917 else if (NewVD->hasLocalStorage())
7918 Diag(NewVD->getLocation(), diag::err_module_private_local)
7919 << 0 << NewVD
7920 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7922 D.getDeclSpec().getModulePrivateSpecLoc());
7923 else {
7924 NewVD->setModulePrivate();
7925 if (NewTemplate)
7926 NewTemplate->setModulePrivate();
7927 for (auto *B : Bindings)
7928 B->setModulePrivate();
7929 }
7930 }
7931
7932 if (getLangOpts().OpenCL) {
7934
7935 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7936 if (TSC != TSCS_unspecified) {
7937 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7938 diag::err_opencl_unknown_type_specifier)
7940 << DeclSpec::getSpecifierName(TSC) << 1;
7941 NewVD->setInvalidDecl();
7942 }
7943 }
7944
7945 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7946 // address space if the table has local storage (semantic checks elsewhere
7947 // will produce an error anyway).
7948 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7949 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7950 !NewVD->hasLocalStorage()) {
7953 NewVD->setType(Type);
7954 }
7955 }
7956
7957 // Handle attributes prior to checking for duplicates in MergeVarDecl
7958 ProcessDeclAttributes(S, NewVD, D);
7959
7960 if (getLangOpts().HLSL)
7962
7963 // FIXME: This is probably the wrong location to be doing this and we should
7964 // probably be doing this for more attributes (especially for function
7965 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7966 // the code to copy attributes would be generated by TableGen.
7967 if (R->isFunctionPointerType())
7968 if (const auto *TT = R->getAs<TypedefType>())
7969 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7970
7971 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7972 getLangOpts().SYCLIsDevice) {
7973 if (EmitTLSUnsupportedError &&
7975 (getLangOpts().OpenMPIsTargetDevice &&
7976 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7977 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7978 diag::err_thread_unsupported);
7979
7980 if (EmitTLSUnsupportedError &&
7981 (LangOpts.SYCLIsDevice ||
7982 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7983 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7984 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7985 // storage [duration]."
7986 if (SC == SC_None && S->getFnParent() != nullptr &&
7987 (NewVD->hasAttr<CUDASharedAttr>() ||
7988 NewVD->hasAttr<CUDAConstantAttr>())) {
7989 NewVD->setStorageClass(SC_Static);
7990 }
7991 }
7992
7993 // Ensure that dllimport globals without explicit storage class are treated as
7994 // extern. The storage class is set above using parsed attributes. Now we can
7995 // check the VarDecl itself.
7996 assert(!NewVD->hasAttr<DLLImportAttr>() ||
7997 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7998 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7999
8000 // In auto-retain/release, infer strong retension for variables of
8001 // retainable type.
8002 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8003 NewVD->setInvalidDecl();
8004
8005 // Handle GNU asm-label extension (encoded as an attribute).
8006 if (Expr *E = (Expr*)D.getAsmLabel()) {
8007 // The parser guarantees this is a string.
8008 StringLiteral *SE = cast<StringLiteral>(E);
8009 StringRef Label = SE->getString();
8010 if (S->getFnParent() != nullptr) {
8011 switch (SC) {
8012 case SC_None:
8013 case SC_Auto:
8014 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8015 break;
8016 case SC_Register:
8017 // Local Named register
8020 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8021 break;
8022 case SC_Static:
8023 case SC_Extern:
8024 case SC_PrivateExtern:
8025 break;
8026 }
8027 } else if (SC == SC_Register) {
8028 // Global Named register
8029 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8030 const auto &TI = Context.getTargetInfo();
8031 bool HasSizeMismatch;
8032
8033 if (!TI.isValidGCCRegisterName(Label))
8034 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8035 else if (!TI.validateGlobalRegisterVariable(Label,
8037 HasSizeMismatch))
8038 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8039 else if (HasSizeMismatch)
8040 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8041 }
8042
8043 if (!R->isIntegralType(Context) && !R->isPointerType()) {
8044 Diag(TInfo->getTypeLoc().getBeginLoc(),
8045 diag::err_asm_unsupported_register_type)
8046 << TInfo->getTypeLoc().getSourceRange();
8047 NewVD->setInvalidDecl(true);
8048 }
8049 }
8050
8051 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8052 /*IsLiteralLabel=*/true,
8053 SE->getStrTokenLoc(0)));
8054 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8055 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8057 if (I != ExtnameUndeclaredIdentifiers.end()) {
8058 if (isDeclExternC(NewVD)) {
8059 NewVD->addAttr(I->second);
8061 } else
8062 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8063 << /*Variable*/1 << NewVD;
8064 }
8065 }
8066
8067 // Find the shadowed declaration before filtering for scope.
8068 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8070 : nullptr;
8071
8072 // Don't consider existing declarations that are in a different
8073 // scope and are out-of-semantic-context declarations (if the new
8074 // declaration has linkage).
8076 D.getCXXScopeSpec().isNotEmpty() ||
8077 IsMemberSpecialization ||
8078 IsVariableTemplateSpecialization);
8079
8080 // Check whether the previous declaration is in the same block scope. This
8081 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8082 if (getLangOpts().CPlusPlus &&
8083 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8085 Previous.isSingleResult() && !Previous.isShadowed() &&
8086 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8087
8088 if (!getLangOpts().CPlusPlus) {
8089 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8090 } else {
8091 // If this is an explicit specialization of a static data member, check it.
8092 if (IsMemberSpecialization && !IsVariableTemplate &&
8093 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8095 NewVD->setInvalidDecl();
8096
8097 // Merge the decl with the existing one if appropriate.
8098 if (!Previous.empty()) {
8099 if (Previous.isSingleResult() &&
8100 isa<FieldDecl>(Previous.getFoundDecl()) &&
8101 D.getCXXScopeSpec().isSet()) {
8102 // The user tried to define a non-static data member
8103 // out-of-line (C++ [dcl.meaning]p1).
8104 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8105 << D.getCXXScopeSpec().getRange();
8106 Previous.clear();
8107 NewVD->setInvalidDecl();
8108 }
8109 } else if (D.getCXXScopeSpec().isSet() &&
8110 !IsVariableTemplateSpecialization) {
8111 // No previous declaration in the qualifying scope.
8112 Diag(D.getIdentifierLoc(), diag::err_no_member)
8113 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8114 << D.getCXXScopeSpec().getRange();
8115 NewVD->setInvalidDecl();
8116 }
8117
8118 if (!IsPlaceholderVariable)
8119 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8120
8121 // CheckVariableDeclaration will set NewVD as invalid if something is in
8122 // error like WebAssembly tables being declared as arrays with a non-zero
8123 // size, but then parsing continues and emits further errors on that line.
8124 // To avoid that we check here if it happened and return nullptr.
8125 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8126 return nullptr;
8127
8128 if (NewTemplate) {
8129 VarTemplateDecl *PrevVarTemplate =
8130 NewVD->getPreviousDecl()
8132 : nullptr;
8133
8134 // Check the template parameter list of this declaration, possibly
8135 // merging in the template parameter list from the previous variable
8136 // template declaration.
8138 TemplateParams,
8139 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8140 : nullptr,
8141 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8142 DC->isDependentContext())
8144 : TPC_VarTemplate))
8145 NewVD->setInvalidDecl();
8146
8147 // If we are providing an explicit specialization of a static variable
8148 // template, make a note of that.
8149 if (PrevVarTemplate &&
8150 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8151 PrevVarTemplate->setMemberSpecialization();
8152 }
8153 }
8154
8155 // Diagnose shadowed variables iff this isn't a redeclaration.
8156 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8157 CheckShadow(NewVD, ShadowedDecl, Previous);
8158
8159 ProcessPragmaWeak(S, NewVD);
8160
8161 // If this is the first declaration of an extern C variable, update
8162 // the map of such variables.
8163 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8164 isIncompleteDeclExternC(*this, NewVD))
8166
8167 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8169 Decl *ManglingContextDecl;
8170 std::tie(MCtx, ManglingContextDecl) =
8172 if (MCtx) {
8174 NewVD, MCtx->getManglingNumber(
8175 NewVD, getMSManglingNumber(getLangOpts(), S)));
8177 }
8178 }
8179
8180 // Special handling of variable named 'main'.
8181 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8182 // C++ [basic.start.main]p3:
8183 // A program that declares
8184 // - a variable main at global scope, or
8185 // - an entity named main with C language linkage (in any namespace)
8186 // is ill-formed
8187 if (getLangOpts().CPlusPlus)
8188 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8189 << NewVD->isExternC();
8190
8191 // In C, and external-linkage variable named main results in undefined
8192 // behavior.
8193 else if (NewVD->hasExternalFormalLinkage())
8194 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8195 }
8196
8197 if (D.isRedeclaration() && !Previous.empty()) {
8198 NamedDecl *Prev = Previous.getRepresentativeDecl();
8199 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8200 D.isFunctionDefinition());
8201 }
8202
8203 if (NewTemplate) {
8204 if (NewVD->isInvalidDecl())
8205 NewTemplate->setInvalidDecl();
8206 ActOnDocumentableDecl(NewTemplate);
8207 return NewTemplate;
8208 }
8209
8210 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8212
8214
8215 return NewVD;
8216}
8217
8218/// Enum describing the %select options in diag::warn_decl_shadow.
8228
8229/// Determine what kind of declaration we're shadowing.
8231 const DeclContext *OldDC) {
8232 if (isa<TypeAliasDecl>(ShadowedDecl))
8233 return SDK_Using;
8234 else if (isa<TypedefDecl>(ShadowedDecl))
8235 return SDK_Typedef;
8236 else if (isa<BindingDecl>(ShadowedDecl))
8237 return SDK_StructuredBinding;
8238 else if (isa<RecordDecl>(OldDC))
8239 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8240
8241 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8242}
8243
8244/// Return the location of the capture if the given lambda captures the given
8245/// variable \p VD, or an invalid source location otherwise.
8247 const VarDecl *VD) {
8248 for (const Capture &Capture : LSI->Captures) {
8250 return Capture.getLocation();
8251 }
8252 return SourceLocation();
8253}
8254
8256 const LookupResult &R) {
8257 // Only diagnose if we're shadowing an unambiguous field or variable.
8259 return false;
8260
8261 // Return false if warning is ignored.
8262 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8263}
8264
8266 const LookupResult &R) {
8268 return nullptr;
8269
8270 // Don't diagnose declarations at file scope.
8271 if (D->hasGlobalStorage() && !D->isStaticLocal())
8272 return nullptr;
8273
8274 NamedDecl *ShadowedDecl = R.getFoundDecl();
8275 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8276 : nullptr;
8277}
8278
8280 const LookupResult &R) {
8281 // Don't warn if typedef declaration is part of a class
8282 if (D->getDeclContext()->isRecord())
8283 return nullptr;
8284
8286 return nullptr;
8287
8288 NamedDecl *ShadowedDecl = R.getFoundDecl();
8289 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8290}
8291
8293 const LookupResult &R) {
8295 return nullptr;
8296
8297 NamedDecl *ShadowedDecl = R.getFoundDecl();
8298 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8299 : nullptr;
8300}
8301
8303 const LookupResult &R) {
8304 DeclContext *NewDC = D->getDeclContext();
8305
8306 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8307 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) {
8308 // Fields are not shadowed by variables in C++ static methods.
8309 if (MD->isStatic())
8310 return;
8311
8312 if (!MD->getParent()->isLambda() && MD->isExplicitObjectMemberFunction())
8313 return;
8314 }
8315 // Fields shadowed by constructor parameters are a special case. Usually
8316 // the constructor initializes the field with the parameter.
8317 if (isa<CXXConstructorDecl>(NewDC))
8318 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8319 // Remember that this was shadowed so we can either warn about its
8320 // modification or its existence depending on warning settings.
8321 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8322 return;
8323 }
8324 }
8325
8326 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8327 if (shadowedVar->isExternC()) {
8328 // For shadowing external vars, make sure that we point to the global
8329 // declaration, not a locally scoped extern declaration.
8330 for (auto *I : shadowedVar->redecls())
8331 if (I->isFileVarDecl()) {
8332 ShadowedDecl = I;
8333 break;
8334 }
8335 }
8336
8337 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8338
8339 unsigned WarningDiag = diag::warn_decl_shadow;
8340 SourceLocation CaptureLoc;
8341 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8342 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8343 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8344 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8345 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8346 if (RD->getLambdaCaptureDefault() == LCD_None) {
8347 // Try to avoid warnings for lambdas with an explicit capture
8348 // list. Warn only when the lambda captures the shadowed decl
8349 // explicitly.
8350 CaptureLoc = getCaptureLocation(LSI, VD);
8351 if (CaptureLoc.isInvalid())
8352 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8353 } else {
8354 // Remember that this was shadowed so we can avoid the warning if
8355 // the shadowed decl isn't captured and the warning settings allow
8356 // it.
8357 cast<LambdaScopeInfo>(getCurFunction())
8358 ->ShadowingDecls.push_back({D, VD});
8359 return;
8360 }
8361 }
8362 if (isa<FieldDecl>(ShadowedDecl)) {
8363 // If lambda can capture this, then emit default shadowing warning,
8364 // Otherwise it is not really a shadowing case since field is not
8365 // available in lambda's body.
8366 // At this point we don't know that lambda can capture this, so
8367 // remember that this was shadowed and delay until we know.
8368 cast<LambdaScopeInfo>(getCurFunction())
8369 ->ShadowingDecls.push_back({D, ShadowedDecl});
8370 return;
8371 }
8372 }
8373 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8374 VD && VD->hasLocalStorage()) {
8375 // A variable can't shadow a local variable in an enclosing scope, if
8376 // they are separated by a non-capturing declaration context.
8377 for (DeclContext *ParentDC = NewDC;
8378 ParentDC && !ParentDC->Equals(OldDC);
8379 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8380 // Only block literals, captured statements, and lambda expressions
8381 // can capture; other scopes don't.
8382 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8383 !isLambdaCallOperator(ParentDC)) {
8384 return;
8385 }
8386 }
8387 }
8388 }
8389 }
8390
8391 // Never warn about shadowing a placeholder variable.
8392 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8393 return;
8394
8395 // Only warn about certain kinds of shadowing for class members.
8396 if (NewDC) {
8397 // In particular, don't warn about shadowing non-class members.
8398 if (NewDC->isRecord() && !OldDC->isRecord())
8399 return;
8400
8401 // Skip shadowing check if we're in a class scope, dealing with an enum
8402 // constant in a different context.
8403 DeclContext *ReDC = NewDC->getRedeclContext();
8404 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8405 return;
8406
8407 // TODO: should we warn about static data members shadowing
8408 // static data members from base classes?
8409
8410 // TODO: don't diagnose for inaccessible shadowed members.
8411 // This is hard to do perfectly because we might friend the
8412 // shadowing context, but that's just a false negative.
8413 }
8414
8415 DeclarationName Name = R.getLookupName();
8416
8417 // Emit warning and note.
8418 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8419 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8420 if (!CaptureLoc.isInvalid())
8421 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8422 << Name << /*explicitly*/ 1;
8423 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8424}
8425
8427 for (const auto &Shadow : LSI->ShadowingDecls) {
8428 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8429 // Try to avoid the warning when the shadowed decl isn't captured.
8430 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8431 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8432 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8433 Diag(Shadow.VD->getLocation(),
8434 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8435 : diag::warn_decl_shadow)
8436 << Shadow.VD->getDeclName()
8437 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8438 if (CaptureLoc.isValid())
8439 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8440 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8441 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8442 } else if (isa<FieldDecl>(ShadowedDecl)) {
8443 Diag(Shadow.VD->getLocation(),
8444 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8445 : diag::warn_decl_shadow_uncaptured_local)
8446 << Shadow.VD->getDeclName()
8447 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8448 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8449 }
8450 }
8451}
8452
8454 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8455 return;
8456
8457 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8459 RedeclarationKind::ForVisibleRedeclaration);
8460 LookupName(R, S);
8461 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8462 CheckShadow(D, ShadowedDecl, R);
8463}
8464
8465/// Check if 'E', which is an expression that is about to be modified, refers
8466/// to a constructor parameter that shadows a field.
8468 // Quickly ignore expressions that can't be shadowing ctor parameters.
8469 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8470 return;
8471 E = E->IgnoreParenImpCasts();
8472 auto *DRE = dyn_cast<DeclRefExpr>(E);
8473 if (!DRE)
8474 return;
8475 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8476 auto I = ShadowingDecls.find(D);
8477 if (I == ShadowingDecls.end())
8478 return;
8479 const NamedDecl *ShadowedDecl = I->second;
8480 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8481 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8482 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8483 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8484
8485 // Avoid issuing multiple warnings about the same decl.
8486 ShadowingDecls.erase(I);
8487}
8488
8489/// Check for conflict between this global or extern "C" declaration and
8490/// previous global or extern "C" declarations. This is only used in C++.
8491template<typename T>
8493 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8494 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8495 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8496
8497 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8498 // The common case: this global doesn't conflict with any extern "C"
8499 // declaration.
8500 return false;
8501 }
8502
8503 if (Prev) {
8504 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8505 // Both the old and new declarations have C language linkage. This is a
8506 // redeclaration.
8507 Previous.clear();
8508 Previous.addDecl(Prev);
8509 return true;
8510 }
8511
8512 // This is a global, non-extern "C" declaration, and there is a previous
8513 // non-global extern "C" declaration. Diagnose if this is a variable
8514 // declaration.
8515 if (!isa<VarDecl>(ND))
8516 return false;
8517 } else {
8518 // The declaration is extern "C". Check for any declaration in the
8519 // translation unit which might conflict.
8520 if (IsGlobal) {
8521 // We have already performed the lookup into the translation unit.
8522 IsGlobal = false;
8523 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8524 I != E; ++I) {
8525 if (isa<VarDecl>(*I)) {
8526 Prev = *I;
8527 break;
8528 }
8529 }
8530 } else {
8532 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8533 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8534 I != E; ++I) {
8535 if (isa<VarDecl>(*I)) {
8536 Prev = *I;
8537 break;
8538 }
8539 // FIXME: If we have any other entity with this name in global scope,
8540 // the declaration is ill-formed, but that is a defect: it breaks the
8541 // 'stat' hack, for instance. Only variables can have mangled name
8542 // clashes with extern "C" declarations, so only they deserve a
8543 // diagnostic.
8544 }
8545 }
8546
8547 if (!Prev)
8548 return false;
8549 }
8550
8551 // Use the first declaration's location to ensure we point at something which
8552 // is lexically inside an extern "C" linkage-spec.
8553 assert(Prev && "should have found a previous declaration to diagnose");
8554 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8555 Prev = FD->getFirstDecl();
8556 else
8557 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8558
8559 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8560 << IsGlobal << ND;
8561 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8562 << IsGlobal;
8563 return false;
8564}
8565
8566/// Apply special rules for handling extern "C" declarations. Returns \c true
8567/// if we have found that this is a redeclaration of some prior entity.
8568///
8569/// Per C++ [dcl.link]p6:
8570/// Two declarations [for a function or variable] with C language linkage
8571/// with the same name that appear in different scopes refer to the same
8572/// [entity]. An entity with C language linkage shall not be declared with
8573/// the same name as an entity in global scope.
8574template<typename T>
8577 if (!S.getLangOpts().CPlusPlus) {
8578 // In C, when declaring a global variable, look for a corresponding 'extern'
8579 // variable declared in function scope. We don't need this in C++, because
8580 // we find local extern decls in the surrounding file-scope DeclContext.
8581 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8582 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8583 Previous.clear();
8584 Previous.addDecl(Prev);
8585 return true;
8586 }
8587 }
8588 return false;
8589 }
8590
8591 // A declaration in the translation unit can conflict with an extern "C"
8592 // declaration.
8593 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8594 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8595
8596 // An extern "C" declaration can conflict with a declaration in the
8597 // translation unit or can be a redeclaration of an extern "C" declaration
8598 // in another scope.
8599 if (isIncompleteDeclExternC(S,ND))
8600 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8601
8602 // Neither global nor extern "C": nothing to do.
8603 return false;
8604}
8605
8606static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8607 QualType T) {
8608 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8609 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8610 // any of its members, even recursively, shall not have an atomic type, or a
8611 // variably modified type, or a type that is volatile or restrict qualified.
8612 if (CanonT->isVariablyModifiedType()) {
8613 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8614 return true;
8615 }
8616
8617 // Arrays are qualified by their element type, so get the base type (this
8618 // works on non-arrays as well).
8619 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8620
8621 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8622 CanonT.isRestrictQualified()) {
8623 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8624 return true;
8625 }
8626
8627 if (CanonT->isRecordType()) {
8628 const RecordDecl *RD = CanonT->getAsRecordDecl();
8629 if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8630 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8631 }))
8632 return true;
8633 }
8634
8635 return false;
8636}
8637
8639 // If the decl is already known invalid, don't check it.
8640 if (NewVD->isInvalidDecl())
8641 return;
8642
8643 QualType T = NewVD->getType();
8644
8645 // Defer checking an 'auto' type until its initializer is attached.
8646 if (T->isUndeducedType())
8647 return;
8648
8649 if (NewVD->hasAttrs())
8651
8652 if (T->isObjCObjectType()) {
8653 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8654 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8656 NewVD->setType(T);
8657 }
8658
8659 // Emit an error if an address space was applied to decl with local storage.
8660 // This includes arrays of objects with address space qualifiers, but not
8661 // automatic variables that point to other address spaces.
8662 // ISO/IEC TR 18037 S5.1.2
8663 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8664 T.getAddressSpace() != LangAS::Default) {
8665 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8666 NewVD->setInvalidDecl();
8667 return;
8668 }
8669
8670 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8671 // scope.
8672 if (getLangOpts().OpenCLVersion == 120 &&
8673 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8674 getLangOpts()) &&
8675 NewVD->isStaticLocal()) {
8676 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8677 NewVD->setInvalidDecl();
8678 return;
8679 }
8680
8681 if (getLangOpts().OpenCL) {
8682 if (!diagnoseOpenCLTypes(*this, NewVD))
8683 return;
8684
8685 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8686 if (NewVD->hasAttr<BlocksAttr>()) {
8687 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8688 return;
8689 }
8690
8691 if (T->isBlockPointerType()) {
8692 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8693 // can't use 'extern' storage class.
8694 if (!T.isConstQualified()) {
8695 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8696 << 0 /*const*/;
8697 NewVD->setInvalidDecl();
8698 return;
8699 }
8700 if (NewVD->hasExternalStorage()) {
8701 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8702 NewVD->setInvalidDecl();
8703 return;
8704 }
8705 }
8706
8707 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8708 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8709 NewVD->hasExternalStorage()) {
8710 if (!T->isSamplerT() && !T->isDependentType() &&
8711 !(T.getAddressSpace() == LangAS::opencl_constant ||
8712 (T.getAddressSpace() == LangAS::opencl_global &&
8713 getOpenCLOptions().areProgramScopeVariablesSupported(
8714 getLangOpts())))) {
8715 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8716 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8717 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8718 << Scope << "global or constant";
8719 else
8720 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8721 << Scope << "constant";
8722 NewVD->setInvalidDecl();
8723 return;
8724 }
8725 } else {
8726 if (T.getAddressSpace() == LangAS::opencl_global) {
8727 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8728 << 1 /*is any function*/ << "global";
8729 NewVD->setInvalidDecl();
8730 return;
8731 }
8732 if (T.getAddressSpace() == LangAS::opencl_constant ||
8733 T.getAddressSpace() == LangAS::opencl_local) {
8735 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8736 // in functions.
8737 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8738 if (T.getAddressSpace() == LangAS::opencl_constant)
8739 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8740 << 0 /*non-kernel only*/ << "constant";
8741 else
8742 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8743 << 0 /*non-kernel only*/ << "local";
8744 NewVD->setInvalidDecl();
8745 return;
8746 }
8747 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8748 // in the outermost scope of a kernel function.
8749 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8750 if (!getCurScope()->isFunctionScope()) {
8751 if (T.getAddressSpace() == LangAS::opencl_constant)
8752 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8753 << "constant";
8754 else
8755 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8756 << "local";
8757 NewVD->setInvalidDecl();
8758 return;
8759 }
8760 }
8761 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8762 // If we are parsing a template we didn't deduce an addr
8763 // space yet.
8764 T.getAddressSpace() != LangAS::Default) {
8765 // Do not allow other address spaces on automatic variable.
8766 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8767 NewVD->setInvalidDecl();
8768 return;
8769 }
8770 }
8771 }
8772
8773 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8774 && !NewVD->hasAttr<BlocksAttr>()) {
8775 if (getLangOpts().getGC() != LangOptions::NonGC)
8776 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8777 else {
8778 assert(!getLangOpts().ObjCAutoRefCount);
8779 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8780 }
8781 }
8782
8783 // WebAssembly tables must be static with a zero length and can't be
8784 // declared within functions.
8785 if (T->isWebAssemblyTableType()) {
8786 if (getCurScope()->getParent()) { // Parent is null at top-level
8787 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8788 NewVD->setInvalidDecl();
8789 return;
8790 }
8791 if (NewVD->getStorageClass() != SC_Static) {
8792 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8793 NewVD->setInvalidDecl();
8794 return;
8795 }
8796 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8797 if (!ATy || ATy->getZExtSize() != 0) {
8798 Diag(NewVD->getLocation(),
8799 diag::err_typecheck_wasm_table_must_have_zero_length);
8800 NewVD->setInvalidDecl();
8801 return;
8802 }
8803 }
8804
8805 // zero sized static arrays are not allowed in HIP device functions
8806 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
8807 if (FunctionDecl *FD = getCurFunctionDecl();
8808 FD &&
8809 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
8810 if (const ConstantArrayType *ArrayT =
8812 ArrayT && ArrayT->isZeroSize()) {
8813 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
8814 }
8815 }
8816 }
8817
8818 bool isVM = T->isVariablyModifiedType();
8819 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8820 NewVD->hasAttr<BlocksAttr>())
8822
8823 if ((isVM && NewVD->hasLinkage()) ||
8824 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8825 bool SizeIsNegative;
8826 llvm::APSInt Oversized;
8828 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8829 QualType FixedT;
8830 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8831 FixedT = FixedTInfo->getType();
8832 else if (FixedTInfo) {
8833 // Type and type-as-written are canonically different. We need to fix up
8834 // both types separately.
8835 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8836 Oversized);
8837 }
8838 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8840 // FIXME: This won't give the correct result for
8841 // int a[10][n];
8842 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8843
8844 if (NewVD->isFileVarDecl())
8845 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8846 << SizeRange;
8847 else if (NewVD->isStaticLocal())
8848 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8849 << SizeRange;
8850 else
8851 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8852 << SizeRange;
8853 NewVD->setInvalidDecl();
8854 return;
8855 }
8856
8857 if (!FixedTInfo) {
8858 if (NewVD->isFileVarDecl())
8859 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8860 else
8861 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8862 NewVD->setInvalidDecl();
8863 return;
8864 }
8865
8866 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8867 NewVD->setType(FixedT);
8868 NewVD->setTypeSourceInfo(FixedTInfo);
8869 }
8870
8871 if (T->isVoidType()) {
8872 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8873 // of objects and functions.
8875 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8876 << T;
8877 NewVD->setInvalidDecl();
8878 return;
8879 }
8880 }
8881
8882 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8883 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8884 NewVD->setInvalidDecl();
8885 return;
8886 }
8887
8888 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8889 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
8890 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8891 NewVD->setInvalidDecl();
8892 return;
8893 }
8894
8895 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8896 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8897 NewVD->setInvalidDecl();
8898 return;
8899 }
8900
8901 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8902 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8903 NewVD->setInvalidDecl();
8904 return;
8905 }
8906
8907 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
8908 !T->isDependentType() &&
8910 diag::err_constexpr_var_non_literal)) {
8911 NewVD->setInvalidDecl();
8912 return;
8913 }
8914
8915 // PPC MMA non-pointer types are not allowed as non-local variable types.
8916 if (Context.getTargetInfo().getTriple().isPPC64() &&
8917 !NewVD->isLocalVarDecl() &&
8918 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
8919 NewVD->setInvalidDecl();
8920 return;
8921 }
8922
8923 // Check that SVE types are only used in functions with SVE available.
8924 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8925 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8926 llvm::StringMap<bool> CallerFeatureMap;
8927 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8928
8929 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
8930 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
8931 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8932 NewVD->setInvalidDecl();
8933 return;
8934 } else if (!IsArmStreamingFunction(FD,
8935 /*IncludeLocallyStreaming=*/true)) {
8936 Diag(NewVD->getLocation(),
8937 diag::err_sve_vector_in_non_streaming_function)
8938 << T;
8939 NewVD->setInvalidDecl();
8940 return;
8941 }
8942 }
8943 }
8944
8945 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8946 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8947 llvm::StringMap<bool> CallerFeatureMap;
8948 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8949 RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
8950 CallerFeatureMap);
8951 }
8952}
8953
8956
8957 // If the decl is already known invalid, don't check it.
8958 if (NewVD->isInvalidDecl())
8959 return false;
8960
8961 // If we did not find anything by this name, look for a non-visible
8962 // extern "C" declaration with the same name.
8963 if (Previous.empty() &&
8965 Previous.setShadowed();
8966
8967 if (!Previous.empty()) {
8968 MergeVarDecl(NewVD, Previous);
8969 return true;
8970 }
8971 return false;
8972}
8973
8976
8977 // Look for methods in base classes that this method might override.
8978 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8979 /*DetectVirtual=*/false);
8980 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8981 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8982 DeclarationName Name = MD->getDeclName();
8983
8984 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8985 // We really want to find the base class destructor here.
8986 QualType T = Context.getTypeDeclType(BaseRecord);
8989 }
8990
8991 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8992 CXXMethodDecl *BaseMD =
8993 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8994 if (!BaseMD || !BaseMD->isVirtual() ||
8995 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8996 /*ConsiderCudaAttrs=*/true))
8997 continue;
8998 if (!CheckExplicitObjectOverride(MD, BaseMD))
8999 continue;
9000 if (Overridden.insert(BaseMD).second) {
9001 MD->addOverriddenMethod(BaseMD);
9006 }
9007
9008 // A method can only override one function from each base class. We
9009 // don't track indirectly overridden methods from bases of bases.
9010 return true;
9011 }
9012
9013 return false;
9014 };
9015
9016 DC->lookupInBases(VisitBase, Paths);
9017 return !Overridden.empty();
9018}
9019
9020namespace {
9021 // Struct for holding all of the extra arguments needed by
9022 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9023 struct ActOnFDArgs {
9024 Scope *S;
9025 Declarator &D;
9026 MultiTemplateParamsArg TemplateParamLists;
9027 bool AddToScope;
9028 };
9029} // end anonymous namespace
9030
9031namespace {
9032
9033// Callback to only accept typo corrections that have a non-zero edit distance.
9034// Also only accept corrections that have the same parent decl.
9035class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9036 public:
9037 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9039 : Context(Context), OriginalFD(TypoFD),
9040 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9041
9042 bool ValidateCandidate(const TypoCorrection &candidate) override {
9043 if (candidate.getEditDistance() == 0)
9044 return false;
9045
9046 SmallVector<unsigned, 1> MismatchedParams;
9047 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9048 CDeclEnd = candidate.end();
9049 CDecl != CDeclEnd; ++CDecl) {
9050 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9051
9052 if (FD && !FD->hasBody() &&
9053 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9054 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9055 CXXRecordDecl *Parent = MD->getParent();
9056 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9057 return true;
9058 } else if (!ExpectedParent) {
9059 return true;
9060 }
9061 }
9062 }
9063
9064 return false;
9065 }
9066
9067 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9068 return std::make_unique<DifferentNameValidatorCCC>(*this);
9069 }
9070
9071 private:
9072 ASTContext &Context;
9073 FunctionDecl *OriginalFD;
9074 CXXRecordDecl *ExpectedParent;
9075};
9076
9077} // end anonymous namespace
9078
9081}
9082
9083/// Generate diagnostics for an invalid function redeclaration.
9084///
9085/// This routine handles generating the diagnostic messages for an invalid
9086/// function redeclaration, including finding possible similar declarations
9087/// or performing typo correction if there are no previous declarations with
9088/// the same name.
9089///
9090/// Returns a NamedDecl iff typo correction was performed and substituting in
9091/// the new declaration name does not cause new errors.
9093 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9094 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9095 DeclarationName Name = NewFD->getDeclName();
9096 DeclContext *NewDC = NewFD->getDeclContext();
9097 SmallVector<unsigned, 1> MismatchedParams;
9099 TypoCorrection Correction;
9100 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9101 unsigned DiagMsg =
9102 IsLocalFriend ? diag::err_no_matching_local_friend :
9103 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9104 diag::err_member_decl_does_not_match;
9105 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9106 IsLocalFriend ? Sema::LookupLocalFriendName
9108 RedeclarationKind::ForVisibleRedeclaration);
9109
9110 NewFD->setInvalidDecl();
9111 if (IsLocalFriend)
9112 SemaRef.LookupName(Prev, S);
9113 else
9114 SemaRef.LookupQualifiedName(Prev, NewDC);
9115 assert(!Prev.isAmbiguous() &&
9116 "Cannot have an ambiguity in previous-declaration lookup");
9117 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9118 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9119 MD ? MD->getParent() : nullptr);
9120 if (!Prev.empty()) {
9121 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9122 Func != FuncEnd; ++Func) {
9123 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9124 if (FD &&
9125 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9126 // Add 1 to the index so that 0 can mean the mismatch didn't
9127 // involve a parameter
9128 unsigned ParamNum =
9129 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9130 NearMatches.push_back(std::make_pair(FD, ParamNum));
9131 }
9132 }
9133 // If the qualified name lookup yielded nothing, try typo correction
9134 } else if ((Correction = SemaRef.CorrectTypo(
9135 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9136 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9137 IsLocalFriend ? nullptr : NewDC))) {
9138 // Set up everything for the call to ActOnFunctionDeclarator
9139 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9140 ExtraArgs.D.getIdentifierLoc());
9141 Previous.clear();
9142 Previous.setLookupName(Correction.getCorrection());
9143 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9144 CDeclEnd = Correction.end();
9145 CDecl != CDeclEnd; ++CDecl) {
9146 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9147 if (FD && !FD->hasBody() &&
9148 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9149 Previous.addDecl(FD);
9150 }
9151 }
9152 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9153
9155 // Retry building the function declaration with the new previous
9156 // declarations, and with errors suppressed.
9157 {
9158 // Trap errors.
9159 Sema::SFINAETrap Trap(SemaRef);
9160
9161 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9162 // pieces need to verify the typo-corrected C++ declaration and hopefully
9163 // eliminate the need for the parameter pack ExtraArgs.
9165 ExtraArgs.S, ExtraArgs.D,
9166 Correction.getCorrectionDecl()->getDeclContext(),
9167 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9168 ExtraArgs.AddToScope);
9169
9170 if (Trap.hasErrorOccurred())
9171 Result = nullptr;
9172 }
9173
9174 if (Result) {
9175 // Determine which correction we picked.
9176 Decl *Canonical = Result->getCanonicalDecl();
9177 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9178 I != E; ++I)
9179 if ((*I)->getCanonicalDecl() == Canonical)
9180 Correction.setCorrectionDecl(*I);
9181
9182 // Let Sema know about the correction.
9184 SemaRef.diagnoseTypo(
9185 Correction,
9186 SemaRef.PDiag(IsLocalFriend
9187 ? diag::err_no_matching_local_friend_suggest
9188 : diag::err_member_decl_does_not_match_suggest)
9189 << Name << NewDC << IsDefinition);
9190 return Result;
9191 }
9192
9193 // Pretend the typo correction never occurred
9194 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9195 ExtraArgs.D.getIdentifierLoc());
9196 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9197 Previous.clear();
9198 Previous.setLookupName(Name);
9199 }
9200
9201 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9202 << Name << NewDC << IsDefinition << NewFD->getLocation();
9203
9204 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9205 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9206 CXXRecordDecl *RD = NewMD->getParent();
9207 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9208 << RD->getName() << RD->getLocation();
9209 }
9210
9211 bool NewFDisConst = NewMD && NewMD->isConst();
9212
9213 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9214 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9215 NearMatch != NearMatchEnd; ++NearMatch) {
9216 FunctionDecl *FD = NearMatch->first;
9217 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9218 bool FDisConst = MD && MD->isConst();
9219 bool IsMember = MD || !IsLocalFriend;
9220
9221 // FIXME: These notes are poorly worded for the local friend case.
9222 if (unsigned Idx = NearMatch->second) {
9223 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9225 if (Loc.isInvalid()) Loc = FD->getLocation();
9226 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9227 : diag::note_local_decl_close_param_match)
9228 << Idx << FDParam->getType()
9229 << NewFD->getParamDecl(Idx - 1)->getType();
9230 } else if (FDisConst != NewFDisConst) {
9231 auto DB = SemaRef.Diag(FD->getLocation(),
9232 diag::note_member_def_close_const_match)
9233 << NewFDisConst << FD->getSourceRange().getEnd();
9234 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9235 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9236 " const");
9237 else if (FTI.hasMethodTypeQualifiers() &&
9238 FTI.getConstQualifierLoc().isValid())
9239 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9240 } else {
9241 SemaRef.Diag(FD->getLocation(),
9242 IsMember ? diag::note_member_def_close_match
9243 : diag::note_local_decl_close_match);
9244 }
9245 }
9246 return nullptr;
9247}
9248
9250 switch (D.getDeclSpec().getStorageClassSpec()) {
9251 default: llvm_unreachable("Unknown storage class!");
9252 case DeclSpec::SCS_auto:
9255 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9256 diag::err_typecheck_sclass_func);
9257 D.getMutableDeclSpec().ClearStorageClassSpecs();
9258 D.setInvalidType();
9259 break;
9260 case DeclSpec::SCS_unspecified: break;
9262 if (D.getDeclSpec().isExternInLinkageSpec())
9263 return SC_None;
9264 return SC_Extern;
9265 case DeclSpec::SCS_static: {
9267 // C99 6.7.1p5:
9268 // The declaration of an identifier for a function that has
9269 // block scope shall have no explicit storage-class specifier
9270 // other than extern
9271 // See also (C++ [dcl.stc]p4).
9272 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9273 diag::err_static_block_func);
9274 break;
9275 } else
9276 return SC_Static;
9277 }
9279 }
9280
9281 // No explicit storage class has already been returned
9282 return SC_None;
9283}
9284
9286 DeclContext *DC, QualType &R,
9287 TypeSourceInfo *TInfo,
9288 StorageClass SC,
9289 bool &IsVirtualOkay) {
9290 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9291 DeclarationName Name = NameInfo.getName();
9292
9293 FunctionDecl *NewFD = nullptr;
9294 bool isInline = D.getDeclSpec().isInlineSpecified();
9295
9296 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9297 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9298 (SemaRef.getLangOpts().C23 &&
9299 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9300
9301 if (SemaRef.getLangOpts().C23)
9302 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9303 diag::err_c23_constexpr_not_variable);
9304 else
9305 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9306 diag::err_constexpr_wrong_decl_kind)
9307 << static_cast<int>(ConstexprKind);
9308 ConstexprKind = ConstexprSpecKind::Unspecified;
9309 D.getMutableDeclSpec().ClearConstexprSpec();
9310 }
9311
9312 if (!SemaRef.getLangOpts().CPlusPlus) {
9313 // Determine whether the function was written with a prototype. This is
9314 // true when:
9315 // - there is a prototype in the declarator, or
9316 // - the type R of the function is some kind of typedef or other non-
9317 // attributed reference to a type name (which eventually refers to a
9318 // function type). Note, we can't always look at the adjusted type to
9319 // check this case because attributes may cause a non-function
9320 // declarator to still have a function type. e.g.,
9321 // typedef void func(int a);
9322 // __attribute__((noreturn)) func other_func; // This has a prototype
9323 bool HasPrototype =
9324 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9325 (D.getDeclSpec().isTypeRep() &&
9326 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9327 ->isFunctionProtoType()) ||
9329 assert(
9330 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9331 "Strict prototypes are required");
9332
9333 NewFD = FunctionDecl::Create(
9334 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9335 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9337 /*TrailingRequiresClause=*/nullptr);
9338 if (D.isInvalidType())
9339 NewFD->setInvalidDecl();
9340
9341 return NewFD;
9342 }
9343
9344 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9345 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9346
9347 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9348
9349 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9350 // This is a C++ constructor declaration.
9351 assert(DC->isRecord() &&
9352 "Constructors can only be declared in a member context");
9353
9354 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9356 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9358 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9359 InheritedConstructor(), TrailingRequiresClause);
9360
9361 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9362 // This is a C++ destructor declaration.
9363 if (DC->isRecord()) {
9364 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9365 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9367 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9368 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9369 /*isImplicitlyDeclared=*/false, ConstexprKind,
9370 TrailingRequiresClause);
9371 // User defined destructors start as not selected if the class definition is still
9372 // not done.
9373 if (Record->isBeingDefined())
9374 NewDD->setIneligibleOrNotSelected(true);
9375
9376 // If the destructor needs an implicit exception specification, set it
9377 // now. FIXME: It'd be nice to be able to create the right type to start
9378 // with, but the type needs to reference the destructor declaration.
9379 if (SemaRef.getLangOpts().CPlusPlus11)
9380 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9381
9382 IsVirtualOkay = true;
9383 return NewDD;
9384
9385 } else {
9386 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9387 D.setInvalidType();
9388
9389 // Create a FunctionDecl to satisfy the function definition parsing
9390 // code path.
9391 return FunctionDecl::Create(
9392 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9393 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9394 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9395 }
9396
9397 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9398 if (!DC->isRecord()) {
9399 SemaRef.Diag(D.getIdentifierLoc(),
9400 diag::err_conv_function_not_member);
9401 return nullptr;
9402 }
9403
9404 SemaRef.CheckConversionDeclarator(D, R, SC);
9405 if (D.isInvalidType())
9406 return nullptr;
9407
9408 IsVirtualOkay = true;
9410 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9411 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9412 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9413 TrailingRequiresClause);
9414
9415 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9416 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9417 return nullptr;
9419 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9420 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9421 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9422 } else if (DC->isRecord()) {
9423 // If the name of the function is the same as the name of the record,
9424 // then this must be an invalid constructor that has a return type.
9425 // (The parser checks for a return type and makes the declarator a
9426 // constructor if it has no return type).
9427 if (Name.getAsIdentifierInfo() &&
9428 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9429 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9430 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9431 << SourceRange(D.getIdentifierLoc());
9432 return nullptr;
9433 }
9434
9435 // This is a C++ method declaration.
9437 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9438 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9439 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9440 IsVirtualOkay = !Ret->isStatic();
9441 return Ret;
9442 } else {
9443 bool isFriend =
9444 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9445 if (!isFriend && SemaRef.CurContext->isRecord())
9446 return nullptr;
9447
9448 // Determine whether the function was written with a
9449 // prototype. This true when:
9450 // - we're in C++ (where every function has a prototype),
9451 return FunctionDecl::Create(
9452 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9453 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9454 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9455 }
9456}
9457
9466
9468 // Size dependent types are just typedefs to normal integer types
9469 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9470 // integers other than by their names.
9471 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9472
9473 // Remove typedefs one by one until we reach a typedef
9474 // for a size dependent type.
9475 QualType DesugaredTy = Ty;
9476 do {
9477 ArrayRef<StringRef> Names(SizeTypeNames);
9478 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9479 if (Names.end() != Match)
9480 return true;
9481
9482 Ty = DesugaredTy;
9483 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9484 } while (DesugaredTy != Ty);
9485
9486 return false;
9487}
9488
9490 if (PT->isDependentType())
9491 return InvalidKernelParam;
9492
9493 if (PT->isPointerOrReferenceType()) {
9494 QualType PointeeType = PT->getPointeeType();
9495 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9496 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9497 PointeeType.getAddressSpace() == LangAS::Default)
9499
9500 if (PointeeType->isPointerType()) {
9501 // This is a pointer to pointer parameter.
9502 // Recursively check inner type.
9503 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9504 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9505 ParamKind == InvalidKernelParam)
9506 return ParamKind;
9507
9508 // OpenCL v3.0 s6.11.a:
9509 // A restriction to pass pointers to pointers only applies to OpenCL C
9510 // v1.2 or below.
9512 return ValidKernelParam;
9513
9514 return PtrPtrKernelParam;
9515 }
9516
9517 // C++ for OpenCL v1.0 s2.4:
9518 // Moreover the types used in parameters of the kernel functions must be:
9519 // Standard layout types for pointer parameters. The same applies to
9520 // reference if an implementation supports them in kernel parameters.
9521 if (S.getLangOpts().OpenCLCPlusPlus &&
9523 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9524 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9525 bool IsStandardLayoutType = true;
9526 if (CXXRec) {
9527 // If template type is not ODR-used its definition is only available
9528 // in the template definition not its instantiation.
9529 // FIXME: This logic doesn't work for types that depend on template
9530 // parameter (PR58590).
9531 if (!CXXRec->hasDefinition())
9532 CXXRec = CXXRec->getTemplateInstantiationPattern();
9533 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9534 IsStandardLayoutType = false;
9535 }
9536 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9537 !IsStandardLayoutType)
9538 return InvalidKernelParam;
9539 }
9540
9541 // OpenCL v1.2 s6.9.p:
9542 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9544 return ValidKernelParam;
9545
9546 return PtrKernelParam;
9547 }
9548
9549 // OpenCL v1.2 s6.9.k:
9550 // Arguments to kernel functions in a program cannot be declared with the
9551 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9552 // uintptr_t or a struct and/or union that contain fields declared to be one
9553 // of these built-in scalar types.
9555 return InvalidKernelParam;
9556
9557 if (PT->isImageType())
9558 return PtrKernelParam;
9559
9560 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9561 return InvalidKernelParam;
9562
9563 // OpenCL extension spec v1.2 s9.5:
9564 // This extension adds support for half scalar and vector types as built-in
9565 // types that can be used for arithmetic operations, conversions etc.
9566 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9567 PT->isHalfType())
9568 return InvalidKernelParam;
9569
9570 // Look into an array argument to check if it has a forbidden type.
9571 if (PT->isArrayType()) {
9572 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9573 // Call ourself to check an underlying type of an array. Since the
9574 // getPointeeOrArrayElementType returns an innermost type which is not an
9575 // array, this recursive call only happens once.
9576 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9577 }
9578
9579 // C++ for OpenCL v1.0 s2.4:
9580 // Moreover the types used in parameters of the kernel functions must be:
9581 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9582 // types) for parameters passed by value;
9583 if (S.getLangOpts().OpenCLCPlusPlus &&
9585 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9586 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9587 return InvalidKernelParam;
9588
9589 if (PT->isRecordType())
9590 return RecordKernelParam;
9591
9592 return ValidKernelParam;
9593}
9594
9596 Sema &S,
9597 Declarator &D,
9598 ParmVarDecl *Param,
9599 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9600 QualType PT = Param->getType();
9601
9602 // Cache the valid types we encounter to avoid rechecking structs that are
9603 // used again
9604 if (ValidTypes.count(PT.getTypePtr()))
9605 return;
9606
9607 switch (getOpenCLKernelParameterType(S, PT)) {
9608 case PtrPtrKernelParam:
9609 // OpenCL v3.0 s6.11.a:
9610 // A kernel function argument cannot be declared as a pointer to a pointer
9611 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9612 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9613 D.setInvalidType();
9614 return;
9615
9617 // OpenCL v1.0 s6.5:
9618 // __kernel function arguments declared to be a pointer of a type can point
9619 // to one of the following address spaces only : __global, __local or
9620 // __constant.
9621 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9622 D.setInvalidType();
9623 return;
9624
9625 // OpenCL v1.2 s6.9.k:
9626 // Arguments to kernel functions in a program cannot be declared with the
9627 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9628 // uintptr_t or a struct and/or union that contain fields declared to be
9629 // one of these built-in scalar types.
9630
9631 case InvalidKernelParam:
9632 // OpenCL v1.2 s6.8 n:
9633 // A kernel function argument cannot be declared
9634 // of event_t type.
9635 // Do not diagnose half type since it is diagnosed as invalid argument
9636 // type for any function elsewhere.
9637 if (!PT->isHalfType()) {
9638 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9639
9640 // Explain what typedefs are involved.
9641 const TypedefType *Typedef = nullptr;
9642 while ((Typedef = PT->getAs<TypedefType>())) {
9643 SourceLocation Loc = Typedef->getDecl()->getLocation();
9644 // SourceLocation may be invalid for a built-in type.
9645 if (Loc.isValid())
9646 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9647 PT = Typedef->desugar();
9648 }
9649 }
9650
9651 D.setInvalidType();
9652 return;
9653
9654 case PtrKernelParam:
9655 case ValidKernelParam:
9656 ValidTypes.insert(PT.getTypePtr());
9657 return;
9658
9659 case RecordKernelParam:
9660 break;
9661 }
9662
9663 // Track nested structs we will inspect
9665
9666 // Track where we are in the nested structs. Items will migrate from
9667 // VisitStack to HistoryStack as we do the DFS for bad field.
9669 HistoryStack.push_back(nullptr);
9670
9671 // At this point we already handled everything except of a RecordType or
9672 // an ArrayType of a RecordType.
9673 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9674 const RecordType *RecTy =
9676 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9677
9678 VisitStack.push_back(RecTy->getDecl());
9679 assert(VisitStack.back() && "First decl null?");
9680
9681 do {
9682 const Decl *Next = VisitStack.pop_back_val();
9683 if (!Next) {
9684 assert(!HistoryStack.empty());
9685 // Found a marker, we have gone up a level
9686 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9687 ValidTypes.insert(Hist->getType().getTypePtr());
9688
9689 continue;
9690 }
9691
9692 // Adds everything except the original parameter declaration (which is not a
9693 // field itself) to the history stack.
9694 const RecordDecl *RD;
9695 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9696 HistoryStack.push_back(Field);
9697
9698 QualType FieldTy = Field->getType();
9699 // Other field types (known to be valid or invalid) are handled while we
9700 // walk around RecordDecl::fields().
9701 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9702 "Unexpected type.");
9703 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9704
9705 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9706 } else {
9707 RD = cast<RecordDecl>(Next);
9708 }
9709
9710 // Add a null marker so we know when we've gone back up a level
9711 VisitStack.push_back(nullptr);
9712
9713 for (const auto *FD : RD->fields()) {
9714 QualType QT = FD->getType();
9715
9716 if (ValidTypes.count(QT.getTypePtr()))
9717 continue;
9718
9720 if (ParamType == ValidKernelParam)
9721 continue;
9722
9723 if (ParamType == RecordKernelParam) {
9724 VisitStack.push_back(FD);
9725 continue;
9726 }
9727
9728 // OpenCL v1.2 s6.9.p:
9729 // Arguments to kernel functions that are declared to be a struct or union
9730 // do not allow OpenCL objects to be passed as elements of the struct or
9731 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9732 // of SVM.
9733 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9734 ParamType == InvalidAddrSpacePtrKernelParam) {
9735 S.Diag(Param->getLocation(),
9736 diag::err_record_with_pointers_kernel_param)
9737 << PT->isUnionType()
9738 << PT;
9739 } else {
9740 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9741 }
9742
9743 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9744 << OrigRecDecl->getDeclName();
9745
9746 // We have an error, now let's go back up through history and show where
9747 // the offending field came from
9749 I = HistoryStack.begin() + 1,
9750 E = HistoryStack.end();
9751 I != E; ++I) {
9752 const FieldDecl *OuterField = *I;
9753 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9754 << OuterField->getType();
9755 }
9756
9757 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9758 << QT->isPointerType()
9759 << QT;
9760 D.setInvalidType();
9761 return;
9762 }
9763 } while (!VisitStack.empty());
9764}
9765
9766/// Find the DeclContext in which a tag is implicitly declared if we see an
9767/// elaborated type specifier in the specified context, and lookup finds
9768/// nothing.
9770 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9771 DC = DC->getParent();
9772 return DC;
9773}
9774
9775/// Find the Scope in which a tag is implicitly declared if we see an
9776/// elaborated type specifier in the specified context, and lookup finds
9777/// nothing.
9778static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9779 while (S->isClassScope() ||
9780 (LangOpts.CPlusPlus &&
9781 S->isFunctionPrototypeScope()) ||
9782 ((S->getFlags() & Scope::DeclScope) == 0) ||
9783 (S->getEntity() && S->getEntity()->isTransparentContext()))
9784 S = S->getParent();
9785 return S;
9786}
9787
9788/// Determine whether a declaration matches a known function in namespace std.
9790 unsigned BuiltinID) {
9791 switch (BuiltinID) {
9792 case Builtin::BI__GetExceptionInfo:
9793 // No type checking whatsoever.
9794 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9795
9796 case Builtin::BIaddressof:
9797 case Builtin::BI__addressof:
9798 case Builtin::BIforward:
9799 case Builtin::BIforward_like:
9800 case Builtin::BImove:
9801 case Builtin::BImove_if_noexcept:
9802 case Builtin::BIas_const: {
9803 // Ensure that we don't treat the algorithm
9804 // OutputIt std::move(InputIt, InputIt, OutputIt)
9805 // as the builtin std::move.
9806 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9807 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9808 }
9809
9810 default:
9811 return false;
9812 }
9813}
9814
9815NamedDecl*
9818 MultiTemplateParamsArg TemplateParamListsRef,
9819 bool &AddToScope) {
9820 QualType R = TInfo->getType();
9821
9822 assert(R->isFunctionType());
9824 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9825
9826 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9827 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9828 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9829 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9830 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9831 TemplateParamLists.back() = Invented;
9832 else
9833 TemplateParamLists.push_back(Invented);
9834 }
9835
9836 // TODO: consider using NameInfo for diagnostic.
9838 DeclarationName Name = NameInfo.getName();
9840
9841 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9842 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9843 diag::err_invalid_thread)
9845
9846 if (D.isFirstDeclarationOfMember())
9848 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9849 D.isCtorOrDtor(), D.getIdentifierLoc());
9850
9851 bool isFriend = false;
9853 bool isMemberSpecialization = false;
9854 bool isFunctionTemplateSpecialization = false;
9855
9856 bool HasExplicitTemplateArgs = false;
9857 TemplateArgumentListInfo TemplateArgs;
9858
9859 bool isVirtualOkay = false;
9860
9861 DeclContext *OriginalDC = DC;
9862 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9863
9864 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9865 isVirtualOkay);
9866 if (!NewFD) return nullptr;
9867
9870
9871 // Set the lexical context. If this is a function-scope declaration, or has a
9872 // C++ scope specifier, or is the object of a friend declaration, the lexical
9873 // context will be different from the semantic context.
9875
9876 if (IsLocalExternDecl)
9877 NewFD->setLocalExternDecl();
9878
9879 if (getLangOpts().CPlusPlus) {
9880 // The rules for implicit inlines changed in C++20 for methods and friends
9881 // with an in-class definition (when such a definition is not attached to
9882 // the global module). This does not affect declarations that are already
9883 // inline (whether explicitly or implicitly by being declared constexpr,
9884 // consteval, etc).
9885 // FIXME: We need a better way to separate C++ standard and clang modules.
9886 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9887 !NewFD->getOwningModule() ||
9888 NewFD->isFromGlobalModule() ||
9890 bool isInline = D.getDeclSpec().isInlineSpecified();
9891 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9892 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9893 isFriend = D.getDeclSpec().isFriendSpecified();
9894 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
9895 // Pre-C++20 [class.friend]p5
9896 // A function can be defined in a friend declaration of a
9897 // class . . . . Such a function is implicitly inline.
9898 // Post C++20 [class.friend]p7
9899 // Such a function is implicitly an inline function if it is attached
9900 // to the global module.
9901 NewFD->setImplicitlyInline();
9902 }
9903
9904 // If this is a method defined in an __interface, and is not a constructor
9905 // or an overloaded operator, then set the pure flag (isVirtual will already
9906 // return true).
9907 if (const CXXRecordDecl *Parent =
9908 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9909 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9910 NewFD->setIsPureVirtual(true);
9911
9912 // C++ [class.union]p2
9913 // A union can have member functions, but not virtual functions.
9914 if (isVirtual && Parent->isUnion()) {
9915 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9916 NewFD->setInvalidDecl();
9917 }
9918 if ((Parent->isClass() || Parent->isStruct()) &&
9919 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9920 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9921 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9922 if (auto *Def = Parent->getDefinition())
9923 Def->setInitMethod(true);
9924 }
9925 }
9926
9927 SetNestedNameSpecifier(*this, NewFD, D);
9928 isMemberSpecialization = false;
9929 isFunctionTemplateSpecialization = false;
9930 if (D.isInvalidType())
9931 NewFD->setInvalidDecl();
9932
9933 // Match up the template parameter lists with the scope specifier, then
9934 // determine whether we have a template or a template specialization.
9935 bool Invalid = false;
9936 TemplateIdAnnotation *TemplateId =
9938 ? D.getName().TemplateId
9939 : nullptr;
9940 TemplateParameterList *TemplateParams =
9942 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9943 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
9944 isMemberSpecialization, Invalid);
9945 if (TemplateParams) {
9946 // Check that we can declare a template here.
9947 if (CheckTemplateDeclScope(S, TemplateParams))
9948 NewFD->setInvalidDecl();
9949
9950 if (TemplateParams->size() > 0) {
9951 // This is a function template
9952
9953 // A destructor cannot be a template.
9954 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9955 Diag(NewFD->getLocation(), diag::err_destructor_template);
9956 NewFD->setInvalidDecl();
9957 // Function template with explicit template arguments.
9958 } else if (TemplateId) {
9959 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9960 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9961 NewFD->setInvalidDecl();
9962 }
9963
9964 // If we're adding a template to a dependent context, we may need to
9965 // rebuilding some of the types used within the template parameter list,
9966 // now that we know what the current instantiation is.
9967 if (DC->isDependentContext()) {
9968 ContextRAII SavedContext(*this, DC);
9970 Invalid = true;
9971 }
9972
9974 NewFD->getLocation(),
9975 Name, TemplateParams,
9976 NewFD);
9977 FunctionTemplate->setLexicalDeclContext(CurContext);
9979
9980 // For source fidelity, store the other template param lists.
9981 if (TemplateParamLists.size() > 1) {
9983 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9984 .drop_back(1));
9985 }
9986 } else {
9987 // This is a function template specialization.
9988 isFunctionTemplateSpecialization = true;
9989 // For source fidelity, store all the template param lists.
9990 if (TemplateParamLists.size() > 0)
9991 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9992
9993 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9994 if (isFriend) {
9995 // We want to remove the "template<>", found here.
9996 SourceRange RemoveRange = TemplateParams->getSourceRange();
9997
9998 // If we remove the template<> and the name is not a
9999 // template-id, we're actually silently creating a problem:
10000 // the friend declaration will refer to an untemplated decl,
10001 // and clearly the user wants a template specialization. So
10002 // we need to insert '<>' after the name.
10003 SourceLocation InsertLoc;
10004 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10005 InsertLoc = D.getName().getSourceRange().getEnd();
10006 InsertLoc = getLocForEndOfToken(InsertLoc);
10007 }
10008
10009 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10010 << Name << RemoveRange
10011 << FixItHint::CreateRemoval(RemoveRange)
10012 << FixItHint::CreateInsertion(InsertLoc, "<>");
10013 Invalid = true;
10014
10015 // Recover by faking up an empty template argument list.
10016 HasExplicitTemplateArgs = true;
10017 TemplateArgs.setLAngleLoc(InsertLoc);
10018 TemplateArgs.setRAngleLoc(InsertLoc);
10019 }
10020 }
10021 } else {
10022 // Check that we can declare a template here.
10023 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10024 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10025 NewFD->setInvalidDecl();
10026
10027 // All template param lists were matched against the scope specifier:
10028 // this is NOT (an explicit specialization of) a template.
10029 if (TemplateParamLists.size() > 0)
10030 // For source fidelity, store all the template param lists.
10031 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10032
10033 // "friend void foo<>(int);" is an implicit specialization decl.
10034 if (isFriend && TemplateId)
10035 isFunctionTemplateSpecialization = true;
10036 }
10037
10038 // If this is a function template specialization and the unqualified-id of
10039 // the declarator-id is a template-id, convert the template argument list
10040 // into our AST format and check for unexpanded packs.
10041 if (isFunctionTemplateSpecialization && TemplateId) {
10042 HasExplicitTemplateArgs = true;
10043
10044 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10045 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10046 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10047 TemplateId->NumArgs);
10048 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10049
10050 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10051 // declaration of a function template partial specialization? Should we
10052 // consider the unexpanded pack context to be a partial specialization?
10053 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10055 ArgLoc, isFriend ? UPPC_FriendDeclaration
10057 NewFD->setInvalidDecl();
10058 }
10059 }
10060
10061 if (Invalid) {
10062 NewFD->setInvalidDecl();
10063 if (FunctionTemplate)
10064 FunctionTemplate->setInvalidDecl();
10065 }
10066
10067 // C++ [dcl.fct.spec]p5:
10068 // The virtual specifier shall only be used in declarations of
10069 // nonstatic class member functions that appear within a
10070 // member-specification of a class declaration; see 10.3.
10071 //
10072 if (isVirtual && !NewFD->isInvalidDecl()) {
10073 if (!isVirtualOkay) {
10074 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10075 diag::err_virtual_non_function);
10076 } else if (!CurContext->isRecord()) {
10077 // 'virtual' was specified outside of the class.
10078 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10079 diag::err_virtual_out_of_class)
10080 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10081 } else if (NewFD->getDescribedFunctionTemplate()) {
10082 // C++ [temp.mem]p3:
10083 // A member function template shall not be virtual.
10084 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10085 diag::err_virtual_member_function_template)
10086 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10087 } else {
10088 // Okay: Add virtual to the method.
10089 NewFD->setVirtualAsWritten(true);
10090 }
10091
10092 if (getLangOpts().CPlusPlus14 &&
10093 NewFD->getReturnType()->isUndeducedType())
10094 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10095 }
10096
10097 // C++ [dcl.fct.spec]p3:
10098 // The inline specifier shall not appear on a block scope function
10099 // declaration.
10100 if (isInline && !NewFD->isInvalidDecl()) {
10102 // 'inline' is not allowed on block scope function declaration.
10103 Diag(D.getDeclSpec().getInlineSpecLoc(),
10104 diag::err_inline_declaration_block_scope) << Name
10105 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10106 }
10107 }
10108
10109 // C++ [dcl.fct.spec]p6:
10110 // The explicit specifier shall be used only in the declaration of a
10111 // constructor or conversion function within its class definition;
10112 // see 12.3.1 and 12.3.2.
10113 if (hasExplicit && !NewFD->isInvalidDecl() &&
10114 !isa<CXXDeductionGuideDecl>(NewFD)) {
10115 if (!CurContext->isRecord()) {
10116 // 'explicit' was specified outside of the class.
10117 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10118 diag::err_explicit_out_of_class)
10119 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10120 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10121 !isa<CXXConversionDecl>(NewFD)) {
10122 // 'explicit' was specified on a function that wasn't a constructor
10123 // or conversion function.
10124 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10125 diag::err_explicit_non_ctor_or_conv_function)
10126 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10127 }
10128 }
10129
10130 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10131 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10132 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10133 // are implicitly inline.
10134 NewFD->setImplicitlyInline();
10135
10136 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10137 // be either constructors or to return a literal type. Therefore,
10138 // destructors cannot be declared constexpr.
10139 if (isa<CXXDestructorDecl>(NewFD) &&
10141 ConstexprKind == ConstexprSpecKind::Consteval)) {
10142 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10143 << static_cast<int>(ConstexprKind);
10144 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10147 }
10148 // C++20 [dcl.constexpr]p2: An allocation function, or a
10149 // deallocation function shall not be declared with the consteval
10150 // specifier.
10151 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10152 (NewFD->getOverloadedOperator() == OO_New ||
10153 NewFD->getOverloadedOperator() == OO_Array_New ||
10154 NewFD->getOverloadedOperator() == OO_Delete ||
10155 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10156 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10157 diag::err_invalid_consteval_decl_kind)
10158 << NewFD;
10160 }
10161 }
10162
10163 // If __module_private__ was specified, mark the function accordingly.
10164 if (D.getDeclSpec().isModulePrivateSpecified()) {
10165 if (isFunctionTemplateSpecialization) {
10166 SourceLocation ModulePrivateLoc
10167 = D.getDeclSpec().getModulePrivateSpecLoc();
10168 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10169 << 0
10170 << FixItHint::CreateRemoval(ModulePrivateLoc);
10171 } else {
10172 NewFD->setModulePrivate();
10173 if (FunctionTemplate)
10174 FunctionTemplate->setModulePrivate();
10175 }
10176 }
10177
10178 if (isFriend) {
10179 if (FunctionTemplate) {
10180 FunctionTemplate->setObjectOfFriendDecl();
10181 FunctionTemplate->setAccess(AS_public);
10182 }
10183 NewFD->setObjectOfFriendDecl();
10184 NewFD->setAccess(AS_public);
10185 }
10186
10187 // If a function is defined as defaulted or deleted, mark it as such now.
10188 // We'll do the relevant checks on defaulted / deleted functions later.
10189 switch (D.getFunctionDefinitionKind()) {
10192 break;
10193
10195 NewFD->setDefaulted();
10196 break;
10197
10199 NewFD->setDeletedAsWritten();
10200 break;
10201 }
10202
10203 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10204 D.isFunctionDefinition()) {
10205 // Pre C++20 [class.mfct]p2:
10206 // A member function may be defined (8.4) in its class definition, in
10207 // which case it is an inline member function (7.1.2)
10208 // Post C++20 [class.mfct]p1:
10209 // If a member function is attached to the global module and is defined
10210 // in its class definition, it is inline.
10211 NewFD->setImplicitlyInline();
10212 }
10213
10214 if (!isFriend && SC != SC_None) {
10215 // C++ [temp.expl.spec]p2:
10216 // The declaration in an explicit-specialization shall not be an
10217 // export-declaration. An explicit specialization shall not use a
10218 // storage-class-specifier other than thread_local.
10219 //
10220 // We diagnose friend declarations with storage-class-specifiers
10221 // elsewhere.
10222 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10223 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10224 diag::ext_explicit_specialization_storage_class)
10226 D.getDeclSpec().getStorageClassSpecLoc());
10227 }
10228
10229 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10230 assert(isa<CXXMethodDecl>(NewFD) &&
10231 "Out-of-line member function should be a CXXMethodDecl");
10232 // C++ [class.static]p1:
10233 // A data or function member of a class may be declared static
10234 // in a class definition, in which case it is a static member of
10235 // the class.
10236
10237 // Complain about the 'static' specifier if it's on an out-of-line
10238 // member function definition.
10239
10240 // MSVC permits the use of a 'static' storage specifier on an
10241 // out-of-line member function template declaration and class member
10242 // template declaration (MSVC versions before 2015), warn about this.
10243 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10244 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10245 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10246 (getLangOpts().MSVCCompat &&
10248 ? diag::ext_static_out_of_line
10249 : diag::err_static_out_of_line)
10251 D.getDeclSpec().getStorageClassSpecLoc());
10252 }
10253 }
10254
10255 // C++11 [except.spec]p15:
10256 // A deallocation function with no exception-specification is treated
10257 // as if it were specified with noexcept(true).
10258 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10259 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10260 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10261 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10263 FPT->getReturnType(), FPT->getParamTypes(),
10265
10266 // C++20 [dcl.inline]/7
10267 // If an inline function or variable that is attached to a named module
10268 // is declared in a definition domain, it shall be defined in that
10269 // domain.
10270 // So, if the current declaration does not have a definition, we must
10271 // check at the end of the TU (or when the PMF starts) to see that we
10272 // have a definition at that point.
10273 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10274 NewFD->isInNamedModule()) {
10275 PendingInlineFuncDecls.insert(NewFD);
10276 }
10277 }
10278
10279 // Filter out previous declarations that don't match the scope.
10281 D.getCXXScopeSpec().isNotEmpty() ||
10282 isMemberSpecialization ||
10283 isFunctionTemplateSpecialization);
10284
10285 // Handle GNU asm-label extension (encoded as an attribute).
10286 if (Expr *E = (Expr*) D.getAsmLabel()) {
10287 // The parser guarantees this is a string.
10288 StringLiteral *SE = cast<StringLiteral>(E);
10289 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10290 /*IsLiteralLabel=*/true,
10291 SE->getStrTokenLoc(0)));
10292 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10293 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10295 if (I != ExtnameUndeclaredIdentifiers.end()) {
10296 if (isDeclExternC(NewFD)) {
10297 NewFD->addAttr(I->second);
10299 } else
10300 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10301 << /*Variable*/0 << NewFD;
10302 }
10303 }
10304
10305 // Copy the parameter declarations from the declarator D to the function
10306 // declaration NewFD, if they are available. First scavenge them into Params.
10308 unsigned FTIIdx;
10309 if (D.isFunctionDeclarator(FTIIdx)) {
10310 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10311
10312 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10313 // function that takes no arguments, not a function that takes a
10314 // single void argument.
10315 // We let through "const void" here because Sema::GetTypeForDeclarator
10316 // already checks for that case.
10317 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10318 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10319 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10320 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10321 Param->setDeclContext(NewFD);
10322 Params.push_back(Param);
10323
10324 if (Param->isInvalidDecl())
10325 NewFD->setInvalidDecl();
10326 }
10327 }
10328
10329 if (!getLangOpts().CPlusPlus) {
10330 // In C, find all the tag declarations from the prototype and move them
10331 // into the function DeclContext. Remove them from the surrounding tag
10332 // injection context of the function, which is typically but not always
10333 // the TU.
10334 DeclContext *PrototypeTagContext =
10336 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10337 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10338
10339 // We don't want to reparent enumerators. Look at their parent enum
10340 // instead.
10341 if (!TD) {
10342 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10343 TD = cast<EnumDecl>(ECD->getDeclContext());
10344 }
10345 if (!TD)
10346 continue;
10347 DeclContext *TagDC = TD->getLexicalDeclContext();
10348 if (!TagDC->containsDecl(TD))
10349 continue;
10350 TagDC->removeDecl(TD);
10351 TD->setDeclContext(NewFD);
10352 NewFD->addDecl(TD);
10353
10354 // Preserve the lexical DeclContext if it is not the surrounding tag
10355 // injection context of the FD. In this example, the semantic context of
10356 // E will be f and the lexical context will be S, while both the
10357 // semantic and lexical contexts of S will be f:
10358 // void f(struct S { enum E { a } f; } s);
10359 if (TagDC != PrototypeTagContext)
10360 TD->setLexicalDeclContext(TagDC);
10361 }
10362 }
10363 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10364 // When we're declaring a function with a typedef, typeof, etc as in the
10365 // following example, we'll need to synthesize (unnamed)
10366 // parameters for use in the declaration.
10367 //
10368 // @code
10369 // typedef void fn(int);
10370 // fn f;
10371 // @endcode
10372
10373 // Synthesize a parameter for each argument type.
10374 for (const auto &AI : FT->param_types()) {
10375 ParmVarDecl *Param =
10376 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10377 Param->setScopeInfo(0, Params.size());
10378 Params.push_back(Param);
10379 }
10380 } else {
10381 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10382 "Should not need args for typedef of non-prototype fn");
10383 }
10384
10385 // Finally, we know we have the right number of parameters, install them.
10386 NewFD->setParams(Params);
10387
10388 if (D.getDeclSpec().isNoreturnSpecified())
10389 NewFD->addAttr(
10390 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10391
10392 // Functions returning a variably modified type violate C99 6.7.5.2p2
10393 // because all functions have linkage.
10394 if (!NewFD->isInvalidDecl() &&
10396 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10397 NewFD->setInvalidDecl();
10398 }
10399
10400 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10401 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10402 !NewFD->hasAttr<SectionAttr>())
10403 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10406
10407 // Apply an implicit SectionAttr if #pragma code_seg is active.
10408 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10409 !NewFD->hasAttr<SectionAttr>()) {
10410 NewFD->addAttr(SectionAttr::CreateImplicit(
10411 Context, CodeSegStack.CurrentValue->getString(),
10412 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10413 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10416 NewFD))
10417 NewFD->dropAttr<SectionAttr>();
10418 }
10419
10420 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10421 // active.
10422 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10423 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10424 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10426
10427 // Apply an implicit CodeSegAttr from class declspec or
10428 // apply an implicit SectionAttr from #pragma code_seg if active.
10429 if (!NewFD->hasAttr<CodeSegAttr>()) {
10431 D.isFunctionDefinition())) {
10432 NewFD->addAttr(SAttr);
10433 }
10434 }
10435
10436 // Handle attributes.
10437 ProcessDeclAttributes(S, NewFD, D);
10438 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10439 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10440 !NewTVA->isDefaultVersion() &&
10441 !Context.getTargetInfo().hasFeature("fmv")) {
10442 // Don't add to scope fmv functions declarations if fmv disabled
10443 AddToScope = false;
10444 return NewFD;
10445 }
10446
10447 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10448 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10449 // type.
10450 //
10451 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10452 // type declaration will generate a compilation error.
10453 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10454 if (AddressSpace != LangAS::Default) {
10455 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10456 NewFD->setInvalidDecl();
10457 }
10458 }
10459
10460 if (!getLangOpts().CPlusPlus) {
10461 // Perform semantic checking on the function declaration.
10462 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10463 CheckMain(NewFD, D.getDeclSpec());
10464
10465 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10466 CheckMSVCRTEntryPoint(NewFD);
10467
10468 if (!NewFD->isInvalidDecl())
10469 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10470 isMemberSpecialization,
10471 D.isFunctionDefinition()));
10472 else if (!Previous.empty())
10473 // Recover gracefully from an invalid redeclaration.
10474 D.setRedeclaration(true);
10475 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10476 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10477 "previous declaration set still overloaded");
10478
10479 // Diagnose no-prototype function declarations with calling conventions that
10480 // don't support variadic calls. Only do this in C and do it after merging
10481 // possibly prototyped redeclarations.
10482 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10483 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10484 CallingConv CC = FT->getExtInfo().getCC();
10485 if (!supportsVariadicCall(CC)) {
10486 // Windows system headers sometimes accidentally use stdcall without
10487 // (void) parameters, so we relax this to a warning.
10488 int DiagID =
10489 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10490 Diag(NewFD->getLocation(), DiagID)
10492 }
10493 }
10494
10500 } else {
10501 // C++11 [replacement.functions]p3:
10502 // The program's definitions shall not be specified as inline.
10503 //
10504 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10505 //
10506 // Suppress the diagnostic if the function is __attribute__((used)), since
10507 // that forces an external definition to be emitted.
10508 if (D.getDeclSpec().isInlineSpecified() &&
10510 !NewFD->hasAttr<UsedAttr>())
10511 Diag(D.getDeclSpec().getInlineSpecLoc(),
10512 diag::ext_operator_new_delete_declared_inline)
10513 << NewFD->getDeclName();
10514
10515 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10516 // C++20 [dcl.decl.general]p4:
10517 // The optional requires-clause in an init-declarator or
10518 // member-declarator shall be present only if the declarator declares a
10519 // templated function.
10520 //
10521 // C++20 [temp.pre]p8:
10522 // An entity is templated if it is
10523 // - a template,
10524 // - an entity defined or created in a templated entity,
10525 // - a member of a templated entity,
10526 // - an enumerator for an enumeration that is a templated entity, or
10527 // - the closure type of a lambda-expression appearing in the
10528 // declaration of a templated entity.
10529 //
10530 // [Note 6: A local class, a local or block variable, or a friend
10531 // function defined in a templated entity is a templated entity.
10532 // — end note]
10533 //
10534 // A templated function is a function template or a function that is
10535 // templated. A templated class is a class template or a class that is
10536 // templated. A templated variable is a variable template or a variable
10537 // that is templated.
10538 if (!FunctionTemplate) {
10539 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10540 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10541 // An explicit specialization shall not have a trailing
10542 // requires-clause unless it declares a function template.
10543 //
10544 // Since a friend function template specialization cannot be
10545 // definition, and since a non-template friend declaration with a
10546 // trailing requires-clause must be a definition, we diagnose
10547 // friend function template specializations with trailing
10548 // requires-clauses on the same path as explicit specializations
10549 // even though they aren't necessarily prohibited by the same
10550 // language rule.
10551 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10552 << isFriend;
10553 } else if (isFriend && NewFD->isTemplated() &&
10554 !D.isFunctionDefinition()) {
10555 // C++ [temp.friend]p9:
10556 // A non-template friend declaration with a requires-clause shall be
10557 // a definition.
10558 Diag(NewFD->getBeginLoc(),
10559 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10560 NewFD->setInvalidDecl();
10561 } else if (!NewFD->isTemplated() ||
10562 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10563 Diag(TRC->getBeginLoc(),
10564 diag::err_constrained_non_templated_function);
10565 }
10566 }
10567 }
10568
10569 // We do not add HD attributes to specializations here because
10570 // they may have different constexpr-ness compared to their
10571 // templates and, after maybeAddHostDeviceAttrs() is applied,
10572 // may end up with different effective targets. Instead, a
10573 // specialization inherits its target attributes from its template
10574 // in the CheckFunctionTemplateSpecialization() call below.
10575 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10577
10578 // Handle explicit specializations of function templates
10579 // and friend function declarations with an explicit
10580 // template argument list.
10581 if (isFunctionTemplateSpecialization) {
10582 bool isDependentSpecialization = false;
10583 if (isFriend) {
10584 // For friend function specializations, this is a dependent
10585 // specialization if its semantic context is dependent, its
10586 // type is dependent, or if its template-id is dependent.
10587 isDependentSpecialization =
10588 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10589 (HasExplicitTemplateArgs &&
10592 TemplateArgs.arguments()));
10593 assert((!isDependentSpecialization ||
10594 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10595 "dependent friend function specialization without template "
10596 "args");
10597 } else {
10598 // For class-scope explicit specializations of function templates,
10599 // if the lexical context is dependent, then the specialization
10600 // is dependent.
10601 isDependentSpecialization =
10603 }
10604
10605 TemplateArgumentListInfo *ExplicitTemplateArgs =
10606 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10607 if (isDependentSpecialization) {
10608 // If it's a dependent specialization, it may not be possible
10609 // to determine the primary template (for explicit specializations)
10610 // or befriended declaration (for friends) until the enclosing
10611 // template is instantiated. In such cases, we store the declarations
10612 // found by name lookup and defer resolution until instantiation.
10614 NewFD, ExplicitTemplateArgs, Previous))
10615 NewFD->setInvalidDecl();
10616 } else if (!NewFD->isInvalidDecl()) {
10617 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10618 Previous))
10619 NewFD->setInvalidDecl();
10620 }
10621 } else if (isMemberSpecialization && !FunctionTemplate) {
10623 NewFD->setInvalidDecl();
10624 }
10625
10626 // Perform semantic checking on the function declaration.
10627 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10628 CheckMain(NewFD, D.getDeclSpec());
10629
10630 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10631 CheckMSVCRTEntryPoint(NewFD);
10632
10633 if (!NewFD->isInvalidDecl())
10634 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10635 isMemberSpecialization,
10636 D.isFunctionDefinition()));
10637 else if (!Previous.empty())
10638 // Recover gracefully from an invalid redeclaration.
10639 D.setRedeclaration(true);
10640
10641 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10642 !D.isRedeclaration() ||
10643 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10644 "previous declaration set still overloaded");
10645
10646 NamedDecl *PrincipalDecl = (FunctionTemplate
10647 ? cast<NamedDecl>(FunctionTemplate)
10648 : NewFD);
10649
10650 if (isFriend && NewFD->getPreviousDecl()) {
10651 AccessSpecifier Access = AS_public;
10652 if (!NewFD->isInvalidDecl())
10653 Access = NewFD->getPreviousDecl()->getAccess();
10654
10655 NewFD->setAccess(Access);
10656 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10657 }
10658
10659 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10661 PrincipalDecl->setNonMemberOperator();
10662
10663 // If we have a function template, check the template parameter
10664 // list. This will check and merge default template arguments.
10665 if (FunctionTemplate) {
10666 FunctionTemplateDecl *PrevTemplate =
10667 FunctionTemplate->getPreviousDecl();
10668 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10669 PrevTemplate ? PrevTemplate->getTemplateParameters()
10670 : nullptr,
10671 D.getDeclSpec().isFriendSpecified()
10672 ? (D.isFunctionDefinition()
10675 : (D.getCXXScopeSpec().isSet() &&
10676 DC && DC->isRecord() &&
10677 DC->isDependentContext())
10680 }
10681
10682 if (NewFD->isInvalidDecl()) {
10683 // Ignore all the rest of this.
10684 } else if (!D.isRedeclaration()) {
10685 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10686 AddToScope };
10687 // Fake up an access specifier if it's supposed to be a class member.
10688 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10689 NewFD->setAccess(AS_public);
10690
10691 // Qualified decls generally require a previous declaration.
10692 if (D.getCXXScopeSpec().isSet()) {
10693 // ...with the major exception of templated-scope or
10694 // dependent-scope friend declarations.
10695
10696 // TODO: we currently also suppress this check in dependent
10697 // contexts because (1) the parameter depth will be off when
10698 // matching friend templates and (2) we might actually be
10699 // selecting a friend based on a dependent factor. But there
10700 // are situations where these conditions don't apply and we
10701 // can actually do this check immediately.
10702 //
10703 // Unless the scope is dependent, it's always an error if qualified
10704 // redeclaration lookup found nothing at all. Diagnose that now;
10705 // nothing will diagnose that error later.
10706 if (isFriend &&
10707 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10708 (!Previous.empty() && CurContext->isDependentContext()))) {
10709 // ignore these
10710 } else if (NewFD->isCPUDispatchMultiVersion() ||
10711 NewFD->isCPUSpecificMultiVersion()) {
10712 // ignore this, we allow the redeclaration behavior here to create new
10713 // versions of the function.
10714 } else {
10715 // The user tried to provide an out-of-line definition for a
10716 // function that is a member of a class or namespace, but there
10717 // was no such member function declared (C++ [class.mfct]p2,
10718 // C++ [namespace.memdef]p2). For example:
10719 //
10720 // class X {
10721 // void f() const;
10722 // };
10723 //
10724 // void X::f() { } // ill-formed
10725 //
10726 // Complain about this problem, and attempt to suggest close
10727 // matches (e.g., those that differ only in cv-qualifiers and
10728 // whether the parameter types are references).
10729
10731 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10732 AddToScope = ExtraArgs.AddToScope;
10733 return Result;
10734 }
10735 }
10736
10737 // Unqualified local friend declarations are required to resolve
10738 // to something.
10739 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10741 *this, Previous, NewFD, ExtraArgs, true, S)) {
10742 AddToScope = ExtraArgs.AddToScope;
10743 return Result;
10744 }
10745 }
10746 } else if (!D.isFunctionDefinition() &&
10747 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10748 !isFriend && !isFunctionTemplateSpecialization &&
10749 !isMemberSpecialization) {
10750 // An out-of-line member function declaration must also be a
10751 // definition (C++ [class.mfct]p2).
10752 // Note that this is not the case for explicit specializations of
10753 // function templates or member functions of class templates, per
10754 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10755 // extension for compatibility with old SWIG code which likes to
10756 // generate them.
10757 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10758 << D.getCXXScopeSpec().getRange();
10759 }
10760 }
10761
10762 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10763 // Any top level function could potentially be specified as an entry.
10764 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10765 HLSL().ActOnTopLevelFunction(NewFD);
10766
10767 if (NewFD->hasAttr<HLSLShaderAttr>())
10768 HLSL().CheckEntryPoint(NewFD);
10769 }
10770
10771 // If this is the first declaration of a library builtin function, add
10772 // attributes as appropriate.
10773 if (!D.isRedeclaration()) {
10774 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10775 if (unsigned BuiltinID = II->getBuiltinID()) {
10776 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10777 if (!InStdNamespace &&
10779 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10780 // Validate the type matches unless this builtin is specified as
10781 // matching regardless of its declared type.
10782 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10783 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10784 } else {
10786 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10787 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10788
10789 if (!Error && !BuiltinType.isNull() &&
10791 NewFD->getType(), BuiltinType))
10792 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10793 }
10794 }
10795 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10796 isStdBuiltin(Context, NewFD, BuiltinID)) {
10797 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10798 }
10799 }
10800 }
10801 }
10802
10803 ProcessPragmaWeak(S, NewFD);
10804 checkAttributesAfterMerging(*this, *NewFD);
10805
10807
10808 if (NewFD->hasAttr<OverloadableAttr>() &&
10809 !NewFD->getType()->getAs<FunctionProtoType>()) {
10810 Diag(NewFD->getLocation(),
10811 diag::err_attribute_overloadable_no_prototype)
10812 << NewFD;
10813 NewFD->dropAttr<OverloadableAttr>();
10814 }
10815
10816 // If there's a #pragma GCC visibility in scope, and this isn't a class
10817 // member, set the visibility of this function.
10818 if (!DC->isRecord() && NewFD->isExternallyVisible())
10820
10821 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10822 // marking the function.
10823 ObjC().AddCFAuditedAttribute(NewFD);
10824
10825 // If this is a function definition, check if we have to apply any
10826 // attributes (i.e. optnone and no_builtin) due to a pragma.
10827 if (D.isFunctionDefinition()) {
10828 AddRangeBasedOptnone(NewFD);
10830 AddSectionMSAllocText(NewFD);
10832 }
10833
10834 // If this is the first declaration of an extern C variable, update
10835 // the map of such variables.
10836 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10837 isIncompleteDeclExternC(*this, NewFD))
10839
10840 // Set this FunctionDecl's range up to the right paren.
10841 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10842
10843 if (D.isRedeclaration() && !Previous.empty()) {
10844 NamedDecl *Prev = Previous.getRepresentativeDecl();
10845 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10846 isMemberSpecialization ||
10847 isFunctionTemplateSpecialization,
10848 D.isFunctionDefinition());
10849 }
10850
10851 if (getLangOpts().CUDA) {
10852 IdentifierInfo *II = NewFD->getIdentifier();
10853 if (II && II->isStr(CUDA().getConfigureFuncName()) &&
10854 !NewFD->isInvalidDecl() &&
10857 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10860 }
10861
10862 // Variadic functions, other than a *declaration* of printf, are not allowed
10863 // in device-side CUDA code, unless someone passed
10864 // -fcuda-allow-variadic-functions.
10865 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10866 (NewFD->hasAttr<CUDADeviceAttr>() ||
10867 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10868 !(II && II->isStr("printf") && NewFD->isExternC() &&
10869 !D.isFunctionDefinition())) {
10870 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10871 }
10872 }
10873
10875
10876
10877
10878 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10879 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10880 if (SC == SC_Static) {
10881 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10882 D.setInvalidType();
10883 }
10884
10885 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10886 if (!NewFD->getReturnType()->isVoidType()) {
10887 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10888 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10889 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10890 : FixItHint());
10891 D.setInvalidType();
10892 }
10893
10895 for (auto *Param : NewFD->parameters())
10896 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10897
10898 if (getLangOpts().OpenCLCPlusPlus) {
10899 if (DC->isRecord()) {
10900 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10901 D.setInvalidType();
10902 }
10903 if (FunctionTemplate) {
10904 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10905 D.setInvalidType();
10906 }
10907 }
10908 }
10909
10910 if (getLangOpts().CPlusPlus) {
10911 // Precalculate whether this is a friend function template with a constraint
10912 // that depends on an enclosing template, per [temp.friend]p9.
10913 if (isFriend && FunctionTemplate &&
10916
10917 // C++ [temp.friend]p9:
10918 // A friend function template with a constraint that depends on a
10919 // template parameter from an enclosing template shall be a definition.
10920 if (!D.isFunctionDefinition()) {
10921 Diag(NewFD->getBeginLoc(),
10922 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10923 NewFD->setInvalidDecl();
10924 }
10925 }
10926
10927 if (FunctionTemplate) {
10928 if (NewFD->isInvalidDecl())
10929 FunctionTemplate->setInvalidDecl();
10930 return FunctionTemplate;
10931 }
10932
10933 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10935 }
10936
10937 for (const ParmVarDecl *Param : NewFD->parameters()) {
10938 QualType PT = Param->getType();
10939
10940 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10941 // types.
10942 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10943 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10944 QualType ElemTy = PipeTy->getElementType();
10945 if (ElemTy->isPointerOrReferenceType()) {
10946 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
10947 D.setInvalidType();
10948 }
10949 }
10950 }
10951 // WebAssembly tables can't be used as function parameters.
10952 if (Context.getTargetInfo().getTriple().isWasm()) {
10954 Diag(Param->getTypeSpecStartLoc(),
10955 diag::err_wasm_table_as_function_parameter);
10956 D.setInvalidType();
10957 }
10958 }
10959 }
10960
10961 // Diagnose availability attributes. Availability cannot be used on functions
10962 // that are run during load/unload.
10963 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10964 if (NewFD->hasAttr<ConstructorAttr>()) {
10965 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10966 << 1;
10967 NewFD->dropAttr<AvailabilityAttr>();
10968 }
10969 if (NewFD->hasAttr<DestructorAttr>()) {
10970 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10971 << 2;
10972 NewFD->dropAttr<AvailabilityAttr>();
10973 }
10974 }
10975
10976 // Diagnose no_builtin attribute on function declaration that are not a
10977 // definition.
10978 // FIXME: We should really be doing this in
10979 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10980 // the FunctionDecl and at this point of the code
10981 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10982 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10983 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10984 switch (D.getFunctionDefinitionKind()) {
10987 Diag(NBA->getLocation(),
10988 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10989 << NBA->getSpelling();
10990 break;
10992 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10993 << NBA->getSpelling();
10994 break;
10996 break;
10997 }
10998
10999 // Similar to no_builtin logic above, at this point of the code
11000 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11001 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11003 !NewFD->isInvalidDecl() &&
11004 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11005 ExternalDeclarations.push_back(NewFD);
11006
11007 return NewFD;
11008}
11009
11010/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11011/// when __declspec(code_seg) "is applied to a class, all member functions of
11012/// the class and nested classes -- this includes compiler-generated special
11013/// member functions -- are put in the specified segment."
11014/// The actual behavior is a little more complicated. The Microsoft compiler
11015/// won't check outer classes if there is an active value from #pragma code_seg.
11016/// The CodeSeg is always applied from the direct parent but only from outer
11017/// classes when the #pragma code_seg stack is empty. See:
11018/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11019/// available since MS has removed the page.
11021 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11022 if (!Method)
11023 return nullptr;
11024 const CXXRecordDecl *Parent = Method->getParent();
11025 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11026 Attr *NewAttr = SAttr->clone(S.getASTContext());
11027 NewAttr->setImplicit(true);
11028 return NewAttr;
11029 }
11030
11031 // The Microsoft compiler won't check outer classes for the CodeSeg
11032 // when the #pragma code_seg stack is active.
11033 if (S.CodeSegStack.CurrentValue)
11034 return nullptr;
11035
11036 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11037 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11038 Attr *NewAttr = SAttr->clone(S.getASTContext());
11039 NewAttr->setImplicit(true);
11040 return NewAttr;
11041 }
11042 }
11043 return nullptr;
11044}
11045
11047 bool IsDefinition) {
11048 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11049 return A;
11050 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11051 CodeSegStack.CurrentValue)
11052 return SectionAttr::CreateImplicit(
11053 getASTContext(), CodeSegStack.CurrentValue->getString(),
11054 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11055 return nullptr;
11056}
11057
11059 QualType NewT, QualType OldT) {
11061 return true;
11062
11063 // For dependently-typed local extern declarations and friends, we can't
11064 // perform a correct type check in general until instantiation:
11065 //
11066 // int f();
11067 // template<typename T> void g() { T f(); }
11068 //
11069 // (valid if g() is only instantiated with T = int).
11070 if (NewT->isDependentType() &&
11071 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11072 return false;
11073
11074 // Similarly, if the previous declaration was a dependent local extern
11075 // declaration, we don't really know its type yet.
11076 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11077 return false;
11078
11079 return true;
11080}
11081
11084 return true;
11085
11086 // Don't chain dependent friend function definitions until instantiation, to
11087 // permit cases like
11088 //
11089 // void func();
11090 // template<typename T> class C1 { friend void func() {} };
11091 // template<typename T> class C2 { friend void func() {} };
11092 //
11093 // ... which is valid if only one of C1 and C2 is ever instantiated.
11094 //
11095 // FIXME: This need only apply to function definitions. For now, we proxy
11096 // this by checking for a file-scope function. We do not want this to apply
11097 // to friend declarations nominating member functions, because that gets in
11098 // the way of access checks.
11100 return false;
11101
11102 auto *VD = dyn_cast<ValueDecl>(D);
11103 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11104 return !VD || !PrevVD ||
11105 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11106 PrevVD->getType());
11107}
11108
11109/// Check the target or target_version attribute of the function for
11110/// MultiVersion validity.
11111///
11112/// Returns true if there was an error, false otherwise.
11113static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11114 const auto *TA = FD->getAttr<TargetAttr>();
11115 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11116
11117 assert((TA || TVA) && "Expecting target or target_version attribute");
11118
11120 enum ErrType { Feature = 0, Architecture = 1 };
11121
11122 if (TA) {
11123 ParsedTargetAttr ParseInfo =
11124 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11125 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11126 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11127 << Architecture << ParseInfo.CPU;
11128 return true;
11129 }
11130 for (const auto &Feat : ParseInfo.Features) {
11131 auto BareFeat = StringRef{Feat}.substr(1);
11132 if (Feat[0] == '-') {
11133 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11134 << Feature << ("no-" + BareFeat).str();
11135 return true;
11136 }
11137
11138 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11139 !TargetInfo.isValidFeatureName(BareFeat) ||
11140 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11141 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11142 << Feature << BareFeat;
11143 return true;
11144 }
11145 }
11146 }
11147
11148 if (TVA) {
11150 ParsedTargetAttr ParseInfo;
11151 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11152 ParseInfo =
11153 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11154 for (auto &Feat : ParseInfo.Features)
11155 Feats.push_back(StringRef{Feat}.substr(1));
11156 } else {
11157 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11158 TVA->getFeatures(Feats);
11159 }
11160 for (const auto &Feat : Feats) {
11161 if (!TargetInfo.validateCpuSupports(Feat)) {
11162 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11163 << Feature << Feat;
11164 return true;
11165 }
11166 }
11167 }
11168 return false;
11169}
11170
11171// Provide a white-list of attributes that are allowed to be combined with
11172// multiversion functions.
11174 MultiVersionKind MVKind) {
11175 // Note: this list/diagnosis must match the list in
11176 // checkMultiversionAttributesAllSame.
11177 switch (Kind) {
11178 default:
11179 return false;
11180 case attr::ArmLocallyStreaming:
11181 return MVKind == MultiVersionKind::TargetVersion ||
11183 case attr::Used:
11184 return MVKind == MultiVersionKind::Target;
11185 case attr::NonNull:
11186 case attr::NoThrow:
11187 return true;
11188 }
11189}
11190
11192 const FunctionDecl *FD,
11193 const FunctionDecl *CausedFD,
11194 MultiVersionKind MVKind) {
11195 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11196 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11197 << static_cast<unsigned>(MVKind) << A;
11198 if (CausedFD)
11199 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11200 return true;
11201 };
11202
11203 for (const Attr *A : FD->attrs()) {
11204 switch (A->getKind()) {
11205 case attr::CPUDispatch:
11206 case attr::CPUSpecific:
11207 if (MVKind != MultiVersionKind::CPUDispatch &&
11209 return Diagnose(S, A);
11210 break;
11211 case attr::Target:
11212 if (MVKind != MultiVersionKind::Target)
11213 return Diagnose(S, A);
11214 break;
11215 case attr::TargetVersion:
11216 if (MVKind != MultiVersionKind::TargetVersion &&
11218 return Diagnose(S, A);
11219 break;
11220 case attr::TargetClones:
11221 if (MVKind != MultiVersionKind::TargetClones &&
11223 return Diagnose(S, A);
11224 break;
11225 default:
11226 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11227 return Diagnose(S, A);
11228 break;
11229 }
11230 }
11231 return false;
11232}
11233
11235 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11236 const PartialDiagnostic &NoProtoDiagID,
11237 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11238 const PartialDiagnosticAt &NoSupportDiagIDAt,
11239 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11240 bool ConstexprSupported, bool CLinkageMayDiffer) {
11241 enum DoesntSupport {
11242 FuncTemplates = 0,
11243 VirtFuncs = 1,
11244 DeducedReturn = 2,
11245 Constructors = 3,
11246 Destructors = 4,
11247 DeletedFuncs = 5,
11248 DefaultedFuncs = 6,
11249 ConstexprFuncs = 7,
11250 ConstevalFuncs = 8,
11251 Lambda = 9,
11252 };
11253 enum Different {
11254 CallingConv = 0,
11255 ReturnType = 1,
11256 ConstexprSpec = 2,
11257 InlineSpec = 3,
11258 Linkage = 4,
11259 LanguageLinkage = 5,
11260 };
11261
11262 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11263 !OldFD->getType()->getAs<FunctionProtoType>()) {
11264 Diag(OldFD->getLocation(), NoProtoDiagID);
11265 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11266 return true;
11267 }
11268
11269 if (NoProtoDiagID.getDiagID() != 0 &&
11270 !NewFD->getType()->getAs<FunctionProtoType>())
11271 return Diag(NewFD->getLocation(), NoProtoDiagID);
11272
11273 if (!TemplatesSupported &&
11275 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11276 << FuncTemplates;
11277
11278 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11279 if (NewCXXFD->isVirtual())
11280 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11281 << VirtFuncs;
11282
11283 if (isa<CXXConstructorDecl>(NewCXXFD))
11284 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11285 << Constructors;
11286
11287 if (isa<CXXDestructorDecl>(NewCXXFD))
11288 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11289 << Destructors;
11290 }
11291
11292 if (NewFD->isDeleted())
11293 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11294 << DeletedFuncs;
11295
11296 if (NewFD->isDefaulted())
11297 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11298 << DefaultedFuncs;
11299
11300 if (!ConstexprSupported && NewFD->isConstexpr())
11301 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11302 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11303
11304 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11305 const auto *NewType = cast<FunctionType>(NewQType);
11306 QualType NewReturnType = NewType->getReturnType();
11307
11308 if (NewReturnType->isUndeducedType())
11309 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11310 << DeducedReturn;
11311
11312 // Ensure the return type is identical.
11313 if (OldFD) {
11314 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11315 const auto *OldType = cast<FunctionType>(OldQType);
11316 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11317 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11318
11319 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11320 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11321
11322 bool ArmStreamingCCMismatched = false;
11323 if (OldFPT && NewFPT) {
11324 unsigned Diff =
11326 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11327 // cannot be mixed.
11330 ArmStreamingCCMismatched = true;
11331 }
11332
11333 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11334 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11335
11336 QualType OldReturnType = OldType->getReturnType();
11337
11338 if (OldReturnType != NewReturnType)
11339 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11340
11341 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11342 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11343
11344 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11345 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11346
11347 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11348 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11349
11350 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11351 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11352
11353 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11354 NewFD->getLocation()))
11355 return true;
11356 }
11357 return false;
11358}
11359
11361 const FunctionDecl *NewFD,
11362 bool CausesMV,
11363 MultiVersionKind MVKind) {
11365 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11366 if (OldFD)
11367 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11368 return true;
11369 }
11370
11371 bool IsCPUSpecificCPUDispatchMVKind =
11374
11375 if (CausesMV && OldFD &&
11376 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11377 return true;
11378
11379 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11380 return true;
11381
11382 // Only allow transition to MultiVersion if it hasn't been used.
11383 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11384 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11385 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11386 return true;
11387 }
11388
11390 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11392 S.PDiag(diag::note_multiversioning_caused_here)),
11394 S.PDiag(diag::err_multiversion_doesnt_support)
11395 << static_cast<unsigned>(MVKind)),
11397 S.PDiag(diag::err_multiversion_diff)),
11398 /*TemplatesSupported=*/false,
11399 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11400 /*CLinkageMayDiffer=*/false);
11401}
11402
11403/// Check the validity of a multiversion function declaration that is the
11404/// first of its kind. Also sets the multiversion'ness' of the function itself.
11405///
11406/// This sets NewFD->isInvalidDecl() to true if there was an error.
11407///
11408/// Returns true if there was an error, false otherwise.
11411 assert(MVKind != MultiVersionKind::None &&
11412 "Function lacks multiversion attribute");
11413 const auto *TA = FD->getAttr<TargetAttr>();
11414 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11415 // The target attribute only causes MV if this declaration is the default,
11416 // otherwise it is treated as a normal function.
11417 if (TA && !TA->isDefaultVersion())
11418 return false;
11419
11420 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11421 FD->setInvalidDecl();
11422 return true;
11423 }
11424
11425 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11426 FD->setInvalidDecl();
11427 return true;
11428 }
11429
11430 FD->setIsMultiVersion();
11431 return false;
11432}
11433
11435 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11437 return true;
11438 }
11439
11440 return false;
11441}
11442
11444 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11445 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11446 return;
11447
11448 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11449 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11450
11451 if (MVKindTo == MultiVersionKind::None &&
11452 (MVKindFrom == MultiVersionKind::TargetVersion ||
11453 MVKindFrom == MultiVersionKind::TargetClones))
11454 To->addAttr(TargetVersionAttr::CreateImplicit(
11455 To->getASTContext(), "default", To->getSourceRange()));
11456}
11457
11459 FunctionDecl *NewFD,
11460 bool &Redeclaration,
11461 NamedDecl *&OldDecl,
11463 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11464
11465 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11466 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11467 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11468 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11469
11470 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11471
11472 // The definitions should be allowed in any order. If we have discovered
11473 // a new target version and the preceeding was the default, then add the
11474 // corresponding attribute to it.
11475 patchDefaultTargetVersion(NewFD, OldFD);
11476
11477 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11478 // to change, this is a simple redeclaration.
11479 if (NewTA && !NewTA->isDefaultVersion() &&
11480 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11481 return false;
11482
11483 // Otherwise, this decl causes MultiVersioning.
11484 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11487 NewFD->setInvalidDecl();
11488 return true;
11489 }
11490
11491 if (CheckMultiVersionValue(S, NewFD)) {
11492 NewFD->setInvalidDecl();
11493 return true;
11494 }
11495
11496 // If this is 'default', permit the forward declaration.
11497 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11498 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11499 Redeclaration = true;
11500 OldDecl = OldFD;
11501 OldFD->setIsMultiVersion();
11502 NewFD->setIsMultiVersion();
11503 return false;
11504 }
11505
11506 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11507 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11508 NewFD->setInvalidDecl();
11509 return true;
11510 }
11511
11512 if (NewTA) {
11513 ParsedTargetAttr OldParsed =
11515 OldTA->getFeaturesStr());
11516 llvm::sort(OldParsed.Features);
11517 ParsedTargetAttr NewParsed =
11519 NewTA->getFeaturesStr());
11520 // Sort order doesn't matter, it just needs to be consistent.
11521 llvm::sort(NewParsed.Features);
11522 if (OldParsed == NewParsed) {
11523 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11524 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11525 NewFD->setInvalidDecl();
11526 return true;
11527 }
11528 }
11529
11530 for (const auto *FD : OldFD->redecls()) {
11531 const auto *CurTA = FD->getAttr<TargetAttr>();
11532 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11533 // We allow forward declarations before ANY multiversioning attributes, but
11534 // nothing after the fact.
11536 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11537 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11538 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11539 << (NewTA ? 0 : 2);
11540 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11541 NewFD->setInvalidDecl();
11542 return true;
11543 }
11544 }
11545
11546 OldFD->setIsMultiVersion();
11547 NewFD->setIsMultiVersion();
11548 Redeclaration = false;
11549 OldDecl = nullptr;
11550 Previous.clear();
11551 return false;
11552}
11553
11555 MultiVersionKind OldKind = Old->getMultiVersionKind();
11556 MultiVersionKind NewKind = New->getMultiVersionKind();
11557
11558 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11559 NewKind == MultiVersionKind::None)
11560 return true;
11561
11562 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11563 switch (OldKind) {
11565 return NewKind == MultiVersionKind::TargetClones;
11567 return NewKind == MultiVersionKind::TargetVersion;
11568 default:
11569 return false;
11570 }
11571 } else {
11572 switch (OldKind) {
11574 return NewKind == MultiVersionKind::CPUSpecific;
11576 return NewKind == MultiVersionKind::CPUDispatch;
11577 default:
11578 return false;
11579 }
11580 }
11581}
11582
11583/// Check the validity of a new function declaration being added to an existing
11584/// multiversioned declaration collection.
11586 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11587 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11588 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11590
11591 // Disallow mixing of multiversioning types.
11592 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11593 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11594 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11595 NewFD->setInvalidDecl();
11596 return true;
11597 }
11598
11599 // Add the default target_version attribute if it's missing.
11600 patchDefaultTargetVersion(OldFD, NewFD);
11601 patchDefaultTargetVersion(NewFD, OldFD);
11602
11603 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11604 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11605 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11606 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11607
11608 ParsedTargetAttr NewParsed;
11609 if (NewTA) {
11611 NewTA->getFeaturesStr());
11612 llvm::sort(NewParsed.Features);
11613 }
11615 if (NewTVA) {
11616 NewTVA->getFeatures(NewFeats);
11617 llvm::sort(NewFeats);
11618 }
11619
11620 bool UseMemberUsingDeclRules =
11621 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11622
11623 bool MayNeedOverloadableChecks =
11625
11626 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11627 // of a previous member of the MultiVersion set.
11628 for (NamedDecl *ND : Previous) {
11629 FunctionDecl *CurFD = ND->getAsFunction();
11630 if (!CurFD || CurFD->isInvalidDecl())
11631 continue;
11632 if (MayNeedOverloadableChecks &&
11633 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11634 continue;
11635
11636 switch (NewMVKind) {
11638 assert(OldMVKind == MultiVersionKind::TargetClones &&
11639 "Only target_clones can be omitted in subsequent declarations");
11640 break;
11642 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11643 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11644 NewFD->setIsMultiVersion();
11645 Redeclaration = true;
11646 OldDecl = ND;
11647 return false;
11648 }
11649
11650 ParsedTargetAttr CurParsed =
11652 CurTA->getFeaturesStr());
11653 llvm::sort(CurParsed.Features);
11654 if (CurParsed == NewParsed) {
11655 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11656 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11657 NewFD->setInvalidDecl();
11658 return true;
11659 }
11660 break;
11661 }
11663 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11664 if (CurTVA->getName() == NewTVA->getName()) {
11665 NewFD->setIsMultiVersion();
11666 Redeclaration = true;
11667 OldDecl = ND;
11668 return false;
11669 }
11671 CurTVA->getFeatures(CurFeats);
11672 llvm::sort(CurFeats);
11673
11674 if (CurFeats == NewFeats) {
11675 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11676 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11677 NewFD->setInvalidDecl();
11678 return true;
11679 }
11680 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11681 // Default
11682 if (NewFeats.empty())
11683 break;
11684
11685 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11687 CurClones->getFeatures(CurFeats, I);
11688 llvm::sort(CurFeats);
11689
11690 if (CurFeats == NewFeats) {
11691 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11692 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11693 NewFD->setInvalidDecl();
11694 return true;
11695 }
11696 }
11697 }
11698 break;
11699 }
11701 assert(NewClones && "MultiVersionKind does not match attribute type");
11702 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11703 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11704 !std::equal(CurClones->featuresStrs_begin(),
11705 CurClones->featuresStrs_end(),
11706 NewClones->featuresStrs_begin())) {
11707 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11708 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11709 NewFD->setInvalidDecl();
11710 return true;
11711 }
11712 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11714 CurTVA->getFeatures(CurFeats);
11715 llvm::sort(CurFeats);
11716
11717 // Default
11718 if (CurFeats.empty())
11719 break;
11720
11721 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11722 NewFeats.clear();
11723 NewClones->getFeatures(NewFeats, I);
11724 llvm::sort(NewFeats);
11725
11726 if (CurFeats == NewFeats) {
11727 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11728 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11729 NewFD->setInvalidDecl();
11730 return true;
11731 }
11732 }
11733 break;
11734 }
11735 Redeclaration = true;
11736 OldDecl = CurFD;
11737 NewFD->setIsMultiVersion();
11738 return false;
11739 }
11742 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11743 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11744 // Handle CPUDispatch/CPUSpecific versions.
11745 // Only 1 CPUDispatch function is allowed, this will make it go through
11746 // the redeclaration errors.
11747 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11748 CurFD->hasAttr<CPUDispatchAttr>()) {
11749 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11750 std::equal(
11751 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11752 NewCPUDisp->cpus_begin(),
11753 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11754 return Cur->getName() == New->getName();
11755 })) {
11756 NewFD->setIsMultiVersion();
11757 Redeclaration = true;
11758 OldDecl = ND;
11759 return false;
11760 }
11761
11762 // If the declarations don't match, this is an error condition.
11763 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11764 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11765 NewFD->setInvalidDecl();
11766 return true;
11767 }
11768 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11769 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11770 std::equal(
11771 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11772 NewCPUSpec->cpus_begin(),
11773 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11774 return Cur->getName() == New->getName();
11775 })) {
11776 NewFD->setIsMultiVersion();
11777 Redeclaration = true;
11778 OldDecl = ND;
11779 return false;
11780 }
11781
11782 // Only 1 version of CPUSpecific is allowed for each CPU.
11783 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11784 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11785 if (CurII == NewII) {
11786 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11787 << NewII;
11788 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11789 NewFD->setInvalidDecl();
11790 return true;
11791 }
11792 }
11793 }
11794 }
11795 break;
11796 }
11797 }
11798 }
11799
11800 // Else, this is simply a non-redecl case. Checking the 'value' is only
11801 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11802 // handled in the attribute adding step.
11803 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
11804 NewFD->setInvalidDecl();
11805 return true;
11806 }
11807
11808 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11809 !OldFD->isMultiVersion(), NewMVKind)) {
11810 NewFD->setInvalidDecl();
11811 return true;
11812 }
11813
11814 // Permit forward declarations in the case where these two are compatible.
11815 if (!OldFD->isMultiVersion()) {
11816 OldFD->setIsMultiVersion();
11817 NewFD->setIsMultiVersion();
11818 Redeclaration = true;
11819 OldDecl = OldFD;
11820 return false;
11821 }
11822
11823 NewFD->setIsMultiVersion();
11824 Redeclaration = false;
11825 OldDecl = nullptr;
11826 Previous.clear();
11827 return false;
11828}
11829
11830/// Check the validity of a mulitversion function declaration.
11831/// Also sets the multiversion'ness' of the function itself.
11832///
11833/// This sets NewFD->isInvalidDecl() to true if there was an error.
11834///
11835/// Returns true if there was an error, false otherwise.
11837 bool &Redeclaration, NamedDecl *&OldDecl,
11839 const TargetInfo &TI = S.getASTContext().getTargetInfo();
11840
11841 // Check if FMV is disabled.
11842 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
11843 return false;
11844
11845 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11846 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11847 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11848 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11849 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11850 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11851
11852 // Main isn't allowed to become a multiversion function, however it IS
11853 // permitted to have 'main' be marked with the 'target' optimization hint,
11854 // for 'target_version' only default is allowed.
11855 if (NewFD->isMain()) {
11856 if (MVKind != MultiVersionKind::None &&
11857 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11858 !(MVKind == MultiVersionKind::TargetVersion &&
11859 NewTVA->isDefaultVersion())) {
11860 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11861 NewFD->setInvalidDecl();
11862 return true;
11863 }
11864 return false;
11865 }
11866
11867 // Target attribute on AArch64 is not used for multiversioning
11868 if (NewTA && TI.getTriple().isAArch64())
11869 return false;
11870
11871 // Target attribute on RISCV is not used for multiversioning
11872 if (NewTA && TI.getTriple().isRISCV())
11873 return false;
11874
11875 if (!OldDecl || !OldDecl->getAsFunction() ||
11876 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
11877 NewFD->getDeclContext()->getRedeclContext())) {
11878 // If there's no previous declaration, AND this isn't attempting to cause
11879 // multiversioning, this isn't an error condition.
11880 if (MVKind == MultiVersionKind::None)
11881 return false;
11882 return CheckMultiVersionFirstFunction(S, NewFD);
11883 }
11884
11885 FunctionDecl *OldFD = OldDecl->getAsFunction();
11886
11887 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11888 return false;
11889
11890 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11891 // for target_clones and target_version.
11892 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11895 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11897 NewFD->setInvalidDecl();
11898 return true;
11899 }
11900
11901 if (!OldFD->isMultiVersion()) {
11902 switch (MVKind) {
11906 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
11908 if (OldFD->isUsed(false)) {
11909 NewFD->setInvalidDecl();
11910 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11911 }
11912 OldFD->setIsMultiVersion();
11913 break;
11914
11918 break;
11919 }
11920 }
11921
11922 // At this point, we have a multiversion function decl (in OldFD) AND an
11923 // appropriate attribute in the current function decl. Resolve that these are
11924 // still compatible with previous declarations.
11925 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11926 NewCPUSpec, NewClones, Redeclaration,
11927 OldDecl, Previous);
11928}
11929
11931 bool IsPure = NewFD->hasAttr<PureAttr>();
11932 bool IsConst = NewFD->hasAttr<ConstAttr>();
11933
11934 // If there are no pure or const attributes, there's nothing to check.
11935 if (!IsPure && !IsConst)
11936 return;
11937
11938 // If the function is marked both pure and const, we retain the const
11939 // attribute because it makes stronger guarantees than the pure attribute, and
11940 // we drop the pure attribute explicitly to prevent later confusion about
11941 // semantics.
11942 if (IsPure && IsConst) {
11943 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
11944 NewFD->dropAttrs<PureAttr>();
11945 }
11946
11947 // Constructors and destructors are functions which return void, so are
11948 // handled here as well.
11949 if (NewFD->getReturnType()->isVoidType()) {
11950 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
11951 << IsConst;
11952 NewFD->dropAttrs<PureAttr, ConstAttr>();
11953 }
11954}
11955
11958 bool IsMemberSpecialization,
11959 bool DeclIsDefn) {
11960 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11961 "Variably modified return types are not handled here");
11962
11963 // Determine whether the type of this function should be merged with
11964 // a previous visible declaration. This never happens for functions in C++,
11965 // and always happens in C if the previous declaration was visible.
11966 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11967 !Previous.isShadowed();
11968
11969 bool Redeclaration = false;
11970 NamedDecl *OldDecl = nullptr;
11971 bool MayNeedOverloadableChecks = false;
11972
11974 // Merge or overload the declaration with an existing declaration of
11975 // the same name, if appropriate.
11976 if (!Previous.empty()) {
11977 // Determine whether NewFD is an overload of PrevDecl or
11978 // a declaration that requires merging. If it's an overload,
11979 // there's no more work to do here; we'll just add the new
11980 // function to the scope.
11982 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11983 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11984 Redeclaration = true;
11985 OldDecl = Candidate;
11986 }
11987 } else {
11988 MayNeedOverloadableChecks = true;
11989 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11990 /*NewIsUsingDecl*/ false)) {
11991 case Ovl_Match:
11992 Redeclaration = true;
11993 break;
11994
11995 case Ovl_NonFunction:
11996 Redeclaration = true;
11997 break;
11998
11999 case Ovl_Overload:
12000 Redeclaration = false;
12001 break;
12002 }
12003 }
12004 }
12005
12006 // Check for a previous extern "C" declaration with this name.
12007 if (!Redeclaration &&
12009 if (!Previous.empty()) {
12010 // This is an extern "C" declaration with the same name as a previous
12011 // declaration, and thus redeclares that entity...
12012 Redeclaration = true;
12013 OldDecl = Previous.getFoundDecl();
12014 MergeTypeWithPrevious = false;
12015
12016 // ... except in the presence of __attribute__((overloadable)).
12017 if (OldDecl->hasAttr<OverloadableAttr>() ||
12018 NewFD->hasAttr<OverloadableAttr>()) {
12019 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12020 MayNeedOverloadableChecks = true;
12021 Redeclaration = false;
12022 OldDecl = nullptr;
12023 }
12024 }
12025 }
12026 }
12027
12028 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12029 return Redeclaration;
12030
12031 // PPC MMA non-pointer types are not allowed as function return types.
12032 if (Context.getTargetInfo().getTriple().isPPC64() &&
12033 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12034 NewFD->setInvalidDecl();
12035 }
12036
12037 CheckConstPureAttributesUsage(*this, NewFD);
12038
12039 // C++ [dcl.spec.auto.general]p12:
12040 // Return type deduction for a templated function with a placeholder in its
12041 // declared type occurs when the definition is instantiated even if the
12042 // function body contains a return statement with a non-type-dependent
12043 // operand.
12044 //
12045 // C++ [temp.dep.expr]p3:
12046 // An id-expression is type-dependent if it is a template-id that is not a
12047 // concept-id and is dependent; or if its terminal name is:
12048 // - [...]
12049 // - associated by name lookup with one or more declarations of member
12050 // functions of a class that is the current instantiation declared with a
12051 // return type that contains a placeholder type,
12052 // - [...]
12053 //
12054 // If this is a templated function with a placeholder in its return type,
12055 // make the placeholder type dependent since it won't be deduced until the
12056 // definition is instantiated. We do this here because it needs to happen
12057 // for implicitly instantiated member functions/member function templates.
12058 if (getLangOpts().CPlusPlus14 &&
12059 (NewFD->isDependentContext() &&
12060 NewFD->getReturnType()->isUndeducedType())) {
12061 const FunctionProtoType *FPT =
12062 NewFD->getType()->castAs<FunctionProtoType>();
12063 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12064 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12065 FPT->getExtProtoInfo()));
12066 }
12067
12068 // C++11 [dcl.constexpr]p8:
12069 // A constexpr specifier for a non-static member function that is not
12070 // a constructor declares that member function to be const.
12071 //
12072 // This needs to be delayed until we know whether this is an out-of-line
12073 // definition of a static member function.
12074 //
12075 // This rule is not present in C++1y, so we produce a backwards
12076 // compatibility warning whenever it happens in C++11.
12077 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12078 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12079 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12080 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
12081 CXXMethodDecl *OldMD = nullptr;
12082 if (OldDecl)
12083 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12084 if (!OldMD || !OldMD->isStatic()) {
12085 const FunctionProtoType *FPT =
12088 EPI.TypeQuals.addConst();
12090 FPT->getParamTypes(), EPI));
12091
12092 // Warn that we did this, if we're not performing template instantiation.
12093 // In that case, we'll have warned already when the template was defined.
12094 if (!inTemplateInstantiation()) {
12095 SourceLocation AddConstLoc;
12098 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12099
12100 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12101 << FixItHint::CreateInsertion(AddConstLoc, " const");
12102 }
12103 }
12104 }
12105
12106 if (Redeclaration) {
12107 // NewFD and OldDecl represent declarations that need to be
12108 // merged.
12109 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12110 DeclIsDefn)) {
12111 NewFD->setInvalidDecl();
12112 return Redeclaration;
12113 }
12114
12115 Previous.clear();
12116 Previous.addDecl(OldDecl);
12117
12118 if (FunctionTemplateDecl *OldTemplateDecl =
12119 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12120 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12121 FunctionTemplateDecl *NewTemplateDecl
12123 assert(NewTemplateDecl && "Template/non-template mismatch");
12124
12125 // The call to MergeFunctionDecl above may have created some state in
12126 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12127 // can add it as a redeclaration.
12128 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12129
12130 NewFD->setPreviousDeclaration(OldFD);
12131 if (NewFD->isCXXClassMember()) {
12132 NewFD->setAccess(OldTemplateDecl->getAccess());
12133 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12134 }
12135
12136 // If this is an explicit specialization of a member that is a function
12137 // template, mark it as a member specialization.
12138 if (IsMemberSpecialization &&
12139 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12140 NewTemplateDecl->setMemberSpecialization();
12141 assert(OldTemplateDecl->isMemberSpecialization());
12142 // Explicit specializations of a member template do not inherit deleted
12143 // status from the parent member template that they are specializing.
12144 if (OldFD->isDeleted()) {
12145 // FIXME: This assert will not hold in the presence of modules.
12146 assert(OldFD->getCanonicalDecl() == OldFD);
12147 // FIXME: We need an update record for this AST mutation.
12148 OldFD->setDeletedAsWritten(false);
12149 }
12150 }
12151
12152 } else {
12153 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12154 auto *OldFD = cast<FunctionDecl>(OldDecl);
12155 // This needs to happen first so that 'inline' propagates.
12156 NewFD->setPreviousDeclaration(OldFD);
12157 if (NewFD->isCXXClassMember())
12158 NewFD->setAccess(OldFD->getAccess());
12159 }
12160 }
12161 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12162 !NewFD->getAttr<OverloadableAttr>()) {
12163 assert((Previous.empty() ||
12164 llvm::any_of(Previous,
12165 [](const NamedDecl *ND) {
12166 return ND->hasAttr<OverloadableAttr>();
12167 })) &&
12168 "Non-redecls shouldn't happen without overloadable present");
12169
12170 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12171 const auto *FD = dyn_cast<FunctionDecl>(ND);
12172 return FD && !FD->hasAttr<OverloadableAttr>();
12173 });
12174
12175 if (OtherUnmarkedIter != Previous.end()) {
12176 Diag(NewFD->getLocation(),
12177 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12178 Diag((*OtherUnmarkedIter)->getLocation(),
12179 diag::note_attribute_overloadable_prev_overload)
12180 << false;
12181
12182 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12183 }
12184 }
12185
12186 if (LangOpts.OpenMP)
12188
12189 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12191
12192 // Semantic checking for this function declaration (in isolation).
12193
12194 if (getLangOpts().CPlusPlus) {
12195 // C++-specific checks.
12196 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12197 CheckConstructor(Constructor);
12198 } else if (CXXDestructorDecl *Destructor =
12199 dyn_cast<CXXDestructorDecl>(NewFD)) {
12200 // We check here for invalid destructor names.
12201 // If we have a friend destructor declaration that is dependent, we can't
12202 // diagnose right away because cases like this are still valid:
12203 // template <class T> struct A { friend T::X::~Y(); };
12204 // struct B { struct Y { ~Y(); }; using X = Y; };
12205 // template struct A<B>;
12207 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12208 CXXRecordDecl *Record = Destructor->getParent();
12210
12212 Context.getCanonicalType(ClassType));
12213 if (NewFD->getDeclName() != Name) {
12214 Diag(NewFD->getLocation(), diag::err_destructor_name);
12215 NewFD->setInvalidDecl();
12216 return Redeclaration;
12217 }
12218 }
12219 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12220 if (auto *TD = Guide->getDescribedFunctionTemplate())
12222
12223 // A deduction guide is not on the list of entities that can be
12224 // explicitly specialized.
12225 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12226 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12227 << /*explicit specialization*/ 1;
12228 }
12229
12230 // Find any virtual functions that this function overrides.
12231 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12232 if (!Method->isFunctionTemplateSpecialization() &&
12233 !Method->getDescribedFunctionTemplate() &&
12234 Method->isCanonicalDecl()) {
12235 AddOverriddenMethods(Method->getParent(), Method);
12236 }
12237 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12238 // C++2a [class.virtual]p6
12239 // A virtual method shall not have a requires-clause.
12241 diag::err_constrained_virtual_method);
12242
12243 if (Method->isStatic())
12245 }
12246
12247 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12248 ActOnConversionDeclarator(Conversion);
12249
12250 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12251 if (NewFD->isOverloadedOperator() &&
12253 NewFD->setInvalidDecl();
12254 return Redeclaration;
12255 }
12256
12257 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12258 if (NewFD->getLiteralIdentifier() &&
12260 NewFD->setInvalidDecl();
12261 return Redeclaration;
12262 }
12263
12264 // In C++, check default arguments now that we have merged decls. Unless
12265 // the lexical context is the class, because in this case this is done
12266 // during delayed parsing anyway.
12267 if (!CurContext->isRecord())
12269
12270 // If this function is declared as being extern "C", then check to see if
12271 // the function returns a UDT (class, struct, or union type) that is not C
12272 // compatible, and if it does, warn the user.
12273 // But, issue any diagnostic on the first declaration only.
12274 if (Previous.empty() && NewFD->isExternC()) {
12275 QualType R = NewFD->getReturnType();
12276 if (R->isIncompleteType() && !R->isVoidType())
12277 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12278 << NewFD << R;
12279 else if (!R.isPODType(Context) && !R->isVoidType() &&
12281 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12282 }
12283
12284 // C++1z [dcl.fct]p6:
12285 // [...] whether the function has a non-throwing exception-specification
12286 // [is] part of the function type
12287 //
12288 // This results in an ABI break between C++14 and C++17 for functions whose
12289 // declared type includes an exception-specification in a parameter or
12290 // return type. (Exception specifications on the function itself are OK in
12291 // most cases, and exception specifications are not permitted in most other
12292 // contexts where they could make it into a mangling.)
12293 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12294 auto HasNoexcept = [&](QualType T) -> bool {
12295 // Strip off declarator chunks that could be between us and a function
12296 // type. We don't need to look far, exception specifications are very
12297 // restricted prior to C++17.
12298 if (auto *RT = T->getAs<ReferenceType>())
12299 T = RT->getPointeeType();
12300 else if (T->isAnyPointerType())
12301 T = T->getPointeeType();
12302 else if (auto *MPT = T->getAs<MemberPointerType>())
12303 T = MPT->getPointeeType();
12304 if (auto *FPT = T->getAs<FunctionProtoType>())
12305 if (FPT->isNothrow())
12306 return true;
12307 return false;
12308 };
12309
12310 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12311 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12312 for (QualType T : FPT->param_types())
12313 AnyNoexcept |= HasNoexcept(T);
12314 if (AnyNoexcept)
12315 Diag(NewFD->getLocation(),
12316 diag::warn_cxx17_compat_exception_spec_in_signature)
12317 << NewFD;
12318 }
12319
12320 if (!Redeclaration && LangOpts.CUDA) {
12321 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12322 for (auto *Parm : NewFD->parameters()) {
12323 if (!Parm->getType()->isDependentType() &&
12324 Parm->hasAttr<CUDAGridConstantAttr>() &&
12325 !(IsKernel && Parm->getType().isConstQualified()))
12326 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12327 diag::err_cuda_grid_constant_not_allowed);
12328 }
12330 }
12331 }
12332
12333 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12335
12336 return Redeclaration;
12337}
12338
12340 // [basic.start.main]p3
12341 // The main function shall not be declared with a linkage-specification.
12342 if (FD->isExternCContext() ||
12343 (FD->isExternCXXContext() &&
12345 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification)
12346 << FD->getLanguageLinkage();
12347
12348 // C++11 [basic.start.main]p3:
12349 // A program that [...] declares main to be inline, static or
12350 // constexpr is ill-formed.
12351 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12352 // appear in a declaration of main.
12353 // static main is not an error under C99, but we should warn about it.
12354 // We accept _Noreturn main as an extension.
12355 if (FD->getStorageClass() == SC_Static)
12357 ? diag::err_static_main : diag::warn_static_main)
12359 if (FD->isInlineSpecified())
12360 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12362 if (DS.isNoreturnSpecified()) {
12363 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12364 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12365 Diag(NoreturnLoc, diag::ext_noreturn_main);
12366 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12367 << FixItHint::CreateRemoval(NoreturnRange);
12368 }
12369 if (FD->isConstexpr()) {
12370 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12371 << FD->isConsteval()
12374 }
12375
12376 if (getLangOpts().OpenCL) {
12377 Diag(FD->getLocation(), diag::err_opencl_no_main)
12378 << FD->hasAttr<OpenCLKernelAttr>();
12379 FD->setInvalidDecl();
12380 return;
12381 }
12382
12383 // Functions named main in hlsl are default entries, but don't have specific
12384 // signatures they are required to conform to.
12385 if (getLangOpts().HLSL)
12386 return;
12387
12388 QualType T = FD->getType();
12389 assert(T->isFunctionType() && "function decl is not of function type");
12390 const FunctionType* FT = T->castAs<FunctionType>();
12391
12392 // Set default calling convention for main()
12393 if (FT->getCallConv() != CC_C) {
12395 FD->setType(QualType(FT, 0));
12397 }
12398
12399 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12400 // In C with GNU extensions we allow main() to have non-integer return
12401 // type, but we should warn about the extension, and we disable the
12402 // implicit-return-zero rule.
12403
12404 // GCC in C mode accepts qualified 'int'.
12406 FD->setHasImplicitReturnZero(true);
12407 else {
12408 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12409 SourceRange RTRange = FD->getReturnTypeSourceRange();
12410 if (RTRange.isValid())
12411 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12412 << FixItHint::CreateReplacement(RTRange, "int");
12413 }
12414 } else {
12415 // In C and C++, main magically returns 0 if you fall off the end;
12416 // set the flag which tells us that.
12417 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12418
12419 // All the standards say that main() should return 'int'.
12421 FD->setHasImplicitReturnZero(true);
12422 else {
12423 // Otherwise, this is just a flat-out error.
12424 SourceRange RTRange = FD->getReturnTypeSourceRange();
12425 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12426 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12427 : FixItHint());
12428 FD->setInvalidDecl(true);
12429 }
12430 }
12431
12432 // Treat protoless main() as nullary.
12433 if (isa<FunctionNoProtoType>(FT)) return;
12434
12435 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12436 unsigned nparams = FTP->getNumParams();
12437 assert(FD->getNumParams() == nparams);
12438
12439 bool HasExtraParameters = (nparams > 3);
12440
12441 if (FTP->isVariadic()) {
12442 Diag(FD->getLocation(), diag::ext_variadic_main);
12443 // FIXME: if we had information about the location of the ellipsis, we
12444 // could add a FixIt hint to remove it as a parameter.
12445 }
12446
12447 // Darwin passes an undocumented fourth argument of type char**. If
12448 // other platforms start sprouting these, the logic below will start
12449 // getting shifty.
12450 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12451 HasExtraParameters = false;
12452
12453 if (HasExtraParameters) {
12454 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12455 FD->setInvalidDecl(true);
12456 nparams = 3;
12457 }
12458
12459 // FIXME: a lot of the following diagnostics would be improved
12460 // if we had some location information about types.
12461
12462 QualType CharPP =
12464 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12465
12466 for (unsigned i = 0; i < nparams; ++i) {
12467 QualType AT = FTP->getParamType(i);
12468
12469 bool mismatch = true;
12470
12472 mismatch = false;
12473 else if (Expected[i] == CharPP) {
12474 // As an extension, the following forms are okay:
12475 // char const **
12476 // char const * const *
12477 // char * const *
12478
12480 const PointerType* PT;
12481 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12482 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12484 Context.CharTy)) {
12485 qs.removeConst();
12486 mismatch = !qs.empty();
12487 }
12488 }
12489
12490 if (mismatch) {
12491 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12492 // TODO: suggest replacing given type with expected type
12493 FD->setInvalidDecl(true);
12494 }
12495 }
12496
12497 if (nparams == 1 && !FD->isInvalidDecl()) {
12498 Diag(FD->getLocation(), diag::warn_main_one_arg);
12499 }
12500
12501 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12502 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12503 FD->setInvalidDecl();
12504 }
12505}
12506
12507static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12508
12509 // Default calling convention for main and wmain is __cdecl
12510 if (FD->getName() == "main" || FD->getName() == "wmain")
12511 return false;
12512
12513 // Default calling convention for MinGW is __cdecl
12514 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12515 if (T.isWindowsGNUEnvironment())
12516 return false;
12517
12518 // Default calling convention for WinMain, wWinMain and DllMain
12519 // is __stdcall on 32 bit Windows
12520 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12521 return true;
12522
12523 return false;
12524}
12525
12527 QualType T = FD->getType();
12528 assert(T->isFunctionType() && "function decl is not of function type");
12529 const FunctionType *FT = T->castAs<FunctionType>();
12530
12531 // Set an implicit return of 'zero' if the function can return some integral,
12532 // enumeration, pointer or nullptr type.
12536 // DllMain is exempt because a return value of zero means it failed.
12537 if (FD->getName() != "DllMain")
12538 FD->setHasImplicitReturnZero(true);
12539
12540 // Explicitly specified calling conventions are applied to MSVC entry points
12541 if (!hasExplicitCallingConv(T)) {
12542 if (isDefaultStdCall(FD, *this)) {
12543 if (FT->getCallConv() != CC_X86StdCall) {
12546 FD->setType(QualType(FT, 0));
12547 }
12548 } else if (FT->getCallConv() != CC_C) {
12551 FD->setType(QualType(FT, 0));
12552 }
12553 }
12554
12555 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12556 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12557 FD->setInvalidDecl();
12558 }
12559}
12560
12562 // FIXME: Need strict checking. In C89, we need to check for
12563 // any assignment, increment, decrement, function-calls, or
12564 // commas outside of a sizeof. In C99, it's the same list,
12565 // except that the aforementioned are allowed in unevaluated
12566 // expressions. Everything else falls under the
12567 // "may accept other forms of constant expressions" exception.
12568 //
12569 // Regular C++ code will not end up here (exceptions: language extensions,
12570 // OpenCL C++ etc), so the constant expression rules there don't matter.
12571 if (Init->isValueDependent()) {
12572 assert(Init->containsErrors() &&
12573 "Dependent code should only occur in error-recovery path.");
12574 return true;
12575 }
12576 const Expr *Culprit;
12577 if (Init->isConstantInitializer(Context, false, &Culprit))
12578 return false;
12579 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12580 return true;
12581}
12582
12583namespace {
12584 // Visits an initialization expression to see if OrigDecl is evaluated in
12585 // its own initialization and throws a warning if it does.
12586 class SelfReferenceChecker
12587 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12588 Sema &S;
12589 Decl *OrigDecl;
12590 bool isRecordType;
12591 bool isPODType;
12592 bool isReferenceType;
12593
12594 bool isInitList;
12595 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12596
12597 public:
12599
12600 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12601 S(S), OrigDecl(OrigDecl) {
12602 isPODType = false;
12603 isRecordType = false;
12604 isReferenceType = false;
12605 isInitList = false;
12606 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12607 isPODType = VD->getType().isPODType(S.Context);
12608 isRecordType = VD->getType()->isRecordType();
12609 isReferenceType = VD->getType()->isReferenceType();
12610 }
12611 }
12612
12613 // For most expressions, just call the visitor. For initializer lists,
12614 // track the index of the field being initialized since fields are
12615 // initialized in order allowing use of previously initialized fields.
12616 void CheckExpr(Expr *E) {
12617 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12618 if (!InitList) {
12619 Visit(E);
12620 return;
12621 }
12622
12623 // Track and increment the index here.
12624 isInitList = true;
12625 InitFieldIndex.push_back(0);
12626 for (auto *Child : InitList->children()) {
12627 CheckExpr(cast<Expr>(Child));
12628 ++InitFieldIndex.back();
12629 }
12630 InitFieldIndex.pop_back();
12631 }
12632
12633 // Returns true if MemberExpr is checked and no further checking is needed.
12634 // Returns false if additional checking is required.
12635 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12637 Expr *Base = E;
12638 bool ReferenceField = false;
12639
12640 // Get the field members used.
12641 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12642 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12643 if (!FD)
12644 return false;
12645 Fields.push_back(FD);
12646 if (FD->getType()->isReferenceType())
12647 ReferenceField = true;
12648 Base = ME->getBase()->IgnoreParenImpCasts();
12649 }
12650
12651 // Keep checking only if the base Decl is the same.
12652 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12653 if (!DRE || DRE->getDecl() != OrigDecl)
12654 return false;
12655
12656 // A reference field can be bound to an unininitialized field.
12657 if (CheckReference && !ReferenceField)
12658 return true;
12659
12660 // Convert FieldDecls to their index number.
12661 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12662 for (const FieldDecl *I : llvm::reverse(Fields))
12663 UsedFieldIndex.push_back(I->getFieldIndex());
12664
12665 // See if a warning is needed by checking the first difference in index
12666 // numbers. If field being used has index less than the field being
12667 // initialized, then the use is safe.
12668 for (auto UsedIter = UsedFieldIndex.begin(),
12669 UsedEnd = UsedFieldIndex.end(),
12670 OrigIter = InitFieldIndex.begin(),
12671 OrigEnd = InitFieldIndex.end();
12672 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12673 if (*UsedIter < *OrigIter)
12674 return true;
12675 if (*UsedIter > *OrigIter)
12676 break;
12677 }
12678
12679 // TODO: Add a different warning which will print the field names.
12680 HandleDeclRefExpr(DRE);
12681 return true;
12682 }
12683
12684 // For most expressions, the cast is directly above the DeclRefExpr.
12685 // For conditional operators, the cast can be outside the conditional
12686 // operator if both expressions are DeclRefExpr's.
12687 void HandleValue(Expr *E) {
12688 E = E->IgnoreParens();
12689 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12690 HandleDeclRefExpr(DRE);
12691 return;
12692 }
12693
12694 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12695 Visit(CO->getCond());
12696 HandleValue(CO->getTrueExpr());
12697 HandleValue(CO->getFalseExpr());
12698 return;
12699 }
12700
12701 if (BinaryConditionalOperator *BCO =
12702 dyn_cast<BinaryConditionalOperator>(E)) {
12703 Visit(BCO->getCond());
12704 HandleValue(BCO->getFalseExpr());
12705 return;
12706 }
12707
12708 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12709 if (Expr *SE = OVE->getSourceExpr())
12710 HandleValue(SE);
12711 return;
12712 }
12713
12714 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12715 if (BO->getOpcode() == BO_Comma) {
12716 Visit(BO->getLHS());
12717 HandleValue(BO->getRHS());
12718 return;
12719 }
12720 }
12721
12722 if (isa<MemberExpr>(E)) {
12723 if (isInitList) {
12724 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12725 false /*CheckReference*/))
12726 return;
12727 }
12728
12730 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12731 // Check for static member variables and don't warn on them.
12732 if (!isa<FieldDecl>(ME->getMemberDecl()))
12733 return;
12734 Base = ME->getBase()->IgnoreParenImpCasts();
12735 }
12736 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12737 HandleDeclRefExpr(DRE);
12738 return;
12739 }
12740
12741 Visit(E);
12742 }
12743
12744 // Reference types not handled in HandleValue are handled here since all
12745 // uses of references are bad, not just r-value uses.
12746 void VisitDeclRefExpr(DeclRefExpr *E) {
12747 if (isReferenceType)
12748 HandleDeclRefExpr(E);
12749 }
12750
12751 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12752 if (E->getCastKind() == CK_LValueToRValue) {
12753 HandleValue(E->getSubExpr());
12754 return;
12755 }
12756
12757 Inherited::VisitImplicitCastExpr(E);
12758 }
12759
12760 void VisitMemberExpr(MemberExpr *E) {
12761 if (isInitList) {
12762 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12763 return;
12764 }
12765
12766 // Don't warn on arrays since they can be treated as pointers.
12767 if (E->getType()->canDecayToPointerType()) return;
12768
12769 // Warn when a non-static method call is followed by non-static member
12770 // field accesses, which is followed by a DeclRefExpr.
12771 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12772 bool Warn = (MD && !MD->isStatic());
12773 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12774 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12775 if (!isa<FieldDecl>(ME->getMemberDecl()))
12776 Warn = false;
12777 Base = ME->getBase()->IgnoreParenImpCasts();
12778 }
12779
12780 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12781 if (Warn)
12782 HandleDeclRefExpr(DRE);
12783 return;
12784 }
12785
12786 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12787 // Visit that expression.
12788 Visit(Base);
12789 }
12790
12791 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12792 Expr *Callee = E->getCallee();
12793
12794 if (isa<UnresolvedLookupExpr>(Callee))
12795 return Inherited::VisitCXXOperatorCallExpr(E);
12796
12797 Visit(Callee);
12798 for (auto Arg: E->arguments())
12799 HandleValue(Arg->IgnoreParenImpCasts());
12800 }
12801
12802 void VisitUnaryOperator(UnaryOperator *E) {
12803 // For POD record types, addresses of its own members are well-defined.
12804 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12805 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12806 if (!isPODType)
12807 HandleValue(E->getSubExpr());
12808 return;
12809 }
12810
12811 if (E->isIncrementDecrementOp()) {
12812 HandleValue(E->getSubExpr());
12813 return;
12814 }
12815
12816 Inherited::VisitUnaryOperator(E);
12817 }
12818
12819 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12820
12821 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12822 if (E->getConstructor()->isCopyConstructor()) {
12823 Expr *ArgExpr = E->getArg(0);
12824 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12825 if (ILE->getNumInits() == 1)
12826 ArgExpr = ILE->getInit(0);
12827 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12828 if (ICE->getCastKind() == CK_NoOp)
12829 ArgExpr = ICE->getSubExpr();
12830 HandleValue(ArgExpr);
12831 return;
12832 }
12833 Inherited::VisitCXXConstructExpr(E);
12834 }
12835
12836 void VisitCallExpr(CallExpr *E) {
12837 // Treat std::move as a use.
12838 if (E->isCallToStdMove()) {
12839 HandleValue(E->getArg(0));
12840 return;
12841 }
12842
12843 Inherited::VisitCallExpr(E);
12844 }
12845
12846 void VisitBinaryOperator(BinaryOperator *E) {
12847 if (E->isCompoundAssignmentOp()) {
12848 HandleValue(E->getLHS());
12849 Visit(E->getRHS());
12850 return;
12851 }
12852
12853 Inherited::VisitBinaryOperator(E);
12854 }
12855
12856 // A custom visitor for BinaryConditionalOperator is needed because the
12857 // regular visitor would check the condition and true expression separately
12858 // but both point to the same place giving duplicate diagnostics.
12859 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12860 Visit(E->getCond());
12861 Visit(E->getFalseExpr());
12862 }
12863
12864 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12865 Decl* ReferenceDecl = DRE->getDecl();
12866 if (OrigDecl != ReferenceDecl) return;
12867 unsigned diag;
12868 if (isReferenceType) {
12869 diag = diag::warn_uninit_self_reference_in_reference_init;
12870 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12871 diag = diag::warn_static_self_reference_in_init;
12872 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12873 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12874 DRE->getDecl()->getType()->isRecordType()) {
12875 diag = diag::warn_uninit_self_reference_in_init;
12876 } else {
12877 // Local variables will be handled by the CFG analysis.
12878 return;
12879 }
12880
12881 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12882 S.PDiag(diag)
12883 << DRE->getDecl() << OrigDecl->getLocation()
12884 << DRE->getSourceRange());
12885 }
12886 };
12887
12888 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12889 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12890 bool DirectInit) {
12891 // Parameters arguments are occassionially constructed with itself,
12892 // for instance, in recursive functions. Skip them.
12893 if (isa<ParmVarDecl>(OrigDecl))
12894 return;
12895
12896 E = E->IgnoreParens();
12897
12898 // Skip checking T a = a where T is not a record or reference type.
12899 // Doing so is a way to silence uninitialized warnings.
12900 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12901 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12902 if (ICE->getCastKind() == CK_LValueToRValue)
12903 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12904 if (DRE->getDecl() == OrigDecl)
12905 return;
12906
12907 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12908 }
12909} // end anonymous namespace
12910
12911namespace {
12912 // Simple wrapper to add the name of a variable or (if no variable is
12913 // available) a DeclarationName into a diagnostic.
12914 struct VarDeclOrName {
12915 VarDecl *VDecl;
12916 DeclarationName Name;
12917
12918 friend const Sema::SemaDiagnosticBuilder &
12919 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12920 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12921 }
12922 };
12923} // end anonymous namespace
12924
12927 TypeSourceInfo *TSI,
12929 Expr *Init) {
12930 bool IsInitCapture = !VDecl;
12931 assert((!VDecl || !VDecl->isInitCapture()) &&
12932 "init captures are expected to be deduced prior to initialization");
12933
12934 VarDeclOrName VN{VDecl, Name};
12935
12937 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12938
12939 // Diagnose auto array declarations in C23, unless it's a supported extension.
12940 if (getLangOpts().C23 && Type->isArrayType() &&
12941 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
12942 Diag(Range.getBegin(), diag::err_auto_not_allowed)
12943 << (int)Deduced->getContainedAutoType()->getKeyword()
12944 << /*in array decl*/ 23 << Range;
12945 return QualType();
12946 }
12947
12948 // C++11 [dcl.spec.auto]p3
12949 if (!Init) {
12950 assert(VDecl && "no init for init capture deduction?");
12951
12952 // Except for class argument deduction, and then for an initializing
12953 // declaration only, i.e. no static at class scope or extern.
12954 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12955 VDecl->hasExternalStorage() ||
12956 VDecl->isStaticDataMember()) {
12957 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12958 << VDecl->getDeclName() << Type;
12959 return QualType();
12960 }
12961 }
12962
12963 ArrayRef<Expr*> DeduceInits;
12964 if (Init)
12965 DeduceInits = Init;
12966
12967 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12968 if (DirectInit && PL)
12969 DeduceInits = PL->exprs();
12970
12971 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12972 assert(VDecl && "non-auto type for init capture deduction?");
12975 VDecl->getLocation(), DirectInit, Init);
12976 // FIXME: Initialization should not be taking a mutable list of inits.
12977 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
12978 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12979 InitsCopy);
12980 }
12981
12982 if (DirectInit) {
12983 if (auto *IL = dyn_cast<InitListExpr>(Init))
12984 DeduceInits = IL->inits();
12985 }
12986
12987 // Deduction only works if we have exactly one source expression.
12988 if (DeduceInits.empty()) {
12989 // It isn't possible to write this directly, but it is possible to
12990 // end up in this situation with "auto x(some_pack...);"
12991 Diag(Init->getBeginLoc(), IsInitCapture
12992 ? diag::err_init_capture_no_expression
12993 : diag::err_auto_var_init_no_expression)
12994 << VN << Type << Range;
12995 return QualType();
12996 }
12997
12998 if (DeduceInits.size() > 1) {
12999 Diag(DeduceInits[1]->getBeginLoc(),
13000 IsInitCapture ? diag::err_init_capture_multiple_expressions
13001 : diag::err_auto_var_init_multiple_expressions)
13002 << VN << Type << Range;
13003 return QualType();
13004 }
13005
13006 Expr *DeduceInit = DeduceInits[0];
13007 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13008 Diag(Init->getBeginLoc(), IsInitCapture
13009 ? diag::err_init_capture_paren_braces
13010 : diag::err_auto_var_init_paren_braces)
13011 << isa<InitListExpr>(Init) << VN << Type << Range;
13012 return QualType();
13013 }
13014
13015 // Expressions default to 'id' when we're in a debugger.
13016 bool DefaultedAnyToId = false;
13017 if (getLangOpts().DebuggerCastResultToId &&
13018 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13020 if (Result.isInvalid()) {
13021 return QualType();
13022 }
13023 Init = Result.get();
13024 DefaultedAnyToId = true;
13025 }
13026
13027 // C++ [dcl.decomp]p1:
13028 // If the assignment-expression [...] has array type A and no ref-qualifier
13029 // is present, e has type cv A
13030 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13032 DeduceInit->getType()->isConstantArrayType())
13033 return Context.getQualifiedType(DeduceInit->getType(),
13034 Type.getQualifiers());
13035
13037 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13039 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13042 if (!IsInitCapture)
13043 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13044 else if (isa<InitListExpr>(Init))
13046 diag::err_init_capture_deduction_failure_from_init_list)
13047 << VN
13048 << (DeduceInit->getType().isNull() ? TSI->getType()
13049 : DeduceInit->getType())
13050 << DeduceInit->getSourceRange();
13051 else
13052 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13053 << VN << TSI->getType()
13054 << (DeduceInit->getType().isNull() ? TSI->getType()
13055 : DeduceInit->getType())
13056 << DeduceInit->getSourceRange();
13057 }
13058
13059 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13060 // 'id' instead of a specific object type prevents most of our usual
13061 // checks.
13062 // We only want to warn outside of template instantiations, though:
13063 // inside a template, the 'id' could have come from a parameter.
13064 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13065 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13067 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13068 }
13069
13070 return DeducedType;
13071}
13072
13074 Expr *Init) {
13075 assert(!Init || !Init->containsErrors());
13077 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13078 VDecl->getSourceRange(), DirectInit, Init);
13079 if (DeducedType.isNull()) {
13080 VDecl->setInvalidDecl();
13081 return true;
13082 }
13083
13084 VDecl->setType(DeducedType);
13085 assert(VDecl->isLinkageValid());
13086
13087 // In ARC, infer lifetime.
13088 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13089 VDecl->setInvalidDecl();
13090
13091 if (getLangOpts().OpenCL)
13093
13094 // If this is a redeclaration, check that the type we just deduced matches
13095 // the previously declared type.
13096 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13097 // We never need to merge the type, because we cannot form an incomplete
13098 // array of auto, nor deduce such a type.
13099 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13100 }
13101
13102 // Check the deduced type is valid for a variable declaration.
13104 return VDecl->isInvalidDecl();
13105}
13106
13109 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13110 Init = EWC->getSubExpr();
13111
13112 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13113 Init = CE->getSubExpr();
13114
13115 QualType InitType = Init->getType();
13118 "shouldn't be called if type doesn't have a non-trivial C struct");
13119 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13120 for (auto *I : ILE->inits()) {
13121 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13122 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13123 continue;
13124 SourceLocation SL = I->getExprLoc();
13126 }
13127 return;
13128 }
13129
13130 if (isa<ImplicitValueInitExpr>(Init)) {
13133 NTCUK_Init);
13134 } else {
13135 // Assume all other explicit initializers involving copying some existing
13136 // object.
13137 // TODO: ignore any explicit initializers where we can guarantee
13138 // copy-elision.
13141 }
13142}
13143
13144namespace {
13145
13146bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13147 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13148 // in the source code or implicitly by the compiler if it is in a union
13149 // defined in a system header and has non-trivial ObjC ownership
13150 // qualifications. We don't want those fields to participate in determining
13151 // whether the containing union is non-trivial.
13152 return FD->hasAttr<UnavailableAttr>();
13153}
13154
13155struct DiagNonTrivalCUnionDefaultInitializeVisitor
13156 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13157 void> {
13158 using Super =
13159 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13160 void>;
13161
13162 DiagNonTrivalCUnionDefaultInitializeVisitor(
13163 QualType OrigTy, SourceLocation OrigLoc,
13164 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13165 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13166
13167 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13168 const FieldDecl *FD, bool InNonTrivialUnion) {
13169 if (const auto *AT = S.Context.getAsArrayType(QT))
13170 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13171 InNonTrivialUnion);
13172 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13173 }
13174
13175 void visitARCStrong(QualType QT, const FieldDecl *FD,
13176 bool InNonTrivialUnion) {
13177 if (InNonTrivialUnion)
13178 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13179 << 1 << 0 << QT << FD->getName();
13180 }
13181
13182 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13183 if (InNonTrivialUnion)
13184 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13185 << 1 << 0 << QT << FD->getName();
13186 }
13187
13188 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13189 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13190 if (RD->isUnion()) {
13191 if (OrigLoc.isValid()) {
13192 bool IsUnion = false;
13193 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13194 IsUnion = OrigRD->isUnion();
13195 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13196 << 0 << OrigTy << IsUnion << UseContext;
13197 // Reset OrigLoc so that this diagnostic is emitted only once.
13198 OrigLoc = SourceLocation();
13199 }
13200 InNonTrivialUnion = true;
13201 }
13202
13203 if (InNonTrivialUnion)
13204 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13205 << 0 << 0 << QT.getUnqualifiedType() << "";
13206
13207 for (const FieldDecl *FD : RD->fields())
13208 if (!shouldIgnoreForRecordTriviality(FD))
13209 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13210 }
13211
13212 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13213
13214 // The non-trivial C union type or the struct/union type that contains a
13215 // non-trivial C union.
13216 QualType OrigTy;
13217 SourceLocation OrigLoc;
13219 Sema &S;
13220};
13221
13222struct DiagNonTrivalCUnionDestructedTypeVisitor
13223 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13224 using Super =
13226
13227 DiagNonTrivalCUnionDestructedTypeVisitor(
13228 QualType OrigTy, SourceLocation OrigLoc,
13229 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13230 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13231
13232 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13233 const FieldDecl *FD, bool InNonTrivialUnion) {
13234 if (const auto *AT = S.Context.getAsArrayType(QT))
13235 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13236 InNonTrivialUnion);
13237 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13238 }
13239
13240 void visitARCStrong(QualType QT, const FieldDecl *FD,
13241 bool InNonTrivialUnion) {
13242 if (InNonTrivialUnion)
13243 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13244 << 1 << 1 << QT << FD->getName();
13245 }
13246
13247 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13248 if (InNonTrivialUnion)
13249 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13250 << 1 << 1 << QT << FD->getName();
13251 }
13252
13253 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13254 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13255 if (RD->isUnion()) {
13256 if (OrigLoc.isValid()) {
13257 bool IsUnion = false;
13258 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13259 IsUnion = OrigRD->isUnion();
13260 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13261 << 1 << OrigTy << IsUnion << UseContext;
13262 // Reset OrigLoc so that this diagnostic is emitted only once.
13263 OrigLoc = SourceLocation();
13264 }
13265 InNonTrivialUnion = true;
13266 }
13267
13268 if (InNonTrivialUnion)
13269 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13270 << 0 << 1 << QT.getUnqualifiedType() << "";
13271
13272 for (const FieldDecl *FD : RD->fields())
13273 if (!shouldIgnoreForRecordTriviality(FD))
13274 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13275 }
13276
13277 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13278 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13279 bool InNonTrivialUnion) {}
13280
13281 // The non-trivial C union type or the struct/union type that contains a
13282 // non-trivial C union.
13283 QualType OrigTy;
13284 SourceLocation OrigLoc;
13286 Sema &S;
13287};
13288
13289struct DiagNonTrivalCUnionCopyVisitor
13290 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13292
13293 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13295 Sema &S)
13296 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13297
13298 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13299 const FieldDecl *FD, bool InNonTrivialUnion) {
13300 if (const auto *AT = S.Context.getAsArrayType(QT))
13301 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13302 InNonTrivialUnion);
13303 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13304 }
13305
13306 void visitARCStrong(QualType QT, const FieldDecl *FD,
13307 bool InNonTrivialUnion) {
13308 if (InNonTrivialUnion)
13309 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13310 << 1 << 2 << QT << FD->getName();
13311 }
13312
13313 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13314 if (InNonTrivialUnion)
13315 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13316 << 1 << 2 << QT << FD->getName();
13317 }
13318
13319 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13320 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13321 if (RD->isUnion()) {
13322 if (OrigLoc.isValid()) {
13323 bool IsUnion = false;
13324 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13325 IsUnion = OrigRD->isUnion();
13326 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13327 << 2 << OrigTy << IsUnion << UseContext;
13328 // Reset OrigLoc so that this diagnostic is emitted only once.
13329 OrigLoc = SourceLocation();
13330 }
13331 InNonTrivialUnion = true;
13332 }
13333
13334 if (InNonTrivialUnion)
13335 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13336 << 0 << 2 << QT.getUnqualifiedType() << "";
13337
13338 for (const FieldDecl *FD : RD->fields())
13339 if (!shouldIgnoreForRecordTriviality(FD))
13340 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13341 }
13342
13343 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13344 const FieldDecl *FD, bool InNonTrivialUnion) {}
13345 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13346 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13347 bool InNonTrivialUnion) {}
13348
13349 // The non-trivial C union type or the struct/union type that contains a
13350 // non-trivial C union.
13351 QualType OrigTy;
13352 SourceLocation OrigLoc;
13354 Sema &S;
13355};
13356
13357} // namespace
13358
13360 NonTrivialCUnionContext UseContext,
13361 unsigned NonTrivialKind) {
13365 "shouldn't be called if type doesn't have a non-trivial C union");
13366
13367 if ((NonTrivialKind & NTCUK_Init) &&
13369 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13370 .visit(QT, nullptr, false);
13371 if ((NonTrivialKind & NTCUK_Destruct) &&
13373 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13374 .visit(QT, nullptr, false);
13375 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13376 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13377 .visit(QT, nullptr, false);
13378}
13379
13381 // If there is no declaration, there was an error parsing it. Just ignore
13382 // the initializer.
13383 if (!RealDecl) {
13384 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13385 return;
13386 }
13387
13388 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13389 if (!Method->isInvalidDecl()) {
13390 // Pure-specifiers are handled in ActOnPureSpecifier.
13391 Diag(Method->getLocation(), diag::err_member_function_initialization)
13392 << Method->getDeclName() << Init->getSourceRange();
13393 Method->setInvalidDecl();
13394 }
13395 return;
13396 }
13397
13398 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13399 if (!VDecl) {
13400 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13401 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13402 RealDecl->setInvalidDecl();
13403 return;
13404 }
13405
13406 if (VDecl->isInvalidDecl()) {
13408 SmallVector<Expr *> SubExprs;
13409 if (Res.isUsable())
13410 SubExprs.push_back(Res.get());
13411 ExprResult Recovery =
13412 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), SubExprs);
13413 if (Expr *E = Recovery.get())
13414 VDecl->setInit(E);
13415 return;
13416 }
13417
13418 // WebAssembly tables can't be used to initialise a variable.
13419 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13420 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13421 VDecl->setInvalidDecl();
13422 return;
13423 }
13424
13425 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13426 if (VDecl->getType()->isUndeducedType()) {
13427 // Attempt typo correction early so that the type of the init expression can
13428 // be deduced based on the chosen correction if the original init contains a
13429 // TypoExpr.
13431 if (!Res.isUsable()) {
13432 // There are unresolved typos in Init, just drop them.
13433 // FIXME: improve the recovery strategy to preserve the Init.
13434 RealDecl->setInvalidDecl();
13435 return;
13436 }
13437 if (Res.get()->containsErrors()) {
13438 // Invalidate the decl as we don't know the type for recovery-expr yet.
13439 RealDecl->setInvalidDecl();
13440 VDecl->setInit(Res.get());
13441 return;
13442 }
13443 Init = Res.get();
13444
13446 return;
13447 }
13448
13449 // dllimport cannot be used on variable definitions.
13450 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13451 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13452 VDecl->setInvalidDecl();
13453 return;
13454 }
13455
13456 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13457 // the identifier has external or internal linkage, the declaration shall
13458 // have no initializer for the identifier.
13459 // C++14 [dcl.init]p5 is the same restriction for C++.
13460 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13461 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13462 VDecl->setInvalidDecl();
13463 return;
13464 }
13465
13466 if (!VDecl->getType()->isDependentType()) {
13467 // A definition must end up with a complete type, which means it must be
13468 // complete with the restriction that an array type might be completed by
13469 // the initializer; note that later code assumes this restriction.
13470 QualType BaseDeclType = VDecl->getType();
13471 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13472 BaseDeclType = Array->getElementType();
13473 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13474 diag::err_typecheck_decl_incomplete_type)) {
13475 RealDecl->setInvalidDecl();
13476 return;
13477 }
13478
13479 // The variable can not have an abstract class type.
13480 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13481 diag::err_abstract_type_in_decl,
13483 VDecl->setInvalidDecl();
13484 }
13485
13486 // C++ [module.import/6] external definitions are not permitted in header
13487 // units.
13488 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13489 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13490 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13491 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13493 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13494 VDecl->setInvalidDecl();
13495 }
13496
13497 // If adding the initializer will turn this declaration into a definition,
13498 // and we already have a definition for this variable, diagnose or otherwise
13499 // handle the situation.
13500 if (VarDecl *Def = VDecl->getDefinition())
13501 if (Def != VDecl &&
13502 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13504 checkVarDeclRedefinition(Def, VDecl))
13505 return;
13506
13507 if (getLangOpts().CPlusPlus) {
13508 // C++ [class.static.data]p4
13509 // If a static data member is of const integral or const
13510 // enumeration type, its declaration in the class definition can
13511 // specify a constant-initializer which shall be an integral
13512 // constant expression (5.19). In that case, the member can appear
13513 // in integral constant expressions. The member shall still be
13514 // defined in a namespace scope if it is used in the program and the
13515 // namespace scope definition shall not contain an initializer.
13516 //
13517 // We already performed a redefinition check above, but for static
13518 // data members we also need to check whether there was an in-class
13519 // declaration with an initializer.
13520 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13521 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13522 << VDecl->getDeclName();
13523 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13524 diag::note_previous_initializer)
13525 << 0;
13526 return;
13527 }
13528
13529 if (VDecl->hasLocalStorage())
13531
13533 VDecl->setInvalidDecl();
13534 return;
13535 }
13536 }
13537
13538 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13539 // a kernel function cannot be initialized."
13540 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13541 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13542 VDecl->setInvalidDecl();
13543 return;
13544 }
13545
13546 // The LoaderUninitialized attribute acts as a definition (of undef).
13547 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13548 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13549 VDecl->setInvalidDecl();
13550 return;
13551 }
13552
13553 // Get the decls type and save a reference for later, since
13554 // CheckInitializerTypes may change it.
13555 QualType DclT = VDecl->getType(), SavT = DclT;
13556
13557 // Expressions default to 'id' when we're in a debugger
13558 // and we are assigning it to a variable of Objective-C pointer type.
13559 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13560 Init->getType() == Context.UnknownAnyTy) {
13562 if (!Result.isUsable()) {
13563 VDecl->setInvalidDecl();
13564 return;
13565 }
13566 Init = Result.get();
13567 }
13568
13569 // Perform the initialization.
13570 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13571 bool IsParenListInit = false;
13572 if (!VDecl->isInvalidDecl()) {
13575 VDecl->getLocation(), DirectInit, Init);
13576
13577 MultiExprArg Args = Init;
13578 if (CXXDirectInit)
13579 Args = MultiExprArg(CXXDirectInit->getExprs(),
13580 CXXDirectInit->getNumExprs());
13581
13582 // Try to correct any TypoExprs in the initialization arguments.
13583 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13585 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13586 [this, Entity, Kind](Expr *E) {
13587 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13588 return Init.Failed() ? ExprError() : E;
13589 });
13590 if (!Res.isUsable()) {
13591 VDecl->setInvalidDecl();
13592 } else if (Res.get() != Args[Idx]) {
13593 Args[Idx] = Res.get();
13594 }
13595 }
13596 if (VDecl->isInvalidDecl())
13597 return;
13598
13599 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13600 /*TopLevelOfInitList=*/false,
13601 /*TreatUnavailableAsInvalid=*/false);
13602 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13603 if (!Result.isUsable()) {
13604 // If the provided initializer fails to initialize the var decl,
13605 // we attach a recovery expr for better recovery.
13606 auto RecoveryExpr =
13607 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13608 if (RecoveryExpr.get())
13609 VDecl->setInit(RecoveryExpr.get());
13610 // In general, for error recovery purposes, the initializer doesn't play
13611 // part in the valid bit of the declaration. There are a few exceptions:
13612 // 1) if the var decl has a deduced auto type, and the type cannot be
13613 // deduced by an invalid initializer;
13614 // 2) if the var decl is a decomposition decl with a non-deduced type,
13615 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13616 // Case 1) was already handled elsewhere.
13617 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13618 VDecl->setInvalidDecl();
13619 return;
13620 }
13621
13622 Init = Result.getAs<Expr>();
13623 IsParenListInit = !InitSeq.steps().empty() &&
13624 InitSeq.step_begin()->Kind ==
13626 QualType VDeclType = VDecl->getType();
13627 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
13628 !VDeclType->isDependentType() &&
13629 Context.getAsIncompleteArrayType(VDeclType) &&
13631 // Bail out if it is not possible to deduce array size from the
13632 // initializer.
13633 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13634 << VDeclType;
13635 VDecl->setInvalidDecl();
13636 return;
13637 }
13638 }
13639
13640 // Check for self-references within variable initializers.
13641 // Variables declared within a function/method body (except for references)
13642 // are handled by a dataflow analysis.
13643 // This is undefined behavior in C++, but valid in C.
13644 if (getLangOpts().CPlusPlus)
13645 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13646 VDecl->getType()->isReferenceType())
13647 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13648
13649 // If the type changed, it means we had an incomplete type that was
13650 // completed by the initializer. For example:
13651 // int ary[] = { 1, 3, 5 };
13652 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13653 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13654 VDecl->setType(DclT);
13655
13656 if (!VDecl->isInvalidDecl()) {
13657 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13658
13659 if (VDecl->hasAttr<BlocksAttr>())
13660 ObjC().checkRetainCycles(VDecl, Init);
13661
13662 // It is safe to assign a weak reference into a strong variable.
13663 // Although this code can still have problems:
13664 // id x = self.weakProp;
13665 // id y = self.weakProp;
13666 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13667 // paths through the function. This should be revisited if
13668 // -Wrepeated-use-of-weak is made flow-sensitive.
13669 if (FunctionScopeInfo *FSI = getCurFunction())
13670 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13672 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13673 Init->getBeginLoc()))
13674 FSI->markSafeWeakUse(Init);
13675 }
13676
13677 // The initialization is usually a full-expression.
13678 //
13679 // FIXME: If this is a braced initialization of an aggregate, it is not
13680 // an expression, and each individual field initializer is a separate
13681 // full-expression. For instance, in:
13682 //
13683 // struct Temp { ~Temp(); };
13684 // struct S { S(Temp); };
13685 // struct T { S a, b; } t = { Temp(), Temp() }
13686 //
13687 // we should destroy the first Temp before constructing the second.
13690 /*DiscardedValue*/ false, VDecl->isConstexpr());
13691 if (!Result.isUsable()) {
13692 VDecl->setInvalidDecl();
13693 return;
13694 }
13695 Init = Result.get();
13696
13697 // Attach the initializer to the decl.
13698 VDecl->setInit(Init);
13699
13700 if (VDecl->isLocalVarDecl()) {
13701 // Don't check the initializer if the declaration is malformed.
13702 if (VDecl->isInvalidDecl()) {
13703 // do nothing
13704
13705 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13706 // This is true even in C++ for OpenCL.
13707 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13709
13710 // Otherwise, C++ does not restrict the initializer.
13711 } else if (getLangOpts().CPlusPlus) {
13712 // do nothing
13713
13714 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13715 // static storage duration shall be constant expressions or string literals.
13716 } else if (VDecl->getStorageClass() == SC_Static) {
13718
13719 // C89 is stricter than C99 for aggregate initializers.
13720 // C89 6.5.7p3: All the expressions [...] in an initializer list
13721 // for an object that has aggregate or union type shall be
13722 // constant expressions.
13723 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13724 isa<InitListExpr>(Init)) {
13725 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13726 }
13727
13728 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13729 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13730 if (VDecl->hasLocalStorage())
13731 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13732 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13733 VDecl->getLexicalDeclContext()->isRecord()) {
13734 // This is an in-class initialization for a static data member, e.g.,
13735 //
13736 // struct S {
13737 // static const int value = 17;
13738 // };
13739
13740 // C++ [class.mem]p4:
13741 // A member-declarator can contain a constant-initializer only
13742 // if it declares a static member (9.4) of const integral or
13743 // const enumeration type, see 9.4.2.
13744 //
13745 // C++11 [class.static.data]p3:
13746 // If a non-volatile non-inline const static data member is of integral
13747 // or enumeration type, its declaration in the class definition can
13748 // specify a brace-or-equal-initializer in which every initializer-clause
13749 // that is an assignment-expression is a constant expression. A static
13750 // data member of literal type can be declared in the class definition
13751 // with the constexpr specifier; if so, its declaration shall specify a
13752 // brace-or-equal-initializer in which every initializer-clause that is
13753 // an assignment-expression is a constant expression.
13754
13755 // Do nothing on dependent types.
13756 if (DclT->isDependentType()) {
13757
13758 // Allow any 'static constexpr' members, whether or not they are of literal
13759 // type. We separately check that every constexpr variable is of literal
13760 // type.
13761 } else if (VDecl->isConstexpr()) {
13762
13763 // Require constness.
13764 } else if (!DclT.isConstQualified()) {
13765 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13766 << Init->getSourceRange();
13767 VDecl->setInvalidDecl();
13768
13769 // We allow integer constant expressions in all cases.
13770 } else if (DclT->isIntegralOrEnumerationType()) {
13771 // Check whether the expression is a constant expression.
13774 // In C++11, a non-constexpr const static data member with an
13775 // in-class initializer cannot be volatile.
13776 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13777 else if (Init->isValueDependent())
13778 ; // Nothing to check.
13779 else if (Init->isIntegerConstantExpr(Context, &Loc))
13780 ; // Ok, it's an ICE!
13781 else if (Init->getType()->isScopedEnumeralType() &&
13782 Init->isCXX11ConstantExpr(Context))
13783 ; // Ok, it is a scoped-enum constant expression.
13784 else if (Init->isEvaluatable(Context)) {
13785 // If we can constant fold the initializer through heroics, accept it,
13786 // but report this as a use of an extension for -pedantic.
13787 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13788 << Init->getSourceRange();
13789 } else {
13790 // Otherwise, this is some crazy unknown case. Report the issue at the
13791 // location provided by the isIntegerConstantExpr failed check.
13792 Diag(Loc, diag::err_in_class_initializer_non_constant)
13793 << Init->getSourceRange();
13794 VDecl->setInvalidDecl();
13795 }
13796
13797 // We allow foldable floating-point constants as an extension.
13798 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13799 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13800 // it anyway and provide a fixit to add the 'constexpr'.
13801 if (getLangOpts().CPlusPlus11) {
13802 Diag(VDecl->getLocation(),
13803 diag::ext_in_class_initializer_float_type_cxx11)
13804 << DclT << Init->getSourceRange();
13805 Diag(VDecl->getBeginLoc(),
13806 diag::note_in_class_initializer_float_type_cxx11)
13807 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13808 } else {
13809 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13810 << DclT << Init->getSourceRange();
13811
13812 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13813 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13814 << Init->getSourceRange();
13815 VDecl->setInvalidDecl();
13816 }
13817 }
13818
13819 // Suggest adding 'constexpr' in C++11 for literal types.
13820 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13821 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13822 << DclT << Init->getSourceRange()
13823 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13824 VDecl->setConstexpr(true);
13825
13826 } else {
13827 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13828 << DclT << Init->getSourceRange();
13829 VDecl->setInvalidDecl();
13830 }
13831 } else if (VDecl->isFileVarDecl()) {
13832 // In C, extern is typically used to avoid tentative definitions when
13833 // declaring variables in headers, but adding an initializer makes it a
13834 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13835 // In C++, extern is often used to give implicitly static const variables
13836 // external linkage, so don't warn in that case. If selectany is present,
13837 // this might be header code intended for C and C++ inclusion, so apply the
13838 // C++ rules.
13839 if (VDecl->getStorageClass() == SC_Extern &&
13840 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13842 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13844 Diag(VDecl->getLocation(), diag::warn_extern_init);
13845
13846 // In Microsoft C++ mode, a const variable defined in namespace scope has
13847 // external linkage by default if the variable is declared with
13848 // __declspec(dllexport).
13851 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13852 VDecl->setStorageClass(SC_Extern);
13853
13854 // C99 6.7.8p4. All file scoped initializers need to be constant.
13855 // Avoid duplicate diagnostics for constexpr variables.
13856 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13857 !VDecl->isConstexpr())
13859 }
13860
13861 QualType InitType = Init->getType();
13862 if (!InitType.isNull() &&
13866
13867 // We will represent direct-initialization similarly to copy-initialization:
13868 // int x(1); -as-> int x = 1;
13869 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13870 //
13871 // Clients that want to distinguish between the two forms, can check for
13872 // direct initializer using VarDecl::getInitStyle().
13873 // A major benefit is that clients that don't particularly care about which
13874 // exactly form was it (like the CodeGen) can handle both cases without
13875 // special case code.
13876
13877 // C++ 8.5p11:
13878 // The form of initialization (using parentheses or '=') is generally
13879 // insignificant, but does matter when the entity being initialized has a
13880 // class type.
13881 if (CXXDirectInit) {
13882 assert(DirectInit && "Call-style initializer must be direct init.");
13883 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13885 } else if (DirectInit) {
13886 // This must be list-initialization. No other way is direct-initialization.
13888 }
13889
13890 if (LangOpts.OpenMP &&
13891 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13892 VDecl->isFileVarDecl())
13893 DeclsToCheckForDeferredDiags.insert(VDecl);
13895}
13896
13898 // Our main concern here is re-establishing invariants like "a
13899 // variable's type is either dependent or complete".
13900 if (!D || D->isInvalidDecl()) return;
13901
13902 VarDecl *VD = dyn_cast<VarDecl>(D);
13903 if (!VD) return;
13904
13905 // Bindings are not usable if we can't make sense of the initializer.
13906 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13907 for (auto *BD : DD->bindings())
13908 BD->setInvalidDecl();
13909
13910 // Auto types are meaningless if we can't make sense of the initializer.
13911 if (VD->getType()->isUndeducedType()) {
13912 D->setInvalidDecl();
13913 return;
13914 }
13915
13916 QualType Ty = VD->getType();
13917 if (Ty->isDependentType()) return;
13918
13919 // Require a complete type.
13922 diag::err_typecheck_decl_incomplete_type)) {
13923 VD->setInvalidDecl();
13924 return;
13925 }
13926
13927 // Require a non-abstract type.
13928 if (RequireNonAbstractType(VD->getLocation(), Ty,
13929 diag::err_abstract_type_in_decl,
13931 VD->setInvalidDecl();
13932 return;
13933 }
13934
13935 // Don't bother complaining about constructors or destructors,
13936 // though.
13937}
13938
13940 // If there is no declaration, there was an error parsing it. Just ignore it.
13941 if (!RealDecl)
13942 return;
13943
13944 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13945 QualType Type = Var->getType();
13946
13947 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13948 if (isa<DecompositionDecl>(RealDecl)) {
13949 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13950 Var->setInvalidDecl();
13951 return;
13952 }
13953
13954 if (Type->isUndeducedType() &&
13955 DeduceVariableDeclarationType(Var, false, nullptr))
13956 return;
13957
13958 // C++11 [class.static.data]p3: A static data member can be declared with
13959 // the constexpr specifier; if so, its declaration shall specify
13960 // a brace-or-equal-initializer.
13961 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13962 // the definition of a variable [...] or the declaration of a static data
13963 // member.
13964 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13965 !Var->isThisDeclarationADemotedDefinition()) {
13966 if (Var->isStaticDataMember()) {
13967 // C++1z removes the relevant rule; the in-class declaration is always
13968 // a definition there.
13969 if (!getLangOpts().CPlusPlus17 &&
13971 Diag(Var->getLocation(),
13972 diag::err_constexpr_static_mem_var_requires_init)
13973 << Var;
13974 Var->setInvalidDecl();
13975 return;
13976 }
13977 } else {
13978 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13979 Var->setInvalidDecl();
13980 return;
13981 }
13982 }
13983
13984 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13985 // be initialized.
13986 if (!Var->isInvalidDecl() &&
13987 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13988 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13989 bool HasConstExprDefaultConstructor = false;
13990 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13991 for (auto *Ctor : RD->ctors()) {
13992 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13993 Ctor->getMethodQualifiers().getAddressSpace() ==
13995 HasConstExprDefaultConstructor = true;
13996 }
13997 }
13998 }
13999 if (!HasConstExprDefaultConstructor) {
14000 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14001 Var->setInvalidDecl();
14002 return;
14003 }
14004 }
14005
14006 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14007 if (Var->getStorageClass() == SC_Extern) {
14008 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14009 << Var;
14010 Var->setInvalidDecl();
14011 return;
14012 }
14013 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14014 diag::err_typecheck_decl_incomplete_type)) {
14015 Var->setInvalidDecl();
14016 return;
14017 }
14018 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14019 if (!RD->hasTrivialDefaultConstructor()) {
14020 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14021 Var->setInvalidDecl();
14022 return;
14023 }
14024 }
14025 // The declaration is uninitialized, no need for further checks.
14026 return;
14027 }
14028
14029 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14030 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14031 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14032 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14034
14035
14036 switch (DefKind) {
14038 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14039 break;
14040
14041 // We have an out-of-line definition of a static data member
14042 // that has an in-class initializer, so we type-check this like
14043 // a declaration.
14044 //
14045 [[fallthrough]];
14046
14048 // It's only a declaration.
14049
14050 // Block scope. C99 6.7p7: If an identifier for an object is
14051 // declared with no linkage (C99 6.2.2p6), the type for the
14052 // object shall be complete.
14053 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14054 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14055 RequireCompleteType(Var->getLocation(), Type,
14056 diag::err_typecheck_decl_incomplete_type))
14057 Var->setInvalidDecl();
14058
14059 // Make sure that the type is not abstract.
14060 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14061 RequireNonAbstractType(Var->getLocation(), Type,
14062 diag::err_abstract_type_in_decl,
14064 Var->setInvalidDecl();
14065 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14066 Var->getStorageClass() == SC_PrivateExtern) {
14067 Diag(Var->getLocation(), diag::warn_private_extern);
14068 Diag(Var->getLocation(), diag::note_private_extern);
14069 }
14070
14072 !Var->isInvalidDecl())
14073 ExternalDeclarations.push_back(Var);
14074
14075 return;
14076
14078 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14079 // object that has file scope without an initializer, and without a
14080 // storage-class specifier or with the storage-class specifier "static",
14081 // constitutes a tentative definition. Note: A tentative definition with
14082 // external linkage is valid (C99 6.2.2p5).
14083 if (!Var->isInvalidDecl()) {
14084 if (const IncompleteArrayType *ArrayT
14087 Var->getLocation(), ArrayT->getElementType(),
14088 diag::err_array_incomplete_or_sizeless_type))
14089 Var->setInvalidDecl();
14090 } else if (Var->getStorageClass() == SC_Static) {
14091 // C99 6.9.2p3: If the declaration of an identifier for an object is
14092 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14093 // declared type shall not be an incomplete type.
14094 // NOTE: code such as the following
14095 // static struct s;
14096 // struct s { int a; };
14097 // is accepted by gcc. Hence here we issue a warning instead of
14098 // an error and we do not invalidate the static declaration.
14099 // NOTE: to avoid multiple warnings, only check the first declaration.
14100 if (Var->isFirstDecl())
14101 RequireCompleteType(Var->getLocation(), Type,
14102 diag::ext_typecheck_decl_incomplete_type);
14103 }
14104 }
14105
14106 // Record the tentative definition; we're done.
14107 if (!Var->isInvalidDecl())
14109 return;
14110 }
14111
14112 // Provide a specific diagnostic for uninitialized variable
14113 // definitions with incomplete array type.
14114 if (Type->isIncompleteArrayType()) {
14115 if (Var->isConstexpr())
14116 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14117 << Var;
14118 else
14119 Diag(Var->getLocation(),
14120 diag::err_typecheck_incomplete_array_needs_initializer);
14121 Var->setInvalidDecl();
14122 return;
14123 }
14124
14125 // Provide a specific diagnostic for uninitialized variable
14126 // definitions with reference type.
14127 if (Type->isReferenceType()) {
14128 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14129 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14130 return;
14131 }
14132
14133 // Do not attempt to type-check the default initializer for a
14134 // variable with dependent type.
14135 if (Type->isDependentType())
14136 return;
14137
14138 if (Var->isInvalidDecl())
14139 return;
14140
14141 if (!Var->hasAttr<AliasAttr>()) {
14142 if (RequireCompleteType(Var->getLocation(),
14144 diag::err_typecheck_decl_incomplete_type)) {
14145 Var->setInvalidDecl();
14146 return;
14147 }
14148 } else {
14149 return;
14150 }
14151
14152 // The variable can not have an abstract class type.
14153 if (RequireNonAbstractType(Var->getLocation(), Type,
14154 diag::err_abstract_type_in_decl,
14156 Var->setInvalidDecl();
14157 return;
14158 }
14159
14160 // Check for jumps past the implicit initializer. C++0x
14161 // clarifies that this applies to a "variable with automatic
14162 // storage duration", not a "local variable".
14163 // C++11 [stmt.dcl]p3
14164 // A program that jumps from a point where a variable with automatic
14165 // storage duration is not in scope to a point where it is in scope is
14166 // ill-formed unless the variable has scalar type, class type with a
14167 // trivial default constructor and a trivial destructor, a cv-qualified
14168 // version of one of these types, or an array of one of the preceding
14169 // types and is declared without an initializer.
14170 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14171 if (const RecordType *Record
14173 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14174 // Mark the function (if we're in one) for further checking even if the
14175 // looser rules of C++11 do not require such checks, so that we can
14176 // diagnose incompatibilities with C++98.
14177 if (!CXXRecord->isPOD())
14179 }
14180 }
14181 // In OpenCL, we can't initialize objects in the __local address space,
14182 // even implicitly, so don't synthesize an implicit initializer.
14183 if (getLangOpts().OpenCL &&
14184 Var->getType().getAddressSpace() == LangAS::opencl_local)
14185 return;
14186 // C++03 [dcl.init]p9:
14187 // If no initializer is specified for an object, and the
14188 // object is of (possibly cv-qualified) non-POD class type (or
14189 // array thereof), the object shall be default-initialized; if
14190 // the object is of const-qualified type, the underlying class
14191 // type shall have a user-declared default
14192 // constructor. Otherwise, if no initializer is specified for
14193 // a non- static object, the object and its subobjects, if
14194 // any, have an indeterminate initial value); if the object
14195 // or any of its subobjects are of const-qualified type, the
14196 // program is ill-formed.
14197 // C++0x [dcl.init]p11:
14198 // If no initializer is specified for an object, the object is
14199 // default-initialized; [...].
14202 = InitializationKind::CreateDefault(Var->getLocation());
14203
14204 InitializationSequence InitSeq(*this, Entity, Kind, {});
14205 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14206
14207 if (Init.get()) {
14208 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14209 // This is important for template substitution.
14210 Var->setInitStyle(VarDecl::CallInit);
14211 } else if (Init.isInvalid()) {
14212 // If default-init fails, attach a recovery-expr initializer to track
14213 // that initialization was attempted and failed.
14214 auto RecoveryExpr =
14215 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14216 if (RecoveryExpr.get())
14217 Var->setInit(RecoveryExpr.get());
14218 }
14219
14221 }
14222}
14223
14225 // If there is no declaration, there was an error parsing it. Ignore it.
14226 if (!D)
14227 return;
14228
14229 VarDecl *VD = dyn_cast<VarDecl>(D);
14230 if (!VD) {
14231 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14232 D->setInvalidDecl();
14233 return;
14234 }
14235
14236 VD->setCXXForRangeDecl(true);
14237
14238 // for-range-declaration cannot be given a storage class specifier.
14239 int Error = -1;
14240 switch (VD->getStorageClass()) {
14241 case SC_None:
14242 break;
14243 case SC_Extern:
14244 Error = 0;
14245 break;
14246 case SC_Static:
14247 Error = 1;
14248 break;
14249 case SC_PrivateExtern:
14250 Error = 2;
14251 break;
14252 case SC_Auto:
14253 Error = 3;
14254 break;
14255 case SC_Register:
14256 Error = 4;
14257 break;
14258 }
14259
14260 // for-range-declaration cannot be given a storage class specifier con't.
14261 switch (VD->getTSCSpec()) {
14262 case TSCS_thread_local:
14263 Error = 6;
14264 break;
14265 case TSCS___thread:
14266 case TSCS__Thread_local:
14267 case TSCS_unspecified:
14268 break;
14269 }
14270
14271 if (Error != -1) {
14272 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14273 << VD << Error;
14274 D->setInvalidDecl();
14275 }
14276}
14277
14279 IdentifierInfo *Ident,
14280 ParsedAttributes &Attrs) {
14281 // C++1y [stmt.iter]p1:
14282 // A range-based for statement of the form
14283 // for ( for-range-identifier : for-range-initializer ) statement
14284 // is equivalent to
14285 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14286 DeclSpec DS(Attrs.getPool().getFactory());
14287
14288 const char *PrevSpec;
14289 unsigned DiagID;
14290 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14292
14294 D.SetIdentifier(Ident, IdentLoc);
14295 D.takeAttributes(Attrs);
14296
14297 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14298 IdentLoc);
14299 Decl *Var = ActOnDeclarator(S, D);
14300 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14302 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14303 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14304 : IdentLoc);
14305}
14306
14308 if (var->isInvalidDecl()) return;
14309
14311
14312 if (getLangOpts().OpenCL) {
14313 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14314 // initialiser
14315 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14316 !var->hasInit()) {
14317 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14318 << 1 /*Init*/;
14319 var->setInvalidDecl();
14320 return;
14321 }
14322 }
14323
14324 // In Objective-C, don't allow jumps past the implicit initialization of a
14325 // local retaining variable.
14326 if (getLangOpts().ObjC &&
14327 var->hasLocalStorage()) {
14328 switch (var->getType().getObjCLifetime()) {
14332 break;
14333
14337 break;
14338 }
14339 }
14340
14341 if (var->hasLocalStorage() &&
14342 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14344
14345 // Warn about externally-visible variables being defined without a
14346 // prior declaration. We only want to do this for global
14347 // declarations, but we also specifically need to avoid doing it for
14348 // class members because the linkage of an anonymous class can
14349 // change if it's later given a typedef name.
14350 if (var->isThisDeclarationADefinition() &&
14351 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14352 var->isExternallyVisible() && var->hasLinkage() &&
14353 !var->isInline() && !var->getDescribedVarTemplate() &&
14354 var->getStorageClass() != SC_Register &&
14355 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14356 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14357 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14358 var->getLocation())) {
14359 // Find a previous declaration that's not a definition.
14360 VarDecl *prev = var->getPreviousDecl();
14361 while (prev && prev->isThisDeclarationADefinition())
14362 prev = prev->getPreviousDecl();
14363
14364 if (!prev) {
14365 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14366 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14367 << /* variable */ 0;
14368 }
14369 }
14370
14371 // Cache the result of checking for constant initialization.
14372 std::optional<bool> CacheHasConstInit;
14373 const Expr *CacheCulprit = nullptr;
14374 auto checkConstInit = [&]() mutable {
14375 if (!CacheHasConstInit)
14376 CacheHasConstInit = var->getInit()->isConstantInitializer(
14377 Context, var->getType()->isReferenceType(), &CacheCulprit);
14378 return *CacheHasConstInit;
14379 };
14380
14381 if (var->getTLSKind() == VarDecl::TLS_Static) {
14382 if (var->getType().isDestructedType()) {
14383 // GNU C++98 edits for __thread, [basic.start.term]p3:
14384 // The type of an object with thread storage duration shall not
14385 // have a non-trivial destructor.
14386 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14388 Diag(var->getLocation(), diag::note_use_thread_local);
14389 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14390 if (!checkConstInit()) {
14391 // GNU C++98 edits for __thread, [basic.start.init]p4:
14392 // An object of thread storage duration shall not require dynamic
14393 // initialization.
14394 // FIXME: Need strict checking here.
14395 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14396 << CacheCulprit->getSourceRange();
14398 Diag(var->getLocation(), diag::note_use_thread_local);
14399 }
14400 }
14401 }
14402
14403
14404 if (!var->getType()->isStructureType() && var->hasInit() &&
14405 isa<InitListExpr>(var->getInit())) {
14406 const auto *ILE = cast<InitListExpr>(var->getInit());
14407 unsigned NumInits = ILE->getNumInits();
14408 if (NumInits > 2)
14409 for (unsigned I = 0; I < NumInits; ++I) {
14410 const auto *Init = ILE->getInit(I);
14411 if (!Init)
14412 break;
14413 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14414 if (!SL)
14415 break;
14416
14417 unsigned NumConcat = SL->getNumConcatenated();
14418 // Diagnose missing comma in string array initialization.
14419 // Do not warn when all the elements in the initializer are concatenated
14420 // together. Do not warn for macros too.
14421 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14422 bool OnlyOneMissingComma = true;
14423 for (unsigned J = I + 1; J < NumInits; ++J) {
14424 const auto *Init = ILE->getInit(J);
14425 if (!Init)
14426 break;
14427 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14428 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14429 OnlyOneMissingComma = false;
14430 break;
14431 }
14432 }
14433
14434 if (OnlyOneMissingComma) {
14436 for (unsigned i = 0; i < NumConcat - 1; ++i)
14437 Hints.push_back(FixItHint::CreateInsertion(
14438 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14439
14440 Diag(SL->getStrTokenLoc(1),
14441 diag::warn_concatenated_literal_array_init)
14442 << Hints;
14443 Diag(SL->getBeginLoc(),
14444 diag::note_concatenated_string_literal_silence);
14445 }
14446 // In any case, stop now.
14447 break;
14448 }
14449 }
14450 }
14451
14452
14453 QualType type = var->getType();
14454
14455 if (var->hasAttr<BlocksAttr>())
14457
14458 Expr *Init = var->getInit();
14459 bool GlobalStorage = var->hasGlobalStorage();
14460 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14462 bool HasConstInit = true;
14463
14464 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14465 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14466 << var;
14467
14468 // Check whether the initializer is sufficiently constant.
14469 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14470 !type->isDependentType() && Init && !Init->isValueDependent() &&
14471 (GlobalStorage || var->isConstexpr() ||
14472 var->mightBeUsableInConstantExpressions(Context))) {
14473 // If this variable might have a constant initializer or might be usable in
14474 // constant expressions, check whether or not it actually is now. We can't
14475 // do this lazily, because the result might depend on things that change
14476 // later, such as which constexpr functions happen to be defined.
14478 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14479 // Prior to C++11, in contexts where a constant initializer is required,
14480 // the set of valid constant initializers is described by syntactic rules
14481 // in [expr.const]p2-6.
14482 // FIXME: Stricter checking for these rules would be useful for constinit /
14483 // -Wglobal-constructors.
14484 HasConstInit = checkConstInit();
14485
14486 // Compute and cache the constant value, and remember that we have a
14487 // constant initializer.
14488 if (HasConstInit) {
14489 (void)var->checkForConstantInitialization(Notes);
14490 Notes.clear();
14491 } else if (CacheCulprit) {
14492 Notes.emplace_back(CacheCulprit->getExprLoc(),
14493 PDiag(diag::note_invalid_subexpr_in_const_expr));
14494 Notes.back().second << CacheCulprit->getSourceRange();
14495 }
14496 } else {
14497 // Evaluate the initializer to see if it's a constant initializer.
14498 HasConstInit = var->checkForConstantInitialization(Notes);
14499 }
14500
14501 if (HasConstInit) {
14502 // FIXME: Consider replacing the initializer with a ConstantExpr.
14503 } else if (var->isConstexpr()) {
14504 SourceLocation DiagLoc = var->getLocation();
14505 // If the note doesn't add any useful information other than a source
14506 // location, fold it into the primary diagnostic.
14507 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14508 diag::note_invalid_subexpr_in_const_expr) {
14509 DiagLoc = Notes[0].first;
14510 Notes.clear();
14511 }
14512 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14513 << var << Init->getSourceRange();
14514 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14515 Diag(Notes[I].first, Notes[I].second);
14516 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14517 auto *Attr = var->getAttr<ConstInitAttr>();
14518 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14519 << Init->getSourceRange();
14520 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14521 << Attr->getRange() << Attr->isConstinit();
14522 for (auto &it : Notes)
14523 Diag(it.first, it.second);
14524 } else if (IsGlobal &&
14525 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14526 var->getLocation())) {
14527 // Warn about globals which don't have a constant initializer. Don't
14528 // warn about globals with a non-trivial destructor because we already
14529 // warned about them.
14530 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14531 if (!(RD && !RD->hasTrivialDestructor())) {
14532 // checkConstInit() here permits trivial default initialization even in
14533 // C++11 onwards, where such an initializer is not a constant initializer
14534 // but nonetheless doesn't require a global constructor.
14535 if (!checkConstInit())
14536 Diag(var->getLocation(), diag::warn_global_constructor)
14537 << Init->getSourceRange();
14538 }
14539 }
14540 }
14541
14542 // Apply section attributes and pragmas to global variables.
14543 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14545 PragmaStack<StringLiteral *> *Stack = nullptr;
14546 int SectionFlags = ASTContext::PSF_Read;
14547 bool MSVCEnv =
14548 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14549 std::optional<QualType::NonConstantStorageReason> Reason;
14550 if (HasConstInit &&
14551 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14552 Stack = &ConstSegStack;
14553 } else {
14554 SectionFlags |= ASTContext::PSF_Write;
14555 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14556 }
14557 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14558 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14559 SectionFlags |= ASTContext::PSF_Implicit;
14560 UnifySection(SA->getName(), SectionFlags, var);
14561 } else if (Stack->CurrentValue) {
14562 if (Stack != &ConstSegStack && MSVCEnv &&
14563 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14564 var->getType().isConstQualified()) {
14565 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14566 NonConstNonReferenceType) &&
14567 "This case should've already been handled elsewhere");
14568 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14569 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14571 : *Reason);
14572 }
14573 SectionFlags |= ASTContext::PSF_Implicit;
14574 auto SectionName = Stack->CurrentValue->getString();
14575 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14576 Stack->CurrentPragmaLocation,
14577 SectionAttr::Declspec_allocate));
14578 if (UnifySection(SectionName, SectionFlags, var))
14579 var->dropAttr<SectionAttr>();
14580 }
14581
14582 // Apply the init_seg attribute if this has an initializer. If the
14583 // initializer turns out to not be dynamic, we'll end up ignoring this
14584 // attribute.
14585 if (CurInitSeg && var->getInit())
14586 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14587 CurInitSegLoc));
14588 }
14589
14590 // All the following checks are C++ only.
14591 if (!getLangOpts().CPlusPlus) {
14592 // If this variable must be emitted, add it as an initializer for the
14593 // current module.
14594 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14595 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14596 return;
14597 }
14598
14599 // Require the destructor.
14600 if (!type->isDependentType())
14601 if (const RecordType *recordType = baseType->getAs<RecordType>())
14603
14604 // If this variable must be emitted, add it as an initializer for the current
14605 // module.
14606 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14607 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14608
14609 // Build the bindings if this is a structured binding declaration.
14610 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14612}
14613
14615 assert(VD->isStaticLocal());
14616
14617 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14618
14619 // Find outermost function when VD is in lambda function.
14620 while (FD && !getDLLAttr(FD) &&
14621 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14622 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14623 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14624 }
14625
14626 if (!FD)
14627 return;
14628
14629 // Static locals inherit dll attributes from their function.
14630 if (Attr *A = getDLLAttr(FD)) {
14631 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14632 NewAttr->setInherited(true);
14633 VD->addAttr(NewAttr);
14634 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14635 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14636 NewAttr->setInherited(true);
14637 VD->addAttr(NewAttr);
14638
14639 // Export this function to enforce exporting this static variable even
14640 // if it is not used in this compilation unit.
14641 if (!FD->hasAttr<DLLExportAttr>())
14642 FD->addAttr(NewAttr);
14643
14644 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14645 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14646 NewAttr->setInherited(true);
14647 VD->addAttr(NewAttr);
14648 }
14649}
14650
14652 assert(VD->getTLSKind());
14653
14654 // Perform TLS alignment check here after attributes attached to the variable
14655 // which may affect the alignment have been processed. Only perform the check
14656 // if the target has a maximum TLS alignment (zero means no constraints).
14657 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14658 // Protect the check so that it's not performed on dependent types and
14659 // dependent alignments (we can't determine the alignment in that case).
14660 if (!VD->hasDependentAlignment()) {
14661 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14662 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14663 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14665 << (unsigned)MaxAlignChars.getQuantity();
14666 }
14667 }
14668 }
14669}
14670
14672 // Note that we are no longer parsing the initializer for this declaration.
14673 ParsingInitForAutoVars.erase(ThisDecl);
14674
14675 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14676 if (!VD)
14677 return;
14678
14679 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14681 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14683 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14687 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14691 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14695 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14698 }
14699
14700 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14701 for (auto *BD : DD->bindings()) {
14703 }
14704 }
14705
14706 CheckInvalidBuiltinCountedByRef(VD->getInit(), InitializerKind);
14707
14708 checkAttributesAfterMerging(*this, *VD);
14709
14710 if (VD->isStaticLocal())
14712
14713 if (VD->getTLSKind())
14715
14716 // Perform check for initializers of device-side global variables.
14717 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14718 // 7.5). We must also apply the same checks to all __shared__
14719 // variables whether they are local or not. CUDA also allows
14720 // constant initializers for __constant__ and __device__ variables.
14721 if (getLangOpts().CUDA)
14723
14724 // Grab the dllimport or dllexport attribute off of the VarDecl.
14725 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14726
14727 // Imported static data members cannot be defined out-of-line.
14728 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14729 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14731 // We allow definitions of dllimport class template static data members
14732 // with a warning.
14734 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14735 bool IsClassTemplateMember =
14736 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14737 Context->getDescribedClassTemplate();
14738
14739 Diag(VD->getLocation(),
14740 IsClassTemplateMember
14741 ? diag::warn_attribute_dllimport_static_field_definition
14742 : diag::err_attribute_dllimport_static_field_definition);
14743 Diag(IA->getLocation(), diag::note_attribute);
14744 if (!IsClassTemplateMember)
14745 VD->setInvalidDecl();
14746 }
14747 }
14748
14749 // dllimport/dllexport variables cannot be thread local, their TLS index
14750 // isn't exported with the variable.
14751 if (DLLAttr && VD->getTLSKind()) {
14752 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14753 if (F && getDLLAttr(F)) {
14754 assert(VD->isStaticLocal());
14755 // But if this is a static local in a dlimport/dllexport function, the
14756 // function will never be inlined, which means the var would never be
14757 // imported, so having it marked import/export is safe.
14758 } else {
14759 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14760 << DLLAttr;
14761 VD->setInvalidDecl();
14762 }
14763 }
14764
14765 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14766 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14767 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14768 << Attr;
14769 VD->dropAttr<UsedAttr>();
14770 }
14771 }
14772 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14773 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14774 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14775 << Attr;
14776 VD->dropAttr<RetainAttr>();
14777 }
14778 }
14779
14780 const DeclContext *DC = VD->getDeclContext();
14781 // If there's a #pragma GCC visibility in scope, and this isn't a class
14782 // member, set the visibility of this variable.
14785
14786 // FIXME: Warn on unused var template partial specializations.
14787 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14789
14790 // Now we have parsed the initializer and can update the table of magic
14791 // tag values.
14792 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14794 return;
14795
14796 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14797 const Expr *MagicValueExpr = VD->getInit();
14798 if (!MagicValueExpr) {
14799 continue;
14800 }
14801 std::optional<llvm::APSInt> MagicValueInt;
14802 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14803 Diag(I->getRange().getBegin(),
14804 diag::err_type_tag_for_datatype_not_ice)
14805 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14806 continue;
14807 }
14808 if (MagicValueInt->getActiveBits() > 64) {
14809 Diag(I->getRange().getBegin(),
14810 diag::err_type_tag_for_datatype_too_large)
14811 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14812 continue;
14813 }
14814 uint64_t MagicValue = MagicValueInt->getZExtValue();
14815 RegisterTypeTagForDatatype(I->getArgumentKind(),
14816 MagicValue,
14817 I->getMatchingCType(),
14818 I->getLayoutCompatible(),
14819 I->getMustBeNull());
14820 }
14821}
14822
14824 auto *VD = dyn_cast<VarDecl>(DD);
14825 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14826}
14827
14829 ArrayRef<Decl *> Group) {
14831
14832 if (DS.isTypeSpecOwned())
14833 Decls.push_back(DS.getRepAsDecl());
14834
14835 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14836 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14837 bool DiagnosedMultipleDecomps = false;
14838 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14839 bool DiagnosedNonDeducedAuto = false;
14840
14841 for (Decl *D : Group) {
14842 if (!D)
14843 continue;
14844 // Check if the Decl has been declared in '#pragma omp declare target'
14845 // directive and has static storage duration.
14846 if (auto *VD = dyn_cast<VarDecl>(D);
14847 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14848 VD->hasGlobalStorage())
14850 // For declarators, there are some additional syntactic-ish checks we need
14851 // to perform.
14852 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14853 if (!FirstDeclaratorInGroup)
14854 FirstDeclaratorInGroup = DD;
14855 if (!FirstDecompDeclaratorInGroup)
14856 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14857 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14858 !hasDeducedAuto(DD))
14859 FirstNonDeducedAutoInGroup = DD;
14860
14861 if (FirstDeclaratorInGroup != DD) {
14862 // A decomposition declaration cannot be combined with any other
14863 // declaration in the same group.
14864 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14865 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14866 diag::err_decomp_decl_not_alone)
14867 << FirstDeclaratorInGroup->getSourceRange()
14868 << DD->getSourceRange();
14869 DiagnosedMultipleDecomps = true;
14870 }
14871
14872 // A declarator that uses 'auto' in any way other than to declare a
14873 // variable with a deduced type cannot be combined with any other
14874 // declarator in the same group.
14875 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14876 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14877 diag::err_auto_non_deduced_not_alone)
14878 << FirstNonDeducedAutoInGroup->getType()
14880 << FirstDeclaratorInGroup->getSourceRange()
14881 << DD->getSourceRange();
14882 DiagnosedNonDeducedAuto = true;
14883 }
14884 }
14885 }
14886
14887 Decls.push_back(D);
14888 }
14889
14891 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14892 handleTagNumbering(Tag, S);
14893 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14895 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14896 }
14897 }
14898
14899 return BuildDeclaratorGroup(Decls);
14900}
14901
14904 // C++14 [dcl.spec.auto]p7: (DR1347)
14905 // If the type that replaces the placeholder type is not the same in each
14906 // deduction, the program is ill-formed.
14907 if (Group.size() > 1) {
14908 QualType Deduced;
14909 VarDecl *DeducedDecl = nullptr;
14910 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14911 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14912 if (!D || D->isInvalidDecl())
14913 break;
14914 DeducedType *DT = D->getType()->getContainedDeducedType();
14915 if (!DT || DT->getDeducedType().isNull())
14916 continue;
14917 if (Deduced.isNull()) {
14918 Deduced = DT->getDeducedType();
14919 DeducedDecl = D;
14920 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14921 auto *AT = dyn_cast<AutoType>(DT);
14922 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14923 diag::err_auto_different_deductions)
14924 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14925 << DeducedDecl->getDeclName() << DT->getDeducedType()
14926 << D->getDeclName();
14927 if (DeducedDecl->hasInit())
14928 Dia << DeducedDecl->getInit()->getSourceRange();
14929 if (D->getInit())
14930 Dia << D->getInit()->getSourceRange();
14931 D->setInvalidDecl();
14932 break;
14933 }
14934 }
14935 }
14936
14938
14939 return DeclGroupPtrTy::make(
14940 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14941}
14942
14945}
14946
14948 // Don't parse the comment if Doxygen diagnostics are ignored.
14949 if (Group.empty() || !Group[0])
14950 return;
14951
14952 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14953 Group[0]->getLocation()) &&
14954 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14955 Group[0]->getLocation()))
14956 return;
14957
14958 if (Group.size() >= 2) {
14959 // This is a decl group. Normally it will contain only declarations
14960 // produced from declarator list. But in case we have any definitions or
14961 // additional declaration references:
14962 // 'typedef struct S {} S;'
14963 // 'typedef struct S *S;'
14964 // 'struct S *pS;'
14965 // FinalizeDeclaratorGroup adds these as separate declarations.
14966 Decl *MaybeTagDecl = Group[0];
14967 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14968 Group = Group.slice(1);
14969 }
14970 }
14971
14972 // FIMXE: We assume every Decl in the group is in the same file.
14973 // This is false when preprocessor constructs the group from decls in
14974 // different files (e. g. macros or #include).
14976}
14977
14979 // Check that there are no default arguments inside the type of this
14980 // parameter.
14981 if (getLangOpts().CPlusPlus)
14983
14984 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14985 if (D.getCXXScopeSpec().isSet()) {
14986 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14987 << D.getCXXScopeSpec().getRange();
14988 }
14989
14990 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14991 // simple identifier except [...irrelevant cases...].
14992 switch (D.getName().getKind()) {
14994 break;
14995
15003 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15005 break;
15006
15009 // GetNameForDeclarator would not produce a useful name in this case.
15010 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15011 break;
15012 }
15013}
15014
15016 SourceLocation ExplicitThisLoc) {
15017 if (!ExplicitThisLoc.isValid())
15018 return;
15019 assert(S.getLangOpts().CPlusPlus &&
15020 "explicit parameter in non-cplusplus mode");
15021 if (!S.getLangOpts().CPlusPlus23)
15022 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15023 << P->getSourceRange();
15024
15025 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15026 // parameter pack.
15027 if (P->isParameterPack()) {
15028 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15029 << P->getSourceRange();
15030 return;
15031 }
15032 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15033 if (LambdaScopeInfo *LSI = S.getCurLambda())
15034 LSI->ExplicitObjectParameter = P;
15035}
15036
15038 SourceLocation ExplicitThisLoc) {
15039 const DeclSpec &DS = D.getDeclSpec();
15040
15041 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15042 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15043 // except for the special case of a single unnamed parameter of type void
15044 // with no storage class specifier, no type qualifier, and no following
15045 // ellipsis terminator.
15046 // Clang applies the C2y rules for 'register void' in all C language modes,
15047 // same as GCC, because it's questionable what that could possibly mean.
15048
15049 // C++03 [dcl.stc]p2 also permits 'auto'.
15050 StorageClass SC = SC_None;
15052 SC = SC_Register;
15053 // In C++11, the 'register' storage class specifier is deprecated.
15054 // In C++17, it is not allowed, but we tolerate it as an extension.
15055 if (getLangOpts().CPlusPlus11) {
15057 ? diag::ext_register_storage_class
15058 : diag::warn_deprecated_register)
15060 } else if (!getLangOpts().CPlusPlus &&
15062 D.getNumTypeObjects() == 0) {
15064 diag::err_invalid_storage_class_in_func_decl)
15066 D.getMutableDeclSpec().ClearStorageClassSpecs();
15067 }
15068 } else if (getLangOpts().CPlusPlus &&
15070 SC = SC_Auto;
15073 diag::err_invalid_storage_class_in_func_decl);
15074 D.getMutableDeclSpec().ClearStorageClassSpecs();
15075 }
15076
15078 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15080 if (DS.isInlineSpecified())
15081 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15082 << getLangOpts().CPlusPlus17;
15083 if (DS.hasConstexprSpecifier())
15084 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15085 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15086
15088
15090
15092 QualType parmDeclType = TInfo->getType();
15093
15094 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15095 const IdentifierInfo *II = D.getIdentifier();
15096 if (II) {
15097 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15098 RedeclarationKind::ForVisibleRedeclaration);
15099 LookupName(R, S);
15100 if (!R.empty()) {
15101 NamedDecl *PrevDecl = *R.begin();
15102 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15103 // Maybe we will complain about the shadowed template parameter.
15104 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15105 // Just pretend that we didn't see the previous declaration.
15106 PrevDecl = nullptr;
15107 }
15108 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15109 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15110 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15111 // Recover by removing the name
15112 II = nullptr;
15113 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15114 D.setInvalidType(true);
15115 }
15116 }
15117 }
15118
15119 // Temporarily put parameter variables in the translation unit, not
15120 // the enclosing context. This prevents them from accidentally
15121 // looking like class members in C++.
15122 ParmVarDecl *New =
15124 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15125
15126 if (D.isInvalidType())
15127 New->setInvalidDecl();
15128
15129 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15130
15131 assert(S->isFunctionPrototypeScope());
15132 assert(S->getFunctionPrototypeDepth() >= 1);
15133 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15134 S->getNextFunctionPrototypeIndex());
15135
15136 // Add the parameter declaration into this scope.
15137 S->AddDecl(New);
15138 if (II)
15139 IdResolver.AddDecl(New);
15140
15141 ProcessDeclAttributes(S, New, D);
15142
15143 if (D.getDeclSpec().isModulePrivateSpecified())
15144 Diag(New->getLocation(), diag::err_module_private_local)
15145 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15146 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15147
15148 if (New->hasAttr<BlocksAttr>()) {
15149 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15150 }
15151
15152 if (getLangOpts().OpenCL)
15154
15155 return New;
15156}
15157
15160 QualType T) {
15161 /* FIXME: setting StartLoc == Loc.
15162 Would it be worth to modify callers so as to provide proper source
15163 location for the unnamed parameters, embedding the parameter's type? */
15164 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15166 SC_None, nullptr);
15167 Param->setImplicit();
15168 return Param;
15169}
15170
15172 // Don't diagnose unused-parameter errors in template instantiations; we
15173 // will already have done so in the template itself.
15175 return;
15176
15177 for (const ParmVarDecl *Parameter : Parameters) {
15178 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15179 !Parameter->hasAttr<UnusedAttr>() &&
15180 !Parameter->getIdentifier()->isPlaceholder()) {
15181 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15182 << Parameter->getDeclName();
15183 }
15184 }
15185}
15186
15188 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15189 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15190 return;
15191
15192 // Warn if the return value is pass-by-value and larger than the specified
15193 // threshold.
15194 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15195 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15196 if (Size > LangOpts.NumLargeByValueCopy)
15197 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15198 }
15199
15200 // Warn if any parameter is pass-by-value and larger than the specified
15201 // threshold.
15202 for (const ParmVarDecl *Parameter : Parameters) {
15203 QualType T = Parameter->getType();
15204 if (T->isDependentType() || !T.isPODType(Context))
15205 continue;
15206 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15207 if (Size > LangOpts.NumLargeByValueCopy)
15208 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15209 << Parameter << Size;
15210 }
15211}
15212
15214 SourceLocation NameLoc,
15215 const IdentifierInfo *Name, QualType T,
15216 TypeSourceInfo *TSInfo, StorageClass SC) {
15217 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15218 if (getLangOpts().ObjCAutoRefCount &&
15219 T.getObjCLifetime() == Qualifiers::OCL_None &&
15220 T->isObjCLifetimeType()) {
15221
15222 Qualifiers::ObjCLifetime lifetime;
15223
15224 // Special cases for arrays:
15225 // - if it's const, use __unsafe_unretained
15226 // - otherwise, it's an error
15227 if (T->isArrayType()) {
15228 if (!T.isConstQualified()) {
15232 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15233 else
15234 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15235 << TSInfo->getTypeLoc().getSourceRange();
15236 }
15238 } else {
15239 lifetime = T->getObjCARCImplicitLifetime();
15240 }
15241 T = Context.getLifetimeQualifiedType(T, lifetime);
15242 }
15243
15244 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15246 TSInfo, SC, nullptr);
15247
15248 // Make a note if we created a new pack in the scope of a lambda, so that
15249 // we know that references to that pack must also be expanded within the
15250 // lambda scope.
15251 if (New->isParameterPack())
15252 if (auto *CSI = getEnclosingLambdaOrBlock())
15253 CSI->LocalPacks.push_back(New);
15254
15259
15260 // Parameter declarators cannot be interface types. All ObjC objects are
15261 // passed by reference.
15262 if (T->isObjCObjectType()) {
15263 SourceLocation TypeEndLoc =
15265 Diag(NameLoc,
15266 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15267 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15269 New->setType(T);
15270 }
15271
15272 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15273 // duration shall not be qualified by an address-space qualifier."
15274 // Since all parameters have automatic store duration, they can not have
15275 // an address space.
15276 if (T.getAddressSpace() != LangAS::Default &&
15277 // OpenCL allows function arguments declared to be an array of a type
15278 // to be qualified with an address space.
15279 !(getLangOpts().OpenCL &&
15280 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15281 // WebAssembly allows reference types as parameters. Funcref in particular
15282 // lives in a different address space.
15283 !(T->isFunctionPointerType() &&
15284 T.getAddressSpace() == LangAS::wasm_funcref)) {
15285 Diag(NameLoc, diag::err_arg_with_address_space);
15286 New->setInvalidDecl();
15287 }
15288
15289 // PPC MMA non-pointer types are not allowed as function argument types.
15290 if (Context.getTargetInfo().getTriple().isPPC64() &&
15291 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15292 New->setInvalidDecl();
15293 }
15294
15295 return New;
15296}
15297
15299 SourceLocation LocAfterDecls) {
15300 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15301
15302 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15303 // in the declaration list shall have at least one declarator, those
15304 // declarators shall only declare identifiers from the identifier list, and
15305 // every identifier in the identifier list shall be declared.
15306 //
15307 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15308 // identifiers it names shall be declared in the declaration list."
15309 //
15310 // This is why we only diagnose in C99 and later. Note, the other conditions
15311 // listed are checked elsewhere.
15312 if (!FTI.hasPrototype) {
15313 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15314 --i;
15315 if (FTI.Params[i].Param == nullptr) {
15316 if (getLangOpts().C99) {
15317 SmallString<256> Code;
15318 llvm::raw_svector_ostream(Code)
15319 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15320 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15321 << FTI.Params[i].Ident
15322 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15323 }
15324
15325 // Implicitly declare the argument as type 'int' for lack of a better
15326 // type.
15327 AttributeFactory attrs;
15328 DeclSpec DS(attrs);
15329 const char* PrevSpec; // unused
15330 unsigned DiagID; // unused
15331 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15332 DiagID, Context.getPrintingPolicy());
15333 // Use the identifier location for the type source range.
15334 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15335 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15338 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15339 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15340 }
15341 }
15342 }
15343}
15344
15345Decl *
15347 MultiTemplateParamsArg TemplateParameterLists,
15348 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15349 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15350 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15351 Scope *ParentScope = FnBodyScope->getParent();
15352
15353 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15354 // we define a non-templated function definition, we will create a declaration
15355 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15356 // The base function declaration will have the equivalent of an `omp declare
15357 // variant` annotation which specifies the mangled definition as a
15358 // specialization function under the OpenMP context defined as part of the
15359 // `omp begin declare variant`.
15361 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15363 ParentScope, D, TemplateParameterLists, Bases);
15364
15365 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15366 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15367 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15368
15369 if (!Bases.empty())
15371 Bases);
15372
15373 return Dcl;
15374}
15375
15378}
15379
15381 const FunctionDecl *&PossiblePrototype) {
15382 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15383 Prev = Prev->getPreviousDecl()) {
15384 // Ignore any declarations that occur in function or method
15385 // scope, because they aren't visible from the header.
15386 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15387 continue;
15388
15389 PossiblePrototype = Prev;
15390 return Prev->getType()->isFunctionProtoType();
15391 }
15392 return false;
15393}
15394
15395static bool
15397 const FunctionDecl *&PossiblePrototype) {
15398 // Don't warn about invalid declarations.
15399 if (FD->isInvalidDecl())
15400 return false;
15401
15402 // Or declarations that aren't global.
15403 if (!FD->isGlobal())
15404 return false;
15405
15406 // Don't warn about C++ member functions.
15407 if (isa<CXXMethodDecl>(FD))
15408 return false;
15409
15410 // Don't warn about 'main'.
15411 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15412 if (IdentifierInfo *II = FD->getIdentifier())
15413 if (II->isStr("main") || II->isStr("efi_main"))
15414 return false;
15415
15416 if (FD->isMSVCRTEntryPoint())
15417 return false;
15418
15419 // Don't warn about inline functions.
15420 if (FD->isInlined())
15421 return false;
15422
15423 // Don't warn about function templates.
15425 return false;
15426
15427 // Don't warn about function template specializations.
15429 return false;
15430
15431 // Don't warn for OpenCL kernels.
15432 if (FD->hasAttr<OpenCLKernelAttr>())
15433 return false;
15434
15435 // Don't warn on explicitly deleted functions.
15436 if (FD->isDeleted())
15437 return false;
15438
15439 // Don't warn on implicitly local functions (such as having local-typed
15440 // parameters).
15441 if (!FD->isExternallyVisible())
15442 return false;
15443
15444 // If we were able to find a potential prototype, don't warn.
15445 if (FindPossiblePrototype(FD, PossiblePrototype))
15446 return false;
15447
15448 return true;
15449}
15450
15451void
15453 const FunctionDecl *EffectiveDefinition,
15454 SkipBodyInfo *SkipBody) {
15455 const FunctionDecl *Definition = EffectiveDefinition;
15456 if (!Definition &&
15457 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15458 return;
15459
15460 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15461 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15462 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15463 // A merged copy of the same function, instantiated as a member of
15464 // the same class, is OK.
15465 if (declaresSameEntity(OrigFD, OrigDef) &&
15466 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15467 cast<Decl>(FD->getLexicalDeclContext())))
15468 return;
15469 }
15470 }
15471 }
15472
15474 return;
15475
15476 // Don't emit an error when this is redefinition of a typo-corrected
15477 // definition.
15479 return;
15480
15481 // If we don't have a visible definition of the function, and it's inline or
15482 // a template, skip the new definition.
15483 if (SkipBody && !hasVisibleDefinition(Definition) &&
15484 (Definition->getFormalLinkage() == Linkage::Internal ||
15485 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15486 Definition->getNumTemplateParameterLists())) {
15487 SkipBody->ShouldSkip = true;
15488 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15489 if (auto *TD = Definition->getDescribedFunctionTemplate())
15492 return;
15493 }
15494
15495 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15496 Definition->getStorageClass() == SC_Extern)
15497 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15498 << FD << getLangOpts().CPlusPlus;
15499 else
15500 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15501
15502 Diag(Definition->getLocation(), diag::note_previous_definition);
15503 FD->setInvalidDecl();
15504}
15505
15507 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15508
15510 LSI->CallOperator = CallOperator;
15511 LSI->Lambda = LambdaClass;
15512 LSI->ReturnType = CallOperator->getReturnType();
15513 // When this function is called in situation where the context of the call
15514 // operator is not entered, we set AfterParameterList to false, so that
15515 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15516 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
15517 // where we would set the CurContext to the lambda operator before
15518 // substituting into it. In this case the flag needs to be true such that
15519 // tryCaptureVariable can correctly handle potential captures thereof.
15520 LSI->AfterParameterList = CurContext == CallOperator;
15521
15522 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
15523 // used at the point of dealing with potential captures.
15524 //
15525 // We don't use LambdaClass->isGenericLambda() because this value doesn't
15526 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
15527 // associated. (Technically, we could recover that list from their
15528 // instantiation patterns, but for now, the GLTemplateParameterList seems
15529 // unnecessary in these cases.)
15530 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
15531 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
15532 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15533
15534 if (LCD == LCD_None)
15536 else if (LCD == LCD_ByCopy)
15538 else if (LCD == LCD_ByRef)
15540 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15541
15543 LSI->Mutable = !CallOperator->isConst();
15544 if (CallOperator->isExplicitObjectMemberFunction())
15545 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15546
15547 // Add the captures to the LSI so they can be noted as already
15548 // captured within tryCaptureVar.
15549 auto I = LambdaClass->field_begin();
15550 for (const auto &C : LambdaClass->captures()) {
15551 if (C.capturesVariable()) {
15552 ValueDecl *VD = C.getCapturedVar();
15553 if (VD->isInitCapture())
15555 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15556 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15557 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15558 /*EllipsisLoc*/C.isPackExpansion()
15559 ? C.getEllipsisLoc() : SourceLocation(),
15560 I->getType(), /*Invalid*/false);
15561
15562 } else if (C.capturesThis()) {
15563 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15564 C.getCaptureKind() == LCK_StarThis);
15565 } else {
15566 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15567 I->getType());
15568 }
15569 ++I;
15570 }
15571 return LSI;
15572}
15573
15575 SkipBodyInfo *SkipBody,
15576 FnBodyKind BodyKind) {
15577 if (!D) {
15578 // Parsing the function declaration failed in some way. Push on a fake scope
15579 // anyway so we can try to parse the function body.
15582 return D;
15583 }
15584
15585 FunctionDecl *FD = nullptr;
15586
15587 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15588 FD = FunTmpl->getTemplatedDecl();
15589 else
15590 FD = cast<FunctionDecl>(D);
15591
15592 // Do not push if it is a lambda because one is already pushed when building
15593 // the lambda in ActOnStartOfLambdaDefinition().
15594 if (!isLambdaCallOperator(FD))
15595 // [expr.const]/p14.1
15596 // An expression or conversion is in an immediate function context if it is
15597 // potentially evaluated and either: its innermost enclosing non-block scope
15598 // is a function parameter scope of an immediate function.
15601 : ExprEvalContexts.back().Context);
15602
15603 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15604 // context is nested in an immediate function context, so smaller contexts
15605 // that appear inside immediate functions (like variable initializers) are
15606 // considered to be inside an immediate function context even though by
15607 // themselves they are not immediate function contexts. But when a new
15608 // function is entered, we need to reset this tracking, since the entered
15609 // function might be not an immediate function.
15610 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15611 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15612 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15613
15614 // Check for defining attributes before the check for redefinition.
15615 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15616 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15617 FD->dropAttr<AliasAttr>();
15618 FD->setInvalidDecl();
15619 }
15620 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15621 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15622 FD->dropAttr<IFuncAttr>();
15623 FD->setInvalidDecl();
15624 }
15625 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15626 if (Context.getTargetInfo().getTriple().isAArch64() &&
15627 !Context.getTargetInfo().hasFeature("fmv") &&
15628 !Attr->isDefaultVersion()) {
15629 // If function multi versioning disabled skip parsing function body
15630 // defined with non-default target_version attribute
15631 if (SkipBody)
15632 SkipBody->ShouldSkip = true;
15633 return nullptr;
15634 }
15635 }
15636
15637 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15638 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15639 Ctor->isDefaultConstructor() &&
15641 // If this is an MS ABI dllexport default constructor, instantiate any
15642 // default arguments.
15644 }
15645 }
15646
15647 // See if this is a redefinition. If 'will have body' (or similar) is already
15648 // set, then these checks were already performed when it was set.
15649 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15651 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15652
15653 // If we're skipping the body, we're done. Don't enter the scope.
15654 if (SkipBody && SkipBody->ShouldSkip)
15655 return D;
15656 }
15657
15658 // Mark this function as "will have a body eventually". This lets users to
15659 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15660 // this function.
15661 FD->setWillHaveBody();
15662
15663 // If we are instantiating a generic lambda call operator, push
15664 // a LambdaScopeInfo onto the function stack. But use the information
15665 // that's already been calculated (ActOnLambdaExpr) to prime the current
15666 // LambdaScopeInfo.
15667 // When the template operator is being specialized, the LambdaScopeInfo,
15668 // has to be properly restored so that tryCaptureVariable doesn't try
15669 // and capture any new variables. In addition when calculating potential
15670 // captures during transformation of nested lambdas, it is necessary to
15671 // have the LSI properly restored.
15673 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15674 // instantiated, explicitly specialized.
15677 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15678 FD->setInvalidDecl();
15680 } else {
15681 assert(inTemplateInstantiation() &&
15682 "There should be an active template instantiation on the stack "
15683 "when instantiating a generic lambda!");
15684 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15685 }
15686 } else {
15687 // Enter a new function scope
15689 }
15690
15691 // Builtin functions cannot be defined.
15692 if (unsigned BuiltinID = FD->getBuiltinID()) {
15695 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15696 FD->setInvalidDecl();
15697 }
15698 }
15699
15700 // The return type of a function definition must be complete (C99 6.9.1p3).
15701 // C++23 [dcl.fct.def.general]/p2
15702 // The type of [...] the return for a function definition
15703 // shall not be a (possibly cv-qualified) class type that is incomplete
15704 // or abstract within the function body unless the function is deleted.
15705 QualType ResultType = FD->getReturnType();
15706 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15707 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15708 (RequireCompleteType(FD->getLocation(), ResultType,
15709 diag::err_func_def_incomplete_result) ||
15711 diag::err_abstract_type_in_decl,
15713 FD->setInvalidDecl();
15714
15715 if (FnBodyScope)
15716 PushDeclContext(FnBodyScope, FD);
15717
15718 // Check the validity of our function parameters
15719 if (BodyKind != FnBodyKind::Delete)
15721 /*CheckParameterNames=*/true);
15722
15723 // Add non-parameter declarations already in the function to the current
15724 // scope.
15725 if (FnBodyScope) {
15726 for (Decl *NPD : FD->decls()) {
15727 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15728 if (!NonParmDecl)
15729 continue;
15730 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15731 "parameters should not be in newly created FD yet");
15732
15733 // If the decl has a name, make it accessible in the current scope.
15734 if (NonParmDecl->getDeclName())
15735 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15736
15737 // Similarly, dive into enums and fish their constants out, making them
15738 // accessible in this scope.
15739 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15740 for (auto *EI : ED->enumerators())
15741 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15742 }
15743 }
15744 }
15745
15746 // Introduce our parameters into the function scope
15747 for (auto *Param : FD->parameters()) {
15748 Param->setOwningFunction(FD);
15749
15750 // If this has an identifier, add it to the scope stack.
15751 if (Param->getIdentifier() && FnBodyScope) {
15752 CheckShadow(FnBodyScope, Param);
15753
15754 PushOnScopeChains(Param, FnBodyScope);
15755 }
15756 }
15757
15758 // C++ [module.import/6] external definitions are not permitted in header
15759 // units. Deleted and Defaulted functions are implicitly inline (but the
15760 // inline state is not set at this point, so check the BodyKind explicitly).
15761 // FIXME: Consider an alternate location for the test where the inlined()
15762 // state is complete.
15763 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15764 !FD->isInvalidDecl() && !FD->isInlined() &&
15765 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15766 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15767 !FD->isTemplateInstantiation()) {
15768 assert(FD->isThisDeclarationADefinition());
15769 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15770 FD->setInvalidDecl();
15771 }
15772
15773 // Ensure that the function's exception specification is instantiated.
15774 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15776
15777 // dllimport cannot be applied to non-inline function definitions.
15778 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15779 !FD->isTemplateInstantiation()) {
15780 assert(!FD->hasAttr<DLLExportAttr>());
15781 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15782 FD->setInvalidDecl();
15783 return D;
15784 }
15785
15786 // Some function attributes (like OptimizeNoneAttr) need actions before
15787 // parsing body started.
15789
15790 // We want to attach documentation to original Decl (which might be
15791 // a function template).
15793 if (getCurLexicalContext()->isObjCContainer() &&
15794 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15795 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15796 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15797
15799
15800 return D;
15801}
15802
15804 if (!FD || FD->isInvalidDecl())
15805 return;
15806 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
15807 FD = TD->getTemplatedDecl();
15808 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
15812 FpPragmaStack.CurrentValue =
15814 }
15815}
15816
15818 ReturnStmt **Returns = Scope->Returns.data();
15819
15820 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15821 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15822 if (!NRVOCandidate->isNRVOVariable())
15823 Returns[I]->setNRVOCandidate(nullptr);
15824 }
15825 }
15826}
15827
15829 // We can't delay parsing the body of a constexpr function template (yet).
15830 if (D.getDeclSpec().hasConstexprSpecifier())
15831 return false;
15832
15833 // We can't delay parsing the body of a function template with a deduced
15834 // return type (yet).
15835 if (D.getDeclSpec().hasAutoTypeSpec()) {
15836 // If the placeholder introduces a non-deduced trailing return type,
15837 // we can still delay parsing it.
15838 if (D.getNumTypeObjects()) {
15839 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15840 if (Outer.Kind == DeclaratorChunk::Function &&
15841 Outer.Fun.hasTrailingReturnType()) {
15842 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15843 return Ty.isNull() || !Ty->isUndeducedType();
15844 }
15845 }
15846 return false;
15847 }
15848
15849 return true;
15850}
15851
15853 // We cannot skip the body of a function (or function template) which is
15854 // constexpr, since we may need to evaluate its body in order to parse the
15855 // rest of the file.
15856 // We cannot skip the body of a function with an undeduced return type,
15857 // because any callers of that function need to know the type.
15858 if (const FunctionDecl *FD = D->getAsFunction()) {
15859 if (FD->isConstexpr())
15860 return false;
15861 // We can't simply call Type::isUndeducedType here, because inside template
15862 // auto can be deduced to a dependent type, which is not considered
15863 // "undeduced".
15864 if (FD->getReturnType()->getContainedDeducedType())
15865 return false;
15866 }
15868}
15869
15871 if (!Decl)
15872 return nullptr;
15873 if (FunctionDecl *FD = Decl->getAsFunction())
15874 FD->setHasSkippedBody();
15875 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15876 MD->setHasSkippedBody();
15877 return Decl;
15878}
15879
15881 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
15882}
15883
15884/// RAII object that pops an ExpressionEvaluationContext when exiting a function
15885/// body.
15887public:
15888 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15890 if (!IsLambda)
15892 }
15893
15894private:
15895 Sema &S;
15896 bool IsLambda = false;
15897};
15898
15900 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15901
15902 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15903 if (auto It = EscapeInfo.find(BD); It != EscapeInfo.end())
15904 return It->second;
15905
15906 bool R = false;
15907 const BlockDecl *CurBD = BD;
15908
15909 do {
15910 R = !CurBD->doesNotEscape();
15911 if (R)
15912 break;
15913 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15914 } while (CurBD);
15915
15916 return EscapeInfo[BD] = R;
15917 };
15918
15919 // If the location where 'self' is implicitly retained is inside a escaping
15920 // block, emit a diagnostic.
15921 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15923 if (IsOrNestedInEscapingBlock(P.second))
15924 S.Diag(P.first, diag::warn_implicitly_retains_self)
15925 << FixItHint::CreateInsertion(P.first, "self->");
15926}
15927
15928static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
15929 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
15930 FD->getDeclName().isIdentifier() && FD->getName() == Name;
15931}
15932
15934 return methodHasName(FD, "get_return_object");
15935}
15936
15938 return FD->isStatic() &&
15939 methodHasName(FD, "get_return_object_on_allocation_failure");
15940}
15941
15944 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15945 return;
15946 // Allow some_promise_type::get_return_object().
15948 return;
15949 if (!FD->hasAttr<CoroWrapperAttr>())
15950 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
15951}
15952
15954 bool IsInstantiation) {
15956 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15957
15958 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15959 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15960
15962 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15963
15964 // If we skip function body, we can't tell if a function is a coroutine.
15965 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
15966 if (FSI->isCoroutine())
15968 else
15970 }
15971
15972 // Diagnose invalid SYCL kernel entry point function declarations
15973 // and build SYCLKernelCallStmts for valid ones.
15974 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
15975 SYCLKernelEntryPointAttr *SKEPAttr =
15976 FD->getAttr<SYCLKernelEntryPointAttr>();
15977 if (FD->isDefaulted()) {
15978 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15979 << /*defaulted function*/ 3;
15980 SKEPAttr->setInvalidAttr();
15981 } else if (FD->isDeleted()) {
15982 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15983 << /*deleted function*/ 2;
15984 SKEPAttr->setInvalidAttr();
15985 } else if (FSI->isCoroutine()) {
15986 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15987 << /*coroutine*/ 7;
15988 SKEPAttr->setInvalidAttr();
15989 } else if (Body && isa<CXXTryStmt>(Body)) {
15990 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15991 << /*function defined with a function try block*/ 8;
15992 SKEPAttr->setInvalidAttr();
15993 }
15994
15995 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
15996 StmtResult SR =
15997 SYCL().BuildSYCLKernelCallStmt(FD, cast<CompoundStmt>(Body));
15998 if (SR.isInvalid())
15999 return nullptr;
16000 Body = SR.get();
16001 }
16002 }
16003
16004 {
16005 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16006 // one is already popped when finishing the lambda in BuildLambdaExpr().
16007 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16008 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16009 if (FD) {
16010 // If this is called by Parser::ParseFunctionDefinition() after marking
16011 // the declaration as deleted, and if the deleted-function-body contains
16012 // a message (C++26), then a DefaultedOrDeletedInfo will have already been
16013 // added to store that message; do not overwrite it in that case.
16014 //
16015 // Since this would always set the body to 'nullptr' in that case anyway,
16016 // which is already done when the function decl is initially created,
16017 // always skipping this irrespective of whether there is a delete message
16018 // should not be a problem.
16019 if (!FD->isDeletedAsWritten())
16020 FD->setBody(Body);
16021 FD->setWillHaveBody(false);
16023
16024 if (getLangOpts().CPlusPlus14) {
16025 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16026 FD->getReturnType()->isUndeducedType()) {
16027 // For a function with a deduced result type to return void,
16028 // the result type as written must be 'auto' or 'decltype(auto)',
16029 // possibly cv-qualified or constrained, but not ref-qualified.
16030 if (!FD->getReturnType()->getAs<AutoType>()) {
16031 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16032 << FD->getReturnType();
16033 FD->setInvalidDecl();
16034 } else {
16035 // Falling off the end of the function is the same as 'return;'.
16036 Expr *Dummy = nullptr;
16038 FD, dcl->getLocation(), Dummy,
16039 FD->getReturnType()->getAs<AutoType>()))
16040 FD->setInvalidDecl();
16041 }
16042 }
16043 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16044 // In C++11, we don't use 'auto' deduction rules for lambda call
16045 // operators because we don't support return type deduction.
16046 auto *LSI = getCurLambda();
16047 if (LSI->HasImplicitReturnType) {
16049
16050 // C++11 [expr.prim.lambda]p4:
16051 // [...] if there are no return statements in the compound-statement
16052 // [the deduced type is] the type void
16053 QualType RetType =
16054 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16055
16056 // Update the return type to the deduced type.
16057 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16058 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16059 Proto->getExtProtoInfo()));
16060 }
16061 }
16062
16063 // If the function implicitly returns zero (like 'main') or is naked,
16064 // don't complain about missing return statements.
16065 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
16067
16068 // MSVC permits the use of pure specifier (=0) on function definition,
16069 // defined at class scope, warn about this non-standard construct.
16070 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16071 !FD->isOutOfLine())
16072 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16073
16074 if (!FD->isInvalidDecl()) {
16075 // Don't diagnose unused parameters of defaulted, deleted or naked
16076 // functions.
16077 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16078 !FD->hasAttr<NakedAttr>())
16081 FD->getReturnType(), FD);
16082
16083 // If this is a structor, we need a vtable.
16084 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16085 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16086 else if (CXXDestructorDecl *Destructor =
16087 dyn_cast<CXXDestructorDecl>(FD))
16088 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16089
16090 // Try to apply the named return value optimization. We have to check
16091 // if we can do this here because lambdas keep return statements around
16092 // to deduce an implicit return type.
16093 if (FD->getReturnType()->isRecordType() &&
16095 computeNRVO(Body, FSI);
16096 }
16097
16098 // GNU warning -Wmissing-prototypes:
16099 // Warn if a global function is defined without a previous
16100 // prototype declaration. This warning is issued even if the
16101 // definition itself provides a prototype. The aim is to detect
16102 // global functions that fail to be declared in header files.
16103 const FunctionDecl *PossiblePrototype = nullptr;
16104 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16105 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16106
16107 if (PossiblePrototype) {
16108 // We found a declaration that is not a prototype,
16109 // but that could be a zero-parameter prototype
16110 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16111 TypeLoc TL = TI->getTypeLoc();
16113 Diag(PossiblePrototype->getLocation(),
16114 diag::note_declaration_not_a_prototype)
16115 << (FD->getNumParams() != 0)
16117 FTL.getRParenLoc(), "void")
16118 : FixItHint{});
16119 }
16120 } else {
16121 // Returns true if the token beginning at this Loc is `const`.
16122 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16123 const LangOptions &LangOpts) {
16124 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
16125 if (LocInfo.first.isInvalid())
16126 return false;
16127
16128 bool Invalid = false;
16129 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16130 if (Invalid)
16131 return false;
16132
16133 if (LocInfo.second > Buffer.size())
16134 return false;
16135
16136 const char *LexStart = Buffer.data() + LocInfo.second;
16137 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16138
16139 return StartTok.consume_front("const") &&
16140 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16141 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16142 };
16143
16144 auto findBeginLoc = [&]() {
16145 // If the return type has `const` qualifier, we want to insert
16146 // `static` before `const` (and not before the typename).
16147 if ((FD->getReturnType()->isAnyPointerType() &&
16150 // But only do this if we can determine where the `const` is.
16151
16152 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16153 getLangOpts()))
16154
16155 return FD->getBeginLoc();
16156 }
16157 return FD->getTypeSpecStartLoc();
16158 };
16160 diag::note_static_for_internal_linkage)
16161 << /* function */ 1
16162 << (FD->getStorageClass() == SC_None
16163 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16164 : FixItHint{});
16165 }
16166 }
16167
16168 // We might not have found a prototype because we didn't wish to warn on
16169 // the lack of a missing prototype. Try again without the checks for
16170 // whether we want to warn on the missing prototype.
16171 if (!PossiblePrototype)
16172 (void)FindPossiblePrototype(FD, PossiblePrototype);
16173
16174 // If the function being defined does not have a prototype, then we may
16175 // need to diagnose it as changing behavior in C23 because we now know
16176 // whether the function accepts arguments or not. This only handles the
16177 // case where the definition has no prototype but does have parameters
16178 // and either there is no previous potential prototype, or the previous
16179 // potential prototype also has no actual prototype. This handles cases
16180 // like:
16181 // void f(); void f(a) int a; {}
16182 // void g(a) int a; {}
16183 // See MergeFunctionDecl() for other cases of the behavior change
16184 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16185 // type without a prototype.
16186 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16187 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16188 !PossiblePrototype->isImplicit()))) {
16189 // The function definition has parameters, so this will change behavior
16190 // in C23. If there is a possible prototype, it comes before the
16191 // function definition.
16192 // FIXME: The declaration may have already been diagnosed as being
16193 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16194 // there's no way to test for the "changes behavior" condition in
16195 // SemaType.cpp when forming the declaration's function type. So, we do
16196 // this awkward dance instead.
16197 //
16198 // If we have a possible prototype and it declares a function with a
16199 // prototype, we don't want to diagnose it; if we have a possible
16200 // prototype and it has no prototype, it may have already been
16201 // diagnosed in SemaType.cpp as deprecated depending on whether
16202 // -Wstrict-prototypes is enabled. If we already warned about it being
16203 // deprecated, add a note that it also changes behavior. If we didn't
16204 // warn about it being deprecated (because the diagnostic is not
16205 // enabled), warn now that it is deprecated and changes behavior.
16206
16207 // This K&R C function definition definitely changes behavior in C23,
16208 // so diagnose it.
16209 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16210 << /*definition*/ 1 << /* not supported in C23 */ 0;
16211
16212 // If we have a possible prototype for the function which is a user-
16213 // visible declaration, we already tested that it has no prototype.
16214 // This will change behavior in C23. This gets a warning rather than a
16215 // note because it's the same behavior-changing problem as with the
16216 // definition.
16217 if (PossiblePrototype)
16218 Diag(PossiblePrototype->getLocation(),
16219 diag::warn_non_prototype_changes_behavior)
16220 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16221 << /*definition*/ 1;
16222 }
16223
16224 // Warn on CPUDispatch with an actual body.
16225 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16226 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16227 if (!CmpndBody->body_empty())
16228 Diag(CmpndBody->body_front()->getBeginLoc(),
16229 diag::warn_dispatch_body_ignored);
16230
16231 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16232 const CXXMethodDecl *KeyFunction;
16233 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16234 MD->isVirtual() &&
16235 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16236 MD == KeyFunction->getCanonicalDecl()) {
16237 // Update the key-function state if necessary for this ABI.
16238 if (FD->isInlined() &&
16241
16242 // If the newly-chosen key function is already defined, then we
16243 // need to mark the vtable as used retroactively.
16244 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16245 const FunctionDecl *Definition;
16246 if (KeyFunction && KeyFunction->isDefined(Definition))
16247 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16248 } else {
16249 // We just defined they key function; mark the vtable as used.
16250 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16251 }
16252 }
16253 }
16254
16255 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16256 "Function parsing confused");
16257 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16258 assert(MD == getCurMethodDecl() && "Method parsing confused");
16259 MD->setBody(Body);
16260 if (!MD->isInvalidDecl()) {
16262 MD->getReturnType(), MD);
16263
16264 if (Body)
16265 computeNRVO(Body, FSI);
16266 }
16267 if (FSI->ObjCShouldCallSuper) {
16268 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16269 << MD->getSelector().getAsString();
16270 FSI->ObjCShouldCallSuper = false;
16271 }
16273 const ObjCMethodDecl *InitMethod = nullptr;
16274 bool isDesignated =
16275 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16276 assert(isDesignated && InitMethod);
16277 (void)isDesignated;
16278
16279 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16280 auto IFace = MD->getClassInterface();
16281 if (!IFace)
16282 return false;
16283 auto SuperD = IFace->getSuperClass();
16284 if (!SuperD)
16285 return false;
16286 return SuperD->getIdentifier() ==
16287 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16288 };
16289 // Don't issue this warning for unavailable inits or direct subclasses
16290 // of NSObject.
16291 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16292 Diag(MD->getLocation(),
16293 diag::warn_objc_designated_init_missing_super_call);
16294 Diag(InitMethod->getLocation(),
16295 diag::note_objc_designated_init_marked_here);
16296 }
16298 }
16299 if (FSI->ObjCWarnForNoInitDelegation) {
16300 // Don't issue this warning for unavailable inits.
16301 if (!MD->isUnavailable())
16302 Diag(MD->getLocation(),
16303 diag::warn_objc_secondary_init_missing_init_call);
16304 FSI->ObjCWarnForNoInitDelegation = false;
16305 }
16306
16308 } else {
16309 // Parsing the function declaration failed in some way. Pop the fake scope
16310 // we pushed on.
16311 PopFunctionScopeInfo(ActivePolicy, dcl);
16312 return nullptr;
16313 }
16314
16315 if (Body && FSI->HasPotentialAvailabilityViolations)
16317
16318 assert(!FSI->ObjCShouldCallSuper &&
16319 "This should only be set for ObjC methods, which should have been "
16320 "handled in the block above.");
16321
16322 // Verify and clean out per-function state.
16323 if (Body && (!FD || !FD->isDefaulted())) {
16324 // C++ constructors that have function-try-blocks can't have return
16325 // statements in the handlers of that block. (C++ [except.handle]p14)
16326 // Verify this.
16327 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16328 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16329
16330 // Verify that gotos and switch cases don't jump into scopes illegally.
16333
16334 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16335 if (!Destructor->getParent()->isDependentType())
16337
16339 Destructor->getParent());
16340 }
16341
16342 // If any errors have occurred, clear out any temporaries that may have
16343 // been leftover. This ensures that these temporaries won't be picked up
16344 // for deletion in some later function.
16347 getDiagnostics().getSuppressAllDiagnostics()) {
16349 }
16350 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16351 // Since the body is valid, issue any analysis-based warnings that are
16352 // enabled.
16353 ActivePolicy = &WP;
16354 }
16355
16356 if (!IsInstantiation && FD &&
16357 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16358 !FD->isInvalidDecl() &&
16360 FD->setInvalidDecl();
16361
16362 if (FD && FD->hasAttr<NakedAttr>()) {
16363 for (const Stmt *S : Body->children()) {
16364 // Allow local register variables without initializer as they don't
16365 // require prologue.
16366 bool RegisterVariables = false;
16367 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16368 for (const auto *Decl : DS->decls()) {
16369 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16370 RegisterVariables =
16371 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16372 if (!RegisterVariables)
16373 break;
16374 }
16375 }
16376 }
16377 if (RegisterVariables)
16378 continue;
16379 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16380 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16381 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16382 FD->setInvalidDecl();
16383 break;
16384 }
16385 }
16386 }
16387
16388 assert(ExprCleanupObjects.size() ==
16389 ExprEvalContexts.back().NumCleanupObjects &&
16390 "Leftover temporaries in function");
16391 assert(!Cleanup.exprNeedsCleanups() &&
16392 "Unaccounted cleanups in function");
16393 assert(MaybeODRUseExprs.empty() &&
16394 "Leftover expressions for odr-use checking");
16395 }
16396 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16397 // the declaration context below. Otherwise, we're unable to transform
16398 // 'this' expressions when transforming immediate context functions.
16399
16400 if (!IsInstantiation)
16402
16403 PopFunctionScopeInfo(ActivePolicy, dcl);
16404 // If any errors have occurred, clear out any temporaries that may have
16405 // been leftover. This ensures that these temporaries won't be picked up for
16406 // deletion in some later function.
16409 }
16410
16411 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16412 !LangOpts.OMPTargetTriples.empty())) ||
16413 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16414 auto ES = getEmissionStatus(FD);
16417 DeclsToCheckForDeferredDiags.insert(FD);
16418 }
16419
16420 if (FD && !FD->isDeleted())
16421 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16422
16423 return dcl;
16424}
16425
16426/// When we finish delayed parsing of an attribute, we must attach it to the
16427/// relevant Decl.
16429 ParsedAttributes &Attrs) {
16430 // Always attach attributes to the underlying decl.
16431 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16432 D = TD->getTemplatedDecl();
16433 ProcessDeclAttributeList(S, D, Attrs);
16435
16436 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16437 if (Method->isStatic())
16439}
16440
16442 IdentifierInfo &II, Scope *S) {
16443 // It is not valid to implicitly define a function in C23.
16445 "Implicit function declarations aren't allowed in this language mode");
16446
16447 // Find the scope in which the identifier is injected and the corresponding
16448 // DeclContext.
16449 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16450 // In that case, we inject the declaration into the translation unit scope
16451 // instead.
16452 Scope *BlockScope = S;
16453 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16454 BlockScope = BlockScope->getParent();
16455
16456 // Loop until we find a DeclContext that is either a function/method or the
16457 // translation unit, which are the only two valid places to implicitly define
16458 // a function. This avoids accidentally defining the function within a tag
16459 // declaration, for example.
16460 Scope *ContextScope = BlockScope;
16461 while (!ContextScope->getEntity() ||
16462 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16463 !ContextScope->getEntity()->isTranslationUnit()))
16464 ContextScope = ContextScope->getParent();
16465 ContextRAII SavedContext(*this, ContextScope->getEntity());
16466
16467 // Before we produce a declaration for an implicitly defined
16468 // function, see whether there was a locally-scoped declaration of
16469 // this name as a function or variable. If so, use that
16470 // (non-visible) declaration, and complain about it.
16471 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16472 if (ExternCPrev) {
16473 // We still need to inject the function into the enclosing block scope so
16474 // that later (non-call) uses can see it.
16475 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16476
16477 // C89 footnote 38:
16478 // If in fact it is not defined as having type "function returning int",
16479 // the behavior is undefined.
16480 if (!isa<FunctionDecl>(ExternCPrev) ||
16482 cast<FunctionDecl>(ExternCPrev)->getType(),
16484 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16485 << ExternCPrev << !getLangOpts().C99;
16486 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16487 return ExternCPrev;
16488 }
16489 }
16490
16491 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16492 unsigned diag_id;
16493 if (II.getName().starts_with("__builtin_"))
16494 diag_id = diag::warn_builtin_unknown;
16495 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16496 else if (getLangOpts().C99)
16497 diag_id = diag::ext_implicit_function_decl_c99;
16498 else
16499 diag_id = diag::warn_implicit_function_decl;
16500
16501 TypoCorrection Corrected;
16502 // Because typo correction is expensive, only do it if the implicit
16503 // function declaration is going to be treated as an error.
16504 //
16505 // Perform the correction before issuing the main diagnostic, as some
16506 // consumers use typo-correction callbacks to enhance the main diagnostic.
16507 if (S && !ExternCPrev &&
16511 S, nullptr, CCC, CTK_NonError);
16512 }
16513
16514 Diag(Loc, diag_id) << &II;
16515 if (Corrected) {
16516 // If the correction is going to suggest an implicitly defined function,
16517 // skip the correction as not being a particularly good idea.
16518 bool Diagnose = true;
16519 if (const auto *D = Corrected.getCorrectionDecl())
16520 Diagnose = !D->isImplicit();
16521 if (Diagnose)
16522 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16523 /*ErrorRecovery*/ false);
16524 }
16525
16526 // If we found a prior declaration of this function, don't bother building
16527 // another one. We've already pushed that one into scope, so there's nothing
16528 // more to do.
16529 if (ExternCPrev)
16530 return ExternCPrev;
16531
16532 // Set a Declarator for the implicit definition: int foo();
16533 const char *Dummy;
16534 AttributeFactory attrFactory;
16535 DeclSpec DS(attrFactory);
16536 unsigned DiagID;
16537 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16539 (void)Error; // Silence warning.
16540 assert(!Error && "Error setting up implicit decl!");
16541 SourceLocation NoLoc;
16543 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16544 /*IsAmbiguous=*/false,
16545 /*LParenLoc=*/NoLoc,
16546 /*Params=*/nullptr,
16547 /*NumParams=*/0,
16548 /*EllipsisLoc=*/NoLoc,
16549 /*RParenLoc=*/NoLoc,
16550 /*RefQualifierIsLvalueRef=*/true,
16551 /*RefQualifierLoc=*/NoLoc,
16552 /*MutableLoc=*/NoLoc, EST_None,
16553 /*ESpecRange=*/SourceRange(),
16554 /*Exceptions=*/nullptr,
16555 /*ExceptionRanges=*/nullptr,
16556 /*NumExceptions=*/0,
16557 /*NoexceptExpr=*/nullptr,
16558 /*ExceptionSpecTokens=*/nullptr,
16559 /*DeclsInPrototype=*/{}, Loc, Loc,
16560 D),
16561 std::move(DS.getAttributes()), SourceLocation());
16562 D.SetIdentifier(&II, Loc);
16563
16564 // Insert this function into the enclosing block scope.
16565 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16566 FD->setImplicit();
16567
16569
16570 return FD;
16571}
16572
16574 FunctionDecl *FD) {
16575 if (FD->isInvalidDecl())
16576 return;
16577
16578 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16579 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16580 return;
16581
16582 std::optional<unsigned> AlignmentParam;
16583 bool IsNothrow = false;
16584 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16585 return;
16586
16587 // C++2a [basic.stc.dynamic.allocation]p4:
16588 // An allocation function that has a non-throwing exception specification
16589 // indicates failure by returning a null pointer value. Any other allocation
16590 // function never returns a null pointer value and indicates failure only by
16591 // throwing an exception [...]
16592 //
16593 // However, -fcheck-new invalidates this possible assumption, so don't add
16594 // NonNull when that is enabled.
16595 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16596 !getLangOpts().CheckNew)
16597 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16598
16599 // C++2a [basic.stc.dynamic.allocation]p2:
16600 // An allocation function attempts to allocate the requested amount of
16601 // storage. [...] If the request succeeds, the value returned by a
16602 // replaceable allocation function is a [...] pointer value p0 different
16603 // from any previously returned value p1 [...]
16604 //
16605 // However, this particular information is being added in codegen,
16606 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16607
16608 // C++2a [basic.stc.dynamic.allocation]p2:
16609 // An allocation function attempts to allocate the requested amount of
16610 // storage. If it is successful, it returns the address of the start of a
16611 // block of storage whose length in bytes is at least as large as the
16612 // requested size.
16613 if (!FD->hasAttr<AllocSizeAttr>()) {
16614 FD->addAttr(AllocSizeAttr::CreateImplicit(
16615 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16616 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16617 }
16618
16619 // C++2a [basic.stc.dynamic.allocation]p3:
16620 // For an allocation function [...], the pointer returned on a successful
16621 // call shall represent the address of storage that is aligned as follows:
16622 // (3.1) If the allocation function takes an argument of type
16623 // std​::​align_­val_­t, the storage will have the alignment
16624 // specified by the value of this argument.
16625 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16626 FD->addAttr(AllocAlignAttr::CreateImplicit(
16627 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16628 }
16629
16630 // FIXME:
16631 // C++2a [basic.stc.dynamic.allocation]p3:
16632 // For an allocation function [...], the pointer returned on a successful
16633 // call shall represent the address of storage that is aligned as follows:
16634 // (3.2) Otherwise, if the allocation function is named operator new[],
16635 // the storage is aligned for any object that does not have
16636 // new-extended alignment ([basic.align]) and is no larger than the
16637 // requested size.
16638 // (3.3) Otherwise, the storage is aligned for any object that does not
16639 // have new-extended alignment and is of the requested size.
16640}
16641
16643 if (FD->isInvalidDecl())
16644 return;
16645
16646 // If this is a built-in function, map its builtin attributes to
16647 // actual attributes.
16648 if (unsigned BuiltinID = FD->getBuiltinID()) {
16649 // Handle printf-formatting attributes.
16650 unsigned FormatIdx;
16651 bool HasVAListArg;
16652 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16653 if (!FD->hasAttr<FormatAttr>()) {
16654 const char *fmt = "printf";
16655 unsigned int NumParams = FD->getNumParams();
16656 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16657 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16658 fmt = "NSString";
16659 FD->addAttr(FormatAttr::CreateImplicit(Context,
16660 &Context.Idents.get(fmt),
16661 FormatIdx+1,
16662 HasVAListArg ? 0 : FormatIdx+2,
16663 FD->getLocation()));
16664 }
16665 }
16666 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16667 HasVAListArg)) {
16668 if (!FD->hasAttr<FormatAttr>())
16669 FD->addAttr(FormatAttr::CreateImplicit(Context,
16670 &Context.Idents.get("scanf"),
16671 FormatIdx+1,
16672 HasVAListArg ? 0 : FormatIdx+2,
16673 FD->getLocation()));
16674 }
16675
16676 // Handle automatically recognized callbacks.
16677 SmallVector<int, 4> Encoding;
16678 if (!FD->hasAttr<CallbackAttr>() &&
16679 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16680 FD->addAttr(CallbackAttr::CreateImplicit(
16681 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16682
16683 // Mark const if we don't care about errno and/or floating point exceptions
16684 // that are the only thing preventing the function from being const. This
16685 // allows IRgen to use LLVM intrinsics for such functions.
16686 bool NoExceptions =
16688 bool ConstWithoutErrnoAndExceptions =
16690 bool ConstWithoutExceptions =
16692 if (!FD->hasAttr<ConstAttr>() &&
16693 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16694 (!ConstWithoutErrnoAndExceptions ||
16695 (!getLangOpts().MathErrno && NoExceptions)) &&
16696 (!ConstWithoutExceptions || NoExceptions))
16697 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16698
16699 // We make "fma" on GNU or Windows const because we know it does not set
16700 // errno in those environments even though it could set errno based on the
16701 // C standard.
16702 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16703 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16704 !FD->hasAttr<ConstAttr>()) {
16705 switch (BuiltinID) {
16706 case Builtin::BI__builtin_fma:
16707 case Builtin::BI__builtin_fmaf:
16708 case Builtin::BI__builtin_fmal:
16709 case Builtin::BIfma:
16710 case Builtin::BIfmaf:
16711 case Builtin::BIfmal:
16712 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16713 break;
16714 default:
16715 break;
16716 }
16717 }
16718
16719 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16720 !FD->hasAttr<ReturnsTwiceAttr>())
16721 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16722 FD->getLocation()));
16723 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16724 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16725 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16726 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16727 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16728 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16729 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16730 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16731 // Add the appropriate attribute, depending on the CUDA compilation mode
16732 // and which target the builtin belongs to. For example, during host
16733 // compilation, aux builtins are __device__, while the rest are __host__.
16734 if (getLangOpts().CUDAIsDevice !=
16736 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16737 else
16738 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16739 }
16740
16741 // Add known guaranteed alignment for allocation functions.
16742 switch (BuiltinID) {
16743 case Builtin::BImemalign:
16744 case Builtin::BIaligned_alloc:
16745 if (!FD->hasAttr<AllocAlignAttr>())
16746 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16747 FD->getLocation()));
16748 break;
16749 default:
16750 break;
16751 }
16752
16753 // Add allocsize attribute for allocation functions.
16754 switch (BuiltinID) {
16755 case Builtin::BIcalloc:
16756 FD->addAttr(AllocSizeAttr::CreateImplicit(
16757 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16758 break;
16759 case Builtin::BImemalign:
16760 case Builtin::BIaligned_alloc:
16761 case Builtin::BIrealloc:
16762 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16763 ParamIdx(), FD->getLocation()));
16764 break;
16765 case Builtin::BImalloc:
16766 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16767 ParamIdx(), FD->getLocation()));
16768 break;
16769 default:
16770 break;
16771 }
16772 }
16773
16778
16779 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16780 // throw, add an implicit nothrow attribute to any extern "C" function we come
16781 // across.
16782 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16783 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16784 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16785 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16786 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16787 }
16788
16789 IdentifierInfo *Name = FD->getIdentifier();
16790 if (!Name)
16791 return;
16793 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16794 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16796 // Okay: this could be a libc/libm/Objective-C function we know
16797 // about.
16798 } else
16799 return;
16800
16801 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16802 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16803 // target-specific builtins, perhaps?
16804 if (!FD->hasAttr<FormatAttr>())
16805 FD->addAttr(FormatAttr::CreateImplicit(Context,
16806 &Context.Idents.get("printf"), 2,
16807 Name->isStr("vasprintf") ? 0 : 3,
16808 FD->getLocation()));
16809 }
16810
16811 if (Name->isStr("__CFStringMakeConstantString")) {
16812 // We already have a __builtin___CFStringMakeConstantString,
16813 // but builds that use -fno-constant-cfstrings don't go through that.
16814 if (!FD->hasAttr<FormatArgAttr>())
16815 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16816 FD->getLocation()));
16817 }
16818}
16819
16821 TypeSourceInfo *TInfo) {
16822 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16823 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16824
16825 if (!TInfo) {
16826 assert(D.isInvalidType() && "no declarator info for valid type");
16828 }
16829
16830 // Scope manipulation handled by caller.
16831 TypedefDecl *NewTD =
16833 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16834
16835 // Bail out immediately if we have an invalid declaration.
16836 if (D.isInvalidType()) {
16837 NewTD->setInvalidDecl();
16838 return NewTD;
16839 }
16840
16841 if (D.getDeclSpec().isModulePrivateSpecified()) {
16843 Diag(NewTD->getLocation(), diag::err_module_private_local)
16844 << 2 << NewTD
16845 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16847 D.getDeclSpec().getModulePrivateSpecLoc());
16848 else
16849 NewTD->setModulePrivate();
16850 }
16851
16852 // C++ [dcl.typedef]p8:
16853 // If the typedef declaration defines an unnamed class (or
16854 // enum), the first typedef-name declared by the declaration
16855 // to be that class type (or enum type) is used to denote the
16856 // class type (or enum type) for linkage purposes only.
16857 // We need to check whether the type was declared in the declaration.
16858 switch (D.getDeclSpec().getTypeSpecType()) {
16859 case TST_enum:
16860 case TST_struct:
16861 case TST_interface:
16862 case TST_union:
16863 case TST_class: {
16864 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16865 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16866 break;
16867 }
16868
16869 default:
16870 break;
16871 }
16872
16873 return NewTD;
16874}
16875
16877 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16878 QualType T = TI->getType();
16879
16880 if (T->isDependentType())
16881 return false;
16882
16883 // This doesn't use 'isIntegralType' despite the error message mentioning
16884 // integral type because isIntegralType would also allow enum types in C.
16885 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16886 if (BT->isInteger())
16887 return false;
16888
16889 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16890 << T << T->isBitIntType();
16891}
16892
16894 QualType EnumUnderlyingTy, bool IsFixed,
16895 const EnumDecl *Prev) {
16896 if (IsScoped != Prev->isScoped()) {
16897 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16898 << Prev->isScoped();
16899 Diag(Prev->getLocation(), diag::note_previous_declaration);
16900 return true;
16901 }
16902
16903 if (IsFixed && Prev->isFixed()) {
16904 if (!EnumUnderlyingTy->isDependentType() &&
16905 !Prev->getIntegerType()->isDependentType() &&
16906 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16907 Prev->getIntegerType())) {
16908 // TODO: Highlight the underlying type of the redeclaration.
16909 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16910 << EnumUnderlyingTy << Prev->getIntegerType();
16911 Diag(Prev->getLocation(), diag::note_previous_declaration)
16912 << Prev->getIntegerTypeRange();
16913 return true;
16914 }
16915 } else if (IsFixed != Prev->isFixed()) {
16916 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16917 << Prev->isFixed();
16918 Diag(Prev->getLocation(), diag::note_previous_declaration);
16919 return true;
16920 }
16921
16922 return false;
16923}
16924
16925/// Get diagnostic %select index for tag kind for
16926/// redeclaration diagnostic message.
16927/// WARNING: Indexes apply to particular diagnostics only!
16928///
16929/// \returns diagnostic %select index.
16931 switch (Tag) {
16933 return 0;
16935 return 1;
16936 case TagTypeKind::Class:
16937 return 2;
16938 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16939 }
16940}
16941
16942/// Determine if tag kind is a class-key compatible with
16943/// class for redeclaration (class, struct, or __interface).
16944///
16945/// \returns true iff the tag kind is compatible.
16947{
16948 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
16950}
16951
16953 TagTypeKind TTK) {
16954 if (isa<TypedefDecl>(PrevDecl))
16955 return NTK_Typedef;
16956 else if (isa<TypeAliasDecl>(PrevDecl))
16957 return NTK_TypeAlias;
16958 else if (isa<ClassTemplateDecl>(PrevDecl))
16959 return NTK_Template;
16960 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16961 return NTK_TypeAliasTemplate;
16962 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16964 switch (TTK) {
16967 case TagTypeKind::Class:
16968 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16969 case TagTypeKind::Union:
16970 return NTK_NonUnion;
16971 case TagTypeKind::Enum:
16972 return NTK_NonEnum;
16973 }
16974 llvm_unreachable("invalid TTK");
16975}
16976
16978 TagTypeKind NewTag, bool isDefinition,
16979 SourceLocation NewTagLoc,
16980 const IdentifierInfo *Name) {
16981 // C++ [dcl.type.elab]p3:
16982 // The class-key or enum keyword present in the
16983 // elaborated-type-specifier shall agree in kind with the
16984 // declaration to which the name in the elaborated-type-specifier
16985 // refers. This rule also applies to the form of
16986 // elaborated-type-specifier that declares a class-name or
16987 // friend class since it can be construed as referring to the
16988 // definition of the class. Thus, in any
16989 // elaborated-type-specifier, the enum keyword shall be used to
16990 // refer to an enumeration (7.2), the union class-key shall be
16991 // used to refer to a union (clause 9), and either the class or
16992 // struct class-key shall be used to refer to a class (clause 9)
16993 // declared using the class or struct class-key.
16994 TagTypeKind OldTag = Previous->getTagKind();
16995 if (OldTag != NewTag &&
16997 return false;
16998
16999 // Tags are compatible, but we might still want to warn on mismatched tags.
17000 // Non-class tags can't be mismatched at this point.
17002 return true;
17003
17004 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17005 // by our warning analysis. We don't want to warn about mismatches with (eg)
17006 // declarations in system headers that are designed to be specialized, but if
17007 // a user asks us to warn, we should warn if their code contains mismatched
17008 // declarations.
17009 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17010 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17011 Loc);
17012 };
17013 if (IsIgnoredLoc(NewTagLoc))
17014 return true;
17015
17016 auto IsIgnored = [&](const TagDecl *Tag) {
17017 return IsIgnoredLoc(Tag->getLocation());
17018 };
17019 while (IsIgnored(Previous)) {
17020 Previous = Previous->getPreviousDecl();
17021 if (!Previous)
17022 return true;
17023 OldTag = Previous->getTagKind();
17024 }
17025
17026 bool isTemplate = false;
17027 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17028 isTemplate = Record->getDescribedClassTemplate();
17029
17031 if (OldTag != NewTag) {
17032 // In a template instantiation, do not offer fix-its for tag mismatches
17033 // since they usually mess up the template instead of fixing the problem.
17034 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17036 << getRedeclDiagFromTagKind(OldTag);
17037 // FIXME: Note previous location?
17038 }
17039 return true;
17040 }
17041
17042 if (isDefinition) {
17043 // On definitions, check all previous tags and issue a fix-it for each
17044 // one that doesn't match the current tag.
17045 if (Previous->getDefinition()) {
17046 // Don't suggest fix-its for redefinitions.
17047 return true;
17048 }
17049
17050 bool previousMismatch = false;
17051 for (const TagDecl *I : Previous->redecls()) {
17052 if (I->getTagKind() != NewTag) {
17053 // Ignore previous declarations for which the warning was disabled.
17054 if (IsIgnored(I))
17055 continue;
17056
17057 if (!previousMismatch) {
17058 previousMismatch = true;
17059 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17061 << getRedeclDiagFromTagKind(I->getTagKind());
17062 }
17063 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17065 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17067 }
17068 }
17069 return true;
17070 }
17071
17072 // Identify the prevailing tag kind: this is the kind of the definition (if
17073 // there is a non-ignored definition), or otherwise the kind of the prior
17074 // (non-ignored) declaration.
17075 const TagDecl *PrevDef = Previous->getDefinition();
17076 if (PrevDef && IsIgnored(PrevDef))
17077 PrevDef = nullptr;
17078 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17079 if (Redecl->getTagKind() != NewTag) {
17080 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17082 << getRedeclDiagFromTagKind(OldTag);
17083 Diag(Redecl->getLocation(), diag::note_previous_use);
17084
17085 // If there is a previous definition, suggest a fix-it.
17086 if (PrevDef) {
17087 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17091 }
17092 }
17093
17094 return true;
17095}
17096
17097/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17098/// from an outer enclosing namespace or file scope inside a friend declaration.
17099/// This should provide the commented out code in the following snippet:
17100/// namespace N {
17101/// struct X;
17102/// namespace M {
17103/// struct Y { friend struct /*N::*/ X; };
17104/// }
17105/// }
17107 SourceLocation NameLoc) {
17108 // While the decl is in a namespace, do repeated lookup of that name and see
17109 // if we get the same namespace back. If we do not, continue until
17110 // translation unit scope, at which point we have a fully qualified NNS.
17113 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17114 // This tag should be declared in a namespace, which can only be enclosed by
17115 // other namespaces. Bail if there's an anonymous namespace in the chain.
17116 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17117 if (!Namespace || Namespace->isAnonymousNamespace())
17118 return FixItHint();
17119 IdentifierInfo *II = Namespace->getIdentifier();
17120 Namespaces.push_back(II);
17121 NamedDecl *Lookup = SemaRef.LookupSingleName(
17122 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17123 if (Lookup == Namespace)
17124 break;
17125 }
17126
17127 // Once we have all the namespaces, reverse them to go outermost first, and
17128 // build an NNS.
17129 SmallString<64> Insertion;
17130 llvm::raw_svector_ostream OS(Insertion);
17131 if (DC->isTranslationUnit())
17132 OS << "::";
17133 std::reverse(Namespaces.begin(), Namespaces.end());
17134 for (auto *II : Namespaces)
17135 OS << II->getName() << "::";
17136 return FixItHint::CreateInsertion(NameLoc, Insertion);
17137}
17138
17139/// Determine whether a tag originally declared in context \p OldDC can
17140/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17141/// found a declaration in \p OldDC as a previous decl, perhaps through a
17142/// using-declaration).
17144 DeclContext *NewDC) {
17145 OldDC = OldDC->getRedeclContext();
17146 NewDC = NewDC->getRedeclContext();
17147
17148 if (OldDC->Equals(NewDC))
17149 return true;
17150
17151 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17152 // encloses the other).
17153 if (S.getLangOpts().MSVCCompat &&
17154 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17155 return true;
17156
17157 return false;
17158}
17159
17161Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17162 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17163 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17164 SourceLocation ModulePrivateLoc,
17165 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17166 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17167 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17168 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17169 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17170 // If this is not a definition, it must have a name.
17171 IdentifierInfo *OrigName = Name;
17172 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17173 "Nameless record must be a definition!");
17174 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17175
17176 OwnedDecl = false;
17178 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17179
17180 // FIXME: Check member specializations more carefully.
17181 bool isMemberSpecialization = false;
17182 bool Invalid = false;
17183
17184 // We only need to do this matching if we have template parameters
17185 // or a scope specifier, which also conveniently avoids this work
17186 // for non-C++ cases.
17187 if (TemplateParameterLists.size() > 0 ||
17188 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17189 TemplateParameterList *TemplateParams =
17191 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17192 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17193
17194 // C++23 [dcl.type.elab] p2:
17195 // If an elaborated-type-specifier is the sole constituent of a
17196 // declaration, the declaration is ill-formed unless it is an explicit
17197 // specialization, an explicit instantiation or it has one of the
17198 // following forms: [...]
17199 // C++23 [dcl.enum] p1:
17200 // If the enum-head-name of an opaque-enum-declaration contains a
17201 // nested-name-specifier, the declaration shall be an explicit
17202 // specialization.
17203 //
17204 // FIXME: Class template partial specializations can be forward declared
17205 // per CWG2213, but the resolution failed to allow qualified forward
17206 // declarations. This is almost certainly unintentional, so we allow them.
17207 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17208 !isMemberSpecialization)
17209 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17211
17212 if (TemplateParams) {
17213 if (Kind == TagTypeKind::Enum) {
17214 Diag(KWLoc, diag::err_enum_template);
17215 return true;
17216 }
17217
17218 if (TemplateParams->size() > 0) {
17219 // This is a declaration or definition of a class template (which may
17220 // be a member of another template).
17221
17222 if (Invalid)
17223 return true;
17224
17225 OwnedDecl = false;
17227 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17228 AS, ModulePrivateLoc,
17229 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17230 TemplateParameterLists.data(), SkipBody);
17231 return Result.get();
17232 } else {
17233 // The "template<>" header is extraneous.
17234 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17235 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17236 isMemberSpecialization = true;
17237 }
17238 }
17239
17240 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17241 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17242 return true;
17243 }
17244
17245 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17246 // C++23 [dcl.type.elab]p4:
17247 // If an elaborated-type-specifier appears with the friend specifier as
17248 // an entire member-declaration, the member-declaration shall have one
17249 // of the following forms:
17250 // friend class-key nested-name-specifier(opt) identifier ;
17251 // friend class-key simple-template-id ;
17252 // friend class-key nested-name-specifier template(opt)
17253 // simple-template-id ;
17254 //
17255 // Since enum is not a class-key, so declarations like "friend enum E;"
17256 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17257 // invalid, most implementations accept so we issue a pedantic warning.
17258 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17259 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17260 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17261 Diag(KWLoc, diag::note_enum_friend)
17262 << (ScopedEnum + ScopedEnumUsesClassTag);
17263 }
17264
17265 // Figure out the underlying type if this a enum declaration. We need to do
17266 // this early, because it's needed to detect if this is an incompatible
17267 // redeclaration.
17268 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17269 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17270
17271 if (Kind == TagTypeKind::Enum) {
17272 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17273 // No underlying type explicitly specified, or we failed to parse the
17274 // type, default to int.
17275 EnumUnderlying = Context.IntTy.getTypePtr();
17276 } else if (UnderlyingType.get()) {
17277 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17278 // integral type; any cv-qualification is ignored.
17279 TypeSourceInfo *TI = nullptr;
17280 GetTypeFromParser(UnderlyingType.get(), &TI);
17281 EnumUnderlying = TI;
17282
17284 // Recover by falling back to int.
17285 EnumUnderlying = Context.IntTy.getTypePtr();
17286
17289 EnumUnderlying = Context.IntTy.getTypePtr();
17290
17291 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17292 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17293 // of 'int'. However, if this is an unfixed forward declaration, don't set
17294 // the underlying type unless the user enables -fms-compatibility. This
17295 // makes unfixed forward declared enums incomplete and is more conforming.
17296 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17297 EnumUnderlying = Context.IntTy.getTypePtr();
17298 }
17299 }
17300
17301 DeclContext *SearchDC = CurContext;
17302 DeclContext *DC = CurContext;
17303 bool isStdBadAlloc = false;
17304 bool isStdAlignValT = false;
17305
17307 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17308 Redecl = RedeclarationKind::NotForRedeclaration;
17309
17310 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17311 /// implemented asks for structural equivalence checking, the returned decl
17312 /// here is passed back to the parser, allowing the tag body to be parsed.
17313 auto createTagFromNewDecl = [&]() -> TagDecl * {
17314 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17315 // If there is an identifier, use the location of the identifier as the
17316 // location of the decl, otherwise use the location of the struct/union
17317 // keyword.
17318 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17319 TagDecl *New = nullptr;
17320
17321 if (Kind == TagTypeKind::Enum) {
17322 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17323 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17324 // If this is an undefined enum, bail.
17325 if (TUK != TagUseKind::Definition && !Invalid)
17326 return nullptr;
17327 if (EnumUnderlying) {
17328 EnumDecl *ED = cast<EnumDecl>(New);
17329 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17331 else
17332 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17333 QualType EnumTy = ED->getIntegerType();
17336 : EnumTy);
17337 }
17338 } else { // struct/union
17339 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17340 nullptr);
17341 }
17342
17343 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17344 // Add alignment attributes if necessary; these attributes are checked
17345 // when the ASTContext lays out the structure.
17346 //
17347 // It is important for implementing the correct semantics that this
17348 // happen here (in ActOnTag). The #pragma pack stack is
17349 // maintained as a result of parser callbacks which can occur at
17350 // many points during the parsing of a struct declaration (because
17351 // the #pragma tokens are effectively skipped over during the
17352 // parsing of the struct).
17353 if (TUK == TagUseKind::Definition &&
17354 (!SkipBody || !SkipBody->ShouldSkip)) {
17357 }
17358 }
17360 return New;
17361 };
17362
17363 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17364 if (Name && SS.isNotEmpty()) {
17365 // We have a nested-name tag ('struct foo::bar').
17366
17367 // Check for invalid 'foo::'.
17368 if (SS.isInvalid()) {
17369 Name = nullptr;
17370 goto CreateNewDecl;
17371 }
17372
17373 // If this is a friend or a reference to a class in a dependent
17374 // context, don't try to make a decl for it.
17375 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17376 DC = computeDeclContext(SS, false);
17377 if (!DC) {
17378 IsDependent = true;
17379 return true;
17380 }
17381 } else {
17382 DC = computeDeclContext(SS, true);
17383 if (!DC) {
17384 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17385 << SS.getRange();
17386 return true;
17387 }
17388 }
17389
17390 if (RequireCompleteDeclContext(SS, DC))
17391 return true;
17392
17393 SearchDC = DC;
17394 // Look-up name inside 'foo::'.
17396
17397 if (Previous.isAmbiguous())
17398 return true;
17399
17400 if (Previous.empty()) {
17401 // Name lookup did not find anything. However, if the
17402 // nested-name-specifier refers to the current instantiation,
17403 // and that current instantiation has any dependent base
17404 // classes, we might find something at instantiation time: treat
17405 // this as a dependent elaborated-type-specifier.
17406 // But this only makes any sense for reference-like lookups.
17407 if (Previous.wasNotFoundInCurrentInstantiation() &&
17408 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17409 IsDependent = true;
17410 return true;
17411 }
17412
17413 // A tag 'foo::bar' must already exist.
17414 Diag(NameLoc, diag::err_not_tag_in_scope)
17415 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17416 Name = nullptr;
17417 Invalid = true;
17418 goto CreateNewDecl;
17419 }
17420 } else if (Name) {
17421 // C++14 [class.mem]p14:
17422 // If T is the name of a class, then each of the following shall have a
17423 // name different from T:
17424 // -- every member of class T that is itself a type
17425 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17426 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17427 return true;
17428
17429 // If this is a named struct, check to see if there was a previous forward
17430 // declaration or definition.
17431 // FIXME: We're looking into outer scopes here, even when we
17432 // shouldn't be. Doing so can result in ambiguities that we
17433 // shouldn't be diagnosing.
17434 LookupName(Previous, S);
17435
17436 // When declaring or defining a tag, ignore ambiguities introduced
17437 // by types using'ed into this scope.
17438 if (Previous.isAmbiguous() &&
17440 LookupResult::Filter F = Previous.makeFilter();
17441 while (F.hasNext()) {
17442 NamedDecl *ND = F.next();
17443 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17444 SearchDC->getRedeclContext()))
17445 F.erase();
17446 }
17447 F.done();
17448 }
17449
17450 // C++11 [namespace.memdef]p3:
17451 // If the name in a friend declaration is neither qualified nor
17452 // a template-id and the declaration is a function or an
17453 // elaborated-type-specifier, the lookup to determine whether
17454 // the entity has been previously declared shall not consider
17455 // any scopes outside the innermost enclosing namespace.
17456 //
17457 // MSVC doesn't implement the above rule for types, so a friend tag
17458 // declaration may be a redeclaration of a type declared in an enclosing
17459 // scope. They do implement this rule for friend functions.
17460 //
17461 // Does it matter that this should be by scope instead of by
17462 // semantic context?
17463 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17464 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17465 LookupResult::Filter F = Previous.makeFilter();
17466 bool FriendSawTagOutsideEnclosingNamespace = false;
17467 while (F.hasNext()) {
17468 NamedDecl *ND = F.next();
17470 if (DC->isFileContext() &&
17471 !EnclosingNS->Encloses(ND->getDeclContext())) {
17472 if (getLangOpts().MSVCCompat)
17473 FriendSawTagOutsideEnclosingNamespace = true;
17474 else
17475 F.erase();
17476 }
17477 }
17478 F.done();
17479
17480 // Diagnose this MSVC extension in the easy case where lookup would have
17481 // unambiguously found something outside the enclosing namespace.
17482 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17483 NamedDecl *ND = Previous.getFoundDecl();
17484 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17485 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17486 }
17487 }
17488
17489 // Note: there used to be some attempt at recovery here.
17490 if (Previous.isAmbiguous())
17491 return true;
17492
17493 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17494 // FIXME: This makes sure that we ignore the contexts associated
17495 // with C structs, unions, and enums when looking for a matching
17496 // tag declaration or definition. See the similar lookup tweak
17497 // in Sema::LookupName; is there a better way to deal with this?
17498 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17499 SearchDC = SearchDC->getParent();
17500 } else if (getLangOpts().CPlusPlus) {
17501 // Inside ObjCContainer want to keep it as a lexical decl context but go
17502 // past it (most often to TranslationUnit) to find the semantic decl
17503 // context.
17504 while (isa<ObjCContainerDecl>(SearchDC))
17505 SearchDC = SearchDC->getParent();
17506 }
17507 } else if (getLangOpts().CPlusPlus) {
17508 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17509 // TagDecl the same way as we skip it for named TagDecl.
17510 while (isa<ObjCContainerDecl>(SearchDC))
17511 SearchDC = SearchDC->getParent();
17512 }
17513
17514 if (Previous.isSingleResult() &&
17515 Previous.getFoundDecl()->isTemplateParameter()) {
17516 // Maybe we will complain about the shadowed template parameter.
17517 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17518 // Just pretend that we didn't see the previous declaration.
17519 Previous.clear();
17520 }
17521
17522 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17523 DC->Equals(getStdNamespace())) {
17524 if (Name->isStr("bad_alloc")) {
17525 // This is a declaration of or a reference to "std::bad_alloc".
17526 isStdBadAlloc = true;
17527
17528 // If std::bad_alloc has been implicitly declared (but made invisible to
17529 // name lookup), fill in this implicit declaration as the previous
17530 // declaration, so that the declarations get chained appropriately.
17531 if (Previous.empty() && StdBadAlloc)
17532 Previous.addDecl(getStdBadAlloc());
17533 } else if (Name->isStr("align_val_t")) {
17534 isStdAlignValT = true;
17535 if (Previous.empty() && StdAlignValT)
17536 Previous.addDecl(getStdAlignValT());
17537 }
17538 }
17539
17540 // If we didn't find a previous declaration, and this is a reference
17541 // (or friend reference), move to the correct scope. In C++, we
17542 // also need to do a redeclaration lookup there, just in case
17543 // there's a shadow friend decl.
17544 if (Name && Previous.empty() &&
17545 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17546 IsTemplateParamOrArg)) {
17547 if (Invalid) goto CreateNewDecl;
17548 assert(SS.isEmpty());
17549
17550 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17551 // C++ [basic.scope.pdecl]p5:
17552 // -- for an elaborated-type-specifier of the form
17553 //
17554 // class-key identifier
17555 //
17556 // if the elaborated-type-specifier is used in the
17557 // decl-specifier-seq or parameter-declaration-clause of a
17558 // function defined in namespace scope, the identifier is
17559 // declared as a class-name in the namespace that contains
17560 // the declaration; otherwise, except as a friend
17561 // declaration, the identifier is declared in the smallest
17562 // non-class, non-function-prototype scope that contains the
17563 // declaration.
17564 //
17565 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17566 // C structs and unions.
17567 //
17568 // It is an error in C++ to declare (rather than define) an enum
17569 // type, including via an elaborated type specifier. We'll
17570 // diagnose that later; for now, declare the enum in the same
17571 // scope as we would have picked for any other tag type.
17572 //
17573 // GNU C also supports this behavior as part of its incomplete
17574 // enum types extension, while GNU C++ does not.
17575 //
17576 // Find the context where we'll be declaring the tag.
17577 // FIXME: We would like to maintain the current DeclContext as the
17578 // lexical context,
17579 SearchDC = getTagInjectionContext(SearchDC);
17580
17581 // Find the scope where we'll be declaring the tag.
17583 } else {
17584 assert(TUK == TagUseKind::Friend);
17585 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17586
17587 // C++ [namespace.memdef]p3:
17588 // If a friend declaration in a non-local class first declares a
17589 // class or function, the friend class or function is a member of
17590 // the innermost enclosing namespace.
17591 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17592 : SearchDC->getEnclosingNamespaceContext();
17593 }
17594
17595 // In C++, we need to do a redeclaration lookup to properly
17596 // diagnose some problems.
17597 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17598 // hidden declaration so that we don't get ambiguity errors when using a
17599 // type declared by an elaborated-type-specifier. In C that is not correct
17600 // and we should instead merge compatible types found by lookup.
17601 if (getLangOpts().CPlusPlus) {
17602 // FIXME: This can perform qualified lookups into function contexts,
17603 // which are meaningless.
17604 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17605 LookupQualifiedName(Previous, SearchDC);
17606 } else {
17607 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17608 LookupName(Previous, S);
17609 }
17610 }
17611
17612 // If we have a known previous declaration to use, then use it.
17613 if (Previous.empty() && SkipBody && SkipBody->Previous)
17614 Previous.addDecl(SkipBody->Previous);
17615
17616 if (!Previous.empty()) {
17617 NamedDecl *PrevDecl = Previous.getFoundDecl();
17618 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17619
17620 // It's okay to have a tag decl in the same scope as a typedef
17621 // which hides a tag decl in the same scope. Finding this
17622 // with a redeclaration lookup can only actually happen in C++.
17623 //
17624 // This is also okay for elaborated-type-specifiers, which is
17625 // technically forbidden by the current standard but which is
17626 // okay according to the likely resolution of an open issue;
17627 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17628 if (getLangOpts().CPlusPlus) {
17629 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17630 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17631 TagDecl *Tag = TT->getDecl();
17632 if (Tag->getDeclName() == Name &&
17633 Tag->getDeclContext()->getRedeclContext()
17634 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17635 PrevDecl = Tag;
17636 Previous.clear();
17637 Previous.addDecl(Tag);
17638 Previous.resolveKind();
17639 }
17640 }
17641 }
17642 }
17643
17644 // If this is a redeclaration of a using shadow declaration, it must
17645 // declare a tag in the same context. In MSVC mode, we allow a
17646 // redefinition if either context is within the other.
17647 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17648 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17649 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
17650 TUK != TagUseKind::Friend &&
17651 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17652 !(OldTag && isAcceptableTagRedeclContext(
17653 *this, OldTag->getDeclContext(), SearchDC))) {
17654 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17655 Diag(Shadow->getTargetDecl()->getLocation(),
17656 diag::note_using_decl_target);
17657 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17658 << 0;
17659 // Recover by ignoring the old declaration.
17660 Previous.clear();
17661 goto CreateNewDecl;
17662 }
17663 }
17664
17665 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17666 // If this is a use of a previous tag, or if the tag is already declared
17667 // in the same scope (so that the definition/declaration completes or
17668 // rementions the tag), reuse the decl.
17669 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17670 isDeclInScope(DirectPrevDecl, SearchDC, S,
17671 SS.isNotEmpty() || isMemberSpecialization)) {
17672 // Make sure that this wasn't declared as an enum and now used as a
17673 // struct or something similar.
17674 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17675 TUK == TagUseKind::Definition, KWLoc,
17676 Name)) {
17677 bool SafeToContinue =
17678 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17679 Kind != TagTypeKind::Enum);
17680 if (SafeToContinue)
17681 Diag(KWLoc, diag::err_use_with_wrong_tag)
17682 << Name
17684 PrevTagDecl->getKindName());
17685 else
17686 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17687 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17688
17689 if (SafeToContinue)
17690 Kind = PrevTagDecl->getTagKind();
17691 else {
17692 // Recover by making this an anonymous redefinition.
17693 Name = nullptr;
17694 Previous.clear();
17695 Invalid = true;
17696 }
17697 }
17698
17699 if (Kind == TagTypeKind::Enum &&
17700 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17701 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17702 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
17703 return PrevTagDecl;
17704
17705 QualType EnumUnderlyingTy;
17706 if (TypeSourceInfo *TI =
17707 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
17708 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17709 else if (const Type *T =
17710 dyn_cast_if_present<const Type *>(EnumUnderlying))
17711 EnumUnderlyingTy = QualType(T, 0);
17712
17713 // All conflicts with previous declarations are recovered by
17714 // returning the previous declaration, unless this is a definition,
17715 // in which case we want the caller to bail out.
17716 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17717 ScopedEnum, EnumUnderlyingTy,
17718 IsFixed, PrevEnum))
17719 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
17720 }
17721
17722 // C++11 [class.mem]p1:
17723 // A member shall not be declared twice in the member-specification,
17724 // except that a nested class or member class template can be declared
17725 // and then later defined.
17726 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
17727 S->isDeclScope(PrevDecl)) {
17728 Diag(NameLoc, diag::ext_member_redeclared);
17729 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17730 }
17731
17732 if (!Invalid) {
17733 // If this is a use, just return the declaration we found, unless
17734 // we have attributes.
17735 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17736 if (!Attrs.empty()) {
17737 // FIXME: Diagnose these attributes. For now, we create a new
17738 // declaration to hold them.
17739 } else if (TUK == TagUseKind::Reference &&
17740 (PrevTagDecl->getFriendObjectKind() ==
17742 PrevDecl->getOwningModule() != getCurrentModule()) &&
17743 SS.isEmpty()) {
17744 // This declaration is a reference to an existing entity, but
17745 // has different visibility from that entity: it either makes
17746 // a friend visible or it makes a type visible in a new module.
17747 // In either case, create a new declaration. We only do this if
17748 // the declaration would have meant the same thing if no prior
17749 // declaration were found, that is, if it was found in the same
17750 // scope where we would have injected a declaration.
17751 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17752 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17753 return PrevTagDecl;
17754 // This is in the injected scope, create a new declaration in
17755 // that scope.
17757 } else {
17758 return PrevTagDecl;
17759 }
17760 }
17761
17762 // Diagnose attempts to redefine a tag.
17763 if (TUK == TagUseKind::Definition) {
17764 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17765 // If we're defining a specialization and the previous definition
17766 // is from an implicit instantiation, don't emit an error
17767 // here; we'll catch this in the general case below.
17768 bool IsExplicitSpecializationAfterInstantiation = false;
17769 if (isMemberSpecialization) {
17770 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17771 IsExplicitSpecializationAfterInstantiation =
17772 RD->getTemplateSpecializationKind() !=
17774 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17775 IsExplicitSpecializationAfterInstantiation =
17776 ED->getTemplateSpecializationKind() !=
17778 }
17779
17780 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17781 // not keep more that one definition around (merge them). However,
17782 // ensure the decl passes the structural compatibility check in
17783 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17784 NamedDecl *Hidden = nullptr;
17785 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17786 // There is a definition of this tag, but it is not visible. We
17787 // explicitly make use of C++'s one definition rule here, and
17788 // assume that this definition is identical to the hidden one
17789 // we already have. Make the existing definition visible and
17790 // use it in place of this one.
17791 if (!getLangOpts().CPlusPlus) {
17792 // Postpone making the old definition visible until after we
17793 // complete parsing the new one and do the structural
17794 // comparison.
17795 SkipBody->CheckSameAsPrevious = true;
17796 SkipBody->New = createTagFromNewDecl();
17797 SkipBody->Previous = Def;
17798 return Def;
17799 } else {
17800 SkipBody->ShouldSkip = true;
17801 SkipBody->Previous = Def;
17803 // Carry on and handle it like a normal definition. We'll
17804 // skip starting the definition later.
17805 }
17806 } else if (!IsExplicitSpecializationAfterInstantiation) {
17807 // A redeclaration in function prototype scope in C isn't
17808 // visible elsewhere, so merely issue a warning.
17809 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17810 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17811 else
17812 Diag(NameLoc, diag::err_redefinition) << Name;
17814 NameLoc.isValid() ? NameLoc : KWLoc);
17815 // If this is a redefinition, recover by making this
17816 // struct be anonymous, which will make any later
17817 // references get the previous definition.
17818 Name = nullptr;
17819 Previous.clear();
17820 Invalid = true;
17821 }
17822 } else {
17823 // If the type is currently being defined, complain
17824 // about a nested redefinition.
17825 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17826 if (TD->isBeingDefined()) {
17827 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17828 Diag(PrevTagDecl->getLocation(),
17829 diag::note_previous_definition);
17830 Name = nullptr;
17831 Previous.clear();
17832 Invalid = true;
17833 }
17834 }
17835
17836 // Okay, this is definition of a previously declared or referenced
17837 // tag. We're going to create a new Decl for it.
17838 }
17839
17840 // Okay, we're going to make a redeclaration. If this is some kind
17841 // of reference, make sure we build the redeclaration in the same DC
17842 // as the original, and ignore the current access specifier.
17843 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17844 SearchDC = PrevTagDecl->getDeclContext();
17845 AS = AS_none;
17846 }
17847 }
17848 // If we get here we have (another) forward declaration or we
17849 // have a definition. Just create a new decl.
17850
17851 } else {
17852 // If we get here, this is a definition of a new tag type in a nested
17853 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17854 // new decl/type. We set PrevDecl to NULL so that the entities
17855 // have distinct types.
17856 Previous.clear();
17857 }
17858 // If we get here, we're going to create a new Decl. If PrevDecl
17859 // is non-NULL, it's a definition of the tag declared by
17860 // PrevDecl. If it's NULL, we have a new definition.
17861
17862 // Otherwise, PrevDecl is not a tag, but was found with tag
17863 // lookup. This is only actually possible in C++, where a few
17864 // things like templates still live in the tag namespace.
17865 } else {
17866 // Use a better diagnostic if an elaborated-type-specifier
17867 // found the wrong kind of type on the first
17868 // (non-redeclaration) lookup.
17869 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
17870 !Previous.isForRedeclaration()) {
17871 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17872 Diag(NameLoc, diag::err_tag_reference_non_tag)
17873 << PrevDecl << NTK << llvm::to_underlying(Kind);
17874 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17875 Invalid = true;
17876
17877 // Otherwise, only diagnose if the declaration is in scope.
17878 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17879 SS.isNotEmpty() || isMemberSpecialization)) {
17880 // do nothing
17881
17882 // Diagnose implicit declarations introduced by elaborated types.
17883 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17884 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17885 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17886 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17887 Invalid = true;
17888
17889 // Otherwise it's a declaration. Call out a particularly common
17890 // case here.
17891 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17892 unsigned Kind = 0;
17893 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17894 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17895 << Name << Kind << TND->getUnderlyingType();
17896 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17897 Invalid = true;
17898
17899 // Otherwise, diagnose.
17900 } else {
17901 // The tag name clashes with something else in the target scope,
17902 // issue an error and recover by making this tag be anonymous.
17903 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17904 notePreviousDefinition(PrevDecl, NameLoc);
17905 Name = nullptr;
17906 Invalid = true;
17907 }
17908
17909 // The existing declaration isn't relevant to us; we're in a
17910 // new scope, so clear out the previous declaration.
17911 Previous.clear();
17912 }
17913 }
17914
17915CreateNewDecl:
17916
17917 TagDecl *PrevDecl = nullptr;
17918 if (Previous.isSingleResult())
17919 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17920
17921 // If there is an identifier, use the location of the identifier as the
17922 // location of the decl, otherwise use the location of the struct/union
17923 // keyword.
17924 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17925
17926 // Otherwise, create a new declaration. If there is a previous
17927 // declaration of the same entity, the two will be linked via
17928 // PrevDecl.
17929 TagDecl *New;
17930
17931 if (Kind == TagTypeKind::Enum) {
17932 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17933 // enum X { A, B, C } D; D should chain to X.
17934 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17935 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17936 ScopedEnumUsesClassTag, IsFixed);
17937
17938 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17939 StdAlignValT = cast<EnumDecl>(New);
17940
17941 // If this is an undefined enum, warn.
17942 if (TUK != TagUseKind::Definition && !Invalid) {
17943 TagDecl *Def;
17944 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17945 // C++0x: 7.2p2: opaque-enum-declaration.
17946 // Conflicts are diagnosed above. Do nothing.
17947 }
17948 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17949 Diag(Loc, diag::ext_forward_ref_enum_def)
17950 << New;
17951 Diag(Def->getLocation(), diag::note_previous_definition);
17952 } else {
17953 unsigned DiagID = diag::ext_forward_ref_enum;
17954 if (getLangOpts().MSVCCompat)
17955 DiagID = diag::ext_ms_forward_ref_enum;
17956 else if (getLangOpts().CPlusPlus)
17957 DiagID = diag::err_forward_ref_enum;
17958 Diag(Loc, DiagID);
17959 }
17960 }
17961
17962 if (EnumUnderlying) {
17963 EnumDecl *ED = cast<EnumDecl>(New);
17964 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17966 else
17967 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17968 QualType EnumTy = ED->getIntegerType();
17971 : EnumTy);
17972 assert(ED->isComplete() && "enum with type should be complete");
17973 }
17974 } else {
17975 // struct/union/class
17976
17977 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17978 // struct X { int A; } D; D should chain to X.
17979 if (getLangOpts().CPlusPlus) {
17980 // FIXME: Look for a way to use RecordDecl for simple structs.
17981 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17982 cast_or_null<CXXRecordDecl>(PrevDecl));
17983
17984 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17985 StdBadAlloc = cast<CXXRecordDecl>(New);
17986 } else
17987 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17988 cast_or_null<RecordDecl>(PrevDecl));
17989 }
17990
17991 // Only C23 and later allow defining new types in 'offsetof()'.
17992 if (OOK != OOK_Outside && TUK == TagUseKind::Definition &&
17994 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17995 << (OOK == OOK_Macro) << New->getSourceRange();
17996
17997 // C++11 [dcl.type]p3:
17998 // A type-specifier-seq shall not define a class or enumeration [...].
17999 if (!Invalid && getLangOpts().CPlusPlus &&
18000 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18001 TUK == TagUseKind::Definition) {
18002 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18003 << Context.getTagDeclType(New);
18004 Invalid = true;
18005 }
18006
18008 DC->getDeclKind() == Decl::Enum) {
18009 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18010 << Context.getTagDeclType(New);
18011 Invalid = true;
18012 }
18013
18014 // Maybe add qualifier info.
18015 if (SS.isNotEmpty()) {
18016 if (SS.isSet()) {
18017 // If this is either a declaration or a definition, check the
18018 // nested-name-specifier against the current context.
18019 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18020 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18021 /*TemplateId=*/nullptr,
18022 isMemberSpecialization))
18023 Invalid = true;
18024
18026 if (TemplateParameterLists.size() > 0) {
18027 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18028 }
18029 }
18030 else
18031 Invalid = true;
18032 }
18033
18034 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18035 // Add alignment attributes if necessary; these attributes are checked when
18036 // the ASTContext lays out the structure.
18037 //
18038 // It is important for implementing the correct semantics that this
18039 // happen here (in ActOnTag). The #pragma pack stack is
18040 // maintained as a result of parser callbacks which can occur at
18041 // many points during the parsing of a struct declaration (because
18042 // the #pragma tokens are effectively skipped over during the
18043 // parsing of the struct).
18044 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18047 }
18048 }
18049
18050 if (ModulePrivateLoc.isValid()) {
18051 if (isMemberSpecialization)
18052 Diag(New->getLocation(), diag::err_module_private_specialization)
18053 << 2
18054 << FixItHint::CreateRemoval(ModulePrivateLoc);
18055 // __module_private__ does not apply to local classes. However, we only
18056 // diagnose this as an error when the declaration specifiers are
18057 // freestanding. Here, we just ignore the __module_private__.
18058 else if (!SearchDC->isFunctionOrMethod())
18059 New->setModulePrivate();
18060 }
18061
18062 // If this is a specialization of a member class (of a class template),
18063 // check the specialization.
18064 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18065 Invalid = true;
18066
18067 // If we're declaring or defining a tag in function prototype scope in C,
18068 // note that this type can only be used within the function and add it to
18069 // the list of decls to inject into the function definition scope.
18070 if ((Name || Kind == TagTypeKind::Enum) &&
18071 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18072 if (getLangOpts().CPlusPlus) {
18073 // C++ [dcl.fct]p6:
18074 // Types shall not be defined in return or parameter types.
18075 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18076 Diag(Loc, diag::err_type_defined_in_param_type)
18077 << Name;
18078 Invalid = true;
18079 }
18080 if (TUK == TagUseKind::Declaration)
18081 Invalid = true;
18082 } else if (!PrevDecl) {
18083 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
18084 }
18085 }
18086
18087 if (Invalid)
18088 New->setInvalidDecl();
18089
18090 // Set the lexical context. If the tag has a C++ scope specifier, the
18091 // lexical context will be different from the semantic context.
18093
18094 // Mark this as a friend decl if applicable.
18095 // In Microsoft mode, a friend declaration also acts as a forward
18096 // declaration so we always pass true to setObjectOfFriendDecl to make
18097 // the tag name visible.
18098 if (TUK == TagUseKind::Friend)
18099 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18100
18101 // Set the access specifier.
18102 if (!Invalid && SearchDC->isRecord())
18103 SetMemberAccessSpecifier(New, PrevDecl, AS);
18104
18105 if (PrevDecl)
18106 CheckRedeclarationInModule(New, PrevDecl);
18107
18108 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
18109 New->startDefinition();
18110
18111 ProcessDeclAttributeList(S, New, Attrs);
18112 AddPragmaAttributes(S, New);
18113
18114 // If this has an identifier, add it to the scope stack.
18115 if (TUK == TagUseKind::Friend) {
18116 // We might be replacing an existing declaration in the lookup tables;
18117 // if so, borrow its access specifier.
18118 if (PrevDecl)
18119 New->setAccess(PrevDecl->getAccess());
18120
18122 DC->makeDeclVisibleInContext(New);
18123 if (Name) // can be null along some error paths
18124 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18125 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18126 } else if (Name) {
18127 S = getNonFieldDeclScope(S);
18128 PushOnScopeChains(New, S, true);
18129 } else {
18130 CurContext->addDecl(New);
18131 }
18132
18133 // If this is the C FILE type, notify the AST context.
18134 if (IdentifierInfo *II = New->getIdentifier())
18135 if (!New->isInvalidDecl() &&
18137 II->isStr("FILE"))
18138 Context.setFILEDecl(New);
18139
18140 if (PrevDecl)
18141 mergeDeclAttributes(New, PrevDecl);
18142
18143 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18146 }
18147
18148 // If there's a #pragma GCC visibility in scope, set the visibility of this
18149 // record.
18151
18152 if (isMemberSpecialization && !New->isInvalidDecl())
18154
18155 OwnedDecl = true;
18156 // In C++, don't return an invalid declaration. We can't recover well from
18157 // the cases where we make the type anonymous.
18158 if (Invalid && getLangOpts().CPlusPlus) {
18159 if (New->isBeingDefined())
18160 if (auto RD = dyn_cast<RecordDecl>(New))
18161 RD->completeDefinition();
18162 return true;
18163 } else if (SkipBody && SkipBody->ShouldSkip) {
18164 return SkipBody->Previous;
18165 } else {
18166 return New;
18167 }
18168}
18169
18172 TagDecl *Tag = cast<TagDecl>(TagD);
18173
18174 // Enter the tag context.
18175 PushDeclContext(S, Tag);
18176
18178
18179 // If there's a #pragma GCC visibility in scope, set the visibility of this
18180 // record.
18182}
18183
18185 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18186 return false;
18187
18188 // Make the previous decl visible.
18190 return true;
18191}
18192
18194 SourceLocation FinalLoc,
18195 bool IsFinalSpelledSealed,
18196 bool IsAbstract,
18197 SourceLocation LBraceLoc) {
18199 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18200
18201 FieldCollector->StartClass();
18202
18203 if (!Record->getIdentifier())
18204 return;
18205
18206 if (IsAbstract)
18207 Record->markAbstract();
18208
18209 if (FinalLoc.isValid()) {
18210 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18211 IsFinalSpelledSealed
18212 ? FinalAttr::Keyword_sealed
18213 : FinalAttr::Keyword_final));
18214 }
18215 // C++ [class]p2:
18216 // [...] The class-name is also inserted into the scope of the
18217 // class itself; this is known as the injected-class-name. For
18218 // purposes of access checking, the injected-class-name is treated
18219 // as if it were a public member name.
18220 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18221 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18222 Record->getLocation(), Record->getIdentifier(),
18223 /*PrevDecl=*/nullptr,
18224 /*DelayTypeCreation=*/true);
18225 Context.getTypeDeclType(InjectedClassName, Record);
18226 InjectedClassName->setImplicit();
18227 InjectedClassName->setAccess(AS_public);
18228 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18229 InjectedClassName->setDescribedClassTemplate(Template);
18230 PushOnScopeChains(InjectedClassName, S);
18231 assert(InjectedClassName->isInjectedClassName() &&
18232 "Broken injected-class-name");
18233}
18234
18236 SourceRange BraceRange) {
18238 TagDecl *Tag = cast<TagDecl>(TagD);
18239 Tag->setBraceRange(BraceRange);
18240
18241 // Make sure we "complete" the definition even it is invalid.
18242 if (Tag->isBeingDefined()) {
18243 assert(Tag->isInvalidDecl() && "We should already have completed it");
18244 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18245 RD->completeDefinition();
18246 }
18247
18248 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18249 FieldCollector->FinishClass();
18250 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18251 auto *Def = RD->getDefinition();
18252 assert(Def && "The record is expected to have a completed definition");
18253 unsigned NumInitMethods = 0;
18254 for (auto *Method : Def->methods()) {
18255 if (!Method->getIdentifier())
18256 continue;
18257 if (Method->getName() == "__init")
18258 NumInitMethods++;
18259 }
18260 if (NumInitMethods > 1 || !Def->hasInitMethod())
18261 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18262 }
18263
18264 // If we're defining a dynamic class in a module interface unit, we always
18265 // need to produce the vtable for it, even if the vtable is not used in the
18266 // current TU.
18267 //
18268 // The case where the current class is not dynamic is handled in
18269 // MarkVTableUsed.
18270 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18271 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18272 }
18273
18274 // Exit this scope of this tag's definition.
18276
18277 if (getCurLexicalContext()->isObjCContainer() &&
18278 Tag->getDeclContext()->isFileContext())
18279 Tag->setTopLevelDeclInObjCContainer();
18280
18281 // Notify the consumer that we've defined a tag.
18282 if (!Tag->isInvalidDecl())
18284
18285 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18286 // from XLs and instead matches the XL #pragma pack(1) behavior.
18287 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18288 AlignPackStack.hasValue()) {
18289 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18290 // Only diagnose #pragma align(packed).
18291 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18292 return;
18293 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18294 if (!RD)
18295 return;
18296 // Only warn if there is at least 1 bitfield member.
18297 if (llvm::any_of(RD->fields(),
18298 [](const FieldDecl *FD) { return FD->isBitField(); }))
18299 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18300 }
18301}
18302
18305 TagDecl *Tag = cast<TagDecl>(TagD);
18306 Tag->setInvalidDecl();
18307
18308 // Make sure we "complete" the definition even it is invalid.
18309 if (Tag->isBeingDefined()) {
18310 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18311 RD->completeDefinition();
18312 }
18313
18314 // We're undoing ActOnTagStartDefinition here, not
18315 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18316 // the FieldCollector.
18317
18319}
18320
18321// Note that FieldName may be null for anonymous bitfields.
18323 const IdentifierInfo *FieldName,
18324 QualType FieldTy, bool IsMsStruct,
18325 Expr *BitWidth) {
18326 assert(BitWidth);
18327 if (BitWidth->containsErrors())
18328 return ExprError();
18329
18330 // C99 6.7.2.1p4 - verify the field type.
18331 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18332 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18333 // Handle incomplete and sizeless types with a specific error.
18334 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18335 diag::err_field_incomplete_or_sizeless))
18336 return ExprError();
18337 if (FieldName)
18338 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18339 << FieldName << FieldTy << BitWidth->getSourceRange();
18340 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18341 << FieldTy << BitWidth->getSourceRange();
18342 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18344 return ExprError();
18345
18346 // If the bit-width is type- or value-dependent, don't try to check
18347 // it now.
18348 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18349 return BitWidth;
18350
18351 llvm::APSInt Value;
18353 if (ICE.isInvalid())
18354 return ICE;
18355 BitWidth = ICE.get();
18356
18357 // Zero-width bitfield is ok for anonymous field.
18358 if (Value == 0 && FieldName)
18359 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18360 << FieldName << BitWidth->getSourceRange();
18361
18362 if (Value.isSigned() && Value.isNegative()) {
18363 if (FieldName)
18364 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18365 << FieldName << toString(Value, 10);
18366 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18367 << toString(Value, 10);
18368 }
18369
18370 // The size of the bit-field must not exceed our maximum permitted object
18371 // size.
18372 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18373 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18374 << !FieldName << FieldName << toString(Value, 10);
18375 }
18376
18377 if (!FieldTy->isDependentType()) {
18378 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18379 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18380 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18381
18382 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18383 // ABI.
18384 bool CStdConstraintViolation =
18385 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18386 bool MSBitfieldViolation =
18387 Value.ugt(TypeStorageSize) &&
18388 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18389 if (CStdConstraintViolation || MSBitfieldViolation) {
18390 unsigned DiagWidth =
18391 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18392 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18393 << (bool)FieldName << FieldName << toString(Value, 10)
18394 << !CStdConstraintViolation << DiagWidth;
18395 }
18396
18397 // Warn on types where the user might conceivably expect to get all
18398 // specified bits as value bits: that's all integral types other than
18399 // 'bool'.
18400 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18401 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18402 << FieldName << toString(Value, 10)
18403 << (unsigned)TypeWidth;
18404 }
18405 }
18406
18407 if (isa<ConstantExpr>(BitWidth))
18408 return BitWidth;
18409 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
18410}
18411
18413 Declarator &D, Expr *BitfieldWidth) {
18414 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18415 D, BitfieldWidth,
18416 /*InitStyle=*/ICIS_NoInit, AS_public);
18417 return Res;
18418}
18419
18421 SourceLocation DeclStart,
18422 Declarator &D, Expr *BitWidth,
18423 InClassInitStyle InitStyle,
18424 AccessSpecifier AS) {
18425 if (D.isDecompositionDeclarator()) {
18426 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18427 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18428 << Decomp.getSourceRange();
18429 return nullptr;
18430 }
18431
18432 const IdentifierInfo *II = D.getIdentifier();
18433 SourceLocation Loc = DeclStart;
18434 if (II) Loc = D.getIdentifierLoc();
18435
18437 QualType T = TInfo->getType();
18438 if (getLangOpts().CPlusPlus) {
18440
18441 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18443 D.setInvalidType();
18444 T = Context.IntTy;
18446 }
18447 }
18448
18449 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18450
18451 if (D.getDeclSpec().isInlineSpecified())
18452 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18453 << getLangOpts().CPlusPlus17;
18454 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18455 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18456 diag::err_invalid_thread)
18458
18459 // Check to see if this name was declared as a member previously
18460 NamedDecl *PrevDecl = nullptr;
18462 RedeclarationKind::ForVisibleRedeclaration);
18463 LookupName(Previous, S);
18464 switch (Previous.getResultKind()) {
18467 PrevDecl = Previous.getAsSingle<NamedDecl>();
18468 break;
18469
18471 PrevDecl = Previous.getRepresentativeDecl();
18472 break;
18473
18477 break;
18478 }
18479 Previous.suppressDiagnostics();
18480
18481 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18482 // Maybe we will complain about the shadowed template parameter.
18483 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18484 // Just pretend that we didn't see the previous declaration.
18485 PrevDecl = nullptr;
18486 }
18487
18488 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18489 PrevDecl = nullptr;
18490
18491 bool Mutable
18492 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18493 SourceLocation TSSL = D.getBeginLoc();
18494 FieldDecl *NewFD
18495 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18496 TSSL, AS, PrevDecl, &D);
18497
18498 if (NewFD->isInvalidDecl())
18499 Record->setInvalidDecl();
18500
18501 if (D.getDeclSpec().isModulePrivateSpecified())
18502 NewFD->setModulePrivate();
18503
18504 if (NewFD->isInvalidDecl() && PrevDecl) {
18505 // Don't introduce NewFD into scope; there's already something
18506 // with the same name in the same scope.
18507 } else if (II) {
18508 PushOnScopeChains(NewFD, S);
18509 } else
18510 Record->addDecl(NewFD);
18511
18512 return NewFD;
18513}
18514
18516 TypeSourceInfo *TInfo,
18518 bool Mutable, Expr *BitWidth,
18519 InClassInitStyle InitStyle,
18520 SourceLocation TSSL,
18521 AccessSpecifier AS, NamedDecl *PrevDecl,
18522 Declarator *D) {
18523 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18524 bool InvalidDecl = false;
18525 if (D) InvalidDecl = D->isInvalidType();
18526
18527 // If we receive a broken type, recover by assuming 'int' and
18528 // marking this declaration as invalid.
18529 if (T.isNull() || T->containsErrors()) {
18530 InvalidDecl = true;
18531 T = Context.IntTy;
18532 }
18533
18535 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18536 bool isIncomplete =
18537 LangOpts.HLSL // HLSL allows sizeless builtin types
18538 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
18540 diag::err_field_incomplete_or_sizeless);
18541 if (isIncomplete) {
18542 // Fields of incomplete type force their record to be invalid.
18543 Record->setInvalidDecl();
18544 InvalidDecl = true;
18545 } else {
18546 NamedDecl *Def;
18547 EltTy->isIncompleteType(&Def);
18548 if (Def && Def->isInvalidDecl()) {
18549 Record->setInvalidDecl();
18550 InvalidDecl = true;
18551 }
18552 }
18553 }
18554
18555 // TR 18037 does not allow fields to be declared with address space
18556 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18558 Diag(Loc, diag::err_field_with_address_space);
18559 Record->setInvalidDecl();
18560 InvalidDecl = true;
18561 }
18562
18563 if (LangOpts.OpenCL) {
18564 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18565 // used as structure or union field: image, sampler, event or block types.
18566 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18567 T->isBlockPointerType()) {
18568 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18569 Record->setInvalidDecl();
18570 InvalidDecl = true;
18571 }
18572 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18573 // is enabled.
18574 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18575 "__cl_clang_bitfields", LangOpts)) {
18576 Diag(Loc, diag::err_opencl_bitfields);
18577 InvalidDecl = true;
18578 }
18579 }
18580
18581 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18582 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18583 T.hasQualifiers()) {
18584 InvalidDecl = true;
18585 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18586 }
18587
18588 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18589 // than a variably modified type.
18590 if (!InvalidDecl && T->isVariablyModifiedType()) {
18592 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18593 InvalidDecl = true;
18594 }
18595
18596 // Fields can not have abstract class types
18597 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18598 diag::err_abstract_type_in_decl,
18600 InvalidDecl = true;
18601
18602 if (InvalidDecl)
18603 BitWidth = nullptr;
18604 // If this is declared as a bit-field, check the bit-field.
18605 if (BitWidth) {
18606 BitWidth =
18607 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18608 if (!BitWidth) {
18609 InvalidDecl = true;
18610 BitWidth = nullptr;
18611 }
18612 }
18613
18614 // Check that 'mutable' is consistent with the type of the declaration.
18615 if (!InvalidDecl && Mutable) {
18616 unsigned DiagID = 0;
18617 if (T->isReferenceType())
18618 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18619 : diag::err_mutable_reference;
18620 else if (T.isConstQualified())
18621 DiagID = diag::err_mutable_const;
18622
18623 if (DiagID) {
18624 SourceLocation ErrLoc = Loc;
18625 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18626 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18627 Diag(ErrLoc, DiagID);
18628 if (DiagID != diag::ext_mutable_reference) {
18629 Mutable = false;
18630 InvalidDecl = true;
18631 }
18632 }
18633 }
18634
18635 // C++11 [class.union]p8 (DR1460):
18636 // At most one variant member of a union may have a
18637 // brace-or-equal-initializer.
18638 if (InitStyle != ICIS_NoInit)
18639 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18640
18641 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18642 BitWidth, Mutable, InitStyle);
18643 if (InvalidDecl)
18644 NewFD->setInvalidDecl();
18645
18646 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18647 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18648 Diag(Loc, diag::err_duplicate_member) << II;
18649 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18650 NewFD->setInvalidDecl();
18651 }
18652
18653 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18654 if (Record->isUnion()) {
18655 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18656 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18657 if (RDecl->getDefinition()) {
18658 // C++ [class.union]p1: An object of a class with a non-trivial
18659 // constructor, a non-trivial copy constructor, a non-trivial
18660 // destructor, or a non-trivial copy assignment operator
18661 // cannot be a member of a union, nor can an array of such
18662 // objects.
18663 if (CheckNontrivialField(NewFD))
18664 NewFD->setInvalidDecl();
18665 }
18666 }
18667
18668 // C++ [class.union]p1: If a union contains a member of reference type,
18669 // the program is ill-formed, except when compiling with MSVC extensions
18670 // enabled.
18671 if (EltTy->isReferenceType()) {
18672 const bool HaveMSExt =
18673 getLangOpts().MicrosoftExt &&
18675
18676 Diag(NewFD->getLocation(),
18677 HaveMSExt ? diag::ext_union_member_of_reference_type
18678 : diag::err_union_member_of_reference_type)
18679 << NewFD->getDeclName() << EltTy;
18680 if (!HaveMSExt)
18681 NewFD->setInvalidDecl();
18682 }
18683 }
18684 }
18685
18686 // FIXME: We need to pass in the attributes given an AST
18687 // representation, not a parser representation.
18688 if (D) {
18689 // FIXME: The current scope is almost... but not entirely... correct here.
18691
18692 if (NewFD->hasAttrs())
18694 }
18695
18696 // In auto-retain/release, infer strong retension for fields of
18697 // retainable type.
18698 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
18699 NewFD->setInvalidDecl();
18700
18701 if (T.isObjCGCWeak())
18702 Diag(Loc, diag::warn_attribute_weak_on_field);
18703
18704 // PPC MMA non-pointer types are not allowed as field types.
18705 if (Context.getTargetInfo().getTriple().isPPC64() &&
18706 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
18707 NewFD->setInvalidDecl();
18708
18709 NewFD->setAccess(AS);
18710 return NewFD;
18711}
18712
18714 assert(FD);
18715 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18716
18717 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18718 return false;
18719
18721 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18722 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18723 if (RDecl->getDefinition()) {
18724 // We check for copy constructors before constructors
18725 // because otherwise we'll never get complaints about
18726 // copy constructors.
18727
18729 // We're required to check for any non-trivial constructors. Since the
18730 // implicit default constructor is suppressed if there are any
18731 // user-declared constructors, we just need to check that there is a
18732 // trivial default constructor and a trivial copy constructor. (We don't
18733 // worry about move constructors here, since this is a C++98 check.)
18734 if (RDecl->hasNonTrivialCopyConstructor())
18736 else if (!RDecl->hasTrivialDefaultConstructor())
18738 else if (RDecl->hasNonTrivialCopyAssignment())
18740 else if (RDecl->hasNonTrivialDestructor())
18742
18743 if (member != CXXSpecialMemberKind::Invalid) {
18744 if (!getLangOpts().CPlusPlus11 &&
18745 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18746 // Objective-C++ ARC: it is an error to have a non-trivial field of
18747 // a union. However, system headers in Objective-C programs
18748 // occasionally have Objective-C lifetime objects within unions,
18749 // and rather than cause the program to fail, we make those
18750 // members unavailable.
18752 if (getSourceManager().isInSystemHeader(Loc)) {
18753 if (!FD->hasAttr<UnavailableAttr>())
18754 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18755 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18756 return false;
18757 }
18758 }
18759
18760 Diag(
18761 FD->getLocation(),
18763 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
18764 : diag::err_illegal_union_or_anon_struct_member)
18765 << FD->getParent()->isUnion() << FD->getDeclName()
18766 << llvm::to_underlying(member);
18767 DiagnoseNontrivial(RDecl, member);
18768 return !getLangOpts().CPlusPlus11;
18769 }
18770 }
18771 }
18772
18773 return false;
18774}
18775
18777 SmallVectorImpl<Decl *> &AllIvarDecls) {
18778 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18779 return;
18780
18781 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18782 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18783
18784 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
18785 return;
18786 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18787 if (!ID) {
18788 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18789 if (!CD->IsClassExtension())
18790 return;
18791 }
18792 // No need to add this to end of @implementation.
18793 else
18794 return;
18795 }
18796 // All conditions are met. Add a new bitfield to the tail end of ivars.
18797 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18798 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18799 Expr *BitWidth =
18800 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
18801
18802 Ivar = ObjCIvarDecl::Create(
18803 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
18805 ObjCIvarDecl::Private, BitWidth, true);
18806 AllIvarDecls.push_back(Ivar);
18807}
18808
18809/// [class.dtor]p4:
18810/// At the end of the definition of a class, overload resolution is
18811/// performed among the prospective destructors declared in that class with
18812/// an empty argument list to select the destructor for the class, also
18813/// known as the selected destructor.
18814///
18815/// We do the overload resolution here, then mark the selected constructor in the AST.
18816/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18818 if (!Record->hasUserDeclaredDestructor()) {
18819 return;
18820 }
18821
18822 SourceLocation Loc = Record->getLocation();
18824
18825 for (auto *Decl : Record->decls()) {
18826 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18827 if (DD->isInvalidDecl())
18828 continue;
18829 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18830 OCS);
18831 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18832 }
18833 }
18834
18835 if (OCS.empty()) {
18836 return;
18837 }
18839 unsigned Msg = 0;
18840 OverloadCandidateDisplayKind DisplayKind;
18841
18842 switch (OCS.BestViableFunction(S, Loc, Best)) {
18843 case OR_Success:
18844 case OR_Deleted:
18845 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18846 break;
18847
18848 case OR_Ambiguous:
18849 Msg = diag::err_ambiguous_destructor;
18850 DisplayKind = OCD_AmbiguousCandidates;
18851 break;
18852
18854 Msg = diag::err_no_viable_destructor;
18855 DisplayKind = OCD_AllCandidates;
18856 break;
18857 }
18858
18859 if (Msg) {
18860 // OpenCL have got their own thing going with destructors. It's slightly broken,
18861 // but we allow it.
18862 if (!S.LangOpts.OpenCL) {
18863 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18864 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18865 Record->setInvalidDecl();
18866 }
18867 // It's a bit hacky: At this point we've raised an error but we want the
18868 // rest of the compiler to continue somehow working. However almost
18869 // everything we'll try to do with the class will depend on there being a
18870 // destructor. So let's pretend the first one is selected and hope for the
18871 // best.
18872 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18873 }
18874}
18875
18876/// [class.mem.special]p5
18877/// Two special member functions are of the same kind if:
18878/// - they are both default constructors,
18879/// - they are both copy or move constructors with the same first parameter
18880/// type, or
18881/// - they are both copy or move assignment operators with the same first
18882/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18884 CXXMethodDecl *M1,
18885 CXXMethodDecl *M2,
18887 // We don't want to compare templates to non-templates: See
18888 // https://github.com/llvm/llvm-project/issues/59206
18890 return bool(M1->getDescribedFunctionTemplate()) ==
18892 // FIXME: better resolve CWG
18893 // https://cplusplus.github.io/CWG/issues/2787.html
18894 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18895 M2->getNonObjectParameter(0)->getType()))
18896 return false;
18899 return false;
18900
18901 return true;
18902}
18903
18904/// [class.mem.special]p6:
18905/// An eligible special member function is a special member function for which:
18906/// - the function is not deleted,
18907/// - the associated constraints, if any, are satisfied, and
18908/// - no special member function of the same kind whose associated constraints
18909/// [CWG2595], if any, are satisfied is more constrained.
18913 SmallVector<bool, 4> SatisfactionStatus;
18914
18915 for (CXXMethodDecl *Method : Methods) {
18916 const Expr *Constraints = Method->getTrailingRequiresClause();
18917 if (!Constraints)
18918 SatisfactionStatus.push_back(true);
18919 else {
18920 ConstraintSatisfaction Satisfaction;
18921 if (S.CheckFunctionConstraints(Method, Satisfaction))
18922 SatisfactionStatus.push_back(false);
18923 else
18924 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18925 }
18926 }
18927
18928 for (size_t i = 0; i < Methods.size(); i++) {
18929 if (!SatisfactionStatus[i])
18930 continue;
18931 CXXMethodDecl *Method = Methods[i];
18932 CXXMethodDecl *OrigMethod = Method;
18933 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18934 OrigMethod = cast<CXXMethodDecl>(MF);
18935
18936 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18937 bool AnotherMethodIsMoreConstrained = false;
18938 for (size_t j = 0; j < Methods.size(); j++) {
18939 if (i == j || !SatisfactionStatus[j])
18940 continue;
18941 CXXMethodDecl *OtherMethod = Methods[j];
18942 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18943 OtherMethod = cast<CXXMethodDecl>(MF);
18944
18945 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18946 CSM))
18947 continue;
18948
18949 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18950 if (!OtherConstraints)
18951 continue;
18952 if (!Constraints) {
18953 AnotherMethodIsMoreConstrained = true;
18954 break;
18955 }
18956 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18957 {Constraints},
18958 AnotherMethodIsMoreConstrained)) {
18959 // There was an error with the constraints comparison. Exit the loop
18960 // and don't consider this function eligible.
18961 AnotherMethodIsMoreConstrained = true;
18962 }
18963 if (AnotherMethodIsMoreConstrained)
18964 break;
18965 }
18966 // FIXME: Do not consider deleted methods as eligible after implementing
18967 // DR1734 and DR1496.
18968 if (!AnotherMethodIsMoreConstrained) {
18969 Method->setIneligibleOrNotSelected(false);
18970 Record->addedEligibleSpecialMemberFunction(Method,
18971 1 << llvm::to_underlying(CSM));
18972 }
18973 }
18974}
18975
18978 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18979 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18980 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18981 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18982 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18983
18984 for (auto *Decl : Record->decls()) {
18985 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18986 if (!MD) {
18987 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18988 if (FTD)
18989 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18990 }
18991 if (!MD)
18992 continue;
18993 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18994 if (CD->isInvalidDecl())
18995 continue;
18996 if (CD->isDefaultConstructor())
18997 DefaultConstructors.push_back(MD);
18998 else if (CD->isCopyConstructor())
18999 CopyConstructors.push_back(MD);
19000 else if (CD->isMoveConstructor())
19001 MoveConstructors.push_back(MD);
19002 } else if (MD->isCopyAssignmentOperator()) {
19003 CopyAssignmentOperators.push_back(MD);
19004 } else if (MD->isMoveAssignmentOperator()) {
19005 MoveAssignmentOperators.push_back(MD);
19006 }
19007 }
19008
19009 SetEligibleMethods(S, Record, DefaultConstructors,
19011 SetEligibleMethods(S, Record, CopyConstructors,
19013 SetEligibleMethods(S, Record, MoveConstructors,
19015 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19017 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19019}
19020
19021void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19022 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19023 SourceLocation RBrac,
19024 const ParsedAttributesView &Attrs) {
19025 assert(EnclosingDecl && "missing record or interface decl");
19026
19027 // If this is an Objective-C @implementation or category and we have
19028 // new fields here we should reset the layout of the interface since
19029 // it will now change.
19030 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19031 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19032 switch (DC->getKind()) {
19033 default: break;
19034 case Decl::ObjCCategory:
19035 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19036 break;
19037 case Decl::ObjCImplementation:
19038 Context.
19039 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19040 break;
19041 }
19042 }
19043
19044 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19045 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19046
19047 // Start counting up the number of named members; make sure to include
19048 // members of anonymous structs and unions in the total.
19049 unsigned NumNamedMembers = 0;
19050 if (Record) {
19051 for (const auto *I : Record->decls()) {
19052 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19053 if (IFD->getDeclName())
19054 ++NumNamedMembers;
19055 }
19056 }
19057
19058 // Verify that all the fields are okay.
19060
19061 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19062 i != end; ++i) {
19063 FieldDecl *FD = cast<FieldDecl>(*i);
19064
19065 // Get the type for the field.
19066 const Type *FDTy = FD->getType().getTypePtr();
19067
19068 if (!FD->isAnonymousStructOrUnion()) {
19069 // Remember all fields written by the user.
19070 RecFields.push_back(FD);
19071 }
19072
19073 // If the field is already invalid for some reason, don't emit more
19074 // diagnostics about it.
19075 if (FD->isInvalidDecl()) {
19076 EnclosingDecl->setInvalidDecl();
19077 continue;
19078 }
19079
19080 // C99 6.7.2.1p2:
19081 // A structure or union shall not contain a member with
19082 // incomplete or function type (hence, a structure shall not
19083 // contain an instance of itself, but may contain a pointer to
19084 // an instance of itself), except that the last member of a
19085 // structure with more than one named member may have incomplete
19086 // array type; such a structure (and any union containing,
19087 // possibly recursively, a member that is such a structure)
19088 // shall not be a member of a structure or an element of an
19089 // array.
19090 bool IsLastField = (i + 1 == Fields.end());
19091 if (FDTy->isFunctionType()) {
19092 // Field declared as a function.
19093 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19094 << FD->getDeclName();
19095 FD->setInvalidDecl();
19096 EnclosingDecl->setInvalidDecl();
19097 continue;
19098 } else if (FDTy->isIncompleteArrayType() &&
19099 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19100 if (Record) {
19101 // Flexible array member.
19102 // Microsoft and g++ is more permissive regarding flexible array.
19103 // It will accept flexible array in union and also
19104 // as the sole element of a struct/class.
19105 unsigned DiagID = 0;
19106 if (!Record->isUnion() && !IsLastField) {
19107 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19108 << FD->getDeclName() << FD->getType()
19109 << llvm::to_underlying(Record->getTagKind());
19110 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19111 FD->setInvalidDecl();
19112 EnclosingDecl->setInvalidDecl();
19113 continue;
19114 } else if (Record->isUnion())
19115 DiagID = getLangOpts().MicrosoftExt
19116 ? diag::ext_flexible_array_union_ms
19117 : diag::ext_flexible_array_union_gnu;
19118 else if (NumNamedMembers < 1)
19119 DiagID = getLangOpts().MicrosoftExt
19120 ? diag::ext_flexible_array_empty_aggregate_ms
19121 : diag::ext_flexible_array_empty_aggregate_gnu;
19122
19123 if (DiagID)
19124 Diag(FD->getLocation(), DiagID)
19125 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19126 // While the layout of types that contain virtual bases is not specified
19127 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19128 // virtual bases after the derived members. This would make a flexible
19129 // array member declared at the end of an object not adjacent to the end
19130 // of the type.
19131 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19132 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19133 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19134 if (!getLangOpts().C99)
19135 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19136 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19137
19138 // If the element type has a non-trivial destructor, we would not
19139 // implicitly destroy the elements, so disallow it for now.
19140 //
19141 // FIXME: GCC allows this. We should probably either implicitly delete
19142 // the destructor of the containing class, or just allow this.
19143 QualType BaseElem = Context.getBaseElementType(FD->getType());
19144 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19145 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19146 << FD->getDeclName() << FD->getType();
19147 FD->setInvalidDecl();
19148 EnclosingDecl->setInvalidDecl();
19149 continue;
19150 }
19151 // Okay, we have a legal flexible array member at the end of the struct.
19152 Record->setHasFlexibleArrayMember(true);
19153 } else {
19154 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19155 // unless they are followed by another ivar. That check is done
19156 // elsewhere, after synthesized ivars are known.
19157 }
19158 } else if (!FDTy->isDependentType() &&
19159 (LangOpts.HLSL // HLSL allows sizeless builtin types
19161 diag::err_incomplete_type)
19163 FD->getLocation(), FD->getType(),
19164 diag::err_field_incomplete_or_sizeless))) {
19165 // Incomplete type
19166 FD->setInvalidDecl();
19167 EnclosingDecl->setInvalidDecl();
19168 continue;
19169 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19170 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19171 // A type which contains a flexible array member is considered to be a
19172 // flexible array member.
19173 Record->setHasFlexibleArrayMember(true);
19174 if (!Record->isUnion()) {
19175 // If this is a struct/class and this is not the last element, reject
19176 // it. Note that GCC supports variable sized arrays in the middle of
19177 // structures.
19178 if (!IsLastField)
19179 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19180 << FD->getDeclName() << FD->getType();
19181 else {
19182 // We support flexible arrays at the end of structs in
19183 // other structs as an extension.
19184 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19185 << FD->getDeclName();
19186 }
19187 }
19188 }
19189 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19191 diag::err_abstract_type_in_decl,
19193 // Ivars can not have abstract class types
19194 FD->setInvalidDecl();
19195 }
19196 if (Record && FDTTy->getDecl()->hasObjectMember())
19197 Record->setHasObjectMember(true);
19198 if (Record && FDTTy->getDecl()->hasVolatileMember())
19199 Record->setHasVolatileMember(true);
19200 } else if (FDTy->isObjCObjectType()) {
19201 /// A field cannot be an Objective-c object
19202 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19205 FD->setType(T);
19206 } else if (Record && Record->isUnion() &&
19208 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19209 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19212 // For backward compatibility, fields of C unions declared in system
19213 // headers that have non-trivial ObjC ownership qualifications are marked
19214 // as unavailable unless the qualifier is explicit and __strong. This can
19215 // break ABI compatibility between programs compiled with ARC and MRR, but
19216 // is a better option than rejecting programs using those unions under
19217 // ARC.
19218 FD->addAttr(UnavailableAttr::CreateImplicit(
19219 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19220 FD->getLocation()));
19221 } else if (getLangOpts().ObjC &&
19222 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19223 !Record->hasObjectMember()) {
19224 if (FD->getType()->isObjCObjectPointerType() ||
19225 FD->getType().isObjCGCStrong())
19226 Record->setHasObjectMember(true);
19227 else if (Context.getAsArrayType(FD->getType())) {
19228 QualType BaseType = Context.getBaseElementType(FD->getType());
19229 if (BaseType->isRecordType() &&
19230 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19231 Record->setHasObjectMember(true);
19232 else if (BaseType->isObjCObjectPointerType() ||
19233 BaseType.isObjCGCStrong())
19234 Record->setHasObjectMember(true);
19235 }
19236 }
19237
19238 if (Record && !getLangOpts().CPlusPlus &&
19239 !shouldIgnoreForRecordTriviality(FD)) {
19240 QualType FT = FD->getType();
19242 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19244 Record->isUnion())
19245 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19246 }
19249 Record->setNonTrivialToPrimitiveCopy(true);
19250 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19251 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19252 }
19253 if (FD->hasAttr<ExplicitInitAttr>())
19254 Record->setHasUninitializedExplicitInitFields(true);
19255 if (FT.isDestructedType()) {
19256 Record->setNonTrivialToPrimitiveDestroy(true);
19257 Record->setParamDestroyedInCallee(true);
19258 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19259 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19260 }
19261
19262 if (const auto *RT = FT->getAs<RecordType>()) {
19263 if (RT->getDecl()->getArgPassingRestrictions() ==
19265 Record->setArgPassingRestrictions(
19268 Record->setArgPassingRestrictions(
19270 }
19271
19272 if (Record && FD->getType().isVolatileQualified())
19273 Record->setHasVolatileMember(true);
19274 // Keep track of the number of named members.
19275 if (FD->getIdentifier())
19276 ++NumNamedMembers;
19277 }
19278
19279 // Okay, we successfully defined 'Record'.
19280 if (Record) {
19281 bool Completed = false;
19282 if (S) {
19283 Scope *Parent = S->getParent();
19284 if (Parent && Parent->isTypeAliasScope() &&
19285 Parent->isTemplateParamScope())
19286 Record->setInvalidDecl();
19287 }
19288
19289 if (CXXRecord) {
19290 if (!CXXRecord->isInvalidDecl()) {
19291 // Set access bits correctly on the directly-declared conversions.
19293 I = CXXRecord->conversion_begin(),
19294 E = CXXRecord->conversion_end(); I != E; ++I)
19295 I.setAccess((*I)->getAccess());
19296 }
19297
19298 // Add any implicitly-declared members to this class.
19300
19301 if (!CXXRecord->isDependentType()) {
19302 if (!CXXRecord->isInvalidDecl()) {
19303 // If we have virtual base classes, we may end up finding multiple
19304 // final overriders for a given virtual function. Check for this
19305 // problem now.
19306 if (CXXRecord->getNumVBases()) {
19307 CXXFinalOverriderMap FinalOverriders;
19308 CXXRecord->getFinalOverriders(FinalOverriders);
19309
19310 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19311 MEnd = FinalOverriders.end();
19312 M != MEnd; ++M) {
19313 for (OverridingMethods::iterator SO = M->second.begin(),
19314 SOEnd = M->second.end();
19315 SO != SOEnd; ++SO) {
19316 assert(SO->second.size() > 0 &&
19317 "Virtual function without overriding functions?");
19318 if (SO->second.size() == 1)
19319 continue;
19320
19321 // C++ [class.virtual]p2:
19322 // In a derived class, if a virtual member function of a base
19323 // class subobject has more than one final overrider the
19324 // program is ill-formed.
19325 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19326 << (const NamedDecl *)M->first << Record;
19327 Diag(M->first->getLocation(),
19328 diag::note_overridden_virtual_function);
19330 OM = SO->second.begin(),
19331 OMEnd = SO->second.end();
19332 OM != OMEnd; ++OM)
19333 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19334 << (const NamedDecl *)M->first << OM->Method->getParent();
19335
19336 Record->setInvalidDecl();
19337 }
19338 }
19339 CXXRecord->completeDefinition(&FinalOverriders);
19340 Completed = true;
19341 }
19342 }
19343 ComputeSelectedDestructor(*this, CXXRecord);
19345 }
19346 }
19347
19348 if (!Completed)
19349 Record->completeDefinition();
19350
19351 // Handle attributes before checking the layout.
19353
19354 // Check to see if a FieldDecl is a pointer to a function.
19355 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19356 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19357 if (!FD) {
19358 // Check whether this is a forward declaration that was inserted by
19359 // Clang. This happens when a non-forward declared / defined type is
19360 // used, e.g.:
19361 //
19362 // struct foo {
19363 // struct bar *(*f)();
19364 // struct bar *(*g)();
19365 // };
19366 //
19367 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19368 // incomplete definition.
19369 if (const auto *TD = dyn_cast<TagDecl>(D))
19370 return !TD->isCompleteDefinition();
19371 return false;
19372 }
19373 QualType FieldType = FD->getType().getDesugaredType(Context);
19374 if (isa<PointerType>(FieldType)) {
19375 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19376 return PointeeType.getDesugaredType(Context)->isFunctionType();
19377 }
19378 return false;
19379 };
19380
19381 // Maybe randomize the record's decls. We automatically randomize a record
19382 // of function pointers, unless it has the "no_randomize_layout" attribute.
19383 if (!getLangOpts().CPlusPlus &&
19384 (Record->hasAttr<RandomizeLayoutAttr>() ||
19385 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19386 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19387 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19388 !Record->isRandomized()) {
19389 SmallVector<Decl *, 32> NewDeclOrdering;
19391 NewDeclOrdering))
19392 Record->reorderDecls(NewDeclOrdering);
19393 }
19394
19395 // We may have deferred checking for a deleted destructor. Check now.
19396 if (CXXRecord) {
19397 auto *Dtor = CXXRecord->getDestructor();
19398 if (Dtor && Dtor->isImplicit() &&
19400 CXXRecord->setImplicitDestructorIsDeleted();
19401 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19402 }
19403 }
19404
19405 if (Record->hasAttrs()) {
19407
19408 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19409 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19410 IA->getRange(), IA->getBestCase(),
19411 IA->getInheritanceModel());
19412 }
19413
19414 // Check if the structure/union declaration is a type that can have zero
19415 // size in C. For C this is a language extension, for C++ it may cause
19416 // compatibility problems.
19417 bool CheckForZeroSize;
19418 if (!getLangOpts().CPlusPlus) {
19419 CheckForZeroSize = true;
19420 } else {
19421 // For C++ filter out types that cannot be referenced in C code.
19422 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19423 CheckForZeroSize =
19424 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19425 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19426 CXXRecord->isCLike();
19427 }
19428 if (CheckForZeroSize) {
19429 bool ZeroSize = true;
19430 bool IsEmpty = true;
19431 unsigned NonBitFields = 0;
19432 for (RecordDecl::field_iterator I = Record->field_begin(),
19433 E = Record->field_end();
19434 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19435 IsEmpty = false;
19436 if (I->isUnnamedBitField()) {
19437 if (!I->isZeroLengthBitField())
19438 ZeroSize = false;
19439 } else {
19440 ++NonBitFields;
19441 QualType FieldType = I->getType();
19442 if (FieldType->isIncompleteType() ||
19443 !Context.getTypeSizeInChars(FieldType).isZero())
19444 ZeroSize = false;
19445 }
19446 }
19447
19448 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19449 // allowed in C++, but warn if its declaration is inside
19450 // extern "C" block.
19451 if (ZeroSize) {
19452 Diag(RecLoc, getLangOpts().CPlusPlus ?
19453 diag::warn_zero_size_struct_union_in_extern_c :
19454 diag::warn_zero_size_struct_union_compat)
19455 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19456 }
19457
19458 // Structs without named members are extension in C (C99 6.7.2.1p7),
19459 // but are accepted by GCC. In C2y, this became implementation-defined
19460 // (C2y 6.7.3.2p10).
19461 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
19462 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
19463 : diag::ext_no_named_members_in_struct_union)
19464 << Record->isUnion();
19465 }
19466 }
19467 } else {
19468 ObjCIvarDecl **ClsFields =
19469 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19470 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19471 ID->setEndOfDefinitionLoc(RBrac);
19472 // Add ivar's to class's DeclContext.
19473 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19474 ClsFields[i]->setLexicalDeclContext(ID);
19475 ID->addDecl(ClsFields[i]);
19476 }
19477 // Must enforce the rule that ivars in the base classes may not be
19478 // duplicates.
19479 if (ID->getSuperClass())
19480 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19481 } else if (ObjCImplementationDecl *IMPDecl =
19482 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19483 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19484 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19485 // Ivar declared in @implementation never belongs to the implementation.
19486 // Only it is in implementation's lexical context.
19487 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19488 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
19489 RBrac);
19490 IMPDecl->setIvarLBraceLoc(LBrac);
19491 IMPDecl->setIvarRBraceLoc(RBrac);
19492 } else if (ObjCCategoryDecl *CDecl =
19493 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19494 // case of ivars in class extension; all other cases have been
19495 // reported as errors elsewhere.
19496 // FIXME. Class extension does not have a LocEnd field.
19497 // CDecl->setLocEnd(RBrac);
19498 // Add ivar's to class extension's DeclContext.
19499 // Diagnose redeclaration of private ivars.
19500 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19501 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19502 if (IDecl) {
19503 if (const ObjCIvarDecl *ClsIvar =
19504 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19505 Diag(ClsFields[i]->getLocation(),
19506 diag::err_duplicate_ivar_declaration);
19507 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19508 continue;
19509 }
19510 for (const auto *Ext : IDecl->known_extensions()) {
19511 if (const ObjCIvarDecl *ClsExtIvar
19512 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19513 Diag(ClsFields[i]->getLocation(),
19514 diag::err_duplicate_ivar_declaration);
19515 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19516 continue;
19517 }
19518 }
19519 }
19520 ClsFields[i]->setLexicalDeclContext(CDecl);
19521 CDecl->addDecl(ClsFields[i]);
19522 }
19523 CDecl->setIvarLBraceLoc(LBrac);
19524 CDecl->setIvarRBraceLoc(RBrac);
19525 }
19526 }
19528}
19529
19530/// Determine whether the given integral value is representable within
19531/// the given type T.
19533 llvm::APSInt &Value,
19534 QualType T) {
19535 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19536 "Integral type required!");
19537 unsigned BitWidth = Context.getIntWidth(T);
19538
19539 if (Value.isUnsigned() || Value.isNonNegative()) {
19541 --BitWidth;
19542 return Value.getActiveBits() <= BitWidth;
19543 }
19544 return Value.getSignificantBits() <= BitWidth;
19545}
19546
19547// Given an integral type, return the next larger integral type
19548// (or a NULL type of no such type exists).
19550 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19551 // enum checking below.
19552 assert((T->isIntegralType(Context) ||
19553 T->isEnumeralType()) && "Integral type required!");
19554 const unsigned NumTypes = 4;
19555 QualType SignedIntegralTypes[NumTypes] = {
19556 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19557 };
19558 QualType UnsignedIntegralTypes[NumTypes] = {
19559 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19560 Context.UnsignedLongLongTy
19561 };
19562
19563 unsigned BitWidth = Context.getTypeSize(T);
19564 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19565 : UnsignedIntegralTypes;
19566 for (unsigned I = 0; I != NumTypes; ++I)
19567 if (Context.getTypeSize(Types[I]) > BitWidth)
19568 return Types[I];
19569
19570 return QualType();
19571}
19572
19574 EnumConstantDecl *LastEnumConst,
19575 SourceLocation IdLoc,
19577 Expr *Val) {
19578 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19579 llvm::APSInt EnumVal(IntWidth);
19580 QualType EltTy;
19581
19583 Val = nullptr;
19584
19585 if (Val)
19586 Val = DefaultLvalueConversion(Val).get();
19587
19588 if (Val) {
19589 if (Enum->isDependentType() || Val->isTypeDependent() ||
19590 Val->containsErrors())
19591 EltTy = Context.DependentTy;
19592 else {
19593 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19594 // underlying type, but do allow it in all other contexts.
19595 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19596 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19597 // constant-expression in the enumerator-definition shall be a converted
19598 // constant expression of the underlying type.
19599 EltTy = Enum->getIntegerType();
19600 ExprResult Converted =
19601 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19603 if (Converted.isInvalid())
19604 Val = nullptr;
19605 else
19606 Val = Converted.get();
19607 } else if (!Val->isValueDependent() &&
19608 !(Val =
19610 .get())) {
19611 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19612 } else {
19613 if (Enum->isComplete()) {
19614 EltTy = Enum->getIntegerType();
19615
19616 // In Obj-C and Microsoft mode, require the enumeration value to be
19617 // representable in the underlying type of the enumeration. In C++11,
19618 // we perform a non-narrowing conversion as part of converted constant
19619 // expression checking.
19620 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19622 .getTriple()
19623 .isWindowsMSVCEnvironment()) {
19624 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19625 } else {
19626 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19627 }
19628 }
19629
19630 // Cast to the underlying type.
19631 Val = ImpCastExprToType(Val, EltTy,
19632 EltTy->isBooleanType() ? CK_IntegralToBoolean
19633 : CK_IntegralCast)
19634 .get();
19635 } else if (getLangOpts().CPlusPlus) {
19636 // C++11 [dcl.enum]p5:
19637 // If the underlying type is not fixed, the type of each enumerator
19638 // is the type of its initializing value:
19639 // - If an initializer is specified for an enumerator, the
19640 // initializing value has the same type as the expression.
19641 EltTy = Val->getType();
19642 } else {
19643 // C99 6.7.2.2p2:
19644 // The expression that defines the value of an enumeration constant
19645 // shall be an integer constant expression that has a value
19646 // representable as an int.
19647
19648 // Complain if the value is not representable in an int.
19650 Diag(IdLoc, getLangOpts().C23
19651 ? diag::warn_c17_compat_enum_value_not_int
19652 : diag::ext_c23_enum_value_not_int)
19653 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
19654 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19655 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19656 // Force the type of the expression to 'int'.
19657 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19658 }
19659 EltTy = Val->getType();
19660 }
19661 }
19662 }
19663 }
19664
19665 if (!Val) {
19666 if (Enum->isDependentType())
19667 EltTy = Context.DependentTy;
19668 else if (!LastEnumConst) {
19669 // C++0x [dcl.enum]p5:
19670 // If the underlying type is not fixed, the type of each enumerator
19671 // is the type of its initializing value:
19672 // - If no initializer is specified for the first enumerator, the
19673 // initializing value has an unspecified integral type.
19674 //
19675 // GCC uses 'int' for its unspecified integral type, as does
19676 // C99 6.7.2.2p3.
19677 if (Enum->isFixed()) {
19678 EltTy = Enum->getIntegerType();
19679 }
19680 else {
19681 EltTy = Context.IntTy;
19682 }
19683 } else {
19684 // Assign the last value + 1.
19685 EnumVal = LastEnumConst->getInitVal();
19686 ++EnumVal;
19687 EltTy = LastEnumConst->getType();
19688
19689 // Check for overflow on increment.
19690 if (EnumVal < LastEnumConst->getInitVal()) {
19691 // C++0x [dcl.enum]p5:
19692 // If the underlying type is not fixed, the type of each enumerator
19693 // is the type of its initializing value:
19694 //
19695 // - Otherwise the type of the initializing value is the same as
19696 // the type of the initializing value of the preceding enumerator
19697 // unless the incremented value is not representable in that type,
19698 // in which case the type is an unspecified integral type
19699 // sufficient to contain the incremented value. If no such type
19700 // exists, the program is ill-formed.
19702 if (T.isNull() || Enum->isFixed()) {
19703 // There is no integral type larger enough to represent this
19704 // value. Complain, then allow the value to wrap around.
19705 EnumVal = LastEnumConst->getInitVal();
19706 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19707 ++EnumVal;
19708 if (Enum->isFixed())
19709 // When the underlying type is fixed, this is ill-formed.
19710 Diag(IdLoc, diag::err_enumerator_wrapped)
19711 << toString(EnumVal, 10)
19712 << EltTy;
19713 else
19714 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19715 << toString(EnumVal, 10);
19716 } else {
19717 EltTy = T;
19718 }
19719
19720 // Retrieve the last enumerator's value, extent that type to the
19721 // type that is supposed to be large enough to represent the incremented
19722 // value, then increment.
19723 EnumVal = LastEnumConst->getInitVal();
19724 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19725 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19726 ++EnumVal;
19727
19728 // If we're not in C++, diagnose the overflow of enumerator values,
19729 // which in C99 means that the enumerator value is not representable in
19730 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
19731 // are representable in some larger integral type and we allow it in
19732 // older language modes as an extension.
19733 // Exclude fixed enumerators since they are diagnosed with an error for
19734 // this case.
19735 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
19736 Diag(IdLoc, getLangOpts().C23
19737 ? diag::warn_c17_compat_enum_value_not_int
19738 : diag::ext_c23_enum_value_not_int)
19739 << 1 << toString(EnumVal, 10) << 1;
19740 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
19741 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19742 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19743 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
19744 : diag::ext_c23_enum_value_not_int)
19745 << 1 << toString(EnumVal, 10) << 1;
19746 }
19747 }
19748 }
19749
19750 if (!EltTy->isDependentType()) {
19751 // Make the enumerator value match the signedness and size of the
19752 // enumerator's type.
19753 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19754 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19755 }
19756
19757 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19758 Val, EnumVal);
19759}
19760
19762 SourceLocation IILoc) {
19763 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19765 return SkipBodyInfo();
19766
19767 // We have an anonymous enum definition. Look up the first enumerator to
19768 // determine if we should merge the definition with an existing one and
19769 // skip the body.
19770 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19772 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19773 if (!PrevECD)
19774 return SkipBodyInfo();
19775
19776 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19777 NamedDecl *Hidden;
19778 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19780 Skip.Previous = Hidden;
19781 return Skip;
19782 }
19783
19784 return SkipBodyInfo();
19785}
19786
19787Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19789 const ParsedAttributesView &Attrs,
19790 SourceLocation EqualLoc, Expr *Val) {
19791 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19792 EnumConstantDecl *LastEnumConst =
19793 cast_or_null<EnumConstantDecl>(lastEnumConst);
19794
19795 // The scope passed in may not be a decl scope. Zip up the scope tree until
19796 // we find one that is.
19797 S = getNonFieldDeclScope(S);
19798
19799 // Verify that there isn't already something declared with this name in this
19800 // scope.
19801 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
19802 RedeclarationKind::ForVisibleRedeclaration);
19803 LookupName(R, S);
19804 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19805
19806 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19807 // Maybe we will complain about the shadowed template parameter.
19808 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19809 // Just pretend that we didn't see the previous declaration.
19810 PrevDecl = nullptr;
19811 }
19812
19813 // C++ [class.mem]p15:
19814 // If T is the name of a class, then each of the following shall have a name
19815 // different from T:
19816 // - every enumerator of every member of class T that is an unscoped
19817 // enumerated type
19818 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19820 DeclarationNameInfo(Id, IdLoc));
19821
19822 EnumConstantDecl *New =
19823 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19824 if (!New)
19825 return nullptr;
19826
19827 if (PrevDecl) {
19828 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19829 // Check for other kinds of shadowing not already handled.
19830 CheckShadow(New, PrevDecl, R);
19831 }
19832
19833 // When in C++, we may get a TagDecl with the same name; in this case the
19834 // enum constant will 'hide' the tag.
19835 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19836 "Received TagDecl when not in C++!");
19837 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19838 if (isa<EnumConstantDecl>(PrevDecl))
19839 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19840 else
19841 Diag(IdLoc, diag::err_redefinition) << Id;
19842 notePreviousDefinition(PrevDecl, IdLoc);
19843 return nullptr;
19844 }
19845 }
19846
19847 // Process attributes.
19848 ProcessDeclAttributeList(S, New, Attrs);
19849 AddPragmaAttributes(S, New);
19850 ProcessAPINotes(New);
19851
19852 // Register this decl in the current scope stack.
19853 New->setAccess(TheEnumDecl->getAccess());
19854 PushOnScopeChains(New, S);
19855
19857
19858 return New;
19859}
19860
19861// Returns true when the enum initial expression does not trigger the
19862// duplicate enum warning. A few common cases are exempted as follows:
19863// Element2 = Element1
19864// Element2 = Element1 + 1
19865// Element2 = Element1 - 1
19866// Where Element2 and Element1 are from the same enum.
19868 Expr *InitExpr = ECD->getInitExpr();
19869 if (!InitExpr)
19870 return true;
19871 InitExpr = InitExpr->IgnoreImpCasts();
19872
19873 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19874 if (!BO->isAdditiveOp())
19875 return true;
19876 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19877 if (!IL)
19878 return true;
19879 if (IL->getValue() != 1)
19880 return true;
19881
19882 InitExpr = BO->getLHS();
19883 }
19884
19885 // This checks if the elements are from the same enum.
19886 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19887 if (!DRE)
19888 return true;
19889
19890 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19891 if (!EnumConstant)
19892 return true;
19893
19894 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19895 Enum)
19896 return true;
19897
19898 return false;
19899}
19900
19901// Emits a warning when an element is implicitly set a value that
19902// a previous element has already been set to.
19905 // Avoid anonymous enums
19906 if (!Enum->getIdentifier())
19907 return;
19908
19909 // Only check for small enums.
19910 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19911 return;
19912
19913 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19914 return;
19915
19916 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19917 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19918
19919 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19920
19921 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19922 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19923
19924 // Use int64_t as a key to avoid needing special handling for map keys.
19925 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19926 llvm::APSInt Val = D->getInitVal();
19927 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19928 };
19929
19930 DuplicatesVector DupVector;
19931 ValueToVectorMap EnumMap;
19932
19933 // Populate the EnumMap with all values represented by enum constants without
19934 // an initializer.
19935 for (auto *Element : Elements) {
19936 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19937
19938 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19939 // this constant. Skip this enum since it may be ill-formed.
19940 if (!ECD) {
19941 return;
19942 }
19943
19944 // Constants with initializers are handled in the next loop.
19945 if (ECD->getInitExpr())
19946 continue;
19947
19948 // Duplicate values are handled in the next loop.
19949 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19950 }
19951
19952 if (EnumMap.size() == 0)
19953 return;
19954
19955 // Create vectors for any values that has duplicates.
19956 for (auto *Element : Elements) {
19957 // The last loop returned if any constant was null.
19958 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19959 if (!ValidDuplicateEnum(ECD, Enum))
19960 continue;
19961
19962 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19963 if (Iter == EnumMap.end())
19964 continue;
19965
19966 DeclOrVector& Entry = Iter->second;
19967 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19968 // Ensure constants are different.
19969 if (D == ECD)
19970 continue;
19971
19972 // Create new vector and push values onto it.
19973 auto Vec = std::make_unique<ECDVector>();
19974 Vec->push_back(D);
19975 Vec->push_back(ECD);
19976
19977 // Update entry to point to the duplicates vector.
19978 Entry = Vec.get();
19979
19980 // Store the vector somewhere we can consult later for quick emission of
19981 // diagnostics.
19982 DupVector.emplace_back(std::move(Vec));
19983 continue;
19984 }
19985
19986 ECDVector *Vec = cast<ECDVector *>(Entry);
19987 // Make sure constants are not added more than once.
19988 if (*Vec->begin() == ECD)
19989 continue;
19990
19991 Vec->push_back(ECD);
19992 }
19993
19994 // Emit diagnostics.
19995 for (const auto &Vec : DupVector) {
19996 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19997
19998 // Emit warning for one enum constant.
19999 auto *FirstECD = Vec->front();
20000 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20001 << FirstECD << toString(FirstECD->getInitVal(), 10)
20002 << FirstECD->getSourceRange();
20003
20004 // Emit one note for each of the remaining enum constants with
20005 // the same value.
20006 for (auto *ECD : llvm::drop_begin(*Vec))
20007 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20008 << ECD << toString(ECD->getInitVal(), 10)
20009 << ECD->getSourceRange();
20010 }
20011}
20012
20013bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20014 bool AllowMask) const {
20015 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20016 assert(ED->isCompleteDefinition() && "expected enum definition");
20017
20018 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
20019 llvm::APInt &FlagBits = R.first->second;
20020
20021 if (R.second) {
20022 for (auto *E : ED->enumerators()) {
20023 const auto &EVal = E->getInitVal();
20024 // Only single-bit enumerators introduce new flag values.
20025 if (EVal.isPowerOf2())
20026 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20027 }
20028 }
20029
20030 // A value is in a flag enum if either its bits are a subset of the enum's
20031 // flag bits (the first condition) or we are allowing masks and the same is
20032 // true of its complement (the second condition). When masks are allowed, we
20033 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20034 //
20035 // While it's true that any value could be used as a mask, the assumption is
20036 // that a mask will have all of the insignificant bits set. Anything else is
20037 // likely a logic error.
20038 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20039 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20040}
20041
20043 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20044 const ParsedAttributesView &Attrs) {
20045 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20047
20048 ProcessDeclAttributeList(S, Enum, Attrs);
20050
20051 if (Enum->isDependentType()) {
20052 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20053 EnumConstantDecl *ECD =
20054 cast_or_null<EnumConstantDecl>(Elements[i]);
20055 if (!ECD) continue;
20056
20057 ECD->setType(EnumType);
20058 }
20059
20060 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20061 return;
20062 }
20063
20064 // Verify that all the values are okay, compute the size of the values, and
20065 // reverse the list.
20066 unsigned NumNegativeBits = 0;
20067 unsigned NumPositiveBits = 0;
20068 bool MembersRepresentableByInt = true;
20069
20070 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20071 EnumConstantDecl *ECD =
20072 cast_or_null<EnumConstantDecl>(Elements[i]);
20073 if (!ECD) continue; // Already issued a diagnostic.
20074
20075 llvm::APSInt InitVal = ECD->getInitVal();
20076
20077 // Keep track of the size of positive and negative values.
20078 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20079 // If the enumerator is zero that should still be counted as a positive
20080 // bit since we need a bit to store the value zero.
20081 unsigned ActiveBits = InitVal.getActiveBits();
20082 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
20083 } else {
20084 NumNegativeBits =
20085 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
20086 }
20087 MembersRepresentableByInt &=
20089 }
20090
20091 // If we have an empty set of enumerators we still need one bit.
20092 // From [dcl.enum]p8
20093 // If the enumerator-list is empty, the values of the enumeration are as if
20094 // the enumeration had a single enumerator with value 0
20095 if (!NumPositiveBits && !NumNegativeBits)
20096 NumPositiveBits = 1;
20097
20098 // Figure out the type that should be used for this enum.
20099 QualType BestType;
20100 unsigned BestWidth;
20101
20102 // C++0x N3000 [conv.prom]p3:
20103 // An rvalue of an unscoped enumeration type whose underlying
20104 // type is not fixed can be converted to an rvalue of the first
20105 // of the following types that can represent all the values of
20106 // the enumeration: int, unsigned int, long int, unsigned long
20107 // int, long long int, or unsigned long long int.
20108 // C99 6.4.4.3p2:
20109 // An identifier declared as an enumeration constant has type int.
20110 // The C99 rule is modified by C23.
20111 QualType BestPromotionType;
20112
20113 bool Packed = Enum->hasAttr<PackedAttr>();
20114 // -fshort-enums is the equivalent to specifying the packed attribute on all
20115 // enum definitions.
20116 if (LangOpts.ShortEnums)
20117 Packed = true;
20118
20119 // If the enum already has a type because it is fixed or dictated by the
20120 // target, promote that type instead of analyzing the enumerators.
20121 if (Enum->isComplete()) {
20122 BestType = Enum->getIntegerType();
20123 if (Context.isPromotableIntegerType(BestType))
20124 BestPromotionType = Context.getPromotedIntegerType(BestType);
20125 else
20126 BestPromotionType = BestType;
20127
20128 BestWidth = Context.getIntWidth(BestType);
20129 } else {
20130 bool EnumTooLarge = Context.computeBestEnumTypes(
20131 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20132 BestWidth = Context.getIntWidth(BestType);
20133 if (EnumTooLarge)
20134 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20135 }
20136
20137 // Loop over all of the enumerator constants, changing their types to match
20138 // the type of the enum if needed.
20139 for (auto *D : Elements) {
20140 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20141 if (!ECD) continue; // Already issued a diagnostic.
20142
20143 // C99 says the enumerators have int type, but we allow, as an
20144 // extension, the enumerators to be larger than int size. If each
20145 // enumerator value fits in an int, type it as an int, otherwise type it the
20146 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20147 // that X has type 'int', not 'unsigned'.
20148
20149 // Determine whether the value fits into an int.
20150 llvm::APSInt InitVal = ECD->getInitVal();
20151
20152 // If it fits into an integer type, force it. Otherwise force it to match
20153 // the enum decl type.
20154 QualType NewTy;
20155 unsigned NewWidth;
20156 bool NewSign;
20157 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20158 MembersRepresentableByInt) {
20159 // C23 6.7.3.3.3p15:
20160 // The enumeration member type for an enumerated type without fixed
20161 // underlying type upon completion is:
20162 // - int if all the values of the enumeration are representable as an
20163 // int; or,
20164 // - the enumerated type
20165 NewTy = Context.IntTy;
20166 NewWidth = Context.getTargetInfo().getIntWidth();
20167 NewSign = true;
20168 } else if (ECD->getType() == BestType) {
20169 // Already the right type!
20170 if (getLangOpts().CPlusPlus)
20171 // C++ [dcl.enum]p4: Following the closing brace of an
20172 // enum-specifier, each enumerator has the type of its
20173 // enumeration.
20174 ECD->setType(EnumType);
20175 continue;
20176 } else {
20177 NewTy = BestType;
20178 NewWidth = BestWidth;
20179 NewSign = BestType->isSignedIntegerOrEnumerationType();
20180 }
20181
20182 // Adjust the APSInt value.
20183 InitVal = InitVal.extOrTrunc(NewWidth);
20184 InitVal.setIsSigned(NewSign);
20185 ECD->setInitVal(Context, InitVal);
20186
20187 // Adjust the Expr initializer and type.
20188 if (ECD->getInitExpr() &&
20189 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20190 ECD->setInitExpr(ImplicitCastExpr::Create(
20191 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20192 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20193 if (getLangOpts().CPlusPlus)
20194 // C++ [dcl.enum]p4: Following the closing brace of an
20195 // enum-specifier, each enumerator has the type of its
20196 // enumeration.
20197 ECD->setType(EnumType);
20198 else
20199 ECD->setType(NewTy);
20200 }
20201
20202 Enum->completeDefinition(BestType, BestPromotionType,
20203 NumPositiveBits, NumNegativeBits);
20204
20205 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20206
20207 if (Enum->isClosedFlag()) {
20208 for (Decl *D : Elements) {
20209 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20210 if (!ECD) continue; // Already issued a diagnostic.
20211
20212 llvm::APSInt InitVal = ECD->getInitVal();
20213 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20214 !IsValueInFlagEnum(Enum, InitVal, true))
20215 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20216 << ECD << Enum;
20217 }
20218 }
20219
20220 // Now that the enum type is defined, ensure it's not been underaligned.
20221 if (Enum->hasAttrs())
20223}
20224
20226 SourceLocation StartLoc,
20227 SourceLocation EndLoc) {
20228 StringLiteral *AsmString = cast<StringLiteral>(expr);
20229
20231 AsmString, StartLoc,
20232 EndLoc);
20233 CurContext->addDecl(New);
20234 return New;
20235}
20236
20238 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20239 CurContext->addDecl(New);
20240 PushDeclContext(S, New);
20242 PushCompoundScope(false);
20243 return New;
20244}
20245
20247 D->setStmt(Statement);
20251}
20252
20254 IdentifierInfo* AliasName,
20255 SourceLocation PragmaLoc,
20256 SourceLocation NameLoc,
20257 SourceLocation AliasNameLoc) {
20258 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20260 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20262 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20263 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20264
20265 // If a declaration that:
20266 // 1) declares a function or a variable
20267 // 2) has external linkage
20268 // already exists, add a label attribute to it.
20269 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20270 if (isDeclExternC(PrevDecl))
20271 PrevDecl->addAttr(Attr);
20272 else
20273 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20274 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20275 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20276 } else
20277 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20278}
20279
20281 SourceLocation PragmaLoc,
20282 SourceLocation NameLoc) {
20283 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20284
20285 if (PrevDecl) {
20286 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20287 } else {
20288 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20289 }
20290}
20291
20293 IdentifierInfo* AliasName,
20294 SourceLocation PragmaLoc,
20295 SourceLocation NameLoc,
20296 SourceLocation AliasNameLoc) {
20297 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20299 WeakInfo W = WeakInfo(Name, NameLoc);
20300
20301 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20302 if (!PrevDecl->hasAttr<AliasAttr>())
20303 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20305 } else {
20306 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20307 }
20308}
20309
20311 bool Final) {
20312 assert(FD && "Expected non-null FunctionDecl");
20313
20314 // SYCL functions can be template, so we check if they have appropriate
20315 // attribute prior to checking if it is a template.
20316 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20318
20319 // Templates are emitted when they're instantiated.
20320 if (FD->isDependentContext())
20322
20323 // Check whether this function is an externally visible definition.
20324 auto IsEmittedForExternalSymbol = [this, FD]() {
20325 // We have to check the GVA linkage of the function's *definition* -- if we
20326 // only have a declaration, we don't know whether or not the function will
20327 // be emitted, because (say) the definition could include "inline".
20328 const FunctionDecl *Def = FD->getDefinition();
20329
20330 // We can't compute linkage when we skip function bodies.
20331 return Def && !Def->hasSkippedBody() &&
20333 getASTContext().GetGVALinkageForFunction(Def));
20334 };
20335
20336 if (LangOpts.OpenMPIsTargetDevice) {
20337 // In OpenMP device mode we will not emit host only functions, or functions
20338 // we don't need due to their linkage.
20339 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20340 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20341 // DevTy may be changed later by
20342 // #pragma omp declare target to(*) device_type(*).
20343 // Therefore DevTy having no value does not imply host. The emission status
20344 // will be checked again at the end of compilation unit with Final = true.
20345 if (DevTy)
20346 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20348 // If we have an explicit value for the device type, or we are in a target
20349 // declare context, we need to emit all extern and used symbols.
20350 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20351 if (IsEmittedForExternalSymbol())
20353 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20354 // we'll omit it.
20355 if (Final)
20357 } else if (LangOpts.OpenMP > 45) {
20358 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20359 // function. In 5.0, no_host was introduced which might cause a function to
20360 // be omitted.
20361 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20362 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20363 if (DevTy)
20364 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20366 }
20367
20368 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20370
20371 if (LangOpts.CUDA) {
20372 // When compiling for device, host functions are never emitted. Similarly,
20373 // when compiling for host, device and global functions are never emitted.
20374 // (Technically, we do emit a host-side stub for global functions, but this
20375 // doesn't count for our purposes here.)
20377 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20379 if (!LangOpts.CUDAIsDevice &&
20382
20383 if (IsEmittedForExternalSymbol())
20385 }
20386
20387 // Otherwise, the function is known-emitted if it's in our set of
20388 // known-emitted functions.
20390}
20391
20393 // Host-side references to a __global__ function refer to the stub, so the
20394 // function itself is never emitted and therefore should not be marked.
20395 // If we have host fn calls kernel fn calls host+device, the HD function
20396 // does not get instantiated on the host. We model this by omitting at the
20397 // call to the kernel from the callgraph. This ensures that, when compiling
20398 // for host, only HD functions actually called from the host get marked as
20399 // known-emitted.
20400 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20402}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
#define SM(sm)
Definition: Cuda.cpp:85
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
const Decl * D
IndirectLocalPath & Path
enum clang::sema::@1727::IndirectLocalPathEntry::EntryKind Kind
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
static bool isDeclExternC(const T &D)
Definition: Decl.cpp:2218
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Iter
Definition: HTMLLogger.cpp:153
static const Decl * getCanonicalDecl(const Decl *D)
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition: MachO.h:27
llvm::MachO::Record Record
Definition: MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition: Mangle.cpp:57
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
Definition: Redeclaration.h:18
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
uint32_t Id
Definition: SemaARM.cpp:1136
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:15899
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6861
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition: SemaDecl.cpp:153
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15396
static bool isMainVar(DeclarationName Name, VarDecl *VD)
Definition: SemaDecl.cpp:7462
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:11434
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:208
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:3353
static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6952
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:3518
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:798
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:6559
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
Definition: SemaDecl.cpp:1473
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
Definition: SemaDecl.cpp:6597
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:2272
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:9249
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:3465
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2786
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
Definition: SemaDecl.cpp:8230
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:9595
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
Definition: SemaDecl.cpp:3280
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
Definition: SemaDecl.cpp:8606
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
Definition: SemaDecl.cpp:11836
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Merge alignment attributes from Old to New, taking into account the special semantics of C11's _Align...
Definition: SemaDecl.cpp:2675
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:4478
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
Definition: SemaDecl.cpp:11930
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15380
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
Definition: SemaDecl.cpp:11554
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:2039
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
Definition: SemaDecl.cpp:15015
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:564
static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6987
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
Definition: SemaDecl.cpp:11443
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:7203
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:19532
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:19903
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
Definition: SemaDecl.cpp:5025
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
Definition: SemaDecl.cpp:2918
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
Definition: SemaDecl.cpp:16946
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:3500
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7040
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:5961
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:4892
static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From, Sema &S)
Definition: SemaDecl.cpp:3244
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:9285
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:9778
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
Definition: SemaDecl.cpp:15928
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:3407
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:8575
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2644
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
Definition: SemaDecl.cpp:9467
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
Definition: SemaDecl.cpp:3043
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:8255
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:17106
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:5312
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:8492
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
Definition: SemaDecl.cpp:1915
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
Definition: SemaDecl.cpp:9789
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:5388
OpenCLParamType
Definition: SemaDecl.cpp:9458
@ InvalidAddrSpacePtrKernelParam
Definition: SemaDecl.cpp:9462
@ ValidKernelParam
Definition: SemaDecl.cpp:9459
@ InvalidKernelParam
Definition: SemaDecl.cpp:9463
@ RecordKernelParam
Definition: SemaDecl.cpp:9464
@ PtrKernelParam
Definition: SemaDecl.cpp:9461
@ PtrPtrKernelParam
Definition: SemaDecl.cpp:9460
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:6070
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:18883
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:584
static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record)
[class.dtor]p4: At the end of the definition of a class, overload resolution is performed among the p...
Definition: SemaDecl.cpp:18817
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:7248
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:5472
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11360
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:9769
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
Definition: SemaDecl.cpp:3314
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:3444
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:16930
static void checkInheritableAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6960
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
Definition: SemaDecl.cpp:2166
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:4375
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:9092
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
Definition: SemaDecl.cpp:5996
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:18910
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:813
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
Definition: SemaDecl.cpp:7275
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:8219
@ SDK_StructuredBinding
Definition: SemaDecl.cpp:8226
@ SDK_Field
Definition: SemaDecl.cpp:8223
@ SDK_Global
Definition: SemaDecl.cpp:8221
@ SDK_Local
Definition: SemaDecl.cpp:8220
@ SDK_Typedef
Definition: SemaDecl.cpp:8224
@ SDK_StaticMember
Definition: SemaDecl.cpp:8222
@ SDK_Using
Definition: SemaDecl.cpp:8225
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4838
static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
Definition: SemaDecl.cpp:7434
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:3428
static void checkWeakAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6908
static void checkSelectAnyAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6940
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:9489
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:5486
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
Definition: SemaDecl.cpp:12507
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
Definition: SemaDecl.cpp:7326
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
Definition: SemaDecl.cpp:1784
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
Definition: SemaDecl.cpp:18976
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11173
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
Definition: SemaDecl.cpp:1773
static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From, F &&propagator)
Definition: SemaDecl.cpp:3259
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2892
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
Definition: SemaDecl.cpp:6481
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:14823
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
Definition: SemaDecl.cpp:7422
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:5943
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1826
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
Definition: SemaDecl.cpp:11113
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
Definition: SemaDecl.cpp:6822
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:5451
static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T, SourceLocation NameLoc, bool WantNontrivialTypeSourceInfo=true)
Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
Definition: SemaDecl.cpp:250
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a new function declaration being added to an existing multiversioned declaratio...
Definition: SemaDecl.cpp:11585
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:8246
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:11409
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:7054
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11191
static void checkAliasAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6927
static void filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don't have linkage, but they still denote the same entity if their types are the...
Definition: SemaDecl.cpp:2399
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:19867
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:19549
static void checkWeakRefAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6918
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:7234
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2663
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
Definition: SemaDecl.cpp:11020
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Definition: SemaDecl.cpp:11458
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1800
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualified na...
Definition: SemaDecl.cpp:17143
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to Wasm.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Definition: SourceCode.cpp:152
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
const NestedNameSpecifier * Specifier
StateNode * Previous
std::string Label
__device__ int
#define bool
Definition: amdgpuintrin.h:20
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
Definition: SemaDecl.cpp:15886
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:15888
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:73
virtual void HandleInlineFunctionDefinition(FunctionDecl *D)
This callback is invoked each time an inline (method or friend) function definition in a class is com...
Definition: ASTConsumer.h:58
virtual bool shouldSkipFunctionBody(Decl *D)
This callback is called for each function if the Parser was initialized with SkipFunctionBodies set t...
Definition: ASTConsumer.h:146
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:113
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
SourceManager & getSourceManager()
Definition: ASTContext.h:741
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2922
QualType getParenType(QualType NamedType) const
CanQualType LongTy
Definition: ASTContext.h:1169
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
ExternCContextDecl * getExternCContextDecl() const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2225
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
QualType getRecordType(const RecordDecl *Decl) const
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
void setObjCIdRedefinitionType(QualType RedefType)
Set the user-written type that redefines id.
Definition: ASTContext.h:2005
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2723
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2739
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:2115
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:2031
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:2093
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:2928
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
CanQualType DependentTy
Definition: ASTContext.h:1188
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
IdentifierTable & Idents
Definition: ASTContext.h:680
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:530
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2213
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:2127
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, unsigned NumPositiveBits, QualType &BestType, QualType &BestPromotionType)
Compute BestType and BestPromotionType for an enum based on the highest number of negative and positi...
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:3021
CanQualType CharTy
Definition: ASTContext.h:1162
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
CanQualType IntTy
Definition: ASTContext.h:1169
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2296
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
void setNonKeyFunction(const CXXMethodDecl *method)
Observe that the given method cannot be a key function.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2203
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2770
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:2489
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1170
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1533
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2925
CanQualType ShortTy
Definition: ASTContext.h:1169
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:2018
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2319
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:2103
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
Definition: ASTContext.h:1169
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
Definition: ASTContext.h:2391
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2397
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2394
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2403
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2400
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:2520
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:3358
Wrapper for source info for arrays.
Definition: TypeLoc.h:1593
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1595
Expr * getSizeExpr() const
Definition: TypeLoc.h:1615
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1623
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1603
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3578
QualType getElementType() const
Definition: Type.h:3590
Attr - This represents one attribute.
Definition: Attr.h:43
attr::Kind getKind() const
Definition: Attr.h:89
bool isInherited() const
Definition: Attr.h:98
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition: Attr.h:103
SourceLocation getLocation() const
Definition: Attr.h:96
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:637
AttributeFactory & getFactory() const
Definition: ParsedAttr.h:733
Type source information for an attributed type.
Definition: TypeLoc.h:876
const T * getAttrAs()
Definition: TypeLoc.h:906
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:890
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:6133
QualType getModifiedType() const
Definition: Type.h:6163
bool isCallingConv() const
Definition: Type.cpp:4204
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6562
AutoTypeKeyword getKeyword() const
Definition: Type.h:6593
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4324
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
A binding in a decomposition declaration.
Definition: DeclCXX.h:4130
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4496
bool doesNotEscape() const
Definition: Decl.h:4647
This class is used for builtin types like 'int'.
Definition: Type.h:3035
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
bool performsCallback(unsigned ID, llvm::SmallVectorImpl< int > &Encoding) const
Determine whether this builtin has callback behavior (see llvm::AbstractCallSites for details).
Definition: Builtins.cpp:219
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:263
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition: Builtins.h:223
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
bool isReturnsTwice(unsigned ID) const
Return true if we know this builtin can return twice.
Definition: Builtins.h:138
bool isImmediate(unsigned ID) const
Returns true if this is an immediate (consteval) function.
Definition: Builtins.h:285
bool isConstWithoutErrnoAndExceptions(unsigned ID) const
Return true if this function has no side effects and doesn't read memory, except for possibly errno o...
Definition: Builtins.h:248
bool allowTypeMismatch(unsigned ID) const
Determines whether a declaration of this builtin should be recognized even if the type doesn't match ...
Definition: Builtins.h:203
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:112
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition: Builtins.h:168
bool isScanfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like scanf in its formatting rules and, if so, set the index to the...
Definition: Builtins.cpp:214
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:183
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:161
bool isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like printf in its formatting rules and, if so, set the index to th...
Definition: Builtins.cpp:209
bool isConstWithoutExceptions(unsigned ID) const
Definition: Builtins.h:252
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache",...
Definition: Builtins.h:175
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition: Builtins.h:117
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:128
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition: Builtins.h:123
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:194
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclCXX.h:195
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2856
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2885
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:3045
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2291
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2990
A mapping from each virtual member function to its set of final overriders.
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2590
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2644
bool isVirtual() const
Definition: DeclCXX.h:2133
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2709
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2623
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:2409
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2239
bool isConst() const
Definition: DeclCXX.h:2130
bool isStatic() const
Definition: DeclCXX.cpp:2321
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2601
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2174
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition: DeclCXX.h:1346
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1252
base_class_iterator bases_end()
Definition: DeclCXX.h:629
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1378
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1563
base_class_range bases()
Definition: DeclCXX.h:620
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1388
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:2037
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
base_class_iterator bases_begin()
Definition: DeclCXX.h:627
capture_const_range captures() const
Definition: DeclCXX.h:1109
bool hasDefinition() const
Definition: DeclCXX.h:572
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:2004
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1071
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:2008
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1300
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:236
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:123
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:149
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
static CharSourceRange getCharRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Declaration of a class template.
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4262
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3616
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:205
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:245
bool isZeroSize() const
Return true if the size is zero.
Definition: Type.h:3686
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3672
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:349
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1372
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2384
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1439
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2104
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2233
bool isFileContext() const
Definition: DeclBase.h:2175
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2065
bool isObjCContainer() const
Definition: DeclBase.h:2143
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1411
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1345
bool isClosure() const
Definition: DeclBase.h:2137
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2120
bool isNamespace() const
Definition: DeclBase.h:2193
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1866
bool isTranslationUnit() const
Definition: DeclBase.h:2180
bool isRecord() const
Definition: DeclBase.h:2184
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2010
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1699
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1780
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1649
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2028
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1435
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2364
bool isFunctionOrMethod() const
Definition: DeclBase.h:2156
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1296
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1396
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1415
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2097
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1426
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition: DeclGroup.h:68
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:550
ValueDecl * getDecl()
Definition: Expr.h:1333
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool isVirtualSpecified() const
Definition: DeclSpec.h:648
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:829
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:309
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:595
static const TST TST_typename
Definition: DeclSpec.h:306
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition: DeclSpec.cpp:645
bool isNoreturnSpecified() const
Definition: DeclSpec.h:661
TST getTypeSpecType() const
Definition: DeclSpec.h:537
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:510
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:860
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:575
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:574
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:709
static const TST TST_interface
Definition: DeclSpec.h:304
static const TST TST_typeofExpr
Definition: DeclSpec.h:308
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:616
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:708
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:662
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:505
static const TST TST_union
Definition: DeclSpec.h:302
SCS
storage-class-specifier
Definition: DeclSpec.h:251
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:654
static const TST TST_int
Definition: DeclSpec.h:285
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:830
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1506
ParsedType getRepAsType() const
Definition: DeclSpec.h:547
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:788
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:502
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:873
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:626
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:617
Expr * getRepAsExpr() const
Definition: DeclSpec.h:555
static const TST TST_enum
Definition: DeclSpec.h:301
static const TST TST_decltype
Definition: DeclSpec.h:311
static bool isDeclRep(TST T)
Definition: DeclSpec.h:469
bool isInlineSpecified() const
Definition: DeclSpec.h:637
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:618
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:310
static const TST TST_class
Definition: DeclSpec.h:305
static const TST TST_void
Definition: DeclSpec.h:279
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:558
static const TST TST_atomic
Definition: DeclSpec.h:321
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:511
Decl * getRepAsDecl() const
Definition: DeclSpec.h:551
static const TST TST_unspecified
Definition: DeclSpec.h:278
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:620
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:649
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:836
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:582
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:792
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:267
static const TST TST_error
Definition: DeclSpec.h:328
bool isTypeSpecOwned() const
Definition: DeclSpec.h:541
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:640
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:621
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:619
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:821
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:651
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:837
static const TST TST_typeofType
Definition: DeclSpec.h:307
static const TST TST_auto
Definition: DeclSpec.h:318
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:832
static const TST TST_struct
Definition: DeclSpec.h:303
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1054
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1069
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:322
bool isInStdNamespace() const
Definition: DeclBase.cpp:430
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:438
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1219
bool isFromGlobalModule() const
Whether this declaration comes from global module.
Definition: DeclBase.cpp:1169
T * getAttr() const
Definition: DeclBase.h:576
bool hasAttrs() const
Definition: DeclBase.h:521
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:528
void addAttr(Attr *A)
Definition: DeclBase.cpp:1019
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:523
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:764
bool isInNamedModule() const
Whether this declaration comes from a named module.
Definition: DeclBase.cpp:1173
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1144
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:159
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:635
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:886
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1212
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1210
@ FOK_Declared
A friend of a previously-declared entity.
Definition: DeclBase.h:1211
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:289
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1118
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:582
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:835
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:254
void dropAttrs()
Definition: DeclBase.cpp:1012
@ 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:1173
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2784
bool isInvalidDecl() const
Definition: DeclBase.h:591
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1162
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:505
SourceLocation getLocation() const
Definition: DeclBase.h:442
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:822
void setImplicit(bool I=true)
Definition: DeclBase.h:597
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:611
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:557
DeclContext * getDeclContext()
Definition: DeclBase.h:451
attr_range attrs() const
Definition: DeclBase.h:538
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
void dropAttr()
Definition: DeclBase.h:559
AttrVec & getAttrs()
Definition: DeclBase.h:527
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:363
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1624
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:911
bool hasAttr() const
Definition: DeclBase.h:580
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1228
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:367
Kind getKind() const
Definition: DeclBase.h:445
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:430
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:735
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:792
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:777
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2039
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2079
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1977
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:822
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:769
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1989
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:810
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2023
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2401
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2050
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2686
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2342
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2397
const ParsedAttributesView & getDeclarationAttributes() const
Definition: DeclSpec.h:2689
A decomposition declaration.
Definition: DeclCXX.h:4189
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3491
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1792
SourceRange getSourceRange() const
Definition: DeclSpec.h:1839
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1837
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6528
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:6549
bool isDeduced() const
Definition: Type.h:6550
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2455
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2435
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2444
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:939
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:954
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2355
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2369
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3291
llvm::APSInt getInitVal() const
Definition: Decl.h:3311
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5527
const Expr * getInitExpr() const
Definition: Decl.h:3309
Represents an enum.
Definition: Decl.h:3861
enumerator_range enumerators() const
Definition: Decl.h:3994
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4066
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:4030
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:4033
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4080
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4895
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4940
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4075
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4915
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:4016
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4021
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6104
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
This represents one expression.
Definition: Expr.h:110
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3097
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3093
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3077
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:276
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:979
void applyChanges(FPOptionsOverride FPO)
Definition: LangOptions.h:1092
bool isFPConstrained() const
Definition: LangOptions.h:907
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
Definition: LangOptions.h:1086
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3136
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4588
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4573
bool isZeroLengthBitField() const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition: Decl.cpp:4631
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5659
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:101
Represents a function declaration or definition.
Definition: Decl.h:1935
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2565
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2404
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4079
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3624
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4072
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4067
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3262
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2249
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2577
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2556
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3898
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3653
param_iterator param_end()
Definition: Decl.h:2662
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2796
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2571
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3597
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2317
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2305
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3509
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4187
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2376
void setWillHaveBody(bool V=true)
Definition: Decl.h:2562
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2371
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4197
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3638
param_iterator param_begin()
Definition: Decl.h:2661
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2698
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3096
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2468
FunctionEffectsRef getFunctionEffects() const
Definition: Decl.h:3009
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3335
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4131
@ TK_MemberSpecialization
Definition: Decl.h:1947
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2763
bool isStatic() const
Definition: Decl.h:2804
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4400
void setTrivial(bool IT)
Definition: Decl.h:2306
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4018
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
bool isDeletedAsWritten() const
Definition: Decl.h:2472
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition: Decl.h:2393
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2288
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3513
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2292
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2356
bool isImmediateEscalating() const
Definition: Decl.cpp:3275
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2284
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2555
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2217
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3328
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2791
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3387
bool param_empty() const
Definition: Decl.h:2660
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2124
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3187
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2153
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3593
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2349
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4423
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2808
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:4012
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:4004
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2401
void setDefaulted(bool D=true)
Definition: Decl.h:2314
bool isConsteval() const
Definition: Decl.h:2410
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition: Decl.h:2737
void setBody(Stmt *B)
Definition: Decl.cpp:3255
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3527
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3133
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition: Decl.h:2387
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4039
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3717
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2146
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3163
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2363
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3210
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2774
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3579
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2561
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:5045
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5371
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4909
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5108
unsigned getNumParams() const
Definition: Type.h:5361
QualType getParamType(unsigned i) const
Definition: Type.h:5363
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:5567
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5394
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5485
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5372
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5368
ArrayRef< QualType > param_types() const
Definition: Type.h:5517
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Definition: DeclTemplate.h:540
Wrapper for source info for functions.
Definition: TypeLoc.h:1460
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4433
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4548
CallingConv getCC() const
Definition: Type.h:4495
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4514
unsigned getRegParm() const
Definition: Type.h:4488
bool getNoCallerSavedRegs() const
Definition: Type.h:4484
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4507
bool getHasRegParm() const
Definition: Type.h:4486
bool getNoReturn() const
Definition: Type.h:4481
bool getProducesResult() const
Definition: Type.h:4482
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:4528
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:4542
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4322
ExtInfo getExtInfo() const
Definition: Type.h:4661
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3535
unsigned getRegParmType() const
Definition: Type.h:4652
CallingConv getCallConv() const
Definition: Type.h:4660
QualType getReturnType() const
Definition: Type.h:4649
bool getCmseNSCallAttr() const
Definition: Type.h:4659
@ SME_PStateSMEnabledMask
Definition: Type.h:4588
@ SME_PStateSMCompatibleMask
Definition: Type.h:4589
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
bool isPlaceholder() const
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
iterator begin(DeclarationName Name)
Returns an iterator over decls with the name 'Name'.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
void InsertDeclAfter(iterator Pos, NamedDecl *D)
Insert the given declaration after the given iterator position.
iterator end()
Returns the end iterator.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
bool isDeclInScope(Decl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3724
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2089
Represents a C array with an unspecified size.
Definition: Type.h:3765
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3335
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5555
void setInherited(bool I)
Definition: Attr.h:155
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2524
Describes an C or C++ initializer list.
Definition: Expr.h:5088
child_range children()
Definition: Expr.h:5280
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
Describes the sequence of initializations required to initialize a given object or reference with a s...
step_iterator step_begin() const
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:7637
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
Describes an entity that is being initialized.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:980
Represents the declaration of a label.
Definition: Decl.h:503
bool isResolvedMSAsmLabel() const
Definition: Decl.h:538
LabelStmt * getStmt() const
Definition: Decl.h:527
bool isMSAsmLabel() const
Definition: Decl.h:537
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:290
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:500
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:673
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:817
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:722
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:535
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:592
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
Definition: LangOptions.h:728
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:574
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:1380
Represents a linkage specification.
Definition: DeclCXX.h:2957
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:3075
void InstantiatedLocal(const Decl *D, Decl *Inst)
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
DeclClass * getAsSingle() const
Definition: Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
bool isAmbiguous() const
Definition: Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition: Lookup.h:670
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition: Lookup.h:146
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3520
Describes a module or submodule.
Definition: Module.h:115
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:121
Module * Parent
The parent of this module.
Definition: Module.h:164
bool isPrivateModule() const
Definition: Module.h:220
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition: Module.h:619
bool isModuleImplementation() const
Is this a module implementation.
Definition: Module.h:635
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:624
bool isImplicitGlobalModule() const
Definition: Module.h:216
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:240
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:195
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:693
@ ClassId_NSObject
Definition: NSAPI.h:30
This represents a decl that may have a name.
Definition: Decl.h:253
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:466
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Decl.cpp:1079
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition: Decl.h:458
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:408
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:699
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1919
bool isExternallyVisible() const
Definition: Decl.h:412
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:376
Represent a C++ namespace.
Definition: Decl.h:551
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:602
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
SourceRange getLocalSourceRange() const
Retrieve the source range covering just the last part of this nested-name-specifier,...
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool containsErrors() const
Whether this nested name specifier contains an error.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2328
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2774
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition: DeclObjC.cpp:79
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2596
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1761
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
Definition: DeclObjC.cpp:1831
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:941
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
param_const_iterator param_end() const
Definition: DeclObjC.h:358
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
bool isOptional() const
Definition: DeclObjC.h:505
ParmVarDecl *const * param_iterator
Definition: DeclObjC.h:350
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:97
Wrapper for void* pointer.
Definition: Ownership.h:50
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(PtrTy P)
Definition: Ownership.h:60
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1021
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1025
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1198
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
MapType::iterator iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:255
Expr ** getExprs()
Definition: Expr.h:5905
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5894
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1235
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1248
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1231
Sugar for parentheses used when specifying types.
Definition: Type.h:3173
Represents a parameter to a function.
Definition: Decl.h:1725
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1785
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1789
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
QualType getOriginalType() const
Definition: Decl.cpp:2931
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2922
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:836
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:916
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:956
AttributePool & getPool() const
Definition: ParsedAttr.h:963
PipeType - OpenCL20.
Definition: Type.h:7786
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1314
Wrapper for source info for pointers.
Definition: TypeLoc.h:1333
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1339
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3199
QualType getPointeeType() const
Definition: Type.h:3209
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
HeaderSearch & getHeaderSearchInfo() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8021
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:8015
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:8084
@ DK_nontrivial_c_struct
Definition: Type.h:1524
PrimitiveDefaultInitializeKind
Definition: Type.h:1452
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2865
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:102
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1209
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1291
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition: Type.cpp:2913
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7937
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8063
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:8078
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7977
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getCanonicalType() const
Definition: Type.h:7989
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8031
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition: Type.cpp:2897
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1428
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8010
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
bool isCanonical() const
Definition: Type.h:7994
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1304
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1437
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2639
NonConstantStorageReason
Definition: Type.h:1013
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: Type.h:1482
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: Type.h:1487
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition: Type.h:8072
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7877
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7884
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4418
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
bool hasConst() const
Definition: Type.h:450
void removeConst()
Definition: Type.h:452
void addConst()
Definition: Type.h:453
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
bool empty() const
Definition: Type.h:640
Represents a struct/union/class.
Definition: Decl.h:4162
bool hasObjectMember() const
Definition: Decl.h:4222
field_range fields() const
Definition: Decl.h:4376
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5059
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5079
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5125
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4361
field_iterator field_begin() const
Definition: Decl.cpp:5113
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6078
RecordDecl * getDecl() const
Definition: Type.h:6088
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:7258
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:863
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
redecl_iterator redecls_end() const
Definition: Redeclarable.h:302
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:5080
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:222
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3440
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3046
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:3094
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition: Scope.h:382
void RemoveDecl(Decl *D)
Definition: Scope.h:354
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:385
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:582
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:271
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
void CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition: SemaARM.cpp:1336
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
void checkAllowedInitializer(VarDecl *VD)
Definition: SemaCUDA.cpp:656
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
Definition: SemaCUDA.cpp:1068
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
void maybeAddHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition: SemaCUDA.cpp:738
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
Definition: SemaCUDA.cpp:1003
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition: SemaCUDA.cpp:803
void CheckEntryPoint(FunctionDecl *FD)
Definition: SemaHLSL.cpp:612
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition: SemaHLSL.cpp:512
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition: SemaHLSL.cpp:579
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition: SemaHLSL.cpp:546
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition: SemaHLSL.cpp:526
void ActOnVariableDeclarator(VarDecl *VD)
Definition: SemaHLSL.cpp:2777
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
Definition: SemaObjC.cpp:1161
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
void AddCFAuditedAttribute(Decl *D)
AddCFAuditedAttribute - Check whether we're currently within '#pragma clang arc_cf_code_audited' and,...
Definition: SemaObjC.cpp:1447
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: SemaObjC.h:591
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Decl *D, SmallVectorImpl< FunctionDecl * > &Bases)
Register D as specialization of all base functions in Bases in the current omp begin/end declare vari...
void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl< FunctionDecl * > &Bases)
The declarator D defines a function in the scope S which is nested in an omp begin/end declare varian...
void ActOnOpenMPDeclareTargetInitializer(Decl *D)
Adds OMPDeclareTargetDeclAttr to referenced variables in declare target directive.
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D, const llvm::StringMap< bool > &FeatureMap)
Definition: SemaRISCV.cpp:1372
StmtResult BuildSYCLKernelCallStmt(FunctionDecl *FD, CompoundStmt *Body)
Definition: SemaSYCL.cpp:415
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition: SemaSYCL.cpp:253
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition: SemaSwift.cpp:26
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition: SemaWasm.cpp:266
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition: SemaWasm.cpp:245
bool IsAlignAttr() const
Definition: Sema.h:1507
Mode getAlignMode() const
Definition: Sema.h:1509
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:985
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:997
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition: Sema.h:3254
static NameClassification VarTemplate(TemplateName Name)
Definition: Sema.h:3264
static NameClassification Unknown()
Definition: Sema.h:3234
static NameClassification OverloadSet(ExprResult E)
Definition: Sema.h:3238
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition: Sema.h:3282
static NameClassification FunctionTemplate(TemplateName Name)
Definition: Sema.h:3270
static NameClassification NonType(NamedDecl *D)
Definition: Sema.h:3244
static NameClassification Concept(TemplateName Name)
Definition: Sema.h:3276
static NameClassification UndeclaredNonType()
Definition: Sema.h:3250
static NameClassification TypeTemplate(TemplateName Name)
Definition: Sema.h:3258
static NameClassification Error()
Definition: Sema.h:3232
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12093
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12123
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:14278
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:11046
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6395
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition: Sema.h:3102
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6716
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12652
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition: Sema.cpp:2388
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:732
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls)
MergeTypedefNameDecl - We just parsed a typedef 'New' which has the same name and scope as a previous...
Definition: SemaDecl.cpp:2471
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
Definition: SemaType.cpp:9134
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:6636
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9816
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Definition: SemaDecl.cpp:1561
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:15171
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:7844
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:5835
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:8986
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8990
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:9009
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:9025
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:9022
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8998
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:8993
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6652
void ActOnPopScope(SourceLocation Loc, Scope *S)
Definition: SemaDecl.cpp:2182
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5345
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15870
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12925
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:36
NonTrivialCUnionContext
Definition: Sema.h:3624
@ NTCUC_CopyInit
Definition: Sema.h:3634
@ NTCUC_AutoVar
Definition: Sema.h:3632
@ NTCUC_DefaultInitializedObject
Definition: Sema.h:3630
@ NTCUC_FunctionReturn
Definition: Sema.h:3628
@ NTCUC_FunctionParam
Definition: Sema.h:3626
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld, bool NewDeclIsDefn)
MergeFunctionDecl - We just parsed a function 'New' from declarator D which has the same name and sco...
Definition: SemaDecl.cpp:3558
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:6129
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
Definition: SemaLookup.cpp:995
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:18303
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
Definition: SemaDecl.cpp:7470
SemaOpenMP & OpenMP()
Definition: Sema.h:1126
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6114
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:867
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:18235
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition: Sema.h:4325
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:3084
PragmaClangSection PragmaClangRodataSection
Definition: Sema.h:1433
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
Definition: SemaDecl.cpp:16441
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:6032
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:15037
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
Definition: SemaAttr.cpp:1190
SemaCUDA & CUDA()
Definition: Sema.h:1071
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17405
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
void ActOnExitFunctionContext()
Definition: SemaDecl.cpp:1457
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
Definition: SemaAttr.cpp:272
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2292
Preprocessor & getPreprocessor() const
Definition: Sema.h:531
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6867
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1664
PragmaStack< StringLiteral * > CodeSegStack
Definition: Sema.h:1658
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
Definition: SemaAttr.cpp:1268
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
DLLImportAttr * mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI)
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6257
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:17163
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:4844
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:12339
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:16642
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
Definition: SemaDecl.cpp:2101
@ Delete
deleted-function-body
ExprResult VerifyBitField(SourceLocation FieldLoc, const IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth)
VerifyBitField - verifies that a bit field expression is an ICE and has the correct width,...
Definition: SemaDecl.cpp:18322
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:18420
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:14651
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
Definition: SemaDecl.cpp:1433
SemaSYCL & SYCL()
Definition: Sema.h:1151
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15506
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1570
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3436
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition: SemaDecl.cpp:643
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
Definition: SemaDecl.cpp:1659
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: SemaDecl.cpp:20225
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15158
ASTContext & Context
Definition: Sema.h:909
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14671
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5821
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool HasMatchedPackOnParmToNonPackOnArg=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:529
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20246
void * SkippedDefinitionContext
Definition: Sema.h:3949
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:916
SemaObjC & ObjC()
Definition: Sema.h:1111
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
Definition: SemaDecl.cpp:5350
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4954
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:72
@ AllowFold
Definition: Sema.h:7245
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1499
PragmaStack< bool > StrictGuardStackCheckStack
Definition: Sema.h:1661
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used.
Definition: Sema.h:3092
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
Definition: SemaDecl.cpp:2333
ASTContext & getASTContext() const
Definition: Sema.h:532
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
void CheckCoroutineWrapper(FunctionDecl *FD)
Definition: SemaDecl.cpp:15942
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
Definition: SemaDecl.cpp:1715
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17838
PragmaStack< StringLiteral * > ConstSegStack
Definition: Sema.h:1657
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:692
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:667
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3101
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition: SemaAttr.cpp:111
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
Definition: SemaDecl.cpp:4801
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9487
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20392
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:817
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
Definition: SemaDecl.cpp:5503
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1575
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
Definition: SemaDecl.cpp:16977
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:9079
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:11796
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:7962
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition: SemaAttr.cpp:792
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
Definition: SemaDecl.cpp:4391
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2180
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken)
Act on the result of classifying a name as a specific non-type declaration.
Definition: SemaDecl.cpp:1249
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:167
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition: Sema.h:4164
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:16876
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition: Sema.h:527
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:82
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2198
void PopCompoundScope()
Definition: Sema.cpp:2330
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:19761
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition: Sema.h:13941
@ UPPC_EnumeratorValue
The enumerator value.
Definition: Sema.h:13944
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13956
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:13950
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13929
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:13968
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition: Sema.h:13953
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:13932
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition: Sema.h:13935
const LangOptions & getLangOpts() const
Definition: Sema.h:525
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
SourceLocation CurInitSegLoc
Definition: Sema.h:1697
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:::lifetimebound]] attr for std:: functions and methods.
Definition: SemaAttr.cpp:219
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition: Sema.h:3109
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1390
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
Definition: SemaDecl.cpp:6612
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:6646
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1600
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition: Sema.h:908
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
Definition: SemaDecl.cpp:8279
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition: Sema.cpp:1980
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
const LangOptions & LangOpts
Definition: Sema.h:907
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2406
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition: Sema.h:15015
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15346
SemaHLSL & HLSL()
Definition: Sema.h:1076
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1832
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11956
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:18515
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
PragmaClangSection PragmaClangRelroSection
Definition: Sema.h:1434
SemaRISCV & RISCV()
Definition: Sema.h:1141
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition: Sema.h:15179
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *RetExpr, const AutoType *AT)
Deduce the return type for a function from a returned expression, per C++1y [dcl.spec....
Definition: SemaStmt.cpp:3717
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:205
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20077
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
SemaSwift & Swift()
Definition: Sema.h:1156
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
Definition: SemaAttr.cpp:1312
PragmaStack< AlignPackInfo > AlignPackStack
Definition: Sema.h:1646
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
Definition: SemaDecl.cpp:15828
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6480
PragmaStack< StringLiteral * > BSSSegStack
Definition: Sema.h:1656
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition: Sema.h:736
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9583
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
Definition: SemaType.cpp:8166
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition: SemaDecl.cpp:862
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
Definition: SemaDecl.cpp:16952
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1377
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8426
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
Definition: SemaDecl.cpp:12526
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:19787
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:940
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2325
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:14903
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Definition: SemaDecl.cpp:2289
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:2264
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:20280
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:18713
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6477
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1324
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
Definition: SemaDecl.cpp:18193
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:9841
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:8954
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3189
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:15009
StringLiteral * CurInitSeg
Last section used with #pragma init_seg.
Definition: Sema.h:1696
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20310
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:9588
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
AddOverriddenMethods - See if a method overrides any in the base classes, and if so,...
Definition: SemaDecl.cpp:8974
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:15452
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:18184
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15376
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1044
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:14943
SemaOpenCL & OpenCL()
Definition: Sema.h:1121
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5826
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15213
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:8467
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1291
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4746
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
Definition: SemaDecl.cpp:15803
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition: Sema.h:3106
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9242
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:15852
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:11058
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13509
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3842
@ NTK_Typedef
Definition: Sema.h:3847
@ NTK_NonUnion
Definition: Sema.h:3845
@ NTK_TypeAlias
Definition: Sema.h:3848
@ NTK_NonClass
Definition: Sema.h:3844
@ NTK_NonEnum
Definition: Sema.h:3846
@ NTK_NonStruct
Definition: Sema.h:3843
@ NTK_TemplateTemplateArgument
Definition: Sema.h:3851
@ NTK_TypeAliasTemplate
Definition: Sema.h:3850
@ NTK_Template
Definition: Sema.h:3849
SourceManager & getSourceManager() const
Definition: Sema.h:530
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_bits attribute.
Definition: Sema.h:3059
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
Definition: SemaDecl.cpp:4316
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:20042
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1342
bool areMultiversionVariantFunctionsCompatible(const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer)
Checks if the variant/multiversion functions are compatible.
Definition: SemaDecl.cpp:11234
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:18170
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
PragmaClangSection PragmaClangTextSection
Definition: Sema.h:1435
@ NTCUK_Destruct
Definition: Sema.h:3654
@ NTCUK_Init
Definition: Sema.h:3653
@ NTCUK_Copy
Definition: Sema.h:3655
PragmaClangSection PragmaClangDataSection
Definition: Sema.h:1432
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20263
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15880
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:13897
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc)
Act on the result of classifying a name as an undeclared (ADL-only) non-type declaration.
Definition: SemaDecl.cpp:1230
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname.
Definition: SemaDecl.cpp:20253
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition: SemaAttr.cpp:89
MaybeODRUseExprSet MaybeODRUseExprs
Definition: Sema.h:6287
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:216
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
TopLevelStmtDecl * ActOnStartTopLevelStmtDecl(Scope *S)
Definition: SemaDecl.cpp:20237
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8302
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
@ CTK_NonError
Definition: Sema.h:9383
@ CTK_ErrorRecovery
Definition: Sema.h:9384
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14307
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14828
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2346
RedeclarationKind forRedeclarationInCurContext() const
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
MergeVarDecl - We just parsed a variable 'New' which has the same name and scope as a previous declar...
Definition: SemaDecl.cpp:4507
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:6054
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition: SemaDecl.cpp:594
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
@ CCEK_Enumerator
Enumerator value with fixed underlying type.
Definition: Sema.h:10000
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
Definition: SemaDecl.cpp:18776
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3095
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
Definition: SemaDecl.cpp:1895
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition: Sema.h:3080
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:288
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:19573
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12561
ASTConsumer & Consumer
Definition: Sema.h:910
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4227
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:9787
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:9779
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:9783
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:6484
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2052
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:945
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1686
@ FirstDecl
Parsing the first decl in a TU.
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
Definition: SemaDecl.cpp:16573
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition: Sema.h:4043
@ AMK_None
Don't merge availability attributes at all.
Definition: Sema.h:4045
@ AMK_Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition: Sema.h:4051
@ AMK_ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition: Sema.h:4054
@ AMK_OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition: Sema.h:4057
@ AMK_Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition: Sema.h:4048
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14947
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5704
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14614
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:17161
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:4824
SemaPPC & PPC()
Definition: Sema.h:1131
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:76
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9120
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:15298
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:872
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1338
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20912
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19021
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD)
Only called on function definitions; if there is a MSVC #pragma optimize in scope,...
Definition: SemaAttr.cpp:1291
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
Definition: SemaDecl.cpp:11082
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:3099
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17915
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7917
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1310
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:912
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
Definition: SemaDecl.cpp:5779
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15937
DiagnosticsEngine & Diags
Definition: Sema.h:911
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:526
FPOptions CurFPFeatures
Definition: Sema.h:905
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15933
NamespaceDecl * getStdNamespace() const
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:6669
PragmaStack< StringLiteral * > DataSegStack
Definition: Sema.h:1655
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:693
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7293
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:14978
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11286
@ TPC_ClassTemplateMember
Definition: Sema.h:11284
@ TPC_FunctionTemplate
Definition: Sema.h:11283
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11287
@ TPC_VarTemplate
Definition: Sema.h:11282
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:6753
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:16428
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2070
void PopDeclContext()
Definition: SemaDecl.cpp:1317
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6066
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1581
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W)
DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak applied to it,...
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8885
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:13939
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:13107
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1566
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:16820
OffsetOfKind
Definition: Sema.h:3866
@ OOK_Outside
Definition: Sema.h:3868
@ OOK_Macro
Definition: Sema.h:3873
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13380
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:18412
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, IdentifierInfo *IIEnvironment)
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
Definition: SemaDecl.cpp:4352
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:14224
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:284
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition: Sema.h:3074
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1963
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21179
PragmaClangSection PragmaClangBSSSection
Definition: Sema.h:1431
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6088
@ AbstractVariableType
Definition: Sema.h:5759
@ AbstractReturnType
Definition: Sema.h:5757
@ AbstractFieldType
Definition: Sema.h:5760
@ AbstractIvarType
Definition: Sema.h:5761
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
void CheckAlignasUnderalignment(Decl *D)
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
Definition: SemaDecl.cpp:1705
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:7966
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand)
Act on the result of classifying a name as an undeclared member of a dependent base class.
Definition: SemaDecl.cpp:1239
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
Definition: SemaType.cpp:8180
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:20292
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:8638
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
Definition: SemaDecl.cpp:1324
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:13073
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New)
Definition: SemaDecl.cpp:2437
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2751
llvm::SmallPtrSet< const NamedDecl *, 4 > TypoCorrectedFunctionDefinitions
The function definitions which were renamed as part of typo-correction to match their respective decl...
Definition: Sema.h:3055
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
Definition: SemaAttr.cpp:1275
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
Definition: SemaDecl.cpp:15817
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:13359
SemaWasm & Wasm()
Definition: Sema.h:1166
IdentifierResolver IdResolver
Definition: Sema.h:3003
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
Definition: SemaDecl.cpp:20013
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2337
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:683
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl * > Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
Definition: SemaDecl.cpp:15187
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition: Sema.h:7925
bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling)
TemplateNameKindForDiagnostics
Describes the detailed kind of a template name. Used in diagnostics.
Definition: Sema.h:3375
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6075
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:16893
SemaARM & ARM()
Definition: Sema.h:1051
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:317
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8268
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Definition: SemaDecl.cpp:1266
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:295
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition: Expr.h:1931
StringRef getString() const
Definition: Expr.h:1855
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3578
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3853
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3701
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3676
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3662
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3681
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4780
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4771
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4763
bool isUnion() const
Definition: Decl.h:3784
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4826
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4863
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3802
TagKind getTagKind() const
Definition: Decl.h:3773
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Definition: TargetCXXABI.h:238
Exposes information about the current target.
Definition: TargetInfo.h:220
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1540
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:519
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
Definition: TargetInfo.h:1826
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1583
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1591
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1530
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1399
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:566
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
Definition: TargetInfo.h:1504
virtual uint64_t getFMVPriority(ArrayRef< StringRef > Features) const
Definition: TargetInfo.h:1534
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1300
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1493
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:657
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:398
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:417
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:207
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6667
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4338
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:4459
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5674
Represents a declaration of a type.
Definition: Decl.h:3384
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3410
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition: TypeLoc.h:338
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1257
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:206
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition: TypeLoc.cpp:749
SourceLocation getTemplateKeywordLoc() const
Get the SourceLocation of the template keyword (if any).
Definition: TypeLoc.cpp:756
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2716
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7908
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:7919
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6930
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3176
The base class of the type hierarchy.
Definition: Type.h:1828
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2511
bool isStructureType() const
Definition: Type.cpp:662
bool isDecltypeType() const
Definition: Type.h:8389
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isDependentSizedArrayType() const
Definition: Type.h:8284
bool isBlockPointerType() const
Definition: Type.h:8206
bool isVoidType() const
Definition: Type.h:8516
bool isBooleanType() const
Definition: Type.h:8648
bool isFunctionReferenceType() const
Definition: Type.h:8239
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2201
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8698
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2935
bool isIncompleteArrayType() const
Definition: Type.h:8272
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8819
bool isDependentAddressSpaceType() const
Definition: Type.h:8330
bool isConstantArrayType() const
Definition: Type.h:8268
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8678
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isArrayType() const
Definition: Type.h:8264
bool isFunctionPointerType() const
Definition: Type.h:8232
bool isPointerType() const
Definition: Type.h:8192
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2517
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8810
bool isReferenceType() const
Definition: Type.h:8210
bool isEnumeralType() const
Definition: Type.h:8296
bool isScalarType() const
Definition: Type.h:8619
bool isVariableArrayType() const
Definition: Type.h:8276
bool isClkEventT() const
Definition: Type.h:8407
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8635
bool isImageType() const
Definition: Type.h:8419
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2812
bool isPipeType() const
Definition: Type.h:8426
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2715
bool isBitIntType() const
Definition: Type.h:8430
bool isOpenCLSpecificType() const
Definition: Type.h:8455
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2707
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2372
bool isHalfType() const
Definition: Type.h:8520
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2045
bool isHLSLSpecificType() const
Definition: Type.h:8473
const RecordType * getAsStructureType() const
Definition: Type.cpp:754
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2501
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2701
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8691
bool isAtomicType() const
Definition: Type.h:8347
bool isFunctionProtoType() const
Definition: Type.h:2536
bool isObjCIdType() const
Definition: Type.h:8367
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2725
bool isObjCObjectType() const
Definition: Type.h:8338
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5046
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8654
bool isEventT() const
Definition: Type.h:8403
bool isPointerOrReferenceType() const
Definition: Type.h:8196
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4989
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:8758
bool isFunctionType() const
Definition: Type.h:8188
bool isObjCObjectPointerType() const
Definition: Type.h:8334
bool isMemberFunctionPointerType() const
Definition: Type.h:8250
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2539
bool isFloatingType() const
Definition: Type.cpp:2283
bool isAnyPointerType() const
Definition: Type.h:8200
TypeClass getTypeClass() const
Definition: Type.h:2341
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:2050
bool isSamplerT() const
Definition: Type.h:8399
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8741
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:638
bool isNullPtrType() const
Definition: Type.h:8553
bool isRecordType() const
Definition: Type.h:8292
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4761
bool isUnionType() const
Definition: Type.cpp:704
bool isFunctionNoProtoType() const
Definition: Type.h:2535
bool isReserveIDT() const
Definition: Type.h:8415
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1924
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1920
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3528
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5576
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3427
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3477
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:3492
QualType getUnderlyingType() const
Definition: Decl.h:3482
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3488
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5585
TypedefNameDecl * getDecl() const
Definition: Type.h:5746
QualType desugar() const
Definition: Type.cpp:3918
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
decl_iterator end()
decl_iterator begin()
SmallVectorImpl< NamedDecl * >::const_iterator const_decl_iterator
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition: ExprCXX.cpp:419
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3343
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3407
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3245
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5416
Represents a variable declaration or definition.
Definition: Decl.h:882
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2786
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2140
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1469
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1513
TLSKind getTLSKind() const
Definition: Decl.cpp:2157
bool hasInit() const
Definition: Decl.cpp:2387
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1396
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2249
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2179
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2433
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2246
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1522
bool isCXXCondDecl() const
Definition: Decl.h:1559
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:893
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition: Decl.h:896
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:890
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2152
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1541
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1177
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2355
void setInlineSpecified()
Definition: Decl.h:1502
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1159
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2748
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1293
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1124
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1495
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1128
const Expr * getInit() const
Definition: Decl.h:1319
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1168
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1135
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2418
void setConstexpr(bool IC)
Definition: Decl.h:1516
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:905
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:908
void setInit(Expr *I)
Definition: Decl.cpp:2449
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2334
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1249
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1246
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1252
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2791
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2234
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1204
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1119
void setImplicitlyInline()
Definition: Decl.h:1507
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1420
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1536
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2682
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1213
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2755
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition: Decl.h:1430
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2662
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3809
Expr * getSizeExpr() const
Definition: Type.h:3828
Captures information about a #pragma weak directive.
Definition: Weak.h:25
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
bool isVariableCapture() const
Definition: ScopeInfo.h:650
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:745
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:732
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:755
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1093
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:737
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition: ScopeInfo.h:141
void addByrefBlockVar(VarDecl *VD)
Definition: ScopeInfo.h:498
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition: ScopeInfo.h:150
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition: ScopeInfo.h:167
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition: ScopeInfo.h:145
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition: ScopeInfo.h:158
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:884
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition: ScopeInfo.h:915
ParmVarDecl * ExplicitObjectParameter
Definition: ScopeInfo.h:881
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition: ScopeInfo.h:948
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:871
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:874
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:896
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
Definition: Randstruct.cpp:173
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:32
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_struct
Definition: Specifiers.h:81
@ TST_class
Definition: Specifiers.h:82
@ TST_union
Definition: Specifiers.h:80
@ TST_enum
Definition: Specifiers.h:79
@ TST_interface
Definition: Specifiers.h:83
ImplicitTypenameContext
Definition: DeclSpec.h:1886
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
@ GNUMode
Definition: LangStandard.h:63
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ GVA_AvailableExternally
Definition: Linkage.h:74
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
Definition: AttrIterator.h:30
CUDAFunctionTarget
Definition: Cuda.h:147
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:35
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
OverloadCandidateDisplayKind
Definition: Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
@ LCK_ByRef
Capturing by reference.
Definition: Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition: Lambda.h:35
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:40
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition: Linkage.h:63
@ CLanguageLinkage
Definition: Linkage.h:64
@ CXXLanguageLinkage
Definition: Linkage.h:65
StorageClass
Storage classes.
Definition: Specifiers.h:248
@ SC_Auto
Definition: Specifiers.h:256
@ SC_PrivateExtern
Definition: Specifiers.h:253
@ SC_Extern
Definition: Specifiers.h:251
@ SC_Register
Definition: Specifiers.h:257
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:235
@ TSCS_thread_local
C++11 thread_local.
Definition: Specifiers.h:241
@ TSCS_unspecified
Definition: Specifiers.h:236
@ TSCS__Thread_local
C11 _Thread_local.
Definition: Specifiers.h:244
@ TSCS___thread
GNU __thread.
Definition: Specifiers.h:238
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Parameter
The parameter type of a method or function.
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:50
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:307
TagUseKind
Definition: Sema.h:447
TagTypeKind
The kind of a tag type.
Definition: Type.h:6877
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
@ Union
The "union" keyword.
@ Enum
The "enum" keyword.
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition: CharInfo.h:108
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
ExprResult ExprError()
Definition: Ownership.h:264
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1488
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
@ TU_Complete
The translation unit is a complete translation unit.
Definition: LangOptions.h:1099
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:75
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:423
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition: Lambda.h:22
@ LCD_ByRef
Definition: Lambda.h:25
@ LCD_None
Definition: Lambda.h:23
@ LCD_ByCopy
Definition: Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:229
const FunctionProtoType * T
MultiVersionKind
Definition: Decl.h:1914
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1278
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:365
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_C
Definition: Specifiers.h:279
@ CC_X86StdCall
Definition: Specifiers.h:280
@ None
The alignment was not explicit in code.
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition: Decl.cpp:5833
ReservedIdentifierStatus
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
@ AS_public
Definition: Specifiers.h:124
@ AS_protected
Definition: Specifiers.h:125
@ AS_none
Definition: Specifiers.h:127
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword).
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1428
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition: DeclSpec.h:1579
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1403
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1362
const IdentifierInfo * Ident
Definition: DeclSpec.h:1334
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1251
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1663
enum clang::DeclaratorChunk::@225 Kind
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:158
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1644
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1687
RetTy visit(QualType FT, Ts &&... Args)
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Extra information about a function prototype.
Definition: Type.h:5193
FunctionEffectsRef FunctionEffects
Definition: Type.h:5203
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:5213
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:58
std::vector< std::string > Features
Definition: TargetInfo.h:59
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
SourceLocation PragmaLocation
Definition: Sema.h:1428
ValueType CurrentValue
Definition: Sema.h:1631
bool CheckSameAsPrevious
Definition: Sema.h:351
NamedDecl * Previous
Definition: Sema.h:352
NamedDecl * New
Definition: Sema.h:353
Information about a template-id annotation token.
unsigned NumArgs
NumArgs - The number of template arguments.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.