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 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11385
11387 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11389 S.PDiag(diag::note_multiversioning_caused_here)),
11391 S.PDiag(diag::err_multiversion_doesnt_support)
11392 << static_cast<unsigned>(MVKind)),
11394 S.PDiag(diag::err_multiversion_diff)),
11395 /*TemplatesSupported=*/false,
11396 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11397 /*CLinkageMayDiffer=*/false);
11398}
11399
11400/// Check the validity of a multiversion function declaration that is the
11401/// first of its kind. Also sets the multiversion'ness' of the function itself.
11402///
11403/// This sets NewFD->isInvalidDecl() to true if there was an error.
11404///
11405/// Returns true if there was an error, false otherwise.
11408 assert(MVKind != MultiVersionKind::None &&
11409 "Function lacks multiversion attribute");
11410 const auto *TA = FD->getAttr<TargetAttr>();
11411 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11412 // The target attribute only causes MV if this declaration is the default,
11413 // otherwise it is treated as a normal function.
11414 if (TA && !TA->isDefaultVersion())
11415 return false;
11416
11417 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11418 FD->setInvalidDecl();
11419 return true;
11420 }
11421
11422 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11423 FD->setInvalidDecl();
11424 return true;
11425 }
11426
11427 FD->setIsMultiVersion();
11428 return false;
11429}
11430
11432 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11434 return true;
11435 }
11436
11437 return false;
11438}
11439
11441 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11442 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11443 return;
11444
11445 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11446 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11447
11448 if (MVKindTo == MultiVersionKind::None &&
11449 (MVKindFrom == MultiVersionKind::TargetVersion ||
11450 MVKindFrom == MultiVersionKind::TargetClones))
11451 To->addAttr(TargetVersionAttr::CreateImplicit(
11452 To->getASTContext(), "default", To->getSourceRange()));
11453}
11454
11456 FunctionDecl *NewFD,
11457 bool &Redeclaration,
11458 NamedDecl *&OldDecl,
11460 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11461
11462 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11463 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11464 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11465 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11466
11467 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11468
11469 // The definitions should be allowed in any order. If we have discovered
11470 // a new target version and the preceeding was the default, then add the
11471 // corresponding attribute to it.
11472 patchDefaultTargetVersion(NewFD, OldFD);
11473
11474 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11475 // to change, this is a simple redeclaration.
11476 if (NewTA && !NewTA->isDefaultVersion() &&
11477 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11478 return false;
11479
11480 // Otherwise, this decl causes MultiVersioning.
11481 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11484 NewFD->setInvalidDecl();
11485 return true;
11486 }
11487
11488 if (CheckMultiVersionValue(S, NewFD)) {
11489 NewFD->setInvalidDecl();
11490 return true;
11491 }
11492
11493 // If this is 'default', permit the forward declaration.
11494 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11495 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11496 Redeclaration = true;
11497 OldDecl = OldFD;
11498 OldFD->setIsMultiVersion();
11499 NewFD->setIsMultiVersion();
11500 return false;
11501 }
11502
11503 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11504 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11505 NewFD->setInvalidDecl();
11506 return true;
11507 }
11508
11509 if (NewTA) {
11510 ParsedTargetAttr OldParsed =
11512 OldTA->getFeaturesStr());
11513 llvm::sort(OldParsed.Features);
11514 ParsedTargetAttr NewParsed =
11516 NewTA->getFeaturesStr());
11517 // Sort order doesn't matter, it just needs to be consistent.
11518 llvm::sort(NewParsed.Features);
11519 if (OldParsed == NewParsed) {
11520 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11521 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11522 NewFD->setInvalidDecl();
11523 return true;
11524 }
11525 }
11526
11527 for (const auto *FD : OldFD->redecls()) {
11528 const auto *CurTA = FD->getAttr<TargetAttr>();
11529 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11530 // We allow forward declarations before ANY multiversioning attributes, but
11531 // nothing after the fact.
11533 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11534 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11535 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11536 << (NewTA ? 0 : 2);
11537 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11538 NewFD->setInvalidDecl();
11539 return true;
11540 }
11541 }
11542
11543 OldFD->setIsMultiVersion();
11544 NewFD->setIsMultiVersion();
11545 Redeclaration = false;
11546 OldDecl = nullptr;
11547 Previous.clear();
11548 return false;
11549}
11550
11552 MultiVersionKind OldKind = Old->getMultiVersionKind();
11553 MultiVersionKind NewKind = New->getMultiVersionKind();
11554
11555 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11556 NewKind == MultiVersionKind::None)
11557 return true;
11558
11559 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11560 switch (OldKind) {
11562 return NewKind == MultiVersionKind::TargetClones;
11564 return NewKind == MultiVersionKind::TargetVersion;
11565 default:
11566 return false;
11567 }
11568 } else {
11569 switch (OldKind) {
11571 return NewKind == MultiVersionKind::CPUSpecific;
11573 return NewKind == MultiVersionKind::CPUDispatch;
11574 default:
11575 return false;
11576 }
11577 }
11578}
11579
11580/// Check the validity of a new function declaration being added to an existing
11581/// multiversioned declaration collection.
11583 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11584 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11585 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11587
11588 // Disallow mixing of multiversioning types.
11589 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11590 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11591 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11592 NewFD->setInvalidDecl();
11593 return true;
11594 }
11595
11596 // Add the default target_version attribute if it's missing.
11597 patchDefaultTargetVersion(OldFD, NewFD);
11598 patchDefaultTargetVersion(NewFD, OldFD);
11599
11600 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11601 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11602 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11603 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11604
11605 ParsedTargetAttr NewParsed;
11606 if (NewTA) {
11608 NewTA->getFeaturesStr());
11609 llvm::sort(NewParsed.Features);
11610 }
11612 if (NewTVA) {
11613 NewTVA->getFeatures(NewFeats);
11614 llvm::sort(NewFeats);
11615 }
11616
11617 bool UseMemberUsingDeclRules =
11618 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11619
11620 bool MayNeedOverloadableChecks =
11622
11623 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11624 // of a previous member of the MultiVersion set.
11625 for (NamedDecl *ND : Previous) {
11626 FunctionDecl *CurFD = ND->getAsFunction();
11627 if (!CurFD || CurFD->isInvalidDecl())
11628 continue;
11629 if (MayNeedOverloadableChecks &&
11630 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11631 continue;
11632
11633 switch (NewMVKind) {
11635 assert(OldMVKind == MultiVersionKind::TargetClones &&
11636 "Only target_clones can be omitted in subsequent declarations");
11637 break;
11639 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11640 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11641 NewFD->setIsMultiVersion();
11642 Redeclaration = true;
11643 OldDecl = ND;
11644 return false;
11645 }
11646
11647 ParsedTargetAttr CurParsed =
11649 CurTA->getFeaturesStr());
11650 llvm::sort(CurParsed.Features);
11651 if (CurParsed == NewParsed) {
11652 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11653 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11654 NewFD->setInvalidDecl();
11655 return true;
11656 }
11657 break;
11658 }
11660 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11661 if (CurTVA->getName() == NewTVA->getName()) {
11662 NewFD->setIsMultiVersion();
11663 Redeclaration = true;
11664 OldDecl = ND;
11665 return false;
11666 }
11668 CurTVA->getFeatures(CurFeats);
11669 llvm::sort(CurFeats);
11670
11671 if (CurFeats == NewFeats) {
11672 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11673 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11674 NewFD->setInvalidDecl();
11675 return true;
11676 }
11677 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11678 // Default
11679 if (NewFeats.empty())
11680 break;
11681
11682 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11684 CurClones->getFeatures(CurFeats, I);
11685 llvm::sort(CurFeats);
11686
11687 if (CurFeats == NewFeats) {
11688 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11689 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11690 NewFD->setInvalidDecl();
11691 return true;
11692 }
11693 }
11694 }
11695 break;
11696 }
11698 assert(NewClones && "MultiVersionKind does not match attribute type");
11699 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11700 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11701 !std::equal(CurClones->featuresStrs_begin(),
11702 CurClones->featuresStrs_end(),
11703 NewClones->featuresStrs_begin())) {
11704 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11705 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11706 NewFD->setInvalidDecl();
11707 return true;
11708 }
11709 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11711 CurTVA->getFeatures(CurFeats);
11712 llvm::sort(CurFeats);
11713
11714 // Default
11715 if (CurFeats.empty())
11716 break;
11717
11718 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11719 NewFeats.clear();
11720 NewClones->getFeatures(NewFeats, I);
11721 llvm::sort(NewFeats);
11722
11723 if (CurFeats == NewFeats) {
11724 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11725 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11726 NewFD->setInvalidDecl();
11727 return true;
11728 }
11729 }
11730 break;
11731 }
11732 Redeclaration = true;
11733 OldDecl = CurFD;
11734 NewFD->setIsMultiVersion();
11735 return false;
11736 }
11739 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11740 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11741 // Handle CPUDispatch/CPUSpecific versions.
11742 // Only 1 CPUDispatch function is allowed, this will make it go through
11743 // the redeclaration errors.
11744 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11745 CurFD->hasAttr<CPUDispatchAttr>()) {
11746 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11747 std::equal(
11748 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11749 NewCPUDisp->cpus_begin(),
11750 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11751 return Cur->getName() == New->getName();
11752 })) {
11753 NewFD->setIsMultiVersion();
11754 Redeclaration = true;
11755 OldDecl = ND;
11756 return false;
11757 }
11758
11759 // If the declarations don't match, this is an error condition.
11760 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11761 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11762 NewFD->setInvalidDecl();
11763 return true;
11764 }
11765 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11766 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11767 std::equal(
11768 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11769 NewCPUSpec->cpus_begin(),
11770 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11771 return Cur->getName() == New->getName();
11772 })) {
11773 NewFD->setIsMultiVersion();
11774 Redeclaration = true;
11775 OldDecl = ND;
11776 return false;
11777 }
11778
11779 // Only 1 version of CPUSpecific is allowed for each CPU.
11780 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11781 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11782 if (CurII == NewII) {
11783 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11784 << NewII;
11785 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11786 NewFD->setInvalidDecl();
11787 return true;
11788 }
11789 }
11790 }
11791 }
11792 break;
11793 }
11794 }
11795 }
11796
11797 // Else, this is simply a non-redecl case. Checking the 'value' is only
11798 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11799 // handled in the attribute adding step.
11800 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
11801 NewFD->setInvalidDecl();
11802 return true;
11803 }
11804
11805 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11806 !OldFD->isMultiVersion(), NewMVKind)) {
11807 NewFD->setInvalidDecl();
11808 return true;
11809 }
11810
11811 // Permit forward declarations in the case where these two are compatible.
11812 if (!OldFD->isMultiVersion()) {
11813 OldFD->setIsMultiVersion();
11814 NewFD->setIsMultiVersion();
11815 Redeclaration = true;
11816 OldDecl = OldFD;
11817 return false;
11818 }
11819
11820 NewFD->setIsMultiVersion();
11821 Redeclaration = false;
11822 OldDecl = nullptr;
11823 Previous.clear();
11824 return false;
11825}
11826
11827/// Check the validity of a mulitversion function declaration.
11828/// Also sets the multiversion'ness' of the function itself.
11829///
11830/// This sets NewFD->isInvalidDecl() to true if there was an error.
11831///
11832/// Returns true if there was an error, false otherwise.
11834 bool &Redeclaration, NamedDecl *&OldDecl,
11836 const TargetInfo &TI = S.getASTContext().getTargetInfo();
11837
11838 // Check if FMV is disabled.
11839 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
11840 return false;
11841
11842 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11843 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11844 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11845 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11846 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11847 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11848
11849 // Main isn't allowed to become a multiversion function, however it IS
11850 // permitted to have 'main' be marked with the 'target' optimization hint,
11851 // for 'target_version' only default is allowed.
11852 if (NewFD->isMain()) {
11853 if (MVKind != MultiVersionKind::None &&
11854 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11855 !(MVKind == MultiVersionKind::TargetVersion &&
11856 NewTVA->isDefaultVersion())) {
11857 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11858 NewFD->setInvalidDecl();
11859 return true;
11860 }
11861 return false;
11862 }
11863
11864 // Target attribute on AArch64 is not used for multiversioning
11865 if (NewTA && TI.getTriple().isAArch64())
11866 return false;
11867
11868 // Target attribute on RISCV is not used for multiversioning
11869 if (NewTA && TI.getTriple().isRISCV())
11870 return false;
11871
11872 if (!OldDecl || !OldDecl->getAsFunction() ||
11873 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
11874 NewFD->getDeclContext()->getRedeclContext())) {
11875 // If there's no previous declaration, AND this isn't attempting to cause
11876 // multiversioning, this isn't an error condition.
11877 if (MVKind == MultiVersionKind::None)
11878 return false;
11879 return CheckMultiVersionFirstFunction(S, NewFD);
11880 }
11881
11882 FunctionDecl *OldFD = OldDecl->getAsFunction();
11883
11884 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11885 return false;
11886
11887 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11888 // for target_clones and target_version.
11889 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11892 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11894 NewFD->setInvalidDecl();
11895 return true;
11896 }
11897
11898 if (!OldFD->isMultiVersion()) {
11899 switch (MVKind) {
11903 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
11905 if (OldFD->isUsed(false)) {
11906 NewFD->setInvalidDecl();
11907 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11908 }
11909 OldFD->setIsMultiVersion();
11910 break;
11911
11915 break;
11916 }
11917 }
11918
11919 // At this point, we have a multiversion function decl (in OldFD) AND an
11920 // appropriate attribute in the current function decl. Resolve that these are
11921 // still compatible with previous declarations.
11922 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11923 NewCPUSpec, NewClones, Redeclaration,
11924 OldDecl, Previous);
11925}
11926
11928 bool IsPure = NewFD->hasAttr<PureAttr>();
11929 bool IsConst = NewFD->hasAttr<ConstAttr>();
11930
11931 // If there are no pure or const attributes, there's nothing to check.
11932 if (!IsPure && !IsConst)
11933 return;
11934
11935 // If the function is marked both pure and const, we retain the const
11936 // attribute because it makes stronger guarantees than the pure attribute, and
11937 // we drop the pure attribute explicitly to prevent later confusion about
11938 // semantics.
11939 if (IsPure && IsConst) {
11940 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
11941 NewFD->dropAttrs<PureAttr>();
11942 }
11943
11944 // Constructors and destructors are functions which return void, so are
11945 // handled here as well.
11946 if (NewFD->getReturnType()->isVoidType()) {
11947 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
11948 << IsConst;
11949 NewFD->dropAttrs<PureAttr, ConstAttr>();
11950 }
11951}
11952
11955 bool IsMemberSpecialization,
11956 bool DeclIsDefn) {
11957 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11958 "Variably modified return types are not handled here");
11959
11960 // Determine whether the type of this function should be merged with
11961 // a previous visible declaration. This never happens for functions in C++,
11962 // and always happens in C if the previous declaration was visible.
11963 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11964 !Previous.isShadowed();
11965
11966 bool Redeclaration = false;
11967 NamedDecl *OldDecl = nullptr;
11968 bool MayNeedOverloadableChecks = false;
11969
11971 // Merge or overload the declaration with an existing declaration of
11972 // the same name, if appropriate.
11973 if (!Previous.empty()) {
11974 // Determine whether NewFD is an overload of PrevDecl or
11975 // a declaration that requires merging. If it's an overload,
11976 // there's no more work to do here; we'll just add the new
11977 // function to the scope.
11979 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11980 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11981 Redeclaration = true;
11982 OldDecl = Candidate;
11983 }
11984 } else {
11985 MayNeedOverloadableChecks = true;
11986 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11987 /*NewIsUsingDecl*/ false)) {
11988 case Ovl_Match:
11989 Redeclaration = true;
11990 break;
11991
11992 case Ovl_NonFunction:
11993 Redeclaration = true;
11994 break;
11995
11996 case Ovl_Overload:
11997 Redeclaration = false;
11998 break;
11999 }
12000 }
12001 }
12002
12003 // Check for a previous extern "C" declaration with this name.
12004 if (!Redeclaration &&
12006 if (!Previous.empty()) {
12007 // This is an extern "C" declaration with the same name as a previous
12008 // declaration, and thus redeclares that entity...
12009 Redeclaration = true;
12010 OldDecl = Previous.getFoundDecl();
12011 MergeTypeWithPrevious = false;
12012
12013 // ... except in the presence of __attribute__((overloadable)).
12014 if (OldDecl->hasAttr<OverloadableAttr>() ||
12015 NewFD->hasAttr<OverloadableAttr>()) {
12016 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12017 MayNeedOverloadableChecks = true;
12018 Redeclaration = false;
12019 OldDecl = nullptr;
12020 }
12021 }
12022 }
12023 }
12024
12025 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12026 return Redeclaration;
12027
12028 // PPC MMA non-pointer types are not allowed as function return types.
12029 if (Context.getTargetInfo().getTriple().isPPC64() &&
12030 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12031 NewFD->setInvalidDecl();
12032 }
12033
12034 CheckConstPureAttributesUsage(*this, NewFD);
12035
12036 // C++ [dcl.spec.auto.general]p12:
12037 // Return type deduction for a templated function with a placeholder in its
12038 // declared type occurs when the definition is instantiated even if the
12039 // function body contains a return statement with a non-type-dependent
12040 // operand.
12041 //
12042 // C++ [temp.dep.expr]p3:
12043 // An id-expression is type-dependent if it is a template-id that is not a
12044 // concept-id and is dependent; or if its terminal name is:
12045 // - [...]
12046 // - associated by name lookup with one or more declarations of member
12047 // functions of a class that is the current instantiation declared with a
12048 // return type that contains a placeholder type,
12049 // - [...]
12050 //
12051 // If this is a templated function with a placeholder in its return type,
12052 // make the placeholder type dependent since it won't be deduced until the
12053 // definition is instantiated. We do this here because it needs to happen
12054 // for implicitly instantiated member functions/member function templates.
12055 if (getLangOpts().CPlusPlus14 &&
12056 (NewFD->isDependentContext() &&
12057 NewFD->getReturnType()->isUndeducedType())) {
12058 const FunctionProtoType *FPT =
12059 NewFD->getType()->castAs<FunctionProtoType>();
12060 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12061 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12062 FPT->getExtProtoInfo()));
12063 }
12064
12065 // C++11 [dcl.constexpr]p8:
12066 // A constexpr specifier for a non-static member function that is not
12067 // a constructor declares that member function to be const.
12068 //
12069 // This needs to be delayed until we know whether this is an out-of-line
12070 // definition of a static member function.
12071 //
12072 // This rule is not present in C++1y, so we produce a backwards
12073 // compatibility warning whenever it happens in C++11.
12074 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12075 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12076 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12077 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
12078 CXXMethodDecl *OldMD = nullptr;
12079 if (OldDecl)
12080 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12081 if (!OldMD || !OldMD->isStatic()) {
12082 const FunctionProtoType *FPT =
12085 EPI.TypeQuals.addConst();
12087 FPT->getParamTypes(), EPI));
12088
12089 // Warn that we did this, if we're not performing template instantiation.
12090 // In that case, we'll have warned already when the template was defined.
12091 if (!inTemplateInstantiation()) {
12092 SourceLocation AddConstLoc;
12095 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12096
12097 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12098 << FixItHint::CreateInsertion(AddConstLoc, " const");
12099 }
12100 }
12101 }
12102
12103 if (Redeclaration) {
12104 // NewFD and OldDecl represent declarations that need to be
12105 // merged.
12106 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12107 DeclIsDefn)) {
12108 NewFD->setInvalidDecl();
12109 return Redeclaration;
12110 }
12111
12112 Previous.clear();
12113 Previous.addDecl(OldDecl);
12114
12115 if (FunctionTemplateDecl *OldTemplateDecl =
12116 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12117 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12118 FunctionTemplateDecl *NewTemplateDecl
12120 assert(NewTemplateDecl && "Template/non-template mismatch");
12121
12122 // The call to MergeFunctionDecl above may have created some state in
12123 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12124 // can add it as a redeclaration.
12125 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12126
12127 NewFD->setPreviousDeclaration(OldFD);
12128 if (NewFD->isCXXClassMember()) {
12129 NewFD->setAccess(OldTemplateDecl->getAccess());
12130 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12131 }
12132
12133 // If this is an explicit specialization of a member that is a function
12134 // template, mark it as a member specialization.
12135 if (IsMemberSpecialization &&
12136 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12137 NewTemplateDecl->setMemberSpecialization();
12138 assert(OldTemplateDecl->isMemberSpecialization());
12139 // Explicit specializations of a member template do not inherit deleted
12140 // status from the parent member template that they are specializing.
12141 if (OldFD->isDeleted()) {
12142 // FIXME: This assert will not hold in the presence of modules.
12143 assert(OldFD->getCanonicalDecl() == OldFD);
12144 // FIXME: We need an update record for this AST mutation.
12145 OldFD->setDeletedAsWritten(false);
12146 }
12147 }
12148
12149 } else {
12150 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12151 auto *OldFD = cast<FunctionDecl>(OldDecl);
12152 // This needs to happen first so that 'inline' propagates.
12153 NewFD->setPreviousDeclaration(OldFD);
12154 if (NewFD->isCXXClassMember())
12155 NewFD->setAccess(OldFD->getAccess());
12156 }
12157 }
12158 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12159 !NewFD->getAttr<OverloadableAttr>()) {
12160 assert((Previous.empty() ||
12161 llvm::any_of(Previous,
12162 [](const NamedDecl *ND) {
12163 return ND->hasAttr<OverloadableAttr>();
12164 })) &&
12165 "Non-redecls shouldn't happen without overloadable present");
12166
12167 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12168 const auto *FD = dyn_cast<FunctionDecl>(ND);
12169 return FD && !FD->hasAttr<OverloadableAttr>();
12170 });
12171
12172 if (OtherUnmarkedIter != Previous.end()) {
12173 Diag(NewFD->getLocation(),
12174 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12175 Diag((*OtherUnmarkedIter)->getLocation(),
12176 diag::note_attribute_overloadable_prev_overload)
12177 << false;
12178
12179 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12180 }
12181 }
12182
12183 if (LangOpts.OpenMP)
12185
12186 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12188
12189 // Semantic checking for this function declaration (in isolation).
12190
12191 if (getLangOpts().CPlusPlus) {
12192 // C++-specific checks.
12193 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12194 CheckConstructor(Constructor);
12195 } else if (CXXDestructorDecl *Destructor =
12196 dyn_cast<CXXDestructorDecl>(NewFD)) {
12197 // We check here for invalid destructor names.
12198 // If we have a friend destructor declaration that is dependent, we can't
12199 // diagnose right away because cases like this are still valid:
12200 // template <class T> struct A { friend T::X::~Y(); };
12201 // struct B { struct Y { ~Y(); }; using X = Y; };
12202 // template struct A<B>;
12204 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12205 CXXRecordDecl *Record = Destructor->getParent();
12207
12209 Context.getCanonicalType(ClassType));
12210 if (NewFD->getDeclName() != Name) {
12211 Diag(NewFD->getLocation(), diag::err_destructor_name);
12212 NewFD->setInvalidDecl();
12213 return Redeclaration;
12214 }
12215 }
12216 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12217 if (auto *TD = Guide->getDescribedFunctionTemplate())
12219
12220 // A deduction guide is not on the list of entities that can be
12221 // explicitly specialized.
12222 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12223 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12224 << /*explicit specialization*/ 1;
12225 }
12226
12227 // Find any virtual functions that this function overrides.
12228 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12229 if (!Method->isFunctionTemplateSpecialization() &&
12230 !Method->getDescribedFunctionTemplate() &&
12231 Method->isCanonicalDecl()) {
12232 AddOverriddenMethods(Method->getParent(), Method);
12233 }
12234 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12235 // C++2a [class.virtual]p6
12236 // A virtual method shall not have a requires-clause.
12238 diag::err_constrained_virtual_method);
12239
12240 if (Method->isStatic())
12242 }
12243
12244 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12245 ActOnConversionDeclarator(Conversion);
12246
12247 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12248 if (NewFD->isOverloadedOperator() &&
12250 NewFD->setInvalidDecl();
12251 return Redeclaration;
12252 }
12253
12254 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12255 if (NewFD->getLiteralIdentifier() &&
12257 NewFD->setInvalidDecl();
12258 return Redeclaration;
12259 }
12260
12261 // In C++, check default arguments now that we have merged decls. Unless
12262 // the lexical context is the class, because in this case this is done
12263 // during delayed parsing anyway.
12264 if (!CurContext->isRecord())
12266
12267 // If this function is declared as being extern "C", then check to see if
12268 // the function returns a UDT (class, struct, or union type) that is not C
12269 // compatible, and if it does, warn the user.
12270 // But, issue any diagnostic on the first declaration only.
12271 if (Previous.empty() && NewFD->isExternC()) {
12272 QualType R = NewFD->getReturnType();
12273 if (R->isIncompleteType() && !R->isVoidType())
12274 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12275 << NewFD << R;
12276 else if (!R.isPODType(Context) && !R->isVoidType() &&
12278 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12279 }
12280
12281 // C++1z [dcl.fct]p6:
12282 // [...] whether the function has a non-throwing exception-specification
12283 // [is] part of the function type
12284 //
12285 // This results in an ABI break between C++14 and C++17 for functions whose
12286 // declared type includes an exception-specification in a parameter or
12287 // return type. (Exception specifications on the function itself are OK in
12288 // most cases, and exception specifications are not permitted in most other
12289 // contexts where they could make it into a mangling.)
12290 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12291 auto HasNoexcept = [&](QualType T) -> bool {
12292 // Strip off declarator chunks that could be between us and a function
12293 // type. We don't need to look far, exception specifications are very
12294 // restricted prior to C++17.
12295 if (auto *RT = T->getAs<ReferenceType>())
12296 T = RT->getPointeeType();
12297 else if (T->isAnyPointerType())
12298 T = T->getPointeeType();
12299 else if (auto *MPT = T->getAs<MemberPointerType>())
12300 T = MPT->getPointeeType();
12301 if (auto *FPT = T->getAs<FunctionProtoType>())
12302 if (FPT->isNothrow())
12303 return true;
12304 return false;
12305 };
12306
12307 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12308 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12309 for (QualType T : FPT->param_types())
12310 AnyNoexcept |= HasNoexcept(T);
12311 if (AnyNoexcept)
12312 Diag(NewFD->getLocation(),
12313 diag::warn_cxx17_compat_exception_spec_in_signature)
12314 << NewFD;
12315 }
12316
12317 if (!Redeclaration && LangOpts.CUDA) {
12318 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12319 for (auto *Parm : NewFD->parameters()) {
12320 if (!Parm->getType()->isDependentType() &&
12321 Parm->hasAttr<CUDAGridConstantAttr>() &&
12322 !(IsKernel && Parm->getType().isConstQualified()))
12323 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12324 diag::err_cuda_grid_constant_not_allowed);
12325 }
12327 }
12328 }
12329
12330 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12332
12333 return Redeclaration;
12334}
12335
12337 // [basic.start.main]p3
12338 // The main function shall not be declared with a linkage-specification.
12339 if (FD->isExternCContext() ||
12340 (FD->isExternCXXContext() &&
12342 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification)
12343 << FD->getLanguageLinkage();
12344
12345 // C++11 [basic.start.main]p3:
12346 // A program that [...] declares main to be inline, static or
12347 // constexpr is ill-formed.
12348 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12349 // appear in a declaration of main.
12350 // static main is not an error under C99, but we should warn about it.
12351 // We accept _Noreturn main as an extension.
12352 if (FD->getStorageClass() == SC_Static)
12354 ? diag::err_static_main : diag::warn_static_main)
12356 if (FD->isInlineSpecified())
12357 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12359 if (DS.isNoreturnSpecified()) {
12360 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12361 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12362 Diag(NoreturnLoc, diag::ext_noreturn_main);
12363 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12364 << FixItHint::CreateRemoval(NoreturnRange);
12365 }
12366 if (FD->isConstexpr()) {
12367 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12368 << FD->isConsteval()
12371 }
12372
12373 if (getLangOpts().OpenCL) {
12374 Diag(FD->getLocation(), diag::err_opencl_no_main)
12375 << FD->hasAttr<OpenCLKernelAttr>();
12376 FD->setInvalidDecl();
12377 return;
12378 }
12379
12380 // Functions named main in hlsl are default entries, but don't have specific
12381 // signatures they are required to conform to.
12382 if (getLangOpts().HLSL)
12383 return;
12384
12385 QualType T = FD->getType();
12386 assert(T->isFunctionType() && "function decl is not of function type");
12387 const FunctionType* FT = T->castAs<FunctionType>();
12388
12389 // Set default calling convention for main()
12390 if (FT->getCallConv() != CC_C) {
12392 FD->setType(QualType(FT, 0));
12394 }
12395
12396 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12397 // In C with GNU extensions we allow main() to have non-integer return
12398 // type, but we should warn about the extension, and we disable the
12399 // implicit-return-zero rule.
12400
12401 // GCC in C mode accepts qualified 'int'.
12403 FD->setHasImplicitReturnZero(true);
12404 else {
12405 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12406 SourceRange RTRange = FD->getReturnTypeSourceRange();
12407 if (RTRange.isValid())
12408 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12409 << FixItHint::CreateReplacement(RTRange, "int");
12410 }
12411 } else {
12412 // In C and C++, main magically returns 0 if you fall off the end;
12413 // set the flag which tells us that.
12414 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12415
12416 // All the standards say that main() should return 'int'.
12418 FD->setHasImplicitReturnZero(true);
12419 else {
12420 // Otherwise, this is just a flat-out error.
12421 SourceRange RTRange = FD->getReturnTypeSourceRange();
12422 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12423 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12424 : FixItHint());
12425 FD->setInvalidDecl(true);
12426 }
12427 }
12428
12429 // Treat protoless main() as nullary.
12430 if (isa<FunctionNoProtoType>(FT)) return;
12431
12432 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12433 unsigned nparams = FTP->getNumParams();
12434 assert(FD->getNumParams() == nparams);
12435
12436 bool HasExtraParameters = (nparams > 3);
12437
12438 if (FTP->isVariadic()) {
12439 Diag(FD->getLocation(), diag::ext_variadic_main);
12440 // FIXME: if we had information about the location of the ellipsis, we
12441 // could add a FixIt hint to remove it as a parameter.
12442 }
12443
12444 // Darwin passes an undocumented fourth argument of type char**. If
12445 // other platforms start sprouting these, the logic below will start
12446 // getting shifty.
12447 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12448 HasExtraParameters = false;
12449
12450 if (HasExtraParameters) {
12451 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12452 FD->setInvalidDecl(true);
12453 nparams = 3;
12454 }
12455
12456 // FIXME: a lot of the following diagnostics would be improved
12457 // if we had some location information about types.
12458
12459 QualType CharPP =
12461 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12462
12463 for (unsigned i = 0; i < nparams; ++i) {
12464 QualType AT = FTP->getParamType(i);
12465
12466 bool mismatch = true;
12467
12469 mismatch = false;
12470 else if (Expected[i] == CharPP) {
12471 // As an extension, the following forms are okay:
12472 // char const **
12473 // char const * const *
12474 // char * const *
12475
12477 const PointerType* PT;
12478 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12479 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12481 Context.CharTy)) {
12482 qs.removeConst();
12483 mismatch = !qs.empty();
12484 }
12485 }
12486
12487 if (mismatch) {
12488 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12489 // TODO: suggest replacing given type with expected type
12490 FD->setInvalidDecl(true);
12491 }
12492 }
12493
12494 if (nparams == 1 && !FD->isInvalidDecl()) {
12495 Diag(FD->getLocation(), diag::warn_main_one_arg);
12496 }
12497
12498 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12499 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12500 FD->setInvalidDecl();
12501 }
12502}
12503
12504static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12505
12506 // Default calling convention for main and wmain is __cdecl
12507 if (FD->getName() == "main" || FD->getName() == "wmain")
12508 return false;
12509
12510 // Default calling convention for MinGW is __cdecl
12511 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12512 if (T.isWindowsGNUEnvironment())
12513 return false;
12514
12515 // Default calling convention for WinMain, wWinMain and DllMain
12516 // is __stdcall on 32 bit Windows
12517 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12518 return true;
12519
12520 return false;
12521}
12522
12524 QualType T = FD->getType();
12525 assert(T->isFunctionType() && "function decl is not of function type");
12526 const FunctionType *FT = T->castAs<FunctionType>();
12527
12528 // Set an implicit return of 'zero' if the function can return some integral,
12529 // enumeration, pointer or nullptr type.
12533 // DllMain is exempt because a return value of zero means it failed.
12534 if (FD->getName() != "DllMain")
12535 FD->setHasImplicitReturnZero(true);
12536
12537 // Explicitly specified calling conventions are applied to MSVC entry points
12538 if (!hasExplicitCallingConv(T)) {
12539 if (isDefaultStdCall(FD, *this)) {
12540 if (FT->getCallConv() != CC_X86StdCall) {
12543 FD->setType(QualType(FT, 0));
12544 }
12545 } else if (FT->getCallConv() != CC_C) {
12548 FD->setType(QualType(FT, 0));
12549 }
12550 }
12551
12552 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12553 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12554 FD->setInvalidDecl();
12555 }
12556}
12557
12559 // FIXME: Need strict checking. In C89, we need to check for
12560 // any assignment, increment, decrement, function-calls, or
12561 // commas outside of a sizeof. In C99, it's the same list,
12562 // except that the aforementioned are allowed in unevaluated
12563 // expressions. Everything else falls under the
12564 // "may accept other forms of constant expressions" exception.
12565 //
12566 // Regular C++ code will not end up here (exceptions: language extensions,
12567 // OpenCL C++ etc), so the constant expression rules there don't matter.
12568 if (Init->isValueDependent()) {
12569 assert(Init->containsErrors() &&
12570 "Dependent code should only occur in error-recovery path.");
12571 return true;
12572 }
12573 const Expr *Culprit;
12574 if (Init->isConstantInitializer(Context, false, &Culprit))
12575 return false;
12576 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12577 return true;
12578}
12579
12580namespace {
12581 // Visits an initialization expression to see if OrigDecl is evaluated in
12582 // its own initialization and throws a warning if it does.
12583 class SelfReferenceChecker
12584 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12585 Sema &S;
12586 Decl *OrigDecl;
12587 bool isRecordType;
12588 bool isPODType;
12589 bool isReferenceType;
12590
12591 bool isInitList;
12592 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12593
12594 public:
12596
12597 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12598 S(S), OrigDecl(OrigDecl) {
12599 isPODType = false;
12600 isRecordType = false;
12601 isReferenceType = false;
12602 isInitList = false;
12603 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12604 isPODType = VD->getType().isPODType(S.Context);
12605 isRecordType = VD->getType()->isRecordType();
12606 isReferenceType = VD->getType()->isReferenceType();
12607 }
12608 }
12609
12610 // For most expressions, just call the visitor. For initializer lists,
12611 // track the index of the field being initialized since fields are
12612 // initialized in order allowing use of previously initialized fields.
12613 void CheckExpr(Expr *E) {
12614 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12615 if (!InitList) {
12616 Visit(E);
12617 return;
12618 }
12619
12620 // Track and increment the index here.
12621 isInitList = true;
12622 InitFieldIndex.push_back(0);
12623 for (auto *Child : InitList->children()) {
12624 CheckExpr(cast<Expr>(Child));
12625 ++InitFieldIndex.back();
12626 }
12627 InitFieldIndex.pop_back();
12628 }
12629
12630 // Returns true if MemberExpr is checked and no further checking is needed.
12631 // Returns false if additional checking is required.
12632 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12634 Expr *Base = E;
12635 bool ReferenceField = false;
12636
12637 // Get the field members used.
12638 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12639 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12640 if (!FD)
12641 return false;
12642 Fields.push_back(FD);
12643 if (FD->getType()->isReferenceType())
12644 ReferenceField = true;
12645 Base = ME->getBase()->IgnoreParenImpCasts();
12646 }
12647
12648 // Keep checking only if the base Decl is the same.
12649 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12650 if (!DRE || DRE->getDecl() != OrigDecl)
12651 return false;
12652
12653 // A reference field can be bound to an unininitialized field.
12654 if (CheckReference && !ReferenceField)
12655 return true;
12656
12657 // Convert FieldDecls to their index number.
12658 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12659 for (const FieldDecl *I : llvm::reverse(Fields))
12660 UsedFieldIndex.push_back(I->getFieldIndex());
12661
12662 // See if a warning is needed by checking the first difference in index
12663 // numbers. If field being used has index less than the field being
12664 // initialized, then the use is safe.
12665 for (auto UsedIter = UsedFieldIndex.begin(),
12666 UsedEnd = UsedFieldIndex.end(),
12667 OrigIter = InitFieldIndex.begin(),
12668 OrigEnd = InitFieldIndex.end();
12669 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12670 if (*UsedIter < *OrigIter)
12671 return true;
12672 if (*UsedIter > *OrigIter)
12673 break;
12674 }
12675
12676 // TODO: Add a different warning which will print the field names.
12677 HandleDeclRefExpr(DRE);
12678 return true;
12679 }
12680
12681 // For most expressions, the cast is directly above the DeclRefExpr.
12682 // For conditional operators, the cast can be outside the conditional
12683 // operator if both expressions are DeclRefExpr's.
12684 void HandleValue(Expr *E) {
12685 E = E->IgnoreParens();
12686 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12687 HandleDeclRefExpr(DRE);
12688 return;
12689 }
12690
12691 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12692 Visit(CO->getCond());
12693 HandleValue(CO->getTrueExpr());
12694 HandleValue(CO->getFalseExpr());
12695 return;
12696 }
12697
12698 if (BinaryConditionalOperator *BCO =
12699 dyn_cast<BinaryConditionalOperator>(E)) {
12700 Visit(BCO->getCond());
12701 HandleValue(BCO->getFalseExpr());
12702 return;
12703 }
12704
12705 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12706 if (Expr *SE = OVE->getSourceExpr())
12707 HandleValue(SE);
12708 return;
12709 }
12710
12711 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12712 if (BO->getOpcode() == BO_Comma) {
12713 Visit(BO->getLHS());
12714 HandleValue(BO->getRHS());
12715 return;
12716 }
12717 }
12718
12719 if (isa<MemberExpr>(E)) {
12720 if (isInitList) {
12721 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12722 false /*CheckReference*/))
12723 return;
12724 }
12725
12727 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12728 // Check for static member variables and don't warn on them.
12729 if (!isa<FieldDecl>(ME->getMemberDecl()))
12730 return;
12731 Base = ME->getBase()->IgnoreParenImpCasts();
12732 }
12733 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12734 HandleDeclRefExpr(DRE);
12735 return;
12736 }
12737
12738 Visit(E);
12739 }
12740
12741 // Reference types not handled in HandleValue are handled here since all
12742 // uses of references are bad, not just r-value uses.
12743 void VisitDeclRefExpr(DeclRefExpr *E) {
12744 if (isReferenceType)
12745 HandleDeclRefExpr(E);
12746 }
12747
12748 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12749 if (E->getCastKind() == CK_LValueToRValue) {
12750 HandleValue(E->getSubExpr());
12751 return;
12752 }
12753
12754 Inherited::VisitImplicitCastExpr(E);
12755 }
12756
12757 void VisitMemberExpr(MemberExpr *E) {
12758 if (isInitList) {
12759 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12760 return;
12761 }
12762
12763 // Don't warn on arrays since they can be treated as pointers.
12764 if (E->getType()->canDecayToPointerType()) return;
12765
12766 // Warn when a non-static method call is followed by non-static member
12767 // field accesses, which is followed by a DeclRefExpr.
12768 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12769 bool Warn = (MD && !MD->isStatic());
12770 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12771 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12772 if (!isa<FieldDecl>(ME->getMemberDecl()))
12773 Warn = false;
12774 Base = ME->getBase()->IgnoreParenImpCasts();
12775 }
12776
12777 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12778 if (Warn)
12779 HandleDeclRefExpr(DRE);
12780 return;
12781 }
12782
12783 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12784 // Visit that expression.
12785 Visit(Base);
12786 }
12787
12788 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12789 Expr *Callee = E->getCallee();
12790
12791 if (isa<UnresolvedLookupExpr>(Callee))
12792 return Inherited::VisitCXXOperatorCallExpr(E);
12793
12794 Visit(Callee);
12795 for (auto Arg: E->arguments())
12796 HandleValue(Arg->IgnoreParenImpCasts());
12797 }
12798
12799 void VisitUnaryOperator(UnaryOperator *E) {
12800 // For POD record types, addresses of its own members are well-defined.
12801 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12802 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12803 if (!isPODType)
12804 HandleValue(E->getSubExpr());
12805 return;
12806 }
12807
12808 if (E->isIncrementDecrementOp()) {
12809 HandleValue(E->getSubExpr());
12810 return;
12811 }
12812
12813 Inherited::VisitUnaryOperator(E);
12814 }
12815
12816 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12817
12818 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12819 if (E->getConstructor()->isCopyConstructor()) {
12820 Expr *ArgExpr = E->getArg(0);
12821 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12822 if (ILE->getNumInits() == 1)
12823 ArgExpr = ILE->getInit(0);
12824 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12825 if (ICE->getCastKind() == CK_NoOp)
12826 ArgExpr = ICE->getSubExpr();
12827 HandleValue(ArgExpr);
12828 return;
12829 }
12830 Inherited::VisitCXXConstructExpr(E);
12831 }
12832
12833 void VisitCallExpr(CallExpr *E) {
12834 // Treat std::move as a use.
12835 if (E->isCallToStdMove()) {
12836 HandleValue(E->getArg(0));
12837 return;
12838 }
12839
12840 Inherited::VisitCallExpr(E);
12841 }
12842
12843 void VisitBinaryOperator(BinaryOperator *E) {
12844 if (E->isCompoundAssignmentOp()) {
12845 HandleValue(E->getLHS());
12846 Visit(E->getRHS());
12847 return;
12848 }
12849
12850 Inherited::VisitBinaryOperator(E);
12851 }
12852
12853 // A custom visitor for BinaryConditionalOperator is needed because the
12854 // regular visitor would check the condition and true expression separately
12855 // but both point to the same place giving duplicate diagnostics.
12856 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12857 Visit(E->getCond());
12858 Visit(E->getFalseExpr());
12859 }
12860
12861 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12862 Decl* ReferenceDecl = DRE->getDecl();
12863 if (OrigDecl != ReferenceDecl) return;
12864 unsigned diag;
12865 if (isReferenceType) {
12866 diag = diag::warn_uninit_self_reference_in_reference_init;
12867 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12868 diag = diag::warn_static_self_reference_in_init;
12869 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12870 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12871 DRE->getDecl()->getType()->isRecordType()) {
12872 diag = diag::warn_uninit_self_reference_in_init;
12873 } else {
12874 // Local variables will be handled by the CFG analysis.
12875 return;
12876 }
12877
12878 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12879 S.PDiag(diag)
12880 << DRE->getDecl() << OrigDecl->getLocation()
12881 << DRE->getSourceRange());
12882 }
12883 };
12884
12885 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12886 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12887 bool DirectInit) {
12888 // Parameters arguments are occassionially constructed with itself,
12889 // for instance, in recursive functions. Skip them.
12890 if (isa<ParmVarDecl>(OrigDecl))
12891 return;
12892
12893 E = E->IgnoreParens();
12894
12895 // Skip checking T a = a where T is not a record or reference type.
12896 // Doing so is a way to silence uninitialized warnings.
12897 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12898 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12899 if (ICE->getCastKind() == CK_LValueToRValue)
12900 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12901 if (DRE->getDecl() == OrigDecl)
12902 return;
12903
12904 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12905 }
12906} // end anonymous namespace
12907
12908namespace {
12909 // Simple wrapper to add the name of a variable or (if no variable is
12910 // available) a DeclarationName into a diagnostic.
12911 struct VarDeclOrName {
12912 VarDecl *VDecl;
12913 DeclarationName Name;
12914
12915 friend const Sema::SemaDiagnosticBuilder &
12916 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12917 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12918 }
12919 };
12920} // end anonymous namespace
12921
12924 TypeSourceInfo *TSI,
12926 Expr *Init) {
12927 bool IsInitCapture = !VDecl;
12928 assert((!VDecl || !VDecl->isInitCapture()) &&
12929 "init captures are expected to be deduced prior to initialization");
12930
12931 VarDeclOrName VN{VDecl, Name};
12932
12934 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12935
12936 // Diagnose auto array declarations in C23, unless it's a supported extension.
12937 if (getLangOpts().C23 && Type->isArrayType() &&
12938 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
12939 Diag(Range.getBegin(), diag::err_auto_not_allowed)
12940 << (int)Deduced->getContainedAutoType()->getKeyword()
12941 << /*in array decl*/ 23 << Range;
12942 return QualType();
12943 }
12944
12945 // C++11 [dcl.spec.auto]p3
12946 if (!Init) {
12947 assert(VDecl && "no init for init capture deduction?");
12948
12949 // Except for class argument deduction, and then for an initializing
12950 // declaration only, i.e. no static at class scope or extern.
12951 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12952 VDecl->hasExternalStorage() ||
12953 VDecl->isStaticDataMember()) {
12954 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12955 << VDecl->getDeclName() << Type;
12956 return QualType();
12957 }
12958 }
12959
12960 ArrayRef<Expr*> DeduceInits;
12961 if (Init)
12962 DeduceInits = Init;
12963
12964 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12965 if (DirectInit && PL)
12966 DeduceInits = PL->exprs();
12967
12968 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12969 assert(VDecl && "non-auto type for init capture deduction?");
12972 VDecl->getLocation(), DirectInit, Init);
12973 // FIXME: Initialization should not be taking a mutable list of inits.
12974 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
12975 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12976 InitsCopy);
12977 }
12978
12979 if (DirectInit) {
12980 if (auto *IL = dyn_cast<InitListExpr>(Init))
12981 DeduceInits = IL->inits();
12982 }
12983
12984 // Deduction only works if we have exactly one source expression.
12985 if (DeduceInits.empty()) {
12986 // It isn't possible to write this directly, but it is possible to
12987 // end up in this situation with "auto x(some_pack...);"
12988 Diag(Init->getBeginLoc(), IsInitCapture
12989 ? diag::err_init_capture_no_expression
12990 : diag::err_auto_var_init_no_expression)
12991 << VN << Type << Range;
12992 return QualType();
12993 }
12994
12995 if (DeduceInits.size() > 1) {
12996 Diag(DeduceInits[1]->getBeginLoc(),
12997 IsInitCapture ? diag::err_init_capture_multiple_expressions
12998 : diag::err_auto_var_init_multiple_expressions)
12999 << VN << Type << Range;
13000 return QualType();
13001 }
13002
13003 Expr *DeduceInit = DeduceInits[0];
13004 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13005 Diag(Init->getBeginLoc(), IsInitCapture
13006 ? diag::err_init_capture_paren_braces
13007 : diag::err_auto_var_init_paren_braces)
13008 << isa<InitListExpr>(Init) << VN << Type << Range;
13009 return QualType();
13010 }
13011
13012 // Expressions default to 'id' when we're in a debugger.
13013 bool DefaultedAnyToId = false;
13014 if (getLangOpts().DebuggerCastResultToId &&
13015 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13017 if (Result.isInvalid()) {
13018 return QualType();
13019 }
13020 Init = Result.get();
13021 DefaultedAnyToId = true;
13022 }
13023
13024 // C++ [dcl.decomp]p1:
13025 // If the assignment-expression [...] has array type A and no ref-qualifier
13026 // is present, e has type cv A
13027 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13029 DeduceInit->getType()->isConstantArrayType())
13030 return Context.getQualifiedType(DeduceInit->getType(),
13031 Type.getQualifiers());
13032
13034 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13036 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13039 if (!IsInitCapture)
13040 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13041 else if (isa<InitListExpr>(Init))
13043 diag::err_init_capture_deduction_failure_from_init_list)
13044 << VN
13045 << (DeduceInit->getType().isNull() ? TSI->getType()
13046 : DeduceInit->getType())
13047 << DeduceInit->getSourceRange();
13048 else
13049 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13050 << VN << TSI->getType()
13051 << (DeduceInit->getType().isNull() ? TSI->getType()
13052 : DeduceInit->getType())
13053 << DeduceInit->getSourceRange();
13054 }
13055
13056 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13057 // 'id' instead of a specific object type prevents most of our usual
13058 // checks.
13059 // We only want to warn outside of template instantiations, though:
13060 // inside a template, the 'id' could have come from a parameter.
13061 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13062 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13064 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13065 }
13066
13067 return DeducedType;
13068}
13069
13071 Expr *Init) {
13072 assert(!Init || !Init->containsErrors());
13074 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13075 VDecl->getSourceRange(), DirectInit, Init);
13076 if (DeducedType.isNull()) {
13077 VDecl->setInvalidDecl();
13078 return true;
13079 }
13080
13081 VDecl->setType(DeducedType);
13082 assert(VDecl->isLinkageValid());
13083
13084 // In ARC, infer lifetime.
13085 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13086 VDecl->setInvalidDecl();
13087
13088 if (getLangOpts().OpenCL)
13090
13091 // If this is a redeclaration, check that the type we just deduced matches
13092 // the previously declared type.
13093 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13094 // We never need to merge the type, because we cannot form an incomplete
13095 // array of auto, nor deduce such a type.
13096 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13097 }
13098
13099 // Check the deduced type is valid for a variable declaration.
13101 return VDecl->isInvalidDecl();
13102}
13103
13106 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13107 Init = EWC->getSubExpr();
13108
13109 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13110 Init = CE->getSubExpr();
13111
13112 QualType InitType = Init->getType();
13115 "shouldn't be called if type doesn't have a non-trivial C struct");
13116 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13117 for (auto *I : ILE->inits()) {
13118 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13119 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13120 continue;
13121 SourceLocation SL = I->getExprLoc();
13123 }
13124 return;
13125 }
13126
13127 if (isa<ImplicitValueInitExpr>(Init)) {
13130 NTCUK_Init);
13131 } else {
13132 // Assume all other explicit initializers involving copying some existing
13133 // object.
13134 // TODO: ignore any explicit initializers where we can guarantee
13135 // copy-elision.
13138 }
13139}
13140
13141namespace {
13142
13143bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13144 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13145 // in the source code or implicitly by the compiler if it is in a union
13146 // defined in a system header and has non-trivial ObjC ownership
13147 // qualifications. We don't want those fields to participate in determining
13148 // whether the containing union is non-trivial.
13149 return FD->hasAttr<UnavailableAttr>();
13150}
13151
13152struct DiagNonTrivalCUnionDefaultInitializeVisitor
13153 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13154 void> {
13155 using Super =
13156 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13157 void>;
13158
13159 DiagNonTrivalCUnionDefaultInitializeVisitor(
13160 QualType OrigTy, SourceLocation OrigLoc,
13161 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13162 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13163
13164 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13165 const FieldDecl *FD, bool InNonTrivialUnion) {
13166 if (const auto *AT = S.Context.getAsArrayType(QT))
13167 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13168 InNonTrivialUnion);
13169 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13170 }
13171
13172 void visitARCStrong(QualType QT, const FieldDecl *FD,
13173 bool InNonTrivialUnion) {
13174 if (InNonTrivialUnion)
13175 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13176 << 1 << 0 << QT << FD->getName();
13177 }
13178
13179 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13180 if (InNonTrivialUnion)
13181 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13182 << 1 << 0 << QT << FD->getName();
13183 }
13184
13185 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13186 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13187 if (RD->isUnion()) {
13188 if (OrigLoc.isValid()) {
13189 bool IsUnion = false;
13190 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13191 IsUnion = OrigRD->isUnion();
13192 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13193 << 0 << OrigTy << IsUnion << UseContext;
13194 // Reset OrigLoc so that this diagnostic is emitted only once.
13195 OrigLoc = SourceLocation();
13196 }
13197 InNonTrivialUnion = true;
13198 }
13199
13200 if (InNonTrivialUnion)
13201 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13202 << 0 << 0 << QT.getUnqualifiedType() << "";
13203
13204 for (const FieldDecl *FD : RD->fields())
13205 if (!shouldIgnoreForRecordTriviality(FD))
13206 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13207 }
13208
13209 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13210
13211 // The non-trivial C union type or the struct/union type that contains a
13212 // non-trivial C union.
13213 QualType OrigTy;
13214 SourceLocation OrigLoc;
13216 Sema &S;
13217};
13218
13219struct DiagNonTrivalCUnionDestructedTypeVisitor
13220 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13221 using Super =
13223
13224 DiagNonTrivalCUnionDestructedTypeVisitor(
13225 QualType OrigTy, SourceLocation OrigLoc,
13226 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13227 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13228
13229 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13230 const FieldDecl *FD, bool InNonTrivialUnion) {
13231 if (const auto *AT = S.Context.getAsArrayType(QT))
13232 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13233 InNonTrivialUnion);
13234 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13235 }
13236
13237 void visitARCStrong(QualType QT, const FieldDecl *FD,
13238 bool InNonTrivialUnion) {
13239 if (InNonTrivialUnion)
13240 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13241 << 1 << 1 << QT << FD->getName();
13242 }
13243
13244 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13245 if (InNonTrivialUnion)
13246 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13247 << 1 << 1 << QT << FD->getName();
13248 }
13249
13250 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13251 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13252 if (RD->isUnion()) {
13253 if (OrigLoc.isValid()) {
13254 bool IsUnion = false;
13255 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13256 IsUnion = OrigRD->isUnion();
13257 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13258 << 1 << OrigTy << IsUnion << UseContext;
13259 // Reset OrigLoc so that this diagnostic is emitted only once.
13260 OrigLoc = SourceLocation();
13261 }
13262 InNonTrivialUnion = true;
13263 }
13264
13265 if (InNonTrivialUnion)
13266 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13267 << 0 << 1 << QT.getUnqualifiedType() << "";
13268
13269 for (const FieldDecl *FD : RD->fields())
13270 if (!shouldIgnoreForRecordTriviality(FD))
13271 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13272 }
13273
13274 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13275 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13276 bool InNonTrivialUnion) {}
13277
13278 // The non-trivial C union type or the struct/union type that contains a
13279 // non-trivial C union.
13280 QualType OrigTy;
13281 SourceLocation OrigLoc;
13283 Sema &S;
13284};
13285
13286struct DiagNonTrivalCUnionCopyVisitor
13287 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13289
13290 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13292 Sema &S)
13293 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13294
13295 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13296 const FieldDecl *FD, bool InNonTrivialUnion) {
13297 if (const auto *AT = S.Context.getAsArrayType(QT))
13298 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13299 InNonTrivialUnion);
13300 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13301 }
13302
13303 void visitARCStrong(QualType QT, const FieldDecl *FD,
13304 bool InNonTrivialUnion) {
13305 if (InNonTrivialUnion)
13306 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13307 << 1 << 2 << QT << FD->getName();
13308 }
13309
13310 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13311 if (InNonTrivialUnion)
13312 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13313 << 1 << 2 << QT << FD->getName();
13314 }
13315
13316 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13317 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13318 if (RD->isUnion()) {
13319 if (OrigLoc.isValid()) {
13320 bool IsUnion = false;
13321 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13322 IsUnion = OrigRD->isUnion();
13323 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13324 << 2 << OrigTy << IsUnion << UseContext;
13325 // Reset OrigLoc so that this diagnostic is emitted only once.
13326 OrigLoc = SourceLocation();
13327 }
13328 InNonTrivialUnion = true;
13329 }
13330
13331 if (InNonTrivialUnion)
13332 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13333 << 0 << 2 << QT.getUnqualifiedType() << "";
13334
13335 for (const FieldDecl *FD : RD->fields())
13336 if (!shouldIgnoreForRecordTriviality(FD))
13337 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13338 }
13339
13340 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13341 const FieldDecl *FD, bool InNonTrivialUnion) {}
13342 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13343 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13344 bool InNonTrivialUnion) {}
13345
13346 // The non-trivial C union type or the struct/union type that contains a
13347 // non-trivial C union.
13348 QualType OrigTy;
13349 SourceLocation OrigLoc;
13351 Sema &S;
13352};
13353
13354} // namespace
13355
13357 NonTrivialCUnionContext UseContext,
13358 unsigned NonTrivialKind) {
13362 "shouldn't be called if type doesn't have a non-trivial C union");
13363
13364 if ((NonTrivialKind & NTCUK_Init) &&
13366 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13367 .visit(QT, nullptr, false);
13368 if ((NonTrivialKind & NTCUK_Destruct) &&
13370 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13371 .visit(QT, nullptr, false);
13372 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13373 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13374 .visit(QT, nullptr, false);
13375}
13376
13378 // If there is no declaration, there was an error parsing it. Just ignore
13379 // the initializer.
13380 if (!RealDecl) {
13381 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13382 return;
13383 }
13384
13385 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13386 if (!Method->isInvalidDecl()) {
13387 // Pure-specifiers are handled in ActOnPureSpecifier.
13388 Diag(Method->getLocation(), diag::err_member_function_initialization)
13389 << Method->getDeclName() << Init->getSourceRange();
13390 Method->setInvalidDecl();
13391 }
13392 return;
13393 }
13394
13395 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13396 if (!VDecl) {
13397 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13398 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13399 RealDecl->setInvalidDecl();
13400 return;
13401 }
13402
13403 if (VDecl->isInvalidDecl()) {
13405 SmallVector<Expr *> SubExprs;
13406 if (Res.isUsable())
13407 SubExprs.push_back(Res.get());
13408 ExprResult Recovery =
13409 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), SubExprs);
13410 if (Expr *E = Recovery.get())
13411 VDecl->setInit(E);
13412 return;
13413 }
13414
13415 // WebAssembly tables can't be used to initialise a variable.
13416 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13417 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13418 VDecl->setInvalidDecl();
13419 return;
13420 }
13421
13422 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13423 if (VDecl->getType()->isUndeducedType()) {
13424 // Attempt typo correction early so that the type of the init expression can
13425 // be deduced based on the chosen correction if the original init contains a
13426 // TypoExpr.
13428 if (!Res.isUsable()) {
13429 // There are unresolved typos in Init, just drop them.
13430 // FIXME: improve the recovery strategy to preserve the Init.
13431 RealDecl->setInvalidDecl();
13432 return;
13433 }
13434 if (Res.get()->containsErrors()) {
13435 // Invalidate the decl as we don't know the type for recovery-expr yet.
13436 RealDecl->setInvalidDecl();
13437 VDecl->setInit(Res.get());
13438 return;
13439 }
13440 Init = Res.get();
13441
13443 return;
13444 }
13445
13446 // dllimport cannot be used on variable definitions.
13447 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13448 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13449 VDecl->setInvalidDecl();
13450 return;
13451 }
13452
13453 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13454 // the identifier has external or internal linkage, the declaration shall
13455 // have no initializer for the identifier.
13456 // C++14 [dcl.init]p5 is the same restriction for C++.
13457 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13458 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13459 VDecl->setInvalidDecl();
13460 return;
13461 }
13462
13463 if (!VDecl->getType()->isDependentType()) {
13464 // A definition must end up with a complete type, which means it must be
13465 // complete with the restriction that an array type might be completed by
13466 // the initializer; note that later code assumes this restriction.
13467 QualType BaseDeclType = VDecl->getType();
13468 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13469 BaseDeclType = Array->getElementType();
13470 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13471 diag::err_typecheck_decl_incomplete_type)) {
13472 RealDecl->setInvalidDecl();
13473 return;
13474 }
13475
13476 // The variable can not have an abstract class type.
13477 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13478 diag::err_abstract_type_in_decl,
13480 VDecl->setInvalidDecl();
13481 }
13482
13483 // C++ [module.import/6] external definitions are not permitted in header
13484 // units.
13485 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13486 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13487 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13488 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13490 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13491 VDecl->setInvalidDecl();
13492 }
13493
13494 // If adding the initializer will turn this declaration into a definition,
13495 // and we already have a definition for this variable, diagnose or otherwise
13496 // handle the situation.
13497 if (VarDecl *Def = VDecl->getDefinition())
13498 if (Def != VDecl &&
13499 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13501 checkVarDeclRedefinition(Def, VDecl))
13502 return;
13503
13504 if (getLangOpts().CPlusPlus) {
13505 // C++ [class.static.data]p4
13506 // If a static data member is of const integral or const
13507 // enumeration type, its declaration in the class definition can
13508 // specify a constant-initializer which shall be an integral
13509 // constant expression (5.19). In that case, the member can appear
13510 // in integral constant expressions. The member shall still be
13511 // defined in a namespace scope if it is used in the program and the
13512 // namespace scope definition shall not contain an initializer.
13513 //
13514 // We already performed a redefinition check above, but for static
13515 // data members we also need to check whether there was an in-class
13516 // declaration with an initializer.
13517 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13518 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13519 << VDecl->getDeclName();
13520 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13521 diag::note_previous_initializer)
13522 << 0;
13523 return;
13524 }
13525
13526 if (VDecl->hasLocalStorage())
13528
13530 VDecl->setInvalidDecl();
13531 return;
13532 }
13533 }
13534
13535 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13536 // a kernel function cannot be initialized."
13537 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13538 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13539 VDecl->setInvalidDecl();
13540 return;
13541 }
13542
13543 // The LoaderUninitialized attribute acts as a definition (of undef).
13544 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13545 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13546 VDecl->setInvalidDecl();
13547 return;
13548 }
13549
13550 // Get the decls type and save a reference for later, since
13551 // CheckInitializerTypes may change it.
13552 QualType DclT = VDecl->getType(), SavT = DclT;
13553
13554 // Expressions default to 'id' when we're in a debugger
13555 // and we are assigning it to a variable of Objective-C pointer type.
13556 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13557 Init->getType() == Context.UnknownAnyTy) {
13559 if (!Result.isUsable()) {
13560 VDecl->setInvalidDecl();
13561 return;
13562 }
13563 Init = Result.get();
13564 }
13565
13566 // Perform the initialization.
13567 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13568 bool IsParenListInit = false;
13569 if (!VDecl->isInvalidDecl()) {
13572 VDecl->getLocation(), DirectInit, Init);
13573
13574 MultiExprArg Args = Init;
13575 if (CXXDirectInit)
13576 Args = MultiExprArg(CXXDirectInit->getExprs(),
13577 CXXDirectInit->getNumExprs());
13578
13579 // Try to correct any TypoExprs in the initialization arguments.
13580 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13582 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13583 [this, Entity, Kind](Expr *E) {
13584 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13585 return Init.Failed() ? ExprError() : E;
13586 });
13587 if (!Res.isUsable()) {
13588 VDecl->setInvalidDecl();
13589 } else if (Res.get() != Args[Idx]) {
13590 Args[Idx] = Res.get();
13591 }
13592 }
13593 if (VDecl->isInvalidDecl())
13594 return;
13595
13596 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13597 /*TopLevelOfInitList=*/false,
13598 /*TreatUnavailableAsInvalid=*/false);
13599 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13600 if (!Result.isUsable()) {
13601 // If the provided initializer fails to initialize the var decl,
13602 // we attach a recovery expr for better recovery.
13603 auto RecoveryExpr =
13604 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13605 if (RecoveryExpr.get())
13606 VDecl->setInit(RecoveryExpr.get());
13607 // In general, for error recovery purposes, the initializer doesn't play
13608 // part in the valid bit of the declaration. There are a few exceptions:
13609 // 1) if the var decl has a deduced auto type, and the type cannot be
13610 // deduced by an invalid initializer;
13611 // 2) if the var decl is a decomposition decl with a non-deduced type,
13612 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13613 // Case 1) was already handled elsewhere.
13614 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13615 VDecl->setInvalidDecl();
13616 return;
13617 }
13618
13619 Init = Result.getAs<Expr>();
13620 IsParenListInit = !InitSeq.steps().empty() &&
13621 InitSeq.step_begin()->Kind ==
13623 QualType VDeclType = VDecl->getType();
13624 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
13625 !VDeclType->isDependentType() &&
13626 Context.getAsIncompleteArrayType(VDeclType) &&
13628 // Bail out if it is not possible to deduce array size from the
13629 // initializer.
13630 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13631 << VDeclType;
13632 VDecl->setInvalidDecl();
13633 return;
13634 }
13635 }
13636
13637 // Check for self-references within variable initializers.
13638 // Variables declared within a function/method body (except for references)
13639 // are handled by a dataflow analysis.
13640 // This is undefined behavior in C++, but valid in C.
13641 if (getLangOpts().CPlusPlus)
13642 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13643 VDecl->getType()->isReferenceType())
13644 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13645
13646 // If the type changed, it means we had an incomplete type that was
13647 // completed by the initializer. For example:
13648 // int ary[] = { 1, 3, 5 };
13649 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13650 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13651 VDecl->setType(DclT);
13652
13653 if (!VDecl->isInvalidDecl()) {
13654 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13655
13656 if (VDecl->hasAttr<BlocksAttr>())
13657 ObjC().checkRetainCycles(VDecl, Init);
13658
13659 // It is safe to assign a weak reference into a strong variable.
13660 // Although this code can still have problems:
13661 // id x = self.weakProp;
13662 // id y = self.weakProp;
13663 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13664 // paths through the function. This should be revisited if
13665 // -Wrepeated-use-of-weak is made flow-sensitive.
13666 if (FunctionScopeInfo *FSI = getCurFunction())
13667 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13669 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13670 Init->getBeginLoc()))
13671 FSI->markSafeWeakUse(Init);
13672 }
13673
13674 // The initialization is usually a full-expression.
13675 //
13676 // FIXME: If this is a braced initialization of an aggregate, it is not
13677 // an expression, and each individual field initializer is a separate
13678 // full-expression. For instance, in:
13679 //
13680 // struct Temp { ~Temp(); };
13681 // struct S { S(Temp); };
13682 // struct T { S a, b; } t = { Temp(), Temp() }
13683 //
13684 // we should destroy the first Temp before constructing the second.
13687 /*DiscardedValue*/ false, VDecl->isConstexpr());
13688 if (!Result.isUsable()) {
13689 VDecl->setInvalidDecl();
13690 return;
13691 }
13692 Init = Result.get();
13693
13694 // Attach the initializer to the decl.
13695 VDecl->setInit(Init);
13696
13697 if (VDecl->isLocalVarDecl()) {
13698 // Don't check the initializer if the declaration is malformed.
13699 if (VDecl->isInvalidDecl()) {
13700 // do nothing
13701
13702 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13703 // This is true even in C++ for OpenCL.
13704 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13706
13707 // Otherwise, C++ does not restrict the initializer.
13708 } else if (getLangOpts().CPlusPlus) {
13709 // do nothing
13710
13711 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13712 // static storage duration shall be constant expressions or string literals.
13713 } else if (VDecl->getStorageClass() == SC_Static) {
13715
13716 // C89 is stricter than C99 for aggregate initializers.
13717 // C89 6.5.7p3: All the expressions [...] in an initializer list
13718 // for an object that has aggregate or union type shall be
13719 // constant expressions.
13720 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13721 isa<InitListExpr>(Init)) {
13722 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13723 }
13724
13725 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13726 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13727 if (VDecl->hasLocalStorage())
13728 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13729 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13730 VDecl->getLexicalDeclContext()->isRecord()) {
13731 // This is an in-class initialization for a static data member, e.g.,
13732 //
13733 // struct S {
13734 // static const int value = 17;
13735 // };
13736
13737 // C++ [class.mem]p4:
13738 // A member-declarator can contain a constant-initializer only
13739 // if it declares a static member (9.4) of const integral or
13740 // const enumeration type, see 9.4.2.
13741 //
13742 // C++11 [class.static.data]p3:
13743 // If a non-volatile non-inline const static data member is of integral
13744 // or enumeration type, its declaration in the class definition can
13745 // specify a brace-or-equal-initializer in which every initializer-clause
13746 // that is an assignment-expression is a constant expression. A static
13747 // data member of literal type can be declared in the class definition
13748 // with the constexpr specifier; if so, its declaration shall specify a
13749 // brace-or-equal-initializer in which every initializer-clause that is
13750 // an assignment-expression is a constant expression.
13751
13752 // Do nothing on dependent types.
13753 if (DclT->isDependentType()) {
13754
13755 // Allow any 'static constexpr' members, whether or not they are of literal
13756 // type. We separately check that every constexpr variable is of literal
13757 // type.
13758 } else if (VDecl->isConstexpr()) {
13759
13760 // Require constness.
13761 } else if (!DclT.isConstQualified()) {
13762 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13763 << Init->getSourceRange();
13764 VDecl->setInvalidDecl();
13765
13766 // We allow integer constant expressions in all cases.
13767 } else if (DclT->isIntegralOrEnumerationType()) {
13768 // Check whether the expression is a constant expression.
13771 // In C++11, a non-constexpr const static data member with an
13772 // in-class initializer cannot be volatile.
13773 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13774 else if (Init->isValueDependent())
13775 ; // Nothing to check.
13776 else if (Init->isIntegerConstantExpr(Context, &Loc))
13777 ; // Ok, it's an ICE!
13778 else if (Init->getType()->isScopedEnumeralType() &&
13779 Init->isCXX11ConstantExpr(Context))
13780 ; // Ok, it is a scoped-enum constant expression.
13781 else if (Init->isEvaluatable(Context)) {
13782 // If we can constant fold the initializer through heroics, accept it,
13783 // but report this as a use of an extension for -pedantic.
13784 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13785 << Init->getSourceRange();
13786 } else {
13787 // Otherwise, this is some crazy unknown case. Report the issue at the
13788 // location provided by the isIntegerConstantExpr failed check.
13789 Diag(Loc, diag::err_in_class_initializer_non_constant)
13790 << Init->getSourceRange();
13791 VDecl->setInvalidDecl();
13792 }
13793
13794 // We allow foldable floating-point constants as an extension.
13795 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13796 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13797 // it anyway and provide a fixit to add the 'constexpr'.
13798 if (getLangOpts().CPlusPlus11) {
13799 Diag(VDecl->getLocation(),
13800 diag::ext_in_class_initializer_float_type_cxx11)
13801 << DclT << Init->getSourceRange();
13802 Diag(VDecl->getBeginLoc(),
13803 diag::note_in_class_initializer_float_type_cxx11)
13804 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13805 } else {
13806 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13807 << DclT << Init->getSourceRange();
13808
13809 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13810 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13811 << Init->getSourceRange();
13812 VDecl->setInvalidDecl();
13813 }
13814 }
13815
13816 // Suggest adding 'constexpr' in C++11 for literal types.
13817 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13818 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13819 << DclT << Init->getSourceRange()
13820 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13821 VDecl->setConstexpr(true);
13822
13823 } else {
13824 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13825 << DclT << Init->getSourceRange();
13826 VDecl->setInvalidDecl();
13827 }
13828 } else if (VDecl->isFileVarDecl()) {
13829 // In C, extern is typically used to avoid tentative definitions when
13830 // declaring variables in headers, but adding an initializer makes it a
13831 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13832 // In C++, extern is often used to give implicitly static const variables
13833 // external linkage, so don't warn in that case. If selectany is present,
13834 // this might be header code intended for C and C++ inclusion, so apply the
13835 // C++ rules.
13836 if (VDecl->getStorageClass() == SC_Extern &&
13837 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13839 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13841 Diag(VDecl->getLocation(), diag::warn_extern_init);
13842
13843 // In Microsoft C++ mode, a const variable defined in namespace scope has
13844 // external linkage by default if the variable is declared with
13845 // __declspec(dllexport).
13848 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13849 VDecl->setStorageClass(SC_Extern);
13850
13851 // C99 6.7.8p4. All file scoped initializers need to be constant.
13852 // Avoid duplicate diagnostics for constexpr variables.
13853 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13854 !VDecl->isConstexpr())
13856 }
13857
13858 QualType InitType = Init->getType();
13859 if (!InitType.isNull() &&
13863
13864 // We will represent direct-initialization similarly to copy-initialization:
13865 // int x(1); -as-> int x = 1;
13866 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13867 //
13868 // Clients that want to distinguish between the two forms, can check for
13869 // direct initializer using VarDecl::getInitStyle().
13870 // A major benefit is that clients that don't particularly care about which
13871 // exactly form was it (like the CodeGen) can handle both cases without
13872 // special case code.
13873
13874 // C++ 8.5p11:
13875 // The form of initialization (using parentheses or '=') is generally
13876 // insignificant, but does matter when the entity being initialized has a
13877 // class type.
13878 if (CXXDirectInit) {
13879 assert(DirectInit && "Call-style initializer must be direct init.");
13880 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13882 } else if (DirectInit) {
13883 // This must be list-initialization. No other way is direct-initialization.
13885 }
13886
13887 if (LangOpts.OpenMP &&
13888 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13889 VDecl->isFileVarDecl())
13890 DeclsToCheckForDeferredDiags.insert(VDecl);
13892}
13893
13895 // Our main concern here is re-establishing invariants like "a
13896 // variable's type is either dependent or complete".
13897 if (!D || D->isInvalidDecl()) return;
13898
13899 VarDecl *VD = dyn_cast<VarDecl>(D);
13900 if (!VD) return;
13901
13902 // Bindings are not usable if we can't make sense of the initializer.
13903 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13904 for (auto *BD : DD->bindings())
13905 BD->setInvalidDecl();
13906
13907 // Auto types are meaningless if we can't make sense of the initializer.
13908 if (VD->getType()->isUndeducedType()) {
13909 D->setInvalidDecl();
13910 return;
13911 }
13912
13913 QualType Ty = VD->getType();
13914 if (Ty->isDependentType()) return;
13915
13916 // Require a complete type.
13919 diag::err_typecheck_decl_incomplete_type)) {
13920 VD->setInvalidDecl();
13921 return;
13922 }
13923
13924 // Require a non-abstract type.
13925 if (RequireNonAbstractType(VD->getLocation(), Ty,
13926 diag::err_abstract_type_in_decl,
13928 VD->setInvalidDecl();
13929 return;
13930 }
13931
13932 // Don't bother complaining about constructors or destructors,
13933 // though.
13934}
13935
13937 // If there is no declaration, there was an error parsing it. Just ignore it.
13938 if (!RealDecl)
13939 return;
13940
13941 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13942 QualType Type = Var->getType();
13943
13944 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13945 if (isa<DecompositionDecl>(RealDecl)) {
13946 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13947 Var->setInvalidDecl();
13948 return;
13949 }
13950
13951 if (Type->isUndeducedType() &&
13952 DeduceVariableDeclarationType(Var, false, nullptr))
13953 return;
13954
13955 // C++11 [class.static.data]p3: A static data member can be declared with
13956 // the constexpr specifier; if so, its declaration shall specify
13957 // a brace-or-equal-initializer.
13958 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13959 // the definition of a variable [...] or the declaration of a static data
13960 // member.
13961 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13962 !Var->isThisDeclarationADemotedDefinition()) {
13963 if (Var->isStaticDataMember()) {
13964 // C++1z removes the relevant rule; the in-class declaration is always
13965 // a definition there.
13966 if (!getLangOpts().CPlusPlus17 &&
13968 Diag(Var->getLocation(),
13969 diag::err_constexpr_static_mem_var_requires_init)
13970 << Var;
13971 Var->setInvalidDecl();
13972 return;
13973 }
13974 } else {
13975 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13976 Var->setInvalidDecl();
13977 return;
13978 }
13979 }
13980
13981 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13982 // be initialized.
13983 if (!Var->isInvalidDecl() &&
13984 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13985 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13986 bool HasConstExprDefaultConstructor = false;
13987 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13988 for (auto *Ctor : RD->ctors()) {
13989 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13990 Ctor->getMethodQualifiers().getAddressSpace() ==
13992 HasConstExprDefaultConstructor = true;
13993 }
13994 }
13995 }
13996 if (!HasConstExprDefaultConstructor) {
13997 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13998 Var->setInvalidDecl();
13999 return;
14000 }
14001 }
14002
14003 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14004 if (Var->getStorageClass() == SC_Extern) {
14005 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14006 << Var;
14007 Var->setInvalidDecl();
14008 return;
14009 }
14010 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14011 diag::err_typecheck_decl_incomplete_type)) {
14012 Var->setInvalidDecl();
14013 return;
14014 }
14015 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14016 if (!RD->hasTrivialDefaultConstructor()) {
14017 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14018 Var->setInvalidDecl();
14019 return;
14020 }
14021 }
14022 // The declaration is uninitialized, no need for further checks.
14023 return;
14024 }
14025
14026 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14027 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14028 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14029 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14031
14032
14033 switch (DefKind) {
14035 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14036 break;
14037
14038 // We have an out-of-line definition of a static data member
14039 // that has an in-class initializer, so we type-check this like
14040 // a declaration.
14041 //
14042 [[fallthrough]];
14043
14045 // It's only a declaration.
14046
14047 // Block scope. C99 6.7p7: If an identifier for an object is
14048 // declared with no linkage (C99 6.2.2p6), the type for the
14049 // object shall be complete.
14050 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14051 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14052 RequireCompleteType(Var->getLocation(), Type,
14053 diag::err_typecheck_decl_incomplete_type))
14054 Var->setInvalidDecl();
14055
14056 // Make sure that the type is not abstract.
14057 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14058 RequireNonAbstractType(Var->getLocation(), Type,
14059 diag::err_abstract_type_in_decl,
14061 Var->setInvalidDecl();
14062 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14063 Var->getStorageClass() == SC_PrivateExtern) {
14064 Diag(Var->getLocation(), diag::warn_private_extern);
14065 Diag(Var->getLocation(), diag::note_private_extern);
14066 }
14067
14069 !Var->isInvalidDecl())
14070 ExternalDeclarations.push_back(Var);
14071
14072 return;
14073
14075 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14076 // object that has file scope without an initializer, and without a
14077 // storage-class specifier or with the storage-class specifier "static",
14078 // constitutes a tentative definition. Note: A tentative definition with
14079 // external linkage is valid (C99 6.2.2p5).
14080 if (!Var->isInvalidDecl()) {
14081 if (const IncompleteArrayType *ArrayT
14084 Var->getLocation(), ArrayT->getElementType(),
14085 diag::err_array_incomplete_or_sizeless_type))
14086 Var->setInvalidDecl();
14087 } else if (Var->getStorageClass() == SC_Static) {
14088 // C99 6.9.2p3: If the declaration of an identifier for an object is
14089 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14090 // declared type shall not be an incomplete type.
14091 // NOTE: code such as the following
14092 // static struct s;
14093 // struct s { int a; };
14094 // is accepted by gcc. Hence here we issue a warning instead of
14095 // an error and we do not invalidate the static declaration.
14096 // NOTE: to avoid multiple warnings, only check the first declaration.
14097 if (Var->isFirstDecl())
14098 RequireCompleteType(Var->getLocation(), Type,
14099 diag::ext_typecheck_decl_incomplete_type);
14100 }
14101 }
14102
14103 // Record the tentative definition; we're done.
14104 if (!Var->isInvalidDecl())
14106 return;
14107 }
14108
14109 // Provide a specific diagnostic for uninitialized variable
14110 // definitions with incomplete array type.
14111 if (Type->isIncompleteArrayType()) {
14112 if (Var->isConstexpr())
14113 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14114 << Var;
14115 else
14116 Diag(Var->getLocation(),
14117 diag::err_typecheck_incomplete_array_needs_initializer);
14118 Var->setInvalidDecl();
14119 return;
14120 }
14121
14122 // Provide a specific diagnostic for uninitialized variable
14123 // definitions with reference type.
14124 if (Type->isReferenceType()) {
14125 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14126 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14127 return;
14128 }
14129
14130 // Do not attempt to type-check the default initializer for a
14131 // variable with dependent type.
14132 if (Type->isDependentType())
14133 return;
14134
14135 if (Var->isInvalidDecl())
14136 return;
14137
14138 if (!Var->hasAttr<AliasAttr>()) {
14139 if (RequireCompleteType(Var->getLocation(),
14141 diag::err_typecheck_decl_incomplete_type)) {
14142 Var->setInvalidDecl();
14143 return;
14144 }
14145 } else {
14146 return;
14147 }
14148
14149 // The variable can not have an abstract class type.
14150 if (RequireNonAbstractType(Var->getLocation(), Type,
14151 diag::err_abstract_type_in_decl,
14153 Var->setInvalidDecl();
14154 return;
14155 }
14156
14157 // Check for jumps past the implicit initializer. C++0x
14158 // clarifies that this applies to a "variable with automatic
14159 // storage duration", not a "local variable".
14160 // C++11 [stmt.dcl]p3
14161 // A program that jumps from a point where a variable with automatic
14162 // storage duration is not in scope to a point where it is in scope is
14163 // ill-formed unless the variable has scalar type, class type with a
14164 // trivial default constructor and a trivial destructor, a cv-qualified
14165 // version of one of these types, or an array of one of the preceding
14166 // types and is declared without an initializer.
14167 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14168 if (const RecordType *Record
14170 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14171 // Mark the function (if we're in one) for further checking even if the
14172 // looser rules of C++11 do not require such checks, so that we can
14173 // diagnose incompatibilities with C++98.
14174 if (!CXXRecord->isPOD())
14176 }
14177 }
14178 // In OpenCL, we can't initialize objects in the __local address space,
14179 // even implicitly, so don't synthesize an implicit initializer.
14180 if (getLangOpts().OpenCL &&
14181 Var->getType().getAddressSpace() == LangAS::opencl_local)
14182 return;
14183 // C++03 [dcl.init]p9:
14184 // If no initializer is specified for an object, and the
14185 // object is of (possibly cv-qualified) non-POD class type (or
14186 // array thereof), the object shall be default-initialized; if
14187 // the object is of const-qualified type, the underlying class
14188 // type shall have a user-declared default
14189 // constructor. Otherwise, if no initializer is specified for
14190 // a non- static object, the object and its subobjects, if
14191 // any, have an indeterminate initial value); if the object
14192 // or any of its subobjects are of const-qualified type, the
14193 // program is ill-formed.
14194 // C++0x [dcl.init]p11:
14195 // If no initializer is specified for an object, the object is
14196 // default-initialized; [...].
14199 = InitializationKind::CreateDefault(Var->getLocation());
14200
14201 InitializationSequence InitSeq(*this, Entity, Kind, {});
14202 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14203
14204 if (Init.get()) {
14205 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14206 // This is important for template substitution.
14207 Var->setInitStyle(VarDecl::CallInit);
14208 } else if (Init.isInvalid()) {
14209 // If default-init fails, attach a recovery-expr initializer to track
14210 // that initialization was attempted and failed.
14211 auto RecoveryExpr =
14212 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14213 if (RecoveryExpr.get())
14214 Var->setInit(RecoveryExpr.get());
14215 }
14216
14218 }
14219}
14220
14222 // If there is no declaration, there was an error parsing it. Ignore it.
14223 if (!D)
14224 return;
14225
14226 VarDecl *VD = dyn_cast<VarDecl>(D);
14227 if (!VD) {
14228 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14229 D->setInvalidDecl();
14230 return;
14231 }
14232
14233 VD->setCXXForRangeDecl(true);
14234
14235 // for-range-declaration cannot be given a storage class specifier.
14236 int Error = -1;
14237 switch (VD->getStorageClass()) {
14238 case SC_None:
14239 break;
14240 case SC_Extern:
14241 Error = 0;
14242 break;
14243 case SC_Static:
14244 Error = 1;
14245 break;
14246 case SC_PrivateExtern:
14247 Error = 2;
14248 break;
14249 case SC_Auto:
14250 Error = 3;
14251 break;
14252 case SC_Register:
14253 Error = 4;
14254 break;
14255 }
14256
14257 // for-range-declaration cannot be given a storage class specifier con't.
14258 switch (VD->getTSCSpec()) {
14259 case TSCS_thread_local:
14260 Error = 6;
14261 break;
14262 case TSCS___thread:
14263 case TSCS__Thread_local:
14264 case TSCS_unspecified:
14265 break;
14266 }
14267
14268 if (Error != -1) {
14269 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14270 << VD << Error;
14271 D->setInvalidDecl();
14272 }
14273}
14274
14276 IdentifierInfo *Ident,
14277 ParsedAttributes &Attrs) {
14278 // C++1y [stmt.iter]p1:
14279 // A range-based for statement of the form
14280 // for ( for-range-identifier : for-range-initializer ) statement
14281 // is equivalent to
14282 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14283 DeclSpec DS(Attrs.getPool().getFactory());
14284
14285 const char *PrevSpec;
14286 unsigned DiagID;
14287 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14289
14291 D.SetIdentifier(Ident, IdentLoc);
14292 D.takeAttributes(Attrs);
14293
14294 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14295 IdentLoc);
14296 Decl *Var = ActOnDeclarator(S, D);
14297 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14299 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14300 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14301 : IdentLoc);
14302}
14303
14305 if (var->isInvalidDecl()) return;
14306
14308
14309 if (getLangOpts().OpenCL) {
14310 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14311 // initialiser
14312 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14313 !var->hasInit()) {
14314 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14315 << 1 /*Init*/;
14316 var->setInvalidDecl();
14317 return;
14318 }
14319 }
14320
14321 // In Objective-C, don't allow jumps past the implicit initialization of a
14322 // local retaining variable.
14323 if (getLangOpts().ObjC &&
14324 var->hasLocalStorage()) {
14325 switch (var->getType().getObjCLifetime()) {
14329 break;
14330
14334 break;
14335 }
14336 }
14337
14338 if (var->hasLocalStorage() &&
14339 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14341
14342 // Warn about externally-visible variables being defined without a
14343 // prior declaration. We only want to do this for global
14344 // declarations, but we also specifically need to avoid doing it for
14345 // class members because the linkage of an anonymous class can
14346 // change if it's later given a typedef name.
14347 if (var->isThisDeclarationADefinition() &&
14348 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14349 var->isExternallyVisible() && var->hasLinkage() &&
14350 !var->isInline() && !var->getDescribedVarTemplate() &&
14351 var->getStorageClass() != SC_Register &&
14352 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14353 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14354 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14355 var->getLocation())) {
14356 // Find a previous declaration that's not a definition.
14357 VarDecl *prev = var->getPreviousDecl();
14358 while (prev && prev->isThisDeclarationADefinition())
14359 prev = prev->getPreviousDecl();
14360
14361 if (!prev) {
14362 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14363 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14364 << /* variable */ 0;
14365 }
14366 }
14367
14368 // Cache the result of checking for constant initialization.
14369 std::optional<bool> CacheHasConstInit;
14370 const Expr *CacheCulprit = nullptr;
14371 auto checkConstInit = [&]() mutable {
14372 if (!CacheHasConstInit)
14373 CacheHasConstInit = var->getInit()->isConstantInitializer(
14374 Context, var->getType()->isReferenceType(), &CacheCulprit);
14375 return *CacheHasConstInit;
14376 };
14377
14378 if (var->getTLSKind() == VarDecl::TLS_Static) {
14379 if (var->getType().isDestructedType()) {
14380 // GNU C++98 edits for __thread, [basic.start.term]p3:
14381 // The type of an object with thread storage duration shall not
14382 // have a non-trivial destructor.
14383 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14385 Diag(var->getLocation(), diag::note_use_thread_local);
14386 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14387 if (!checkConstInit()) {
14388 // GNU C++98 edits for __thread, [basic.start.init]p4:
14389 // An object of thread storage duration shall not require dynamic
14390 // initialization.
14391 // FIXME: Need strict checking here.
14392 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14393 << CacheCulprit->getSourceRange();
14395 Diag(var->getLocation(), diag::note_use_thread_local);
14396 }
14397 }
14398 }
14399
14400
14401 if (!var->getType()->isStructureType() && var->hasInit() &&
14402 isa<InitListExpr>(var->getInit())) {
14403 const auto *ILE = cast<InitListExpr>(var->getInit());
14404 unsigned NumInits = ILE->getNumInits();
14405 if (NumInits > 2)
14406 for (unsigned I = 0; I < NumInits; ++I) {
14407 const auto *Init = ILE->getInit(I);
14408 if (!Init)
14409 break;
14410 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14411 if (!SL)
14412 break;
14413
14414 unsigned NumConcat = SL->getNumConcatenated();
14415 // Diagnose missing comma in string array initialization.
14416 // Do not warn when all the elements in the initializer are concatenated
14417 // together. Do not warn for macros too.
14418 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14419 bool OnlyOneMissingComma = true;
14420 for (unsigned J = I + 1; J < NumInits; ++J) {
14421 const auto *Init = ILE->getInit(J);
14422 if (!Init)
14423 break;
14424 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14425 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14426 OnlyOneMissingComma = false;
14427 break;
14428 }
14429 }
14430
14431 if (OnlyOneMissingComma) {
14433 for (unsigned i = 0; i < NumConcat - 1; ++i)
14434 Hints.push_back(FixItHint::CreateInsertion(
14435 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14436
14437 Diag(SL->getStrTokenLoc(1),
14438 diag::warn_concatenated_literal_array_init)
14439 << Hints;
14440 Diag(SL->getBeginLoc(),
14441 diag::note_concatenated_string_literal_silence);
14442 }
14443 // In any case, stop now.
14444 break;
14445 }
14446 }
14447 }
14448
14449
14450 QualType type = var->getType();
14451
14452 if (var->hasAttr<BlocksAttr>())
14454
14455 Expr *Init = var->getInit();
14456 bool GlobalStorage = var->hasGlobalStorage();
14457 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14459 bool HasConstInit = true;
14460
14461 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14462 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14463 << var;
14464
14465 // Check whether the initializer is sufficiently constant.
14466 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14467 !type->isDependentType() && Init && !Init->isValueDependent() &&
14468 (GlobalStorage || var->isConstexpr() ||
14469 var->mightBeUsableInConstantExpressions(Context))) {
14470 // If this variable might have a constant initializer or might be usable in
14471 // constant expressions, check whether or not it actually is now. We can't
14472 // do this lazily, because the result might depend on things that change
14473 // later, such as which constexpr functions happen to be defined.
14475 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14476 // Prior to C++11, in contexts where a constant initializer is required,
14477 // the set of valid constant initializers is described by syntactic rules
14478 // in [expr.const]p2-6.
14479 // FIXME: Stricter checking for these rules would be useful for constinit /
14480 // -Wglobal-constructors.
14481 HasConstInit = checkConstInit();
14482
14483 // Compute and cache the constant value, and remember that we have a
14484 // constant initializer.
14485 if (HasConstInit) {
14486 (void)var->checkForConstantInitialization(Notes);
14487 Notes.clear();
14488 } else if (CacheCulprit) {
14489 Notes.emplace_back(CacheCulprit->getExprLoc(),
14490 PDiag(diag::note_invalid_subexpr_in_const_expr));
14491 Notes.back().second << CacheCulprit->getSourceRange();
14492 }
14493 } else {
14494 // Evaluate the initializer to see if it's a constant initializer.
14495 HasConstInit = var->checkForConstantInitialization(Notes);
14496 }
14497
14498 if (HasConstInit) {
14499 // FIXME: Consider replacing the initializer with a ConstantExpr.
14500 } else if (var->isConstexpr()) {
14501 SourceLocation DiagLoc = var->getLocation();
14502 // If the note doesn't add any useful information other than a source
14503 // location, fold it into the primary diagnostic.
14504 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14505 diag::note_invalid_subexpr_in_const_expr) {
14506 DiagLoc = Notes[0].first;
14507 Notes.clear();
14508 }
14509 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14510 << var << Init->getSourceRange();
14511 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14512 Diag(Notes[I].first, Notes[I].second);
14513 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14514 auto *Attr = var->getAttr<ConstInitAttr>();
14515 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14516 << Init->getSourceRange();
14517 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14518 << Attr->getRange() << Attr->isConstinit();
14519 for (auto &it : Notes)
14520 Diag(it.first, it.second);
14521 } else if (IsGlobal &&
14522 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14523 var->getLocation())) {
14524 // Warn about globals which don't have a constant initializer. Don't
14525 // warn about globals with a non-trivial destructor because we already
14526 // warned about them.
14527 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14528 if (!(RD && !RD->hasTrivialDestructor())) {
14529 // checkConstInit() here permits trivial default initialization even in
14530 // C++11 onwards, where such an initializer is not a constant initializer
14531 // but nonetheless doesn't require a global constructor.
14532 if (!checkConstInit())
14533 Diag(var->getLocation(), diag::warn_global_constructor)
14534 << Init->getSourceRange();
14535 }
14536 }
14537 }
14538
14539 // Apply section attributes and pragmas to global variables.
14540 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14542 PragmaStack<StringLiteral *> *Stack = nullptr;
14543 int SectionFlags = ASTContext::PSF_Read;
14544 bool MSVCEnv =
14545 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14546 std::optional<QualType::NonConstantStorageReason> Reason;
14547 if (HasConstInit &&
14548 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14549 Stack = &ConstSegStack;
14550 } else {
14551 SectionFlags |= ASTContext::PSF_Write;
14552 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14553 }
14554 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14555 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14556 SectionFlags |= ASTContext::PSF_Implicit;
14557 UnifySection(SA->getName(), SectionFlags, var);
14558 } else if (Stack->CurrentValue) {
14559 if (Stack != &ConstSegStack && MSVCEnv &&
14560 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14561 var->getType().isConstQualified()) {
14562 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14563 NonConstNonReferenceType) &&
14564 "This case should've already been handled elsewhere");
14565 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14566 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14568 : *Reason);
14569 }
14570 SectionFlags |= ASTContext::PSF_Implicit;
14571 auto SectionName = Stack->CurrentValue->getString();
14572 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14573 Stack->CurrentPragmaLocation,
14574 SectionAttr::Declspec_allocate));
14575 if (UnifySection(SectionName, SectionFlags, var))
14576 var->dropAttr<SectionAttr>();
14577 }
14578
14579 // Apply the init_seg attribute if this has an initializer. If the
14580 // initializer turns out to not be dynamic, we'll end up ignoring this
14581 // attribute.
14582 if (CurInitSeg && var->getInit())
14583 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14584 CurInitSegLoc));
14585 }
14586
14587 // All the following checks are C++ only.
14588 if (!getLangOpts().CPlusPlus) {
14589 // If this variable must be emitted, add it as an initializer for the
14590 // current module.
14591 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14592 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14593 return;
14594 }
14595
14596 // Require the destructor.
14597 if (!type->isDependentType())
14598 if (const RecordType *recordType = baseType->getAs<RecordType>())
14600
14601 // If this variable must be emitted, add it as an initializer for the current
14602 // module.
14603 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14604 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14605
14606 // Build the bindings if this is a structured binding declaration.
14607 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14609}
14610
14612 assert(VD->isStaticLocal());
14613
14614 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14615
14616 // Find outermost function when VD is in lambda function.
14617 while (FD && !getDLLAttr(FD) &&
14618 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14619 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14620 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14621 }
14622
14623 if (!FD)
14624 return;
14625
14626 // Static locals inherit dll attributes from their function.
14627 if (Attr *A = getDLLAttr(FD)) {
14628 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14629 NewAttr->setInherited(true);
14630 VD->addAttr(NewAttr);
14631 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14632 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14633 NewAttr->setInherited(true);
14634 VD->addAttr(NewAttr);
14635
14636 // Export this function to enforce exporting this static variable even
14637 // if it is not used in this compilation unit.
14638 if (!FD->hasAttr<DLLExportAttr>())
14639 FD->addAttr(NewAttr);
14640
14641 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14642 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14643 NewAttr->setInherited(true);
14644 VD->addAttr(NewAttr);
14645 }
14646}
14647
14649 assert(VD->getTLSKind());
14650
14651 // Perform TLS alignment check here after attributes attached to the variable
14652 // which may affect the alignment have been processed. Only perform the check
14653 // if the target has a maximum TLS alignment (zero means no constraints).
14654 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14655 // Protect the check so that it's not performed on dependent types and
14656 // dependent alignments (we can't determine the alignment in that case).
14657 if (!VD->hasDependentAlignment()) {
14658 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14659 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14660 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14662 << (unsigned)MaxAlignChars.getQuantity();
14663 }
14664 }
14665 }
14666}
14667
14669 // Note that we are no longer parsing the initializer for this declaration.
14670 ParsingInitForAutoVars.erase(ThisDecl);
14671
14672 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14673 if (!VD)
14674 return;
14675
14676 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14678 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14680 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14684 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14688 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14692 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14695 }
14696
14697 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14698 for (auto *BD : DD->bindings()) {
14700 }
14701 }
14702
14703 CheckInvalidBuiltinCountedByRef(VD->getInit(), InitializerKind);
14704
14705 checkAttributesAfterMerging(*this, *VD);
14706
14707 if (VD->isStaticLocal())
14709
14710 if (VD->getTLSKind())
14712
14713 // Perform check for initializers of device-side global variables.
14714 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14715 // 7.5). We must also apply the same checks to all __shared__
14716 // variables whether they are local or not. CUDA also allows
14717 // constant initializers for __constant__ and __device__ variables.
14718 if (getLangOpts().CUDA)
14720
14721 // Grab the dllimport or dllexport attribute off of the VarDecl.
14722 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14723
14724 // Imported static data members cannot be defined out-of-line.
14725 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14726 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14728 // We allow definitions of dllimport class template static data members
14729 // with a warning.
14731 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14732 bool IsClassTemplateMember =
14733 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14734 Context->getDescribedClassTemplate();
14735
14736 Diag(VD->getLocation(),
14737 IsClassTemplateMember
14738 ? diag::warn_attribute_dllimport_static_field_definition
14739 : diag::err_attribute_dllimport_static_field_definition);
14740 Diag(IA->getLocation(), diag::note_attribute);
14741 if (!IsClassTemplateMember)
14742 VD->setInvalidDecl();
14743 }
14744 }
14745
14746 // dllimport/dllexport variables cannot be thread local, their TLS index
14747 // isn't exported with the variable.
14748 if (DLLAttr && VD->getTLSKind()) {
14749 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14750 if (F && getDLLAttr(F)) {
14751 assert(VD->isStaticLocal());
14752 // But if this is a static local in a dlimport/dllexport function, the
14753 // function will never be inlined, which means the var would never be
14754 // imported, so having it marked import/export is safe.
14755 } else {
14756 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14757 << DLLAttr;
14758 VD->setInvalidDecl();
14759 }
14760 }
14761
14762 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14763 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14764 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14765 << Attr;
14766 VD->dropAttr<UsedAttr>();
14767 }
14768 }
14769 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14770 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14771 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14772 << Attr;
14773 VD->dropAttr<RetainAttr>();
14774 }
14775 }
14776
14777 const DeclContext *DC = VD->getDeclContext();
14778 // If there's a #pragma GCC visibility in scope, and this isn't a class
14779 // member, set the visibility of this variable.
14782
14783 // FIXME: Warn on unused var template partial specializations.
14784 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14786
14787 // Now we have parsed the initializer and can update the table of magic
14788 // tag values.
14789 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14791 return;
14792
14793 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14794 const Expr *MagicValueExpr = VD->getInit();
14795 if (!MagicValueExpr) {
14796 continue;
14797 }
14798 std::optional<llvm::APSInt> MagicValueInt;
14799 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14800 Diag(I->getRange().getBegin(),
14801 diag::err_type_tag_for_datatype_not_ice)
14802 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14803 continue;
14804 }
14805 if (MagicValueInt->getActiveBits() > 64) {
14806 Diag(I->getRange().getBegin(),
14807 diag::err_type_tag_for_datatype_too_large)
14808 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14809 continue;
14810 }
14811 uint64_t MagicValue = MagicValueInt->getZExtValue();
14812 RegisterTypeTagForDatatype(I->getArgumentKind(),
14813 MagicValue,
14814 I->getMatchingCType(),
14815 I->getLayoutCompatible(),
14816 I->getMustBeNull());
14817 }
14818}
14819
14821 auto *VD = dyn_cast<VarDecl>(DD);
14822 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14823}
14824
14826 ArrayRef<Decl *> Group) {
14828
14829 if (DS.isTypeSpecOwned())
14830 Decls.push_back(DS.getRepAsDecl());
14831
14832 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14833 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14834 bool DiagnosedMultipleDecomps = false;
14835 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14836 bool DiagnosedNonDeducedAuto = false;
14837
14838 for (Decl *D : Group) {
14839 if (!D)
14840 continue;
14841 // Check if the Decl has been declared in '#pragma omp declare target'
14842 // directive and has static storage duration.
14843 if (auto *VD = dyn_cast<VarDecl>(D);
14844 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14845 VD->hasGlobalStorage())
14847 // For declarators, there are some additional syntactic-ish checks we need
14848 // to perform.
14849 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14850 if (!FirstDeclaratorInGroup)
14851 FirstDeclaratorInGroup = DD;
14852 if (!FirstDecompDeclaratorInGroup)
14853 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14854 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14855 !hasDeducedAuto(DD))
14856 FirstNonDeducedAutoInGroup = DD;
14857
14858 if (FirstDeclaratorInGroup != DD) {
14859 // A decomposition declaration cannot be combined with any other
14860 // declaration in the same group.
14861 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14862 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14863 diag::err_decomp_decl_not_alone)
14864 << FirstDeclaratorInGroup->getSourceRange()
14865 << DD->getSourceRange();
14866 DiagnosedMultipleDecomps = true;
14867 }
14868
14869 // A declarator that uses 'auto' in any way other than to declare a
14870 // variable with a deduced type cannot be combined with any other
14871 // declarator in the same group.
14872 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14873 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14874 diag::err_auto_non_deduced_not_alone)
14875 << FirstNonDeducedAutoInGroup->getType()
14877 << FirstDeclaratorInGroup->getSourceRange()
14878 << DD->getSourceRange();
14879 DiagnosedNonDeducedAuto = true;
14880 }
14881 }
14882 }
14883
14884 Decls.push_back(D);
14885 }
14886
14888 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14889 handleTagNumbering(Tag, S);
14890 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14892 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14893 }
14894 }
14895
14896 return BuildDeclaratorGroup(Decls);
14897}
14898
14901 // C++14 [dcl.spec.auto]p7: (DR1347)
14902 // If the type that replaces the placeholder type is not the same in each
14903 // deduction, the program is ill-formed.
14904 if (Group.size() > 1) {
14905 QualType Deduced;
14906 VarDecl *DeducedDecl = nullptr;
14907 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14908 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14909 if (!D || D->isInvalidDecl())
14910 break;
14911 DeducedType *DT = D->getType()->getContainedDeducedType();
14912 if (!DT || DT->getDeducedType().isNull())
14913 continue;
14914 if (Deduced.isNull()) {
14915 Deduced = DT->getDeducedType();
14916 DeducedDecl = D;
14917 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14918 auto *AT = dyn_cast<AutoType>(DT);
14919 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14920 diag::err_auto_different_deductions)
14921 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14922 << DeducedDecl->getDeclName() << DT->getDeducedType()
14923 << D->getDeclName();
14924 if (DeducedDecl->hasInit())
14925 Dia << DeducedDecl->getInit()->getSourceRange();
14926 if (D->getInit())
14927 Dia << D->getInit()->getSourceRange();
14928 D->setInvalidDecl();
14929 break;
14930 }
14931 }
14932 }
14933
14935
14936 return DeclGroupPtrTy::make(
14937 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14938}
14939
14942}
14943
14945 // Don't parse the comment if Doxygen diagnostics are ignored.
14946 if (Group.empty() || !Group[0])
14947 return;
14948
14949 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14950 Group[0]->getLocation()) &&
14951 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14952 Group[0]->getLocation()))
14953 return;
14954
14955 if (Group.size() >= 2) {
14956 // This is a decl group. Normally it will contain only declarations
14957 // produced from declarator list. But in case we have any definitions or
14958 // additional declaration references:
14959 // 'typedef struct S {} S;'
14960 // 'typedef struct S *S;'
14961 // 'struct S *pS;'
14962 // FinalizeDeclaratorGroup adds these as separate declarations.
14963 Decl *MaybeTagDecl = Group[0];
14964 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14965 Group = Group.slice(1);
14966 }
14967 }
14968
14969 // FIMXE: We assume every Decl in the group is in the same file.
14970 // This is false when preprocessor constructs the group from decls in
14971 // different files (e. g. macros or #include).
14973}
14974
14976 // Check that there are no default arguments inside the type of this
14977 // parameter.
14978 if (getLangOpts().CPlusPlus)
14980
14981 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14982 if (D.getCXXScopeSpec().isSet()) {
14983 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14984 << D.getCXXScopeSpec().getRange();
14985 }
14986
14987 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14988 // simple identifier except [...irrelevant cases...].
14989 switch (D.getName().getKind()) {
14991 break;
14992
15000 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15002 break;
15003
15006 // GetNameForDeclarator would not produce a useful name in this case.
15007 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15008 break;
15009 }
15010}
15011
15013 SourceLocation ExplicitThisLoc) {
15014 if (!ExplicitThisLoc.isValid())
15015 return;
15016 assert(S.getLangOpts().CPlusPlus &&
15017 "explicit parameter in non-cplusplus mode");
15018 if (!S.getLangOpts().CPlusPlus23)
15019 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15020 << P->getSourceRange();
15021
15022 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15023 // parameter pack.
15024 if (P->isParameterPack()) {
15025 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15026 << P->getSourceRange();
15027 return;
15028 }
15029 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15030 if (LambdaScopeInfo *LSI = S.getCurLambda())
15031 LSI->ExplicitObjectParameter = P;
15032}
15033
15035 SourceLocation ExplicitThisLoc) {
15036 const DeclSpec &DS = D.getDeclSpec();
15037
15038 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15039 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15040 // except for the special case of a single unnamed parameter of type void
15041 // with no storage class specifier, no type qualifier, and no following
15042 // ellipsis terminator.
15043 // Clang applies the C2y rules for 'register void' in all C language modes,
15044 // same as GCC, because it's questionable what that could possibly mean.
15045
15046 // C++03 [dcl.stc]p2 also permits 'auto'.
15047 StorageClass SC = SC_None;
15049 SC = SC_Register;
15050 // In C++11, the 'register' storage class specifier is deprecated.
15051 // In C++17, it is not allowed, but we tolerate it as an extension.
15052 if (getLangOpts().CPlusPlus11) {
15054 ? diag::ext_register_storage_class
15055 : diag::warn_deprecated_register)
15057 } else if (!getLangOpts().CPlusPlus &&
15059 D.getNumTypeObjects() == 0) {
15061 diag::err_invalid_storage_class_in_func_decl)
15063 D.getMutableDeclSpec().ClearStorageClassSpecs();
15064 }
15065 } else if (getLangOpts().CPlusPlus &&
15067 SC = SC_Auto;
15070 diag::err_invalid_storage_class_in_func_decl);
15071 D.getMutableDeclSpec().ClearStorageClassSpecs();
15072 }
15073
15075 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15077 if (DS.isInlineSpecified())
15078 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15079 << getLangOpts().CPlusPlus17;
15080 if (DS.hasConstexprSpecifier())
15081 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15082 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15083
15085
15087
15089 QualType parmDeclType = TInfo->getType();
15090
15091 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15092 const IdentifierInfo *II = D.getIdentifier();
15093 if (II) {
15094 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15095 RedeclarationKind::ForVisibleRedeclaration);
15096 LookupName(R, S);
15097 if (!R.empty()) {
15098 NamedDecl *PrevDecl = *R.begin();
15099 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15100 // Maybe we will complain about the shadowed template parameter.
15101 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15102 // Just pretend that we didn't see the previous declaration.
15103 PrevDecl = nullptr;
15104 }
15105 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15106 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15107 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15108 // Recover by removing the name
15109 II = nullptr;
15110 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15111 D.setInvalidType(true);
15112 }
15113 }
15114 }
15115
15116 // Temporarily put parameter variables in the translation unit, not
15117 // the enclosing context. This prevents them from accidentally
15118 // looking like class members in C++.
15119 ParmVarDecl *New =
15121 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15122
15123 if (D.isInvalidType())
15124 New->setInvalidDecl();
15125
15126 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15127
15128 assert(S->isFunctionPrototypeScope());
15129 assert(S->getFunctionPrototypeDepth() >= 1);
15130 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15131 S->getNextFunctionPrototypeIndex());
15132
15133 // Add the parameter declaration into this scope.
15134 S->AddDecl(New);
15135 if (II)
15136 IdResolver.AddDecl(New);
15137
15138 ProcessDeclAttributes(S, New, D);
15139
15140 if (D.getDeclSpec().isModulePrivateSpecified())
15141 Diag(New->getLocation(), diag::err_module_private_local)
15142 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15143 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15144
15145 if (New->hasAttr<BlocksAttr>()) {
15146 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15147 }
15148
15149 if (getLangOpts().OpenCL)
15151
15152 return New;
15153}
15154
15157 QualType T) {
15158 /* FIXME: setting StartLoc == Loc.
15159 Would it be worth to modify callers so as to provide proper source
15160 location for the unnamed parameters, embedding the parameter's type? */
15161 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15163 SC_None, nullptr);
15164 Param->setImplicit();
15165 return Param;
15166}
15167
15169 // Don't diagnose unused-parameter errors in template instantiations; we
15170 // will already have done so in the template itself.
15172 return;
15173
15174 for (const ParmVarDecl *Parameter : Parameters) {
15175 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15176 !Parameter->hasAttr<UnusedAttr>() &&
15177 !Parameter->getIdentifier()->isPlaceholder()) {
15178 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15179 << Parameter->getDeclName();
15180 }
15181 }
15182}
15183
15185 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15186 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15187 return;
15188
15189 // Warn if the return value is pass-by-value and larger than the specified
15190 // threshold.
15191 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15192 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15193 if (Size > LangOpts.NumLargeByValueCopy)
15194 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15195 }
15196
15197 // Warn if any parameter is pass-by-value and larger than the specified
15198 // threshold.
15199 for (const ParmVarDecl *Parameter : Parameters) {
15200 QualType T = Parameter->getType();
15201 if (T->isDependentType() || !T.isPODType(Context))
15202 continue;
15203 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15204 if (Size > LangOpts.NumLargeByValueCopy)
15205 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15206 << Parameter << Size;
15207 }
15208}
15209
15211 SourceLocation NameLoc,
15212 const IdentifierInfo *Name, QualType T,
15213 TypeSourceInfo *TSInfo, StorageClass SC) {
15214 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15215 if (getLangOpts().ObjCAutoRefCount &&
15216 T.getObjCLifetime() == Qualifiers::OCL_None &&
15217 T->isObjCLifetimeType()) {
15218
15219 Qualifiers::ObjCLifetime lifetime;
15220
15221 // Special cases for arrays:
15222 // - if it's const, use __unsafe_unretained
15223 // - otherwise, it's an error
15224 if (T->isArrayType()) {
15225 if (!T.isConstQualified()) {
15229 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15230 else
15231 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15232 << TSInfo->getTypeLoc().getSourceRange();
15233 }
15235 } else {
15236 lifetime = T->getObjCARCImplicitLifetime();
15237 }
15238 T = Context.getLifetimeQualifiedType(T, lifetime);
15239 }
15240
15241 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15243 TSInfo, SC, nullptr);
15244
15245 // Make a note if we created a new pack in the scope of a lambda, so that
15246 // we know that references to that pack must also be expanded within the
15247 // lambda scope.
15248 if (New->isParameterPack())
15249 if (auto *CSI = getEnclosingLambdaOrBlock())
15250 CSI->LocalPacks.push_back(New);
15251
15256
15257 // Parameter declarators cannot be interface types. All ObjC objects are
15258 // passed by reference.
15259 if (T->isObjCObjectType()) {
15260 SourceLocation TypeEndLoc =
15262 Diag(NameLoc,
15263 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15264 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15266 New->setType(T);
15267 }
15268
15269 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15270 // duration shall not be qualified by an address-space qualifier."
15271 // Since all parameters have automatic store duration, they can not have
15272 // an address space.
15273 if (T.getAddressSpace() != LangAS::Default &&
15274 // OpenCL allows function arguments declared to be an array of a type
15275 // to be qualified with an address space.
15276 !(getLangOpts().OpenCL &&
15277 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15278 // WebAssembly allows reference types as parameters. Funcref in particular
15279 // lives in a different address space.
15280 !(T->isFunctionPointerType() &&
15281 T.getAddressSpace() == LangAS::wasm_funcref)) {
15282 Diag(NameLoc, diag::err_arg_with_address_space);
15283 New->setInvalidDecl();
15284 }
15285
15286 // PPC MMA non-pointer types are not allowed as function argument types.
15287 if (Context.getTargetInfo().getTriple().isPPC64() &&
15288 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15289 New->setInvalidDecl();
15290 }
15291
15292 return New;
15293}
15294
15296 SourceLocation LocAfterDecls) {
15297 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15298
15299 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15300 // in the declaration list shall have at least one declarator, those
15301 // declarators shall only declare identifiers from the identifier list, and
15302 // every identifier in the identifier list shall be declared.
15303 //
15304 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15305 // identifiers it names shall be declared in the declaration list."
15306 //
15307 // This is why we only diagnose in C99 and later. Note, the other conditions
15308 // listed are checked elsewhere.
15309 if (!FTI.hasPrototype) {
15310 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15311 --i;
15312 if (FTI.Params[i].Param == nullptr) {
15313 if (getLangOpts().C99) {
15314 SmallString<256> Code;
15315 llvm::raw_svector_ostream(Code)
15316 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15317 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15318 << FTI.Params[i].Ident
15319 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15320 }
15321
15322 // Implicitly declare the argument as type 'int' for lack of a better
15323 // type.
15324 AttributeFactory attrs;
15325 DeclSpec DS(attrs);
15326 const char* PrevSpec; // unused
15327 unsigned DiagID; // unused
15328 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15329 DiagID, Context.getPrintingPolicy());
15330 // Use the identifier location for the type source range.
15331 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15332 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15335 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15336 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15337 }
15338 }
15339 }
15340}
15341
15342Decl *
15344 MultiTemplateParamsArg TemplateParameterLists,
15345 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15346 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15347 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15348 Scope *ParentScope = FnBodyScope->getParent();
15349
15350 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15351 // we define a non-templated function definition, we will create a declaration
15352 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15353 // The base function declaration will have the equivalent of an `omp declare
15354 // variant` annotation which specifies the mangled definition as a
15355 // specialization function under the OpenMP context defined as part of the
15356 // `omp begin declare variant`.
15358 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15360 ParentScope, D, TemplateParameterLists, Bases);
15361
15362 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15363 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15364 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15365
15366 if (!Bases.empty())
15368 Bases);
15369
15370 return Dcl;
15371}
15372
15375}
15376
15378 const FunctionDecl *&PossiblePrototype) {
15379 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15380 Prev = Prev->getPreviousDecl()) {
15381 // Ignore any declarations that occur in function or method
15382 // scope, because they aren't visible from the header.
15383 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15384 continue;
15385
15386 PossiblePrototype = Prev;
15387 return Prev->getType()->isFunctionProtoType();
15388 }
15389 return false;
15390}
15391
15392static bool
15394 const FunctionDecl *&PossiblePrototype) {
15395 // Don't warn about invalid declarations.
15396 if (FD->isInvalidDecl())
15397 return false;
15398
15399 // Or declarations that aren't global.
15400 if (!FD->isGlobal())
15401 return false;
15402
15403 // Don't warn about C++ member functions.
15404 if (isa<CXXMethodDecl>(FD))
15405 return false;
15406
15407 // Don't warn about 'main'.
15408 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15409 if (IdentifierInfo *II = FD->getIdentifier())
15410 if (II->isStr("main") || II->isStr("efi_main"))
15411 return false;
15412
15413 if (FD->isMSVCRTEntryPoint())
15414 return false;
15415
15416 // Don't warn about inline functions.
15417 if (FD->isInlined())
15418 return false;
15419
15420 // Don't warn about function templates.
15422 return false;
15423
15424 // Don't warn about function template specializations.
15426 return false;
15427
15428 // Don't warn for OpenCL kernels.
15429 if (FD->hasAttr<OpenCLKernelAttr>())
15430 return false;
15431
15432 // Don't warn on explicitly deleted functions.
15433 if (FD->isDeleted())
15434 return false;
15435
15436 // Don't warn on implicitly local functions (such as having local-typed
15437 // parameters).
15438 if (!FD->isExternallyVisible())
15439 return false;
15440
15441 // If we were able to find a potential prototype, don't warn.
15442 if (FindPossiblePrototype(FD, PossiblePrototype))
15443 return false;
15444
15445 return true;
15446}
15447
15448void
15450 const FunctionDecl *EffectiveDefinition,
15451 SkipBodyInfo *SkipBody) {
15452 const FunctionDecl *Definition = EffectiveDefinition;
15453 if (!Definition &&
15454 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15455 return;
15456
15457 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15458 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15459 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15460 // A merged copy of the same function, instantiated as a member of
15461 // the same class, is OK.
15462 if (declaresSameEntity(OrigFD, OrigDef) &&
15463 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15464 cast<Decl>(FD->getLexicalDeclContext())))
15465 return;
15466 }
15467 }
15468 }
15469
15471 return;
15472
15473 // Don't emit an error when this is redefinition of a typo-corrected
15474 // definition.
15476 return;
15477
15478 // If we don't have a visible definition of the function, and it's inline or
15479 // a template, skip the new definition.
15480 if (SkipBody && !hasVisibleDefinition(Definition) &&
15481 (Definition->getFormalLinkage() == Linkage::Internal ||
15482 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15483 Definition->getNumTemplateParameterLists())) {
15484 SkipBody->ShouldSkip = true;
15485 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15486 if (auto *TD = Definition->getDescribedFunctionTemplate())
15489 return;
15490 }
15491
15492 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15493 Definition->getStorageClass() == SC_Extern)
15494 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15495 << FD << getLangOpts().CPlusPlus;
15496 else
15497 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15498
15499 Diag(Definition->getLocation(), diag::note_previous_definition);
15500 FD->setInvalidDecl();
15501}
15502
15504 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15505
15507 LSI->CallOperator = CallOperator;
15508 LSI->Lambda = LambdaClass;
15509 LSI->ReturnType = CallOperator->getReturnType();
15510 // When this function is called in situation where the context of the call
15511 // operator is not entered, we set AfterParameterList to false, so that
15512 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15513 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
15514 // where we would set the CurContext to the lambda operator before
15515 // substituting into it. In this case the flag needs to be true such that
15516 // tryCaptureVariable can correctly handle potential captures thereof.
15517 LSI->AfterParameterList = CurContext == CallOperator;
15518
15519 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
15520 // used at the point of dealing with potential captures.
15521 //
15522 // We don't use LambdaClass->isGenericLambda() because this value doesn't
15523 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
15524 // associated. (Technically, we could recover that list from their
15525 // instantiation patterns, but for now, the GLTemplateParameterList seems
15526 // unnecessary in these cases.)
15527 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
15528 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
15529 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15530
15531 if (LCD == LCD_None)
15533 else if (LCD == LCD_ByCopy)
15535 else if (LCD == LCD_ByRef)
15537 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15538
15540 LSI->Mutable = !CallOperator->isConst();
15541 if (CallOperator->isExplicitObjectMemberFunction())
15542 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15543
15544 // Add the captures to the LSI so they can be noted as already
15545 // captured within tryCaptureVar.
15546 auto I = LambdaClass->field_begin();
15547 for (const auto &C : LambdaClass->captures()) {
15548 if (C.capturesVariable()) {
15549 ValueDecl *VD = C.getCapturedVar();
15550 if (VD->isInitCapture())
15552 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15553 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15554 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15555 /*EllipsisLoc*/C.isPackExpansion()
15556 ? C.getEllipsisLoc() : SourceLocation(),
15557 I->getType(), /*Invalid*/false);
15558
15559 } else if (C.capturesThis()) {
15560 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15561 C.getCaptureKind() == LCK_StarThis);
15562 } else {
15563 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15564 I->getType());
15565 }
15566 ++I;
15567 }
15568 return LSI;
15569}
15570
15572 SkipBodyInfo *SkipBody,
15573 FnBodyKind BodyKind) {
15574 if (!D) {
15575 // Parsing the function declaration failed in some way. Push on a fake scope
15576 // anyway so we can try to parse the function body.
15579 return D;
15580 }
15581
15582 FunctionDecl *FD = nullptr;
15583
15584 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15585 FD = FunTmpl->getTemplatedDecl();
15586 else
15587 FD = cast<FunctionDecl>(D);
15588
15589 // Do not push if it is a lambda because one is already pushed when building
15590 // the lambda in ActOnStartOfLambdaDefinition().
15591 if (!isLambdaCallOperator(FD))
15592 // [expr.const]/p14.1
15593 // An expression or conversion is in an immediate function context if it is
15594 // potentially evaluated and either: its innermost enclosing non-block scope
15595 // is a function parameter scope of an immediate function.
15598 : ExprEvalContexts.back().Context);
15599
15600 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15601 // context is nested in an immediate function context, so smaller contexts
15602 // that appear inside immediate functions (like variable initializers) are
15603 // considered to be inside an immediate function context even though by
15604 // themselves they are not immediate function contexts. But when a new
15605 // function is entered, we need to reset this tracking, since the entered
15606 // function might be not an immediate function.
15607 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15608 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15609 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15610
15611 // Check for defining attributes before the check for redefinition.
15612 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15613 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15614 FD->dropAttr<AliasAttr>();
15615 FD->setInvalidDecl();
15616 }
15617 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15618 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15619 FD->dropAttr<IFuncAttr>();
15620 FD->setInvalidDecl();
15621 }
15622 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15623 if (Context.getTargetInfo().getTriple().isAArch64() &&
15624 !Context.getTargetInfo().hasFeature("fmv") &&
15625 !Attr->isDefaultVersion()) {
15626 // If function multi versioning disabled skip parsing function body
15627 // defined with non-default target_version attribute
15628 if (SkipBody)
15629 SkipBody->ShouldSkip = true;
15630 return nullptr;
15631 }
15632 }
15633
15634 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15635 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15636 Ctor->isDefaultConstructor() &&
15638 // If this is an MS ABI dllexport default constructor, instantiate any
15639 // default arguments.
15641 }
15642 }
15643
15644 // See if this is a redefinition. If 'will have body' (or similar) is already
15645 // set, then these checks were already performed when it was set.
15646 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15648 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15649
15650 // If we're skipping the body, we're done. Don't enter the scope.
15651 if (SkipBody && SkipBody->ShouldSkip)
15652 return D;
15653 }
15654
15655 // Mark this function as "will have a body eventually". This lets users to
15656 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15657 // this function.
15658 FD->setWillHaveBody();
15659
15660 // If we are instantiating a generic lambda call operator, push
15661 // a LambdaScopeInfo onto the function stack. But use the information
15662 // that's already been calculated (ActOnLambdaExpr) to prime the current
15663 // LambdaScopeInfo.
15664 // When the template operator is being specialized, the LambdaScopeInfo,
15665 // has to be properly restored so that tryCaptureVariable doesn't try
15666 // and capture any new variables. In addition when calculating potential
15667 // captures during transformation of nested lambdas, it is necessary to
15668 // have the LSI properly restored.
15670 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15671 // instantiated, explicitly specialized.
15674 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15675 FD->setInvalidDecl();
15677 } else {
15678 assert(inTemplateInstantiation() &&
15679 "There should be an active template instantiation on the stack "
15680 "when instantiating a generic lambda!");
15681 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15682 }
15683 } else {
15684 // Enter a new function scope
15686 }
15687
15688 // Builtin functions cannot be defined.
15689 if (unsigned BuiltinID = FD->getBuiltinID()) {
15692 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15693 FD->setInvalidDecl();
15694 }
15695 }
15696
15697 // The return type of a function definition must be complete (C99 6.9.1p3).
15698 // C++23 [dcl.fct.def.general]/p2
15699 // The type of [...] the return for a function definition
15700 // shall not be a (possibly cv-qualified) class type that is incomplete
15701 // or abstract within the function body unless the function is deleted.
15702 QualType ResultType = FD->getReturnType();
15703 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15704 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15705 (RequireCompleteType(FD->getLocation(), ResultType,
15706 diag::err_func_def_incomplete_result) ||
15708 diag::err_abstract_type_in_decl,
15710 FD->setInvalidDecl();
15711
15712 if (FnBodyScope)
15713 PushDeclContext(FnBodyScope, FD);
15714
15715 // Check the validity of our function parameters
15716 if (BodyKind != FnBodyKind::Delete)
15718 /*CheckParameterNames=*/true);
15719
15720 // Add non-parameter declarations already in the function to the current
15721 // scope.
15722 if (FnBodyScope) {
15723 for (Decl *NPD : FD->decls()) {
15724 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15725 if (!NonParmDecl)
15726 continue;
15727 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15728 "parameters should not be in newly created FD yet");
15729
15730 // If the decl has a name, make it accessible in the current scope.
15731 if (NonParmDecl->getDeclName())
15732 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15733
15734 // Similarly, dive into enums and fish their constants out, making them
15735 // accessible in this scope.
15736 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15737 for (auto *EI : ED->enumerators())
15738 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15739 }
15740 }
15741 }
15742
15743 // Introduce our parameters into the function scope
15744 for (auto *Param : FD->parameters()) {
15745 Param->setOwningFunction(FD);
15746
15747 // If this has an identifier, add it to the scope stack.
15748 if (Param->getIdentifier() && FnBodyScope) {
15749 CheckShadow(FnBodyScope, Param);
15750
15751 PushOnScopeChains(Param, FnBodyScope);
15752 }
15753 }
15754
15755 // C++ [module.import/6] external definitions are not permitted in header
15756 // units. Deleted and Defaulted functions are implicitly inline (but the
15757 // inline state is not set at this point, so check the BodyKind explicitly).
15758 // FIXME: Consider an alternate location for the test where the inlined()
15759 // state is complete.
15760 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15761 !FD->isInvalidDecl() && !FD->isInlined() &&
15762 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15763 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15764 !FD->isTemplateInstantiation()) {
15765 assert(FD->isThisDeclarationADefinition());
15766 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15767 FD->setInvalidDecl();
15768 }
15769
15770 // Ensure that the function's exception specification is instantiated.
15771 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15773
15774 // dllimport cannot be applied to non-inline function definitions.
15775 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15776 !FD->isTemplateInstantiation()) {
15777 assert(!FD->hasAttr<DLLExportAttr>());
15778 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15779 FD->setInvalidDecl();
15780 return D;
15781 }
15782
15783 // Some function attributes (like OptimizeNoneAttr) need actions before
15784 // parsing body started.
15786
15787 // We want to attach documentation to original Decl (which might be
15788 // a function template).
15790 if (getCurLexicalContext()->isObjCContainer() &&
15791 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15792 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15793 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15794
15796
15797 return D;
15798}
15799
15801 if (!FD || FD->isInvalidDecl())
15802 return;
15803 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
15804 FD = TD->getTemplatedDecl();
15805 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
15809 FpPragmaStack.CurrentValue =
15811 }
15812}
15813
15815 ReturnStmt **Returns = Scope->Returns.data();
15816
15817 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15818 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15819 if (!NRVOCandidate->isNRVOVariable())
15820 Returns[I]->setNRVOCandidate(nullptr);
15821 }
15822 }
15823}
15824
15826 // We can't delay parsing the body of a constexpr function template (yet).
15827 if (D.getDeclSpec().hasConstexprSpecifier())
15828 return false;
15829
15830 // We can't delay parsing the body of a function template with a deduced
15831 // return type (yet).
15832 if (D.getDeclSpec().hasAutoTypeSpec()) {
15833 // If the placeholder introduces a non-deduced trailing return type,
15834 // we can still delay parsing it.
15835 if (D.getNumTypeObjects()) {
15836 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15837 if (Outer.Kind == DeclaratorChunk::Function &&
15838 Outer.Fun.hasTrailingReturnType()) {
15839 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15840 return Ty.isNull() || !Ty->isUndeducedType();
15841 }
15842 }
15843 return false;
15844 }
15845
15846 return true;
15847}
15848
15850 // We cannot skip the body of a function (or function template) which is
15851 // constexpr, since we may need to evaluate its body in order to parse the
15852 // rest of the file.
15853 // We cannot skip the body of a function with an undeduced return type,
15854 // because any callers of that function need to know the type.
15855 if (const FunctionDecl *FD = D->getAsFunction()) {
15856 if (FD->isConstexpr())
15857 return false;
15858 // We can't simply call Type::isUndeducedType here, because inside template
15859 // auto can be deduced to a dependent type, which is not considered
15860 // "undeduced".
15861 if (FD->getReturnType()->getContainedDeducedType())
15862 return false;
15863 }
15865}
15866
15868 if (!Decl)
15869 return nullptr;
15870 if (FunctionDecl *FD = Decl->getAsFunction())
15871 FD->setHasSkippedBody();
15872 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15873 MD->setHasSkippedBody();
15874 return Decl;
15875}
15876
15878 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
15879}
15880
15881/// RAII object that pops an ExpressionEvaluationContext when exiting a function
15882/// body.
15884public:
15885 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15887 if (!IsLambda)
15889 }
15890
15891private:
15892 Sema &S;
15893 bool IsLambda = false;
15894};
15895
15897 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15898
15899 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15900 if (auto It = EscapeInfo.find(BD); It != EscapeInfo.end())
15901 return It->second;
15902
15903 bool R = false;
15904 const BlockDecl *CurBD = BD;
15905
15906 do {
15907 R = !CurBD->doesNotEscape();
15908 if (R)
15909 break;
15910 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15911 } while (CurBD);
15912
15913 return EscapeInfo[BD] = R;
15914 };
15915
15916 // If the location where 'self' is implicitly retained is inside a escaping
15917 // block, emit a diagnostic.
15918 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15920 if (IsOrNestedInEscapingBlock(P.second))
15921 S.Diag(P.first, diag::warn_implicitly_retains_self)
15922 << FixItHint::CreateInsertion(P.first, "self->");
15923}
15924
15925static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
15926 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
15927 FD->getDeclName().isIdentifier() && FD->getName() == Name;
15928}
15929
15931 return methodHasName(FD, "get_return_object");
15932}
15933
15935 return FD->isStatic() &&
15936 methodHasName(FD, "get_return_object_on_allocation_failure");
15937}
15938
15941 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15942 return;
15943 // Allow some_promise_type::get_return_object().
15945 return;
15946 if (!FD->hasAttr<CoroWrapperAttr>())
15947 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
15948}
15949
15951 bool IsInstantiation) {
15953 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15954
15955 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15956 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15957
15959 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15960
15961 // If we skip function body, we can't tell if a function is a coroutine.
15962 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
15963 if (FSI->isCoroutine())
15965 else
15967 }
15968
15969 // Diagnose invalid SYCL kernel entry point function declarations.
15970 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
15971 SYCLKernelEntryPointAttr *SKEPAttr =
15972 FD->getAttr<SYCLKernelEntryPointAttr>();
15973 if (FD->isDefaulted()) {
15974 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15975 << /*defaulted function*/ 3;
15976 SKEPAttr->setInvalidAttr();
15977 } else if (FD->isDeleted()) {
15978 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15979 << /*deleted function*/ 2;
15980 SKEPAttr->setInvalidAttr();
15981 } else if (FSI->isCoroutine()) {
15982 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15983 << /*coroutine*/ 7;
15984 SKEPAttr->setInvalidAttr();
15985 }
15986 }
15987
15988 {
15989 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15990 // one is already popped when finishing the lambda in BuildLambdaExpr().
15991 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15992 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15993 if (FD) {
15994 // If this is called by Parser::ParseFunctionDefinition() after marking
15995 // the declaration as deleted, and if the deleted-function-body contains
15996 // a message (C++26), then a DefaultedOrDeletedInfo will have already been
15997 // added to store that message; do not overwrite it in that case.
15998 //
15999 // Since this would always set the body to 'nullptr' in that case anyway,
16000 // which is already done when the function decl is initially created,
16001 // always skipping this irrespective of whether there is a delete message
16002 // should not be a problem.
16003 if (!FD->isDeletedAsWritten())
16004 FD->setBody(Body);
16005 FD->setWillHaveBody(false);
16007
16008 if (getLangOpts().CPlusPlus14) {
16009 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16010 FD->getReturnType()->isUndeducedType()) {
16011 // For a function with a deduced result type to return void,
16012 // the result type as written must be 'auto' or 'decltype(auto)',
16013 // possibly cv-qualified or constrained, but not ref-qualified.
16014 if (!FD->getReturnType()->getAs<AutoType>()) {
16015 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16016 << FD->getReturnType();
16017 FD->setInvalidDecl();
16018 } else {
16019 // Falling off the end of the function is the same as 'return;'.
16020 Expr *Dummy = nullptr;
16022 FD, dcl->getLocation(), Dummy,
16023 FD->getReturnType()->getAs<AutoType>()))
16024 FD->setInvalidDecl();
16025 }
16026 }
16027 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16028 // In C++11, we don't use 'auto' deduction rules for lambda call
16029 // operators because we don't support return type deduction.
16030 auto *LSI = getCurLambda();
16031 if (LSI->HasImplicitReturnType) {
16033
16034 // C++11 [expr.prim.lambda]p4:
16035 // [...] if there are no return statements in the compound-statement
16036 // [the deduced type is] the type void
16037 QualType RetType =
16038 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16039
16040 // Update the return type to the deduced type.
16041 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16042 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16043 Proto->getExtProtoInfo()));
16044 }
16045 }
16046
16047 // If the function implicitly returns zero (like 'main') or is naked,
16048 // don't complain about missing return statements.
16049 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
16051
16052 // MSVC permits the use of pure specifier (=0) on function definition,
16053 // defined at class scope, warn about this non-standard construct.
16054 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16055 !FD->isOutOfLine())
16056 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16057
16058 if (!FD->isInvalidDecl()) {
16059 // Don't diagnose unused parameters of defaulted, deleted or naked
16060 // functions.
16061 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16062 !FD->hasAttr<NakedAttr>())
16065 FD->getReturnType(), FD);
16066
16067 // If this is a structor, we need a vtable.
16068 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16069 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16070 else if (CXXDestructorDecl *Destructor =
16071 dyn_cast<CXXDestructorDecl>(FD))
16072 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16073
16074 // Try to apply the named return value optimization. We have to check
16075 // if we can do this here because lambdas keep return statements around
16076 // to deduce an implicit return type.
16077 if (FD->getReturnType()->isRecordType() &&
16079 computeNRVO(Body, FSI);
16080 }
16081
16082 // GNU warning -Wmissing-prototypes:
16083 // Warn if a global function is defined without a previous
16084 // prototype declaration. This warning is issued even if the
16085 // definition itself provides a prototype. The aim is to detect
16086 // global functions that fail to be declared in header files.
16087 const FunctionDecl *PossiblePrototype = nullptr;
16088 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16089 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16090
16091 if (PossiblePrototype) {
16092 // We found a declaration that is not a prototype,
16093 // but that could be a zero-parameter prototype
16094 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16095 TypeLoc TL = TI->getTypeLoc();
16097 Diag(PossiblePrototype->getLocation(),
16098 diag::note_declaration_not_a_prototype)
16099 << (FD->getNumParams() != 0)
16101 FTL.getRParenLoc(), "void")
16102 : FixItHint{});
16103 }
16104 } else {
16105 // Returns true if the token beginning at this Loc is `const`.
16106 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16107 const LangOptions &LangOpts) {
16108 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
16109 if (LocInfo.first.isInvalid())
16110 return false;
16111
16112 bool Invalid = false;
16113 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16114 if (Invalid)
16115 return false;
16116
16117 if (LocInfo.second > Buffer.size())
16118 return false;
16119
16120 const char *LexStart = Buffer.data() + LocInfo.second;
16121 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16122
16123 return StartTok.consume_front("const") &&
16124 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16125 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16126 };
16127
16128 auto findBeginLoc = [&]() {
16129 // If the return type has `const` qualifier, we want to insert
16130 // `static` before `const` (and not before the typename).
16131 if ((FD->getReturnType()->isAnyPointerType() &&
16134 // But only do this if we can determine where the `const` is.
16135
16136 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16137 getLangOpts()))
16138
16139 return FD->getBeginLoc();
16140 }
16141 return FD->getTypeSpecStartLoc();
16142 };
16144 diag::note_static_for_internal_linkage)
16145 << /* function */ 1
16146 << (FD->getStorageClass() == SC_None
16147 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16148 : FixItHint{});
16149 }
16150 }
16151
16152 // We might not have found a prototype because we didn't wish to warn on
16153 // the lack of a missing prototype. Try again without the checks for
16154 // whether we want to warn on the missing prototype.
16155 if (!PossiblePrototype)
16156 (void)FindPossiblePrototype(FD, PossiblePrototype);
16157
16158 // If the function being defined does not have a prototype, then we may
16159 // need to diagnose it as changing behavior in C23 because we now know
16160 // whether the function accepts arguments or not. This only handles the
16161 // case where the definition has no prototype but does have parameters
16162 // and either there is no previous potential prototype, or the previous
16163 // potential prototype also has no actual prototype. This handles cases
16164 // like:
16165 // void f(); void f(a) int a; {}
16166 // void g(a) int a; {}
16167 // See MergeFunctionDecl() for other cases of the behavior change
16168 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16169 // type without a prototype.
16170 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16171 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16172 !PossiblePrototype->isImplicit()))) {
16173 // The function definition has parameters, so this will change behavior
16174 // in C23. If there is a possible prototype, it comes before the
16175 // function definition.
16176 // FIXME: The declaration may have already been diagnosed as being
16177 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16178 // there's no way to test for the "changes behavior" condition in
16179 // SemaType.cpp when forming the declaration's function type. So, we do
16180 // this awkward dance instead.
16181 //
16182 // If we have a possible prototype and it declares a function with a
16183 // prototype, we don't want to diagnose it; if we have a possible
16184 // prototype and it has no prototype, it may have already been
16185 // diagnosed in SemaType.cpp as deprecated depending on whether
16186 // -Wstrict-prototypes is enabled. If we already warned about it being
16187 // deprecated, add a note that it also changes behavior. If we didn't
16188 // warn about it being deprecated (because the diagnostic is not
16189 // enabled), warn now that it is deprecated and changes behavior.
16190
16191 // This K&R C function definition definitely changes behavior in C23,
16192 // so diagnose it.
16193 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16194 << /*definition*/ 1 << /* not supported in C23 */ 0;
16195
16196 // If we have a possible prototype for the function which is a user-
16197 // visible declaration, we already tested that it has no prototype.
16198 // This will change behavior in C23. This gets a warning rather than a
16199 // note because it's the same behavior-changing problem as with the
16200 // definition.
16201 if (PossiblePrototype)
16202 Diag(PossiblePrototype->getLocation(),
16203 diag::warn_non_prototype_changes_behavior)
16204 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16205 << /*definition*/ 1;
16206 }
16207
16208 // Warn on CPUDispatch with an actual body.
16209 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16210 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16211 if (!CmpndBody->body_empty())
16212 Diag(CmpndBody->body_front()->getBeginLoc(),
16213 diag::warn_dispatch_body_ignored);
16214
16215 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16216 const CXXMethodDecl *KeyFunction;
16217 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16218 MD->isVirtual() &&
16219 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16220 MD == KeyFunction->getCanonicalDecl()) {
16221 // Update the key-function state if necessary for this ABI.
16222 if (FD->isInlined() &&
16225
16226 // If the newly-chosen key function is already defined, then we
16227 // need to mark the vtable as used retroactively.
16228 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16229 const FunctionDecl *Definition;
16230 if (KeyFunction && KeyFunction->isDefined(Definition))
16231 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16232 } else {
16233 // We just defined they key function; mark the vtable as used.
16234 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16235 }
16236 }
16237 }
16238
16239 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16240 "Function parsing confused");
16241 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16242 assert(MD == getCurMethodDecl() && "Method parsing confused");
16243 MD->setBody(Body);
16244 if (!MD->isInvalidDecl()) {
16246 MD->getReturnType(), MD);
16247
16248 if (Body)
16249 computeNRVO(Body, FSI);
16250 }
16251 if (FSI->ObjCShouldCallSuper) {
16252 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16253 << MD->getSelector().getAsString();
16254 FSI->ObjCShouldCallSuper = false;
16255 }
16257 const ObjCMethodDecl *InitMethod = nullptr;
16258 bool isDesignated =
16259 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16260 assert(isDesignated && InitMethod);
16261 (void)isDesignated;
16262
16263 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16264 auto IFace = MD->getClassInterface();
16265 if (!IFace)
16266 return false;
16267 auto SuperD = IFace->getSuperClass();
16268 if (!SuperD)
16269 return false;
16270 return SuperD->getIdentifier() ==
16271 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16272 };
16273 // Don't issue this warning for unavailable inits or direct subclasses
16274 // of NSObject.
16275 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16276 Diag(MD->getLocation(),
16277 diag::warn_objc_designated_init_missing_super_call);
16278 Diag(InitMethod->getLocation(),
16279 diag::note_objc_designated_init_marked_here);
16280 }
16282 }
16283 if (FSI->ObjCWarnForNoInitDelegation) {
16284 // Don't issue this warning for unavailable inits.
16285 if (!MD->isUnavailable())
16286 Diag(MD->getLocation(),
16287 diag::warn_objc_secondary_init_missing_init_call);
16288 FSI->ObjCWarnForNoInitDelegation = false;
16289 }
16290
16292 } else {
16293 // Parsing the function declaration failed in some way. Pop the fake scope
16294 // we pushed on.
16295 PopFunctionScopeInfo(ActivePolicy, dcl);
16296 return nullptr;
16297 }
16298
16299 if (Body && FSI->HasPotentialAvailabilityViolations)
16301
16302 assert(!FSI->ObjCShouldCallSuper &&
16303 "This should only be set for ObjC methods, which should have been "
16304 "handled in the block above.");
16305
16306 // Verify and clean out per-function state.
16307 if (Body && (!FD || !FD->isDefaulted())) {
16308 // C++ constructors that have function-try-blocks can't have return
16309 // statements in the handlers of that block. (C++ [except.handle]p14)
16310 // Verify this.
16311 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16312 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16313
16314 // Verify that gotos and switch cases don't jump into scopes illegally.
16317
16318 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16319 if (!Destructor->getParent()->isDependentType())
16321
16323 Destructor->getParent());
16324 }
16325
16326 // If any errors have occurred, clear out any temporaries that may have
16327 // been leftover. This ensures that these temporaries won't be picked up
16328 // for deletion in some later function.
16331 getDiagnostics().getSuppressAllDiagnostics()) {
16333 }
16334 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16335 // Since the body is valid, issue any analysis-based warnings that are
16336 // enabled.
16337 ActivePolicy = &WP;
16338 }
16339
16340 if (!IsInstantiation && FD &&
16341 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16342 !FD->isInvalidDecl() &&
16344 FD->setInvalidDecl();
16345
16346 if (FD && FD->hasAttr<NakedAttr>()) {
16347 for (const Stmt *S : Body->children()) {
16348 // Allow local register variables without initializer as they don't
16349 // require prologue.
16350 bool RegisterVariables = false;
16351 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16352 for (const auto *Decl : DS->decls()) {
16353 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16354 RegisterVariables =
16355 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16356 if (!RegisterVariables)
16357 break;
16358 }
16359 }
16360 }
16361 if (RegisterVariables)
16362 continue;
16363 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16364 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16365 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16366 FD->setInvalidDecl();
16367 break;
16368 }
16369 }
16370 }
16371
16372 assert(ExprCleanupObjects.size() ==
16373 ExprEvalContexts.back().NumCleanupObjects &&
16374 "Leftover temporaries in function");
16375 assert(!Cleanup.exprNeedsCleanups() &&
16376 "Unaccounted cleanups in function");
16377 assert(MaybeODRUseExprs.empty() &&
16378 "Leftover expressions for odr-use checking");
16379 }
16380 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16381 // the declaration context below. Otherwise, we're unable to transform
16382 // 'this' expressions when transforming immediate context functions.
16383
16384 if (!IsInstantiation)
16386
16387 PopFunctionScopeInfo(ActivePolicy, dcl);
16388 // If any errors have occurred, clear out any temporaries that may have
16389 // been leftover. This ensures that these temporaries won't be picked up for
16390 // deletion in some later function.
16393 }
16394
16395 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16396 !LangOpts.OMPTargetTriples.empty())) ||
16397 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16398 auto ES = getEmissionStatus(FD);
16401 DeclsToCheckForDeferredDiags.insert(FD);
16402 }
16403
16404 if (FD && !FD->isDeleted())
16405 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16406
16407 return dcl;
16408}
16409
16410/// When we finish delayed parsing of an attribute, we must attach it to the
16411/// relevant Decl.
16413 ParsedAttributes &Attrs) {
16414 // Always attach attributes to the underlying decl.
16415 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16416 D = TD->getTemplatedDecl();
16417 ProcessDeclAttributeList(S, D, Attrs);
16419
16420 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16421 if (Method->isStatic())
16423}
16424
16426 IdentifierInfo &II, Scope *S) {
16427 // It is not valid to implicitly define a function in C23.
16429 "Implicit function declarations aren't allowed in this language mode");
16430
16431 // Find the scope in which the identifier is injected and the corresponding
16432 // DeclContext.
16433 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16434 // In that case, we inject the declaration into the translation unit scope
16435 // instead.
16436 Scope *BlockScope = S;
16437 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16438 BlockScope = BlockScope->getParent();
16439
16440 // Loop until we find a DeclContext that is either a function/method or the
16441 // translation unit, which are the only two valid places to implicitly define
16442 // a function. This avoids accidentally defining the function within a tag
16443 // declaration, for example.
16444 Scope *ContextScope = BlockScope;
16445 while (!ContextScope->getEntity() ||
16446 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16447 !ContextScope->getEntity()->isTranslationUnit()))
16448 ContextScope = ContextScope->getParent();
16449 ContextRAII SavedContext(*this, ContextScope->getEntity());
16450
16451 // Before we produce a declaration for an implicitly defined
16452 // function, see whether there was a locally-scoped declaration of
16453 // this name as a function or variable. If so, use that
16454 // (non-visible) declaration, and complain about it.
16455 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16456 if (ExternCPrev) {
16457 // We still need to inject the function into the enclosing block scope so
16458 // that later (non-call) uses can see it.
16459 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16460
16461 // C89 footnote 38:
16462 // If in fact it is not defined as having type "function returning int",
16463 // the behavior is undefined.
16464 if (!isa<FunctionDecl>(ExternCPrev) ||
16466 cast<FunctionDecl>(ExternCPrev)->getType(),
16468 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16469 << ExternCPrev << !getLangOpts().C99;
16470 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16471 return ExternCPrev;
16472 }
16473 }
16474
16475 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16476 unsigned diag_id;
16477 if (II.getName().starts_with("__builtin_"))
16478 diag_id = diag::warn_builtin_unknown;
16479 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16480 else if (getLangOpts().C99)
16481 diag_id = diag::ext_implicit_function_decl_c99;
16482 else
16483 diag_id = diag::warn_implicit_function_decl;
16484
16485 TypoCorrection Corrected;
16486 // Because typo correction is expensive, only do it if the implicit
16487 // function declaration is going to be treated as an error.
16488 //
16489 // Perform the correction before issuing the main diagnostic, as some
16490 // consumers use typo-correction callbacks to enhance the main diagnostic.
16491 if (S && !ExternCPrev &&
16495 S, nullptr, CCC, CTK_NonError);
16496 }
16497
16498 Diag(Loc, diag_id) << &II;
16499 if (Corrected) {
16500 // If the correction is going to suggest an implicitly defined function,
16501 // skip the correction as not being a particularly good idea.
16502 bool Diagnose = true;
16503 if (const auto *D = Corrected.getCorrectionDecl())
16504 Diagnose = !D->isImplicit();
16505 if (Diagnose)
16506 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16507 /*ErrorRecovery*/ false);
16508 }
16509
16510 // If we found a prior declaration of this function, don't bother building
16511 // another one. We've already pushed that one into scope, so there's nothing
16512 // more to do.
16513 if (ExternCPrev)
16514 return ExternCPrev;
16515
16516 // Set a Declarator for the implicit definition: int foo();
16517 const char *Dummy;
16518 AttributeFactory attrFactory;
16519 DeclSpec DS(attrFactory);
16520 unsigned DiagID;
16521 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16523 (void)Error; // Silence warning.
16524 assert(!Error && "Error setting up implicit decl!");
16525 SourceLocation NoLoc;
16527 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16528 /*IsAmbiguous=*/false,
16529 /*LParenLoc=*/NoLoc,
16530 /*Params=*/nullptr,
16531 /*NumParams=*/0,
16532 /*EllipsisLoc=*/NoLoc,
16533 /*RParenLoc=*/NoLoc,
16534 /*RefQualifierIsLvalueRef=*/true,
16535 /*RefQualifierLoc=*/NoLoc,
16536 /*MutableLoc=*/NoLoc, EST_None,
16537 /*ESpecRange=*/SourceRange(),
16538 /*Exceptions=*/nullptr,
16539 /*ExceptionRanges=*/nullptr,
16540 /*NumExceptions=*/0,
16541 /*NoexceptExpr=*/nullptr,
16542 /*ExceptionSpecTokens=*/nullptr,
16543 /*DeclsInPrototype=*/{}, Loc, Loc,
16544 D),
16545 std::move(DS.getAttributes()), SourceLocation());
16546 D.SetIdentifier(&II, Loc);
16547
16548 // Insert this function into the enclosing block scope.
16549 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16550 FD->setImplicit();
16551
16553
16554 return FD;
16555}
16556
16558 FunctionDecl *FD) {
16559 if (FD->isInvalidDecl())
16560 return;
16561
16562 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16563 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16564 return;
16565
16566 std::optional<unsigned> AlignmentParam;
16567 bool IsNothrow = false;
16568 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16569 return;
16570
16571 // C++2a [basic.stc.dynamic.allocation]p4:
16572 // An allocation function that has a non-throwing exception specification
16573 // indicates failure by returning a null pointer value. Any other allocation
16574 // function never returns a null pointer value and indicates failure only by
16575 // throwing an exception [...]
16576 //
16577 // However, -fcheck-new invalidates this possible assumption, so don't add
16578 // NonNull when that is enabled.
16579 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16580 !getLangOpts().CheckNew)
16581 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16582
16583 // C++2a [basic.stc.dynamic.allocation]p2:
16584 // An allocation function attempts to allocate the requested amount of
16585 // storage. [...] If the request succeeds, the value returned by a
16586 // replaceable allocation function is a [...] pointer value p0 different
16587 // from any previously returned value p1 [...]
16588 //
16589 // However, this particular information is being added in codegen,
16590 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16591
16592 // C++2a [basic.stc.dynamic.allocation]p2:
16593 // An allocation function attempts to allocate the requested amount of
16594 // storage. If it is successful, it returns the address of the start of a
16595 // block of storage whose length in bytes is at least as large as the
16596 // requested size.
16597 if (!FD->hasAttr<AllocSizeAttr>()) {
16598 FD->addAttr(AllocSizeAttr::CreateImplicit(
16599 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16600 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16601 }
16602
16603 // C++2a [basic.stc.dynamic.allocation]p3:
16604 // For an allocation function [...], the pointer returned on a successful
16605 // call shall represent the address of storage that is aligned as follows:
16606 // (3.1) If the allocation function takes an argument of type
16607 // std​::​align_­val_­t, the storage will have the alignment
16608 // specified by the value of this argument.
16609 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16610 FD->addAttr(AllocAlignAttr::CreateImplicit(
16611 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16612 }
16613
16614 // FIXME:
16615 // C++2a [basic.stc.dynamic.allocation]p3:
16616 // For an allocation function [...], the pointer returned on a successful
16617 // call shall represent the address of storage that is aligned as follows:
16618 // (3.2) Otherwise, if the allocation function is named operator new[],
16619 // the storage is aligned for any object that does not have
16620 // new-extended alignment ([basic.align]) and is no larger than the
16621 // requested size.
16622 // (3.3) Otherwise, the storage is aligned for any object that does not
16623 // have new-extended alignment and is of the requested size.
16624}
16625
16627 if (FD->isInvalidDecl())
16628 return;
16629
16630 // If this is a built-in function, map its builtin attributes to
16631 // actual attributes.
16632 if (unsigned BuiltinID = FD->getBuiltinID()) {
16633 // Handle printf-formatting attributes.
16634 unsigned FormatIdx;
16635 bool HasVAListArg;
16636 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16637 if (!FD->hasAttr<FormatAttr>()) {
16638 const char *fmt = "printf";
16639 unsigned int NumParams = FD->getNumParams();
16640 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16641 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16642 fmt = "NSString";
16643 FD->addAttr(FormatAttr::CreateImplicit(Context,
16644 &Context.Idents.get(fmt),
16645 FormatIdx+1,
16646 HasVAListArg ? 0 : FormatIdx+2,
16647 FD->getLocation()));
16648 }
16649 }
16650 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16651 HasVAListArg)) {
16652 if (!FD->hasAttr<FormatAttr>())
16653 FD->addAttr(FormatAttr::CreateImplicit(Context,
16654 &Context.Idents.get("scanf"),
16655 FormatIdx+1,
16656 HasVAListArg ? 0 : FormatIdx+2,
16657 FD->getLocation()));
16658 }
16659
16660 // Handle automatically recognized callbacks.
16661 SmallVector<int, 4> Encoding;
16662 if (!FD->hasAttr<CallbackAttr>() &&
16663 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16664 FD->addAttr(CallbackAttr::CreateImplicit(
16665 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16666
16667 // Mark const if we don't care about errno and/or floating point exceptions
16668 // that are the only thing preventing the function from being const. This
16669 // allows IRgen to use LLVM intrinsics for such functions.
16670 bool NoExceptions =
16672 bool ConstWithoutErrnoAndExceptions =
16674 bool ConstWithoutExceptions =
16676 if (!FD->hasAttr<ConstAttr>() &&
16677 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16678 (!ConstWithoutErrnoAndExceptions ||
16679 (!getLangOpts().MathErrno && NoExceptions)) &&
16680 (!ConstWithoutExceptions || NoExceptions))
16681 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16682
16683 // We make "fma" on GNU or Windows const because we know it does not set
16684 // errno in those environments even though it could set errno based on the
16685 // C standard.
16686 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16687 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16688 !FD->hasAttr<ConstAttr>()) {
16689 switch (BuiltinID) {
16690 case Builtin::BI__builtin_fma:
16691 case Builtin::BI__builtin_fmaf:
16692 case Builtin::BI__builtin_fmal:
16693 case Builtin::BIfma:
16694 case Builtin::BIfmaf:
16695 case Builtin::BIfmal:
16696 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16697 break;
16698 default:
16699 break;
16700 }
16701 }
16702
16703 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16704 !FD->hasAttr<ReturnsTwiceAttr>())
16705 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16706 FD->getLocation()));
16707 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16708 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16709 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16710 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16711 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16712 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16713 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16714 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16715 // Add the appropriate attribute, depending on the CUDA compilation mode
16716 // and which target the builtin belongs to. For example, during host
16717 // compilation, aux builtins are __device__, while the rest are __host__.
16718 if (getLangOpts().CUDAIsDevice !=
16720 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16721 else
16722 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16723 }
16724
16725 // Add known guaranteed alignment for allocation functions.
16726 switch (BuiltinID) {
16727 case Builtin::BImemalign:
16728 case Builtin::BIaligned_alloc:
16729 if (!FD->hasAttr<AllocAlignAttr>())
16730 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16731 FD->getLocation()));
16732 break;
16733 default:
16734 break;
16735 }
16736
16737 // Add allocsize attribute for allocation functions.
16738 switch (BuiltinID) {
16739 case Builtin::BIcalloc:
16740 FD->addAttr(AllocSizeAttr::CreateImplicit(
16741 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16742 break;
16743 case Builtin::BImemalign:
16744 case Builtin::BIaligned_alloc:
16745 case Builtin::BIrealloc:
16746 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16747 ParamIdx(), FD->getLocation()));
16748 break;
16749 case Builtin::BImalloc:
16750 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16751 ParamIdx(), FD->getLocation()));
16752 break;
16753 default:
16754 break;
16755 }
16756 }
16757
16762
16763 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16764 // throw, add an implicit nothrow attribute to any extern "C" function we come
16765 // across.
16766 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16767 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16768 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16769 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16770 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16771 }
16772
16773 IdentifierInfo *Name = FD->getIdentifier();
16774 if (!Name)
16775 return;
16777 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16778 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16780 // Okay: this could be a libc/libm/Objective-C function we know
16781 // about.
16782 } else
16783 return;
16784
16785 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16786 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16787 // target-specific builtins, perhaps?
16788 if (!FD->hasAttr<FormatAttr>())
16789 FD->addAttr(FormatAttr::CreateImplicit(Context,
16790 &Context.Idents.get("printf"), 2,
16791 Name->isStr("vasprintf") ? 0 : 3,
16792 FD->getLocation()));
16793 }
16794
16795 if (Name->isStr("__CFStringMakeConstantString")) {
16796 // We already have a __builtin___CFStringMakeConstantString,
16797 // but builds that use -fno-constant-cfstrings don't go through that.
16798 if (!FD->hasAttr<FormatArgAttr>())
16799 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16800 FD->getLocation()));
16801 }
16802}
16803
16805 TypeSourceInfo *TInfo) {
16806 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16807 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16808
16809 if (!TInfo) {
16810 assert(D.isInvalidType() && "no declarator info for valid type");
16812 }
16813
16814 // Scope manipulation handled by caller.
16815 TypedefDecl *NewTD =
16817 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16818
16819 // Bail out immediately if we have an invalid declaration.
16820 if (D.isInvalidType()) {
16821 NewTD->setInvalidDecl();
16822 return NewTD;
16823 }
16824
16825 if (D.getDeclSpec().isModulePrivateSpecified()) {
16827 Diag(NewTD->getLocation(), diag::err_module_private_local)
16828 << 2 << NewTD
16829 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16831 D.getDeclSpec().getModulePrivateSpecLoc());
16832 else
16833 NewTD->setModulePrivate();
16834 }
16835
16836 // C++ [dcl.typedef]p8:
16837 // If the typedef declaration defines an unnamed class (or
16838 // enum), the first typedef-name declared by the declaration
16839 // to be that class type (or enum type) is used to denote the
16840 // class type (or enum type) for linkage purposes only.
16841 // We need to check whether the type was declared in the declaration.
16842 switch (D.getDeclSpec().getTypeSpecType()) {
16843 case TST_enum:
16844 case TST_struct:
16845 case TST_interface:
16846 case TST_union:
16847 case TST_class: {
16848 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16849 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16850 break;
16851 }
16852
16853 default:
16854 break;
16855 }
16856
16857 return NewTD;
16858}
16859
16861 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16862 QualType T = TI->getType();
16863
16864 if (T->isDependentType())
16865 return false;
16866
16867 // This doesn't use 'isIntegralType' despite the error message mentioning
16868 // integral type because isIntegralType would also allow enum types in C.
16869 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16870 if (BT->isInteger())
16871 return false;
16872
16873 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16874 << T << T->isBitIntType();
16875}
16876
16878 QualType EnumUnderlyingTy, bool IsFixed,
16879 const EnumDecl *Prev) {
16880 if (IsScoped != Prev->isScoped()) {
16881 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16882 << Prev->isScoped();
16883 Diag(Prev->getLocation(), diag::note_previous_declaration);
16884 return true;
16885 }
16886
16887 if (IsFixed && Prev->isFixed()) {
16888 if (!EnumUnderlyingTy->isDependentType() &&
16889 !Prev->getIntegerType()->isDependentType() &&
16890 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16891 Prev->getIntegerType())) {
16892 // TODO: Highlight the underlying type of the redeclaration.
16893 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16894 << EnumUnderlyingTy << Prev->getIntegerType();
16895 Diag(Prev->getLocation(), diag::note_previous_declaration)
16896 << Prev->getIntegerTypeRange();
16897 return true;
16898 }
16899 } else if (IsFixed != Prev->isFixed()) {
16900 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16901 << Prev->isFixed();
16902 Diag(Prev->getLocation(), diag::note_previous_declaration);
16903 return true;
16904 }
16905
16906 return false;
16907}
16908
16909/// Get diagnostic %select index for tag kind for
16910/// redeclaration diagnostic message.
16911/// WARNING: Indexes apply to particular diagnostics only!
16912///
16913/// \returns diagnostic %select index.
16915 switch (Tag) {
16917 return 0;
16919 return 1;
16920 case TagTypeKind::Class:
16921 return 2;
16922 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16923 }
16924}
16925
16926/// Determine if tag kind is a class-key compatible with
16927/// class for redeclaration (class, struct, or __interface).
16928///
16929/// \returns true iff the tag kind is compatible.
16931{
16932 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
16934}
16935
16937 TagTypeKind TTK) {
16938 if (isa<TypedefDecl>(PrevDecl))
16939 return NTK_Typedef;
16940 else if (isa<TypeAliasDecl>(PrevDecl))
16941 return NTK_TypeAlias;
16942 else if (isa<ClassTemplateDecl>(PrevDecl))
16943 return NTK_Template;
16944 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16945 return NTK_TypeAliasTemplate;
16946 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16948 switch (TTK) {
16951 case TagTypeKind::Class:
16952 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16953 case TagTypeKind::Union:
16954 return NTK_NonUnion;
16955 case TagTypeKind::Enum:
16956 return NTK_NonEnum;
16957 }
16958 llvm_unreachable("invalid TTK");
16959}
16960
16962 TagTypeKind NewTag, bool isDefinition,
16963 SourceLocation NewTagLoc,
16964 const IdentifierInfo *Name) {
16965 // C++ [dcl.type.elab]p3:
16966 // The class-key or enum keyword present in the
16967 // elaborated-type-specifier shall agree in kind with the
16968 // declaration to which the name in the elaborated-type-specifier
16969 // refers. This rule also applies to the form of
16970 // elaborated-type-specifier that declares a class-name or
16971 // friend class since it can be construed as referring to the
16972 // definition of the class. Thus, in any
16973 // elaborated-type-specifier, the enum keyword shall be used to
16974 // refer to an enumeration (7.2), the union class-key shall be
16975 // used to refer to a union (clause 9), and either the class or
16976 // struct class-key shall be used to refer to a class (clause 9)
16977 // declared using the class or struct class-key.
16978 TagTypeKind OldTag = Previous->getTagKind();
16979 if (OldTag != NewTag &&
16981 return false;
16982
16983 // Tags are compatible, but we might still want to warn on mismatched tags.
16984 // Non-class tags can't be mismatched at this point.
16986 return true;
16987
16988 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16989 // by our warning analysis. We don't want to warn about mismatches with (eg)
16990 // declarations in system headers that are designed to be specialized, but if
16991 // a user asks us to warn, we should warn if their code contains mismatched
16992 // declarations.
16993 auto IsIgnoredLoc = [&](SourceLocation Loc) {
16994 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16995 Loc);
16996 };
16997 if (IsIgnoredLoc(NewTagLoc))
16998 return true;
16999
17000 auto IsIgnored = [&](const TagDecl *Tag) {
17001 return IsIgnoredLoc(Tag->getLocation());
17002 };
17003 while (IsIgnored(Previous)) {
17004 Previous = Previous->getPreviousDecl();
17005 if (!Previous)
17006 return true;
17007 OldTag = Previous->getTagKind();
17008 }
17009
17010 bool isTemplate = false;
17011 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17012 isTemplate = Record->getDescribedClassTemplate();
17013
17015 if (OldTag != NewTag) {
17016 // In a template instantiation, do not offer fix-its for tag mismatches
17017 // since they usually mess up the template instead of fixing the problem.
17018 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17020 << getRedeclDiagFromTagKind(OldTag);
17021 // FIXME: Note previous location?
17022 }
17023 return true;
17024 }
17025
17026 if (isDefinition) {
17027 // On definitions, check all previous tags and issue a fix-it for each
17028 // one that doesn't match the current tag.
17029 if (Previous->getDefinition()) {
17030 // Don't suggest fix-its for redefinitions.
17031 return true;
17032 }
17033
17034 bool previousMismatch = false;
17035 for (const TagDecl *I : Previous->redecls()) {
17036 if (I->getTagKind() != NewTag) {
17037 // Ignore previous declarations for which the warning was disabled.
17038 if (IsIgnored(I))
17039 continue;
17040
17041 if (!previousMismatch) {
17042 previousMismatch = true;
17043 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17045 << getRedeclDiagFromTagKind(I->getTagKind());
17046 }
17047 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17049 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17051 }
17052 }
17053 return true;
17054 }
17055
17056 // Identify the prevailing tag kind: this is the kind of the definition (if
17057 // there is a non-ignored definition), or otherwise the kind of the prior
17058 // (non-ignored) declaration.
17059 const TagDecl *PrevDef = Previous->getDefinition();
17060 if (PrevDef && IsIgnored(PrevDef))
17061 PrevDef = nullptr;
17062 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17063 if (Redecl->getTagKind() != NewTag) {
17064 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17066 << getRedeclDiagFromTagKind(OldTag);
17067 Diag(Redecl->getLocation(), diag::note_previous_use);
17068
17069 // If there is a previous definition, suggest a fix-it.
17070 if (PrevDef) {
17071 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17075 }
17076 }
17077
17078 return true;
17079}
17080
17081/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17082/// from an outer enclosing namespace or file scope inside a friend declaration.
17083/// This should provide the commented out code in the following snippet:
17084/// namespace N {
17085/// struct X;
17086/// namespace M {
17087/// struct Y { friend struct /*N::*/ X; };
17088/// }
17089/// }
17091 SourceLocation NameLoc) {
17092 // While the decl is in a namespace, do repeated lookup of that name and see
17093 // if we get the same namespace back. If we do not, continue until
17094 // translation unit scope, at which point we have a fully qualified NNS.
17097 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17098 // This tag should be declared in a namespace, which can only be enclosed by
17099 // other namespaces. Bail if there's an anonymous namespace in the chain.
17100 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17101 if (!Namespace || Namespace->isAnonymousNamespace())
17102 return FixItHint();
17103 IdentifierInfo *II = Namespace->getIdentifier();
17104 Namespaces.push_back(II);
17105 NamedDecl *Lookup = SemaRef.LookupSingleName(
17106 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17107 if (Lookup == Namespace)
17108 break;
17109 }
17110
17111 // Once we have all the namespaces, reverse them to go outermost first, and
17112 // build an NNS.
17113 SmallString<64> Insertion;
17114 llvm::raw_svector_ostream OS(Insertion);
17115 if (DC->isTranslationUnit())
17116 OS << "::";
17117 std::reverse(Namespaces.begin(), Namespaces.end());
17118 for (auto *II : Namespaces)
17119 OS << II->getName() << "::";
17120 return FixItHint::CreateInsertion(NameLoc, Insertion);
17121}
17122
17123/// Determine whether a tag originally declared in context \p OldDC can
17124/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17125/// found a declaration in \p OldDC as a previous decl, perhaps through a
17126/// using-declaration).
17128 DeclContext *NewDC) {
17129 OldDC = OldDC->getRedeclContext();
17130 NewDC = NewDC->getRedeclContext();
17131
17132 if (OldDC->Equals(NewDC))
17133 return true;
17134
17135 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17136 // encloses the other).
17137 if (S.getLangOpts().MSVCCompat &&
17138 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17139 return true;
17140
17141 return false;
17142}
17143
17145Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17146 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17147 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17148 SourceLocation ModulePrivateLoc,
17149 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17150 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17151 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17152 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17153 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17154 // If this is not a definition, it must have a name.
17155 IdentifierInfo *OrigName = Name;
17156 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17157 "Nameless record must be a definition!");
17158 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17159
17160 OwnedDecl = false;
17162 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17163
17164 // FIXME: Check member specializations more carefully.
17165 bool isMemberSpecialization = false;
17166 bool Invalid = false;
17167
17168 // We only need to do this matching if we have template parameters
17169 // or a scope specifier, which also conveniently avoids this work
17170 // for non-C++ cases.
17171 if (TemplateParameterLists.size() > 0 ||
17172 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17173 TemplateParameterList *TemplateParams =
17175 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17176 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17177
17178 // C++23 [dcl.type.elab] p2:
17179 // If an elaborated-type-specifier is the sole constituent of a
17180 // declaration, the declaration is ill-formed unless it is an explicit
17181 // specialization, an explicit instantiation or it has one of the
17182 // following forms: [...]
17183 // C++23 [dcl.enum] p1:
17184 // If the enum-head-name of an opaque-enum-declaration contains a
17185 // nested-name-specifier, the declaration shall be an explicit
17186 // specialization.
17187 //
17188 // FIXME: Class template partial specializations can be forward declared
17189 // per CWG2213, but the resolution failed to allow qualified forward
17190 // declarations. This is almost certainly unintentional, so we allow them.
17191 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17192 !isMemberSpecialization)
17193 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17195
17196 if (TemplateParams) {
17197 if (Kind == TagTypeKind::Enum) {
17198 Diag(KWLoc, diag::err_enum_template);
17199 return true;
17200 }
17201
17202 if (TemplateParams->size() > 0) {
17203 // This is a declaration or definition of a class template (which may
17204 // be a member of another template).
17205
17206 if (Invalid)
17207 return true;
17208
17209 OwnedDecl = false;
17211 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17212 AS, ModulePrivateLoc,
17213 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17214 TemplateParameterLists.data(), SkipBody);
17215 return Result.get();
17216 } else {
17217 // The "template<>" header is extraneous.
17218 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17219 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17220 isMemberSpecialization = true;
17221 }
17222 }
17223
17224 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17225 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17226 return true;
17227 }
17228
17229 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17230 // C++23 [dcl.type.elab]p4:
17231 // If an elaborated-type-specifier appears with the friend specifier as
17232 // an entire member-declaration, the member-declaration shall have one
17233 // of the following forms:
17234 // friend class-key nested-name-specifier(opt) identifier ;
17235 // friend class-key simple-template-id ;
17236 // friend class-key nested-name-specifier template(opt)
17237 // simple-template-id ;
17238 //
17239 // Since enum is not a class-key, so declarations like "friend enum E;"
17240 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17241 // invalid, most implementations accept so we issue a pedantic warning.
17242 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17243 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17244 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17245 Diag(KWLoc, diag::note_enum_friend)
17246 << (ScopedEnum + ScopedEnumUsesClassTag);
17247 }
17248
17249 // Figure out the underlying type if this a enum declaration. We need to do
17250 // this early, because it's needed to detect if this is an incompatible
17251 // redeclaration.
17252 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17253 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17254
17255 if (Kind == TagTypeKind::Enum) {
17256 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17257 // No underlying type explicitly specified, or we failed to parse the
17258 // type, default to int.
17259 EnumUnderlying = Context.IntTy.getTypePtr();
17260 } else if (UnderlyingType.get()) {
17261 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17262 // integral type; any cv-qualification is ignored.
17263 TypeSourceInfo *TI = nullptr;
17264 GetTypeFromParser(UnderlyingType.get(), &TI);
17265 EnumUnderlying = TI;
17266
17268 // Recover by falling back to int.
17269 EnumUnderlying = Context.IntTy.getTypePtr();
17270
17273 EnumUnderlying = Context.IntTy.getTypePtr();
17274
17275 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17276 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17277 // of 'int'. However, if this is an unfixed forward declaration, don't set
17278 // the underlying type unless the user enables -fms-compatibility. This
17279 // makes unfixed forward declared enums incomplete and is more conforming.
17280 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17281 EnumUnderlying = Context.IntTy.getTypePtr();
17282 }
17283 }
17284
17285 DeclContext *SearchDC = CurContext;
17286 DeclContext *DC = CurContext;
17287 bool isStdBadAlloc = false;
17288 bool isStdAlignValT = false;
17289
17291 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17292 Redecl = RedeclarationKind::NotForRedeclaration;
17293
17294 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17295 /// implemented asks for structural equivalence checking, the returned decl
17296 /// here is passed back to the parser, allowing the tag body to be parsed.
17297 auto createTagFromNewDecl = [&]() -> TagDecl * {
17298 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17299 // If there is an identifier, use the location of the identifier as the
17300 // location of the decl, otherwise use the location of the struct/union
17301 // keyword.
17302 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17303 TagDecl *New = nullptr;
17304
17305 if (Kind == TagTypeKind::Enum) {
17306 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17307 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17308 // If this is an undefined enum, bail.
17309 if (TUK != TagUseKind::Definition && !Invalid)
17310 return nullptr;
17311 if (EnumUnderlying) {
17312 EnumDecl *ED = cast<EnumDecl>(New);
17313 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17315 else
17316 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17317 QualType EnumTy = ED->getIntegerType();
17320 : EnumTy);
17321 }
17322 } else { // struct/union
17323 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17324 nullptr);
17325 }
17326
17327 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17328 // Add alignment attributes if necessary; these attributes are checked
17329 // when the ASTContext lays out the structure.
17330 //
17331 // It is important for implementing the correct semantics that this
17332 // happen here (in ActOnTag). The #pragma pack stack is
17333 // maintained as a result of parser callbacks which can occur at
17334 // many points during the parsing of a struct declaration (because
17335 // the #pragma tokens are effectively skipped over during the
17336 // parsing of the struct).
17337 if (TUK == TagUseKind::Definition &&
17338 (!SkipBody || !SkipBody->ShouldSkip)) {
17341 }
17342 }
17344 return New;
17345 };
17346
17347 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17348 if (Name && SS.isNotEmpty()) {
17349 // We have a nested-name tag ('struct foo::bar').
17350
17351 // Check for invalid 'foo::'.
17352 if (SS.isInvalid()) {
17353 Name = nullptr;
17354 goto CreateNewDecl;
17355 }
17356
17357 // If this is a friend or a reference to a class in a dependent
17358 // context, don't try to make a decl for it.
17359 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17360 DC = computeDeclContext(SS, false);
17361 if (!DC) {
17362 IsDependent = true;
17363 return true;
17364 }
17365 } else {
17366 DC = computeDeclContext(SS, true);
17367 if (!DC) {
17368 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17369 << SS.getRange();
17370 return true;
17371 }
17372 }
17373
17374 if (RequireCompleteDeclContext(SS, DC))
17375 return true;
17376
17377 SearchDC = DC;
17378 // Look-up name inside 'foo::'.
17380
17381 if (Previous.isAmbiguous())
17382 return true;
17383
17384 if (Previous.empty()) {
17385 // Name lookup did not find anything. However, if the
17386 // nested-name-specifier refers to the current instantiation,
17387 // and that current instantiation has any dependent base
17388 // classes, we might find something at instantiation time: treat
17389 // this as a dependent elaborated-type-specifier.
17390 // But this only makes any sense for reference-like lookups.
17391 if (Previous.wasNotFoundInCurrentInstantiation() &&
17392 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17393 IsDependent = true;
17394 return true;
17395 }
17396
17397 // A tag 'foo::bar' must already exist.
17398 Diag(NameLoc, diag::err_not_tag_in_scope)
17399 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17400 Name = nullptr;
17401 Invalid = true;
17402 goto CreateNewDecl;
17403 }
17404 } else if (Name) {
17405 // C++14 [class.mem]p14:
17406 // If T is the name of a class, then each of the following shall have a
17407 // name different from T:
17408 // -- every member of class T that is itself a type
17409 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17410 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17411 return true;
17412
17413 // If this is a named struct, check to see if there was a previous forward
17414 // declaration or definition.
17415 // FIXME: We're looking into outer scopes here, even when we
17416 // shouldn't be. Doing so can result in ambiguities that we
17417 // shouldn't be diagnosing.
17418 LookupName(Previous, S);
17419
17420 // When declaring or defining a tag, ignore ambiguities introduced
17421 // by types using'ed into this scope.
17422 if (Previous.isAmbiguous() &&
17424 LookupResult::Filter F = Previous.makeFilter();
17425 while (F.hasNext()) {
17426 NamedDecl *ND = F.next();
17427 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17428 SearchDC->getRedeclContext()))
17429 F.erase();
17430 }
17431 F.done();
17432 }
17433
17434 // C++11 [namespace.memdef]p3:
17435 // If the name in a friend declaration is neither qualified nor
17436 // a template-id and the declaration is a function or an
17437 // elaborated-type-specifier, the lookup to determine whether
17438 // the entity has been previously declared shall not consider
17439 // any scopes outside the innermost enclosing namespace.
17440 //
17441 // MSVC doesn't implement the above rule for types, so a friend tag
17442 // declaration may be a redeclaration of a type declared in an enclosing
17443 // scope. They do implement this rule for friend functions.
17444 //
17445 // Does it matter that this should be by scope instead of by
17446 // semantic context?
17447 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17448 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17449 LookupResult::Filter F = Previous.makeFilter();
17450 bool FriendSawTagOutsideEnclosingNamespace = false;
17451 while (F.hasNext()) {
17452 NamedDecl *ND = F.next();
17454 if (DC->isFileContext() &&
17455 !EnclosingNS->Encloses(ND->getDeclContext())) {
17456 if (getLangOpts().MSVCCompat)
17457 FriendSawTagOutsideEnclosingNamespace = true;
17458 else
17459 F.erase();
17460 }
17461 }
17462 F.done();
17463
17464 // Diagnose this MSVC extension in the easy case where lookup would have
17465 // unambiguously found something outside the enclosing namespace.
17466 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17467 NamedDecl *ND = Previous.getFoundDecl();
17468 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17469 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17470 }
17471 }
17472
17473 // Note: there used to be some attempt at recovery here.
17474 if (Previous.isAmbiguous())
17475 return true;
17476
17477 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17478 // FIXME: This makes sure that we ignore the contexts associated
17479 // with C structs, unions, and enums when looking for a matching
17480 // tag declaration or definition. See the similar lookup tweak
17481 // in Sema::LookupName; is there a better way to deal with this?
17482 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17483 SearchDC = SearchDC->getParent();
17484 } else if (getLangOpts().CPlusPlus) {
17485 // Inside ObjCContainer want to keep it as a lexical decl context but go
17486 // past it (most often to TranslationUnit) to find the semantic decl
17487 // context.
17488 while (isa<ObjCContainerDecl>(SearchDC))
17489 SearchDC = SearchDC->getParent();
17490 }
17491 } else if (getLangOpts().CPlusPlus) {
17492 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17493 // TagDecl the same way as we skip it for named TagDecl.
17494 while (isa<ObjCContainerDecl>(SearchDC))
17495 SearchDC = SearchDC->getParent();
17496 }
17497
17498 if (Previous.isSingleResult() &&
17499 Previous.getFoundDecl()->isTemplateParameter()) {
17500 // Maybe we will complain about the shadowed template parameter.
17501 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17502 // Just pretend that we didn't see the previous declaration.
17503 Previous.clear();
17504 }
17505
17506 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17507 DC->Equals(getStdNamespace())) {
17508 if (Name->isStr("bad_alloc")) {
17509 // This is a declaration of or a reference to "std::bad_alloc".
17510 isStdBadAlloc = true;
17511
17512 // If std::bad_alloc has been implicitly declared (but made invisible to
17513 // name lookup), fill in this implicit declaration as the previous
17514 // declaration, so that the declarations get chained appropriately.
17515 if (Previous.empty() && StdBadAlloc)
17516 Previous.addDecl(getStdBadAlloc());
17517 } else if (Name->isStr("align_val_t")) {
17518 isStdAlignValT = true;
17519 if (Previous.empty() && StdAlignValT)
17520 Previous.addDecl(getStdAlignValT());
17521 }
17522 }
17523
17524 // If we didn't find a previous declaration, and this is a reference
17525 // (or friend reference), move to the correct scope. In C++, we
17526 // also need to do a redeclaration lookup there, just in case
17527 // there's a shadow friend decl.
17528 if (Name && Previous.empty() &&
17529 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17530 IsTemplateParamOrArg)) {
17531 if (Invalid) goto CreateNewDecl;
17532 assert(SS.isEmpty());
17533
17534 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17535 // C++ [basic.scope.pdecl]p5:
17536 // -- for an elaborated-type-specifier of the form
17537 //
17538 // class-key identifier
17539 //
17540 // if the elaborated-type-specifier is used in the
17541 // decl-specifier-seq or parameter-declaration-clause of a
17542 // function defined in namespace scope, the identifier is
17543 // declared as a class-name in the namespace that contains
17544 // the declaration; otherwise, except as a friend
17545 // declaration, the identifier is declared in the smallest
17546 // non-class, non-function-prototype scope that contains the
17547 // declaration.
17548 //
17549 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17550 // C structs and unions.
17551 //
17552 // It is an error in C++ to declare (rather than define) an enum
17553 // type, including via an elaborated type specifier. We'll
17554 // diagnose that later; for now, declare the enum in the same
17555 // scope as we would have picked for any other tag type.
17556 //
17557 // GNU C also supports this behavior as part of its incomplete
17558 // enum types extension, while GNU C++ does not.
17559 //
17560 // Find the context where we'll be declaring the tag.
17561 // FIXME: We would like to maintain the current DeclContext as the
17562 // lexical context,
17563 SearchDC = getTagInjectionContext(SearchDC);
17564
17565 // Find the scope where we'll be declaring the tag.
17567 } else {
17568 assert(TUK == TagUseKind::Friend);
17569 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17570
17571 // C++ [namespace.memdef]p3:
17572 // If a friend declaration in a non-local class first declares a
17573 // class or function, the friend class or function is a member of
17574 // the innermost enclosing namespace.
17575 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17576 : SearchDC->getEnclosingNamespaceContext();
17577 }
17578
17579 // In C++, we need to do a redeclaration lookup to properly
17580 // diagnose some problems.
17581 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17582 // hidden declaration so that we don't get ambiguity errors when using a
17583 // type declared by an elaborated-type-specifier. In C that is not correct
17584 // and we should instead merge compatible types found by lookup.
17585 if (getLangOpts().CPlusPlus) {
17586 // FIXME: This can perform qualified lookups into function contexts,
17587 // which are meaningless.
17588 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17589 LookupQualifiedName(Previous, SearchDC);
17590 } else {
17591 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17592 LookupName(Previous, S);
17593 }
17594 }
17595
17596 // If we have a known previous declaration to use, then use it.
17597 if (Previous.empty() && SkipBody && SkipBody->Previous)
17598 Previous.addDecl(SkipBody->Previous);
17599
17600 if (!Previous.empty()) {
17601 NamedDecl *PrevDecl = Previous.getFoundDecl();
17602 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17603
17604 // It's okay to have a tag decl in the same scope as a typedef
17605 // which hides a tag decl in the same scope. Finding this
17606 // with a redeclaration lookup can only actually happen in C++.
17607 //
17608 // This is also okay for elaborated-type-specifiers, which is
17609 // technically forbidden by the current standard but which is
17610 // okay according to the likely resolution of an open issue;
17611 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17612 if (getLangOpts().CPlusPlus) {
17613 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17614 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17615 TagDecl *Tag = TT->getDecl();
17616 if (Tag->getDeclName() == Name &&
17617 Tag->getDeclContext()->getRedeclContext()
17618 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17619 PrevDecl = Tag;
17620 Previous.clear();
17621 Previous.addDecl(Tag);
17622 Previous.resolveKind();
17623 }
17624 }
17625 }
17626 }
17627
17628 // If this is a redeclaration of a using shadow declaration, it must
17629 // declare a tag in the same context. In MSVC mode, we allow a
17630 // redefinition if either context is within the other.
17631 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17632 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17633 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
17634 TUK != TagUseKind::Friend &&
17635 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17636 !(OldTag && isAcceptableTagRedeclContext(
17637 *this, OldTag->getDeclContext(), SearchDC))) {
17638 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17639 Diag(Shadow->getTargetDecl()->getLocation(),
17640 diag::note_using_decl_target);
17641 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17642 << 0;
17643 // Recover by ignoring the old declaration.
17644 Previous.clear();
17645 goto CreateNewDecl;
17646 }
17647 }
17648
17649 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17650 // If this is a use of a previous tag, or if the tag is already declared
17651 // in the same scope (so that the definition/declaration completes or
17652 // rementions the tag), reuse the decl.
17653 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17654 isDeclInScope(DirectPrevDecl, SearchDC, S,
17655 SS.isNotEmpty() || isMemberSpecialization)) {
17656 // Make sure that this wasn't declared as an enum and now used as a
17657 // struct or something similar.
17658 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17659 TUK == TagUseKind::Definition, KWLoc,
17660 Name)) {
17661 bool SafeToContinue =
17662 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17663 Kind != TagTypeKind::Enum);
17664 if (SafeToContinue)
17665 Diag(KWLoc, diag::err_use_with_wrong_tag)
17666 << Name
17668 PrevTagDecl->getKindName());
17669 else
17670 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17671 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17672
17673 if (SafeToContinue)
17674 Kind = PrevTagDecl->getTagKind();
17675 else {
17676 // Recover by making this an anonymous redefinition.
17677 Name = nullptr;
17678 Previous.clear();
17679 Invalid = true;
17680 }
17681 }
17682
17683 if (Kind == TagTypeKind::Enum &&
17684 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17685 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17686 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
17687 return PrevTagDecl;
17688
17689 QualType EnumUnderlyingTy;
17690 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17691 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17692 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17693 EnumUnderlyingTy = QualType(T, 0);
17694
17695 // All conflicts with previous declarations are recovered by
17696 // returning the previous declaration, unless this is a definition,
17697 // in which case we want the caller to bail out.
17698 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17699 ScopedEnum, EnumUnderlyingTy,
17700 IsFixed, PrevEnum))
17701 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
17702 }
17703
17704 // C++11 [class.mem]p1:
17705 // A member shall not be declared twice in the member-specification,
17706 // except that a nested class or member class template can be declared
17707 // and then later defined.
17708 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
17709 S->isDeclScope(PrevDecl)) {
17710 Diag(NameLoc, diag::ext_member_redeclared);
17711 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17712 }
17713
17714 if (!Invalid) {
17715 // If this is a use, just return the declaration we found, unless
17716 // we have attributes.
17717 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17718 if (!Attrs.empty()) {
17719 // FIXME: Diagnose these attributes. For now, we create a new
17720 // declaration to hold them.
17721 } else if (TUK == TagUseKind::Reference &&
17722 (PrevTagDecl->getFriendObjectKind() ==
17724 PrevDecl->getOwningModule() != getCurrentModule()) &&
17725 SS.isEmpty()) {
17726 // This declaration is a reference to an existing entity, but
17727 // has different visibility from that entity: it either makes
17728 // a friend visible or it makes a type visible in a new module.
17729 // In either case, create a new declaration. We only do this if
17730 // the declaration would have meant the same thing if no prior
17731 // declaration were found, that is, if it was found in the same
17732 // scope where we would have injected a declaration.
17733 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17734 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17735 return PrevTagDecl;
17736 // This is in the injected scope, create a new declaration in
17737 // that scope.
17739 } else {
17740 return PrevTagDecl;
17741 }
17742 }
17743
17744 // Diagnose attempts to redefine a tag.
17745 if (TUK == TagUseKind::Definition) {
17746 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17747 // If we're defining a specialization and the previous definition
17748 // is from an implicit instantiation, don't emit an error
17749 // here; we'll catch this in the general case below.
17750 bool IsExplicitSpecializationAfterInstantiation = false;
17751 if (isMemberSpecialization) {
17752 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17753 IsExplicitSpecializationAfterInstantiation =
17754 RD->getTemplateSpecializationKind() !=
17756 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17757 IsExplicitSpecializationAfterInstantiation =
17758 ED->getTemplateSpecializationKind() !=
17760 }
17761
17762 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17763 // not keep more that one definition around (merge them). However,
17764 // ensure the decl passes the structural compatibility check in
17765 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17766 NamedDecl *Hidden = nullptr;
17767 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17768 // There is a definition of this tag, but it is not visible. We
17769 // explicitly make use of C++'s one definition rule here, and
17770 // assume that this definition is identical to the hidden one
17771 // we already have. Make the existing definition visible and
17772 // use it in place of this one.
17773 if (!getLangOpts().CPlusPlus) {
17774 // Postpone making the old definition visible until after we
17775 // complete parsing the new one and do the structural
17776 // comparison.
17777 SkipBody->CheckSameAsPrevious = true;
17778 SkipBody->New = createTagFromNewDecl();
17779 SkipBody->Previous = Def;
17780 return Def;
17781 } else {
17782 SkipBody->ShouldSkip = true;
17783 SkipBody->Previous = Def;
17785 // Carry on and handle it like a normal definition. We'll
17786 // skip starting the definition later.
17787 }
17788 } else if (!IsExplicitSpecializationAfterInstantiation) {
17789 // A redeclaration in function prototype scope in C isn't
17790 // visible elsewhere, so merely issue a warning.
17791 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17792 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17793 else
17794 Diag(NameLoc, diag::err_redefinition) << Name;
17796 NameLoc.isValid() ? NameLoc : KWLoc);
17797 // If this is a redefinition, recover by making this
17798 // struct be anonymous, which will make any later
17799 // references get the previous definition.
17800 Name = nullptr;
17801 Previous.clear();
17802 Invalid = true;
17803 }
17804 } else {
17805 // If the type is currently being defined, complain
17806 // about a nested redefinition.
17807 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17808 if (TD->isBeingDefined()) {
17809 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17810 Diag(PrevTagDecl->getLocation(),
17811 diag::note_previous_definition);
17812 Name = nullptr;
17813 Previous.clear();
17814 Invalid = true;
17815 }
17816 }
17817
17818 // Okay, this is definition of a previously declared or referenced
17819 // tag. We're going to create a new Decl for it.
17820 }
17821
17822 // Okay, we're going to make a redeclaration. If this is some kind
17823 // of reference, make sure we build the redeclaration in the same DC
17824 // as the original, and ignore the current access specifier.
17825 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17826 SearchDC = PrevTagDecl->getDeclContext();
17827 AS = AS_none;
17828 }
17829 }
17830 // If we get here we have (another) forward declaration or we
17831 // have a definition. Just create a new decl.
17832
17833 } else {
17834 // If we get here, this is a definition of a new tag type in a nested
17835 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17836 // new decl/type. We set PrevDecl to NULL so that the entities
17837 // have distinct types.
17838 Previous.clear();
17839 }
17840 // If we get here, we're going to create a new Decl. If PrevDecl
17841 // is non-NULL, it's a definition of the tag declared by
17842 // PrevDecl. If it's NULL, we have a new definition.
17843
17844 // Otherwise, PrevDecl is not a tag, but was found with tag
17845 // lookup. This is only actually possible in C++, where a few
17846 // things like templates still live in the tag namespace.
17847 } else {
17848 // Use a better diagnostic if an elaborated-type-specifier
17849 // found the wrong kind of type on the first
17850 // (non-redeclaration) lookup.
17851 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
17852 !Previous.isForRedeclaration()) {
17853 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17854 Diag(NameLoc, diag::err_tag_reference_non_tag)
17855 << PrevDecl << NTK << llvm::to_underlying(Kind);
17856 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17857 Invalid = true;
17858
17859 // Otherwise, only diagnose if the declaration is in scope.
17860 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17861 SS.isNotEmpty() || isMemberSpecialization)) {
17862 // do nothing
17863
17864 // Diagnose implicit declarations introduced by elaborated types.
17865 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17866 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17867 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17868 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17869 Invalid = true;
17870
17871 // Otherwise it's a declaration. Call out a particularly common
17872 // case here.
17873 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17874 unsigned Kind = 0;
17875 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17876 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17877 << Name << Kind << TND->getUnderlyingType();
17878 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17879 Invalid = true;
17880
17881 // Otherwise, diagnose.
17882 } else {
17883 // The tag name clashes with something else in the target scope,
17884 // issue an error and recover by making this tag be anonymous.
17885 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17886 notePreviousDefinition(PrevDecl, NameLoc);
17887 Name = nullptr;
17888 Invalid = true;
17889 }
17890
17891 // The existing declaration isn't relevant to us; we're in a
17892 // new scope, so clear out the previous declaration.
17893 Previous.clear();
17894 }
17895 }
17896
17897CreateNewDecl:
17898
17899 TagDecl *PrevDecl = nullptr;
17900 if (Previous.isSingleResult())
17901 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17902
17903 // If there is an identifier, use the location of the identifier as the
17904 // location of the decl, otherwise use the location of the struct/union
17905 // keyword.
17906 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17907
17908 // Otherwise, create a new declaration. If there is a previous
17909 // declaration of the same entity, the two will be linked via
17910 // PrevDecl.
17911 TagDecl *New;
17912
17913 if (Kind == TagTypeKind::Enum) {
17914 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17915 // enum X { A, B, C } D; D should chain to X.
17916 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17917 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17918 ScopedEnumUsesClassTag, IsFixed);
17919
17920 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17921 StdAlignValT = cast<EnumDecl>(New);
17922
17923 // If this is an undefined enum, warn.
17924 if (TUK != TagUseKind::Definition && !Invalid) {
17925 TagDecl *Def;
17926 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17927 // C++0x: 7.2p2: opaque-enum-declaration.
17928 // Conflicts are diagnosed above. Do nothing.
17929 }
17930 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17931 Diag(Loc, diag::ext_forward_ref_enum_def)
17932 << New;
17933 Diag(Def->getLocation(), diag::note_previous_definition);
17934 } else {
17935 unsigned DiagID = diag::ext_forward_ref_enum;
17936 if (getLangOpts().MSVCCompat)
17937 DiagID = diag::ext_ms_forward_ref_enum;
17938 else if (getLangOpts().CPlusPlus)
17939 DiagID = diag::err_forward_ref_enum;
17940 Diag(Loc, DiagID);
17941 }
17942 }
17943
17944 if (EnumUnderlying) {
17945 EnumDecl *ED = cast<EnumDecl>(New);
17946 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17948 else
17949 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17950 QualType EnumTy = ED->getIntegerType();
17953 : EnumTy);
17954 assert(ED->isComplete() && "enum with type should be complete");
17955 }
17956 } else {
17957 // struct/union/class
17958
17959 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17960 // struct X { int A; } D; D should chain to X.
17961 if (getLangOpts().CPlusPlus) {
17962 // FIXME: Look for a way to use RecordDecl for simple structs.
17963 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17964 cast_or_null<CXXRecordDecl>(PrevDecl));
17965
17966 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17967 StdBadAlloc = cast<CXXRecordDecl>(New);
17968 } else
17969 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17970 cast_or_null<RecordDecl>(PrevDecl));
17971 }
17972
17973 // Only C23 and later allow defining new types in 'offsetof()'.
17974 if (OOK != OOK_Outside && TUK == TagUseKind::Definition &&
17976 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17977 << (OOK == OOK_Macro) << New->getSourceRange();
17978
17979 // C++11 [dcl.type]p3:
17980 // A type-specifier-seq shall not define a class or enumeration [...].
17981 if (!Invalid && getLangOpts().CPlusPlus &&
17982 (IsTypeSpecifier || IsTemplateParamOrArg) &&
17983 TUK == TagUseKind::Definition) {
17984 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17985 << Context.getTagDeclType(New);
17986 Invalid = true;
17987 }
17988
17990 DC->getDeclKind() == Decl::Enum) {
17991 Diag(New->getLocation(), diag::err_type_defined_in_enum)
17992 << Context.getTagDeclType(New);
17993 Invalid = true;
17994 }
17995
17996 // Maybe add qualifier info.
17997 if (SS.isNotEmpty()) {
17998 if (SS.isSet()) {
17999 // If this is either a declaration or a definition, check the
18000 // nested-name-specifier against the current context.
18001 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18002 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18003 /*TemplateId=*/nullptr,
18004 isMemberSpecialization))
18005 Invalid = true;
18006
18008 if (TemplateParameterLists.size() > 0) {
18009 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18010 }
18011 }
18012 else
18013 Invalid = true;
18014 }
18015
18016 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18017 // Add alignment attributes if necessary; these attributes are checked when
18018 // the ASTContext lays out the structure.
18019 //
18020 // It is important for implementing the correct semantics that this
18021 // happen here (in ActOnTag). The #pragma pack stack is
18022 // maintained as a result of parser callbacks which can occur at
18023 // many points during the parsing of a struct declaration (because
18024 // the #pragma tokens are effectively skipped over during the
18025 // parsing of the struct).
18026 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18029 }
18030 }
18031
18032 if (ModulePrivateLoc.isValid()) {
18033 if (isMemberSpecialization)
18034 Diag(New->getLocation(), diag::err_module_private_specialization)
18035 << 2
18036 << FixItHint::CreateRemoval(ModulePrivateLoc);
18037 // __module_private__ does not apply to local classes. However, we only
18038 // diagnose this as an error when the declaration specifiers are
18039 // freestanding. Here, we just ignore the __module_private__.
18040 else if (!SearchDC->isFunctionOrMethod())
18041 New->setModulePrivate();
18042 }
18043
18044 // If this is a specialization of a member class (of a class template),
18045 // check the specialization.
18046 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18047 Invalid = true;
18048
18049 // If we're declaring or defining a tag in function prototype scope in C,
18050 // note that this type can only be used within the function and add it to
18051 // the list of decls to inject into the function definition scope.
18052 if ((Name || Kind == TagTypeKind::Enum) &&
18053 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18054 if (getLangOpts().CPlusPlus) {
18055 // C++ [dcl.fct]p6:
18056 // Types shall not be defined in return or parameter types.
18057 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18058 Diag(Loc, diag::err_type_defined_in_param_type)
18059 << Name;
18060 Invalid = true;
18061 }
18062 if (TUK == TagUseKind::Declaration)
18063 Invalid = true;
18064 } else if (!PrevDecl) {
18065 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
18066 }
18067 }
18068
18069 if (Invalid)
18070 New->setInvalidDecl();
18071
18072 // Set the lexical context. If the tag has a C++ scope specifier, the
18073 // lexical context will be different from the semantic context.
18075
18076 // Mark this as a friend decl if applicable.
18077 // In Microsoft mode, a friend declaration also acts as a forward
18078 // declaration so we always pass true to setObjectOfFriendDecl to make
18079 // the tag name visible.
18080 if (TUK == TagUseKind::Friend)
18081 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18082
18083 // Set the access specifier.
18084 if (!Invalid && SearchDC->isRecord())
18085 SetMemberAccessSpecifier(New, PrevDecl, AS);
18086
18087 if (PrevDecl)
18088 CheckRedeclarationInModule(New, PrevDecl);
18089
18090 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
18091 New->startDefinition();
18092
18093 ProcessDeclAttributeList(S, New, Attrs);
18094 AddPragmaAttributes(S, New);
18095
18096 // If this has an identifier, add it to the scope stack.
18097 if (TUK == TagUseKind::Friend) {
18098 // We might be replacing an existing declaration in the lookup tables;
18099 // if so, borrow its access specifier.
18100 if (PrevDecl)
18101 New->setAccess(PrevDecl->getAccess());
18102
18104 DC->makeDeclVisibleInContext(New);
18105 if (Name) // can be null along some error paths
18106 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18107 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18108 } else if (Name) {
18109 S = getNonFieldDeclScope(S);
18110 PushOnScopeChains(New, S, true);
18111 } else {
18112 CurContext->addDecl(New);
18113 }
18114
18115 // If this is the C FILE type, notify the AST context.
18116 if (IdentifierInfo *II = New->getIdentifier())
18117 if (!New->isInvalidDecl() &&
18119 II->isStr("FILE"))
18120 Context.setFILEDecl(New);
18121
18122 if (PrevDecl)
18123 mergeDeclAttributes(New, PrevDecl);
18124
18125 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18128 }
18129
18130 // If there's a #pragma GCC visibility in scope, set the visibility of this
18131 // record.
18133
18134 if (isMemberSpecialization && !New->isInvalidDecl())
18136
18137 OwnedDecl = true;
18138 // In C++, don't return an invalid declaration. We can't recover well from
18139 // the cases where we make the type anonymous.
18140 if (Invalid && getLangOpts().CPlusPlus) {
18141 if (New->isBeingDefined())
18142 if (auto RD = dyn_cast<RecordDecl>(New))
18143 RD->completeDefinition();
18144 return true;
18145 } else if (SkipBody && SkipBody->ShouldSkip) {
18146 return SkipBody->Previous;
18147 } else {
18148 return New;
18149 }
18150}
18151
18154 TagDecl *Tag = cast<TagDecl>(TagD);
18155
18156 // Enter the tag context.
18157 PushDeclContext(S, Tag);
18158
18160
18161 // If there's a #pragma GCC visibility in scope, set the visibility of this
18162 // record.
18164}
18165
18167 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18168 return false;
18169
18170 // Make the previous decl visible.
18172 return true;
18173}
18174
18176 SourceLocation FinalLoc,
18177 bool IsFinalSpelledSealed,
18178 bool IsAbstract,
18179 SourceLocation LBraceLoc) {
18181 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18182
18183 FieldCollector->StartClass();
18184
18185 if (!Record->getIdentifier())
18186 return;
18187
18188 if (IsAbstract)
18189 Record->markAbstract();
18190
18191 if (FinalLoc.isValid()) {
18192 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18193 IsFinalSpelledSealed
18194 ? FinalAttr::Keyword_sealed
18195 : FinalAttr::Keyword_final));
18196 }
18197 // C++ [class]p2:
18198 // [...] The class-name is also inserted into the scope of the
18199 // class itself; this is known as the injected-class-name. For
18200 // purposes of access checking, the injected-class-name is treated
18201 // as if it were a public member name.
18202 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18203 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18204 Record->getLocation(), Record->getIdentifier(),
18205 /*PrevDecl=*/nullptr,
18206 /*DelayTypeCreation=*/true);
18207 Context.getTypeDeclType(InjectedClassName, Record);
18208 InjectedClassName->setImplicit();
18209 InjectedClassName->setAccess(AS_public);
18210 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18211 InjectedClassName->setDescribedClassTemplate(Template);
18212 PushOnScopeChains(InjectedClassName, S);
18213 assert(InjectedClassName->isInjectedClassName() &&
18214 "Broken injected-class-name");
18215}
18216
18218 SourceRange BraceRange) {
18220 TagDecl *Tag = cast<TagDecl>(TagD);
18221 Tag->setBraceRange(BraceRange);
18222
18223 // Make sure we "complete" the definition even it is invalid.
18224 if (Tag->isBeingDefined()) {
18225 assert(Tag->isInvalidDecl() && "We should already have completed it");
18226 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18227 RD->completeDefinition();
18228 }
18229
18230 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18231 FieldCollector->FinishClass();
18232 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18233 auto *Def = RD->getDefinition();
18234 assert(Def && "The record is expected to have a completed definition");
18235 unsigned NumInitMethods = 0;
18236 for (auto *Method : Def->methods()) {
18237 if (!Method->getIdentifier())
18238 continue;
18239 if (Method->getName() == "__init")
18240 NumInitMethods++;
18241 }
18242 if (NumInitMethods > 1 || !Def->hasInitMethod())
18243 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18244 }
18245
18246 // If we're defining a dynamic class in a module interface unit, we always
18247 // need to produce the vtable for it, even if the vtable is not used in the
18248 // current TU.
18249 //
18250 // The case where the current class is not dynamic is handled in
18251 // MarkVTableUsed.
18252 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18253 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18254 }
18255
18256 // Exit this scope of this tag's definition.
18258
18259 if (getCurLexicalContext()->isObjCContainer() &&
18260 Tag->getDeclContext()->isFileContext())
18261 Tag->setTopLevelDeclInObjCContainer();
18262
18263 // Notify the consumer that we've defined a tag.
18264 if (!Tag->isInvalidDecl())
18266
18267 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18268 // from XLs and instead matches the XL #pragma pack(1) behavior.
18269 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18270 AlignPackStack.hasValue()) {
18271 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18272 // Only diagnose #pragma align(packed).
18273 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18274 return;
18275 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18276 if (!RD)
18277 return;
18278 // Only warn if there is at least 1 bitfield member.
18279 if (llvm::any_of(RD->fields(),
18280 [](const FieldDecl *FD) { return FD->isBitField(); }))
18281 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18282 }
18283}
18284
18287 TagDecl *Tag = cast<TagDecl>(TagD);
18288 Tag->setInvalidDecl();
18289
18290 // Make sure we "complete" the definition even it is invalid.
18291 if (Tag->isBeingDefined()) {
18292 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18293 RD->completeDefinition();
18294 }
18295
18296 // We're undoing ActOnTagStartDefinition here, not
18297 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18298 // the FieldCollector.
18299
18301}
18302
18303// Note that FieldName may be null for anonymous bitfields.
18305 const IdentifierInfo *FieldName,
18306 QualType FieldTy, bool IsMsStruct,
18307 Expr *BitWidth) {
18308 assert(BitWidth);
18309 if (BitWidth->containsErrors())
18310 return ExprError();
18311
18312 // C99 6.7.2.1p4 - verify the field type.
18313 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18314 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18315 // Handle incomplete and sizeless types with a specific error.
18316 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18317 diag::err_field_incomplete_or_sizeless))
18318 return ExprError();
18319 if (FieldName)
18320 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18321 << FieldName << FieldTy << BitWidth->getSourceRange();
18322 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18323 << FieldTy << BitWidth->getSourceRange();
18324 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18326 return ExprError();
18327
18328 // If the bit-width is type- or value-dependent, don't try to check
18329 // it now.
18330 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18331 return BitWidth;
18332
18333 llvm::APSInt Value;
18335 if (ICE.isInvalid())
18336 return ICE;
18337 BitWidth = ICE.get();
18338
18339 // Zero-width bitfield is ok for anonymous field.
18340 if (Value == 0 && FieldName)
18341 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18342 << FieldName << BitWidth->getSourceRange();
18343
18344 if (Value.isSigned() && Value.isNegative()) {
18345 if (FieldName)
18346 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18347 << FieldName << toString(Value, 10);
18348 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18349 << toString(Value, 10);
18350 }
18351
18352 // The size of the bit-field must not exceed our maximum permitted object
18353 // size.
18354 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18355 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18356 << !FieldName << FieldName << toString(Value, 10);
18357 }
18358
18359 if (!FieldTy->isDependentType()) {
18360 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18361 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18362 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18363
18364 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18365 // ABI.
18366 bool CStdConstraintViolation =
18367 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18368 bool MSBitfieldViolation =
18369 Value.ugt(TypeStorageSize) &&
18370 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18371 if (CStdConstraintViolation || MSBitfieldViolation) {
18372 unsigned DiagWidth =
18373 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18374 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18375 << (bool)FieldName << FieldName << toString(Value, 10)
18376 << !CStdConstraintViolation << DiagWidth;
18377 }
18378
18379 // Warn on types where the user might conceivably expect to get all
18380 // specified bits as value bits: that's all integral types other than
18381 // 'bool'.
18382 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18383 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18384 << FieldName << toString(Value, 10)
18385 << (unsigned)TypeWidth;
18386 }
18387 }
18388
18389 if (isa<ConstantExpr>(BitWidth))
18390 return BitWidth;
18391 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
18392}
18393
18395 Declarator &D, Expr *BitfieldWidth) {
18396 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18397 D, BitfieldWidth,
18398 /*InitStyle=*/ICIS_NoInit, AS_public);
18399 return Res;
18400}
18401
18403 SourceLocation DeclStart,
18404 Declarator &D, Expr *BitWidth,
18405 InClassInitStyle InitStyle,
18406 AccessSpecifier AS) {
18407 if (D.isDecompositionDeclarator()) {
18408 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18409 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18410 << Decomp.getSourceRange();
18411 return nullptr;
18412 }
18413
18414 const IdentifierInfo *II = D.getIdentifier();
18415 SourceLocation Loc = DeclStart;
18416 if (II) Loc = D.getIdentifierLoc();
18417
18419 QualType T = TInfo->getType();
18420 if (getLangOpts().CPlusPlus) {
18422
18423 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18425 D.setInvalidType();
18426 T = Context.IntTy;
18428 }
18429 }
18430
18431 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18432
18433 if (D.getDeclSpec().isInlineSpecified())
18434 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18435 << getLangOpts().CPlusPlus17;
18436 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18437 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18438 diag::err_invalid_thread)
18440
18441 // Check to see if this name was declared as a member previously
18442 NamedDecl *PrevDecl = nullptr;
18444 RedeclarationKind::ForVisibleRedeclaration);
18445 LookupName(Previous, S);
18446 switch (Previous.getResultKind()) {
18449 PrevDecl = Previous.getAsSingle<NamedDecl>();
18450 break;
18451
18453 PrevDecl = Previous.getRepresentativeDecl();
18454 break;
18455
18459 break;
18460 }
18461 Previous.suppressDiagnostics();
18462
18463 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18464 // Maybe we will complain about the shadowed template parameter.
18465 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18466 // Just pretend that we didn't see the previous declaration.
18467 PrevDecl = nullptr;
18468 }
18469
18470 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18471 PrevDecl = nullptr;
18472
18473 bool Mutable
18474 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18475 SourceLocation TSSL = D.getBeginLoc();
18476 FieldDecl *NewFD
18477 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18478 TSSL, AS, PrevDecl, &D);
18479
18480 if (NewFD->isInvalidDecl())
18481 Record->setInvalidDecl();
18482
18483 if (D.getDeclSpec().isModulePrivateSpecified())
18484 NewFD->setModulePrivate();
18485
18486 if (NewFD->isInvalidDecl() && PrevDecl) {
18487 // Don't introduce NewFD into scope; there's already something
18488 // with the same name in the same scope.
18489 } else if (II) {
18490 PushOnScopeChains(NewFD, S);
18491 } else
18492 Record->addDecl(NewFD);
18493
18494 return NewFD;
18495}
18496
18498 TypeSourceInfo *TInfo,
18500 bool Mutable, Expr *BitWidth,
18501 InClassInitStyle InitStyle,
18502 SourceLocation TSSL,
18503 AccessSpecifier AS, NamedDecl *PrevDecl,
18504 Declarator *D) {
18505 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18506 bool InvalidDecl = false;
18507 if (D) InvalidDecl = D->isInvalidType();
18508
18509 // If we receive a broken type, recover by assuming 'int' and
18510 // marking this declaration as invalid.
18511 if (T.isNull() || T->containsErrors()) {
18512 InvalidDecl = true;
18513 T = Context.IntTy;
18514 }
18515
18517 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18518 bool isIncomplete =
18519 LangOpts.HLSL // HLSL allows sizeless builtin types
18520 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
18522 diag::err_field_incomplete_or_sizeless);
18523 if (isIncomplete) {
18524 // Fields of incomplete type force their record to be invalid.
18525 Record->setInvalidDecl();
18526 InvalidDecl = true;
18527 } else {
18528 NamedDecl *Def;
18529 EltTy->isIncompleteType(&Def);
18530 if (Def && Def->isInvalidDecl()) {
18531 Record->setInvalidDecl();
18532 InvalidDecl = true;
18533 }
18534 }
18535 }
18536
18537 // TR 18037 does not allow fields to be declared with address space
18538 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18540 Diag(Loc, diag::err_field_with_address_space);
18541 Record->setInvalidDecl();
18542 InvalidDecl = true;
18543 }
18544
18545 if (LangOpts.OpenCL) {
18546 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18547 // used as structure or union field: image, sampler, event or block types.
18548 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18549 T->isBlockPointerType()) {
18550 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18551 Record->setInvalidDecl();
18552 InvalidDecl = true;
18553 }
18554 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18555 // is enabled.
18556 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18557 "__cl_clang_bitfields", LangOpts)) {
18558 Diag(Loc, diag::err_opencl_bitfields);
18559 InvalidDecl = true;
18560 }
18561 }
18562
18563 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18564 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18565 T.hasQualifiers()) {
18566 InvalidDecl = true;
18567 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18568 }
18569
18570 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18571 // than a variably modified type.
18572 if (!InvalidDecl && T->isVariablyModifiedType()) {
18574 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18575 InvalidDecl = true;
18576 }
18577
18578 // Fields can not have abstract class types
18579 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18580 diag::err_abstract_type_in_decl,
18582 InvalidDecl = true;
18583
18584 if (InvalidDecl)
18585 BitWidth = nullptr;
18586 // If this is declared as a bit-field, check the bit-field.
18587 if (BitWidth) {
18588 BitWidth =
18589 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18590 if (!BitWidth) {
18591 InvalidDecl = true;
18592 BitWidth = nullptr;
18593 }
18594 }
18595
18596 // Check that 'mutable' is consistent with the type of the declaration.
18597 if (!InvalidDecl && Mutable) {
18598 unsigned DiagID = 0;
18599 if (T->isReferenceType())
18600 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18601 : diag::err_mutable_reference;
18602 else if (T.isConstQualified())
18603 DiagID = diag::err_mutable_const;
18604
18605 if (DiagID) {
18606 SourceLocation ErrLoc = Loc;
18607 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18608 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18609 Diag(ErrLoc, DiagID);
18610 if (DiagID != diag::ext_mutable_reference) {
18611 Mutable = false;
18612 InvalidDecl = true;
18613 }
18614 }
18615 }
18616
18617 // C++11 [class.union]p8 (DR1460):
18618 // At most one variant member of a union may have a
18619 // brace-or-equal-initializer.
18620 if (InitStyle != ICIS_NoInit)
18621 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18622
18623 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18624 BitWidth, Mutable, InitStyle);
18625 if (InvalidDecl)
18626 NewFD->setInvalidDecl();
18627
18628 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18629 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18630 Diag(Loc, diag::err_duplicate_member) << II;
18631 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18632 NewFD->setInvalidDecl();
18633 }
18634
18635 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18636 if (Record->isUnion()) {
18637 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18638 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18639 if (RDecl->getDefinition()) {
18640 // C++ [class.union]p1: An object of a class with a non-trivial
18641 // constructor, a non-trivial copy constructor, a non-trivial
18642 // destructor, or a non-trivial copy assignment operator
18643 // cannot be a member of a union, nor can an array of such
18644 // objects.
18645 if (CheckNontrivialField(NewFD))
18646 NewFD->setInvalidDecl();
18647 }
18648 }
18649
18650 // C++ [class.union]p1: If a union contains a member of reference type,
18651 // the program is ill-formed, except when compiling with MSVC extensions
18652 // enabled.
18653 if (EltTy->isReferenceType()) {
18654 const bool HaveMSExt =
18655 getLangOpts().MicrosoftExt &&
18657
18658 Diag(NewFD->getLocation(),
18659 HaveMSExt ? diag::ext_union_member_of_reference_type
18660 : diag::err_union_member_of_reference_type)
18661 << NewFD->getDeclName() << EltTy;
18662 if (!HaveMSExt)
18663 NewFD->setInvalidDecl();
18664 }
18665 }
18666 }
18667
18668 // FIXME: We need to pass in the attributes given an AST
18669 // representation, not a parser representation.
18670 if (D) {
18671 // FIXME: The current scope is almost... but not entirely... correct here.
18673
18674 if (NewFD->hasAttrs())
18676 }
18677
18678 // In auto-retain/release, infer strong retension for fields of
18679 // retainable type.
18680 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
18681 NewFD->setInvalidDecl();
18682
18683 if (T.isObjCGCWeak())
18684 Diag(Loc, diag::warn_attribute_weak_on_field);
18685
18686 // PPC MMA non-pointer types are not allowed as field types.
18687 if (Context.getTargetInfo().getTriple().isPPC64() &&
18688 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
18689 NewFD->setInvalidDecl();
18690
18691 NewFD->setAccess(AS);
18692 return NewFD;
18693}
18694
18696 assert(FD);
18697 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18698
18699 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18700 return false;
18701
18703 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18704 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18705 if (RDecl->getDefinition()) {
18706 // We check for copy constructors before constructors
18707 // because otherwise we'll never get complaints about
18708 // copy constructors.
18709
18711 // We're required to check for any non-trivial constructors. Since the
18712 // implicit default constructor is suppressed if there are any
18713 // user-declared constructors, we just need to check that there is a
18714 // trivial default constructor and a trivial copy constructor. (We don't
18715 // worry about move constructors here, since this is a C++98 check.)
18716 if (RDecl->hasNonTrivialCopyConstructor())
18718 else if (!RDecl->hasTrivialDefaultConstructor())
18720 else if (RDecl->hasNonTrivialCopyAssignment())
18722 else if (RDecl->hasNonTrivialDestructor())
18724
18725 if (member != CXXSpecialMemberKind::Invalid) {
18726 if (!getLangOpts().CPlusPlus11 &&
18727 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18728 // Objective-C++ ARC: it is an error to have a non-trivial field of
18729 // a union. However, system headers in Objective-C programs
18730 // occasionally have Objective-C lifetime objects within unions,
18731 // and rather than cause the program to fail, we make those
18732 // members unavailable.
18734 if (getSourceManager().isInSystemHeader(Loc)) {
18735 if (!FD->hasAttr<UnavailableAttr>())
18736 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18737 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18738 return false;
18739 }
18740 }
18741
18742 Diag(
18743 FD->getLocation(),
18745 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
18746 : diag::err_illegal_union_or_anon_struct_member)
18747 << FD->getParent()->isUnion() << FD->getDeclName()
18748 << llvm::to_underlying(member);
18749 DiagnoseNontrivial(RDecl, member);
18750 return !getLangOpts().CPlusPlus11;
18751 }
18752 }
18753 }
18754
18755 return false;
18756}
18757
18759 SmallVectorImpl<Decl *> &AllIvarDecls) {
18760 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18761 return;
18762
18763 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18764 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18765
18766 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
18767 return;
18768 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18769 if (!ID) {
18770 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18771 if (!CD->IsClassExtension())
18772 return;
18773 }
18774 // No need to add this to end of @implementation.
18775 else
18776 return;
18777 }
18778 // All conditions are met. Add a new bitfield to the tail end of ivars.
18779 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18780 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18781 Expr *BitWidth =
18782 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
18783
18784 Ivar = ObjCIvarDecl::Create(
18785 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
18787 ObjCIvarDecl::Private, BitWidth, true);
18788 AllIvarDecls.push_back(Ivar);
18789}
18790
18791/// [class.dtor]p4:
18792/// At the end of the definition of a class, overload resolution is
18793/// performed among the prospective destructors declared in that class with
18794/// an empty argument list to select the destructor for the class, also
18795/// known as the selected destructor.
18796///
18797/// We do the overload resolution here, then mark the selected constructor in the AST.
18798/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18800 if (!Record->hasUserDeclaredDestructor()) {
18801 return;
18802 }
18803
18804 SourceLocation Loc = Record->getLocation();
18806
18807 for (auto *Decl : Record->decls()) {
18808 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18809 if (DD->isInvalidDecl())
18810 continue;
18811 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18812 OCS);
18813 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18814 }
18815 }
18816
18817 if (OCS.empty()) {
18818 return;
18819 }
18821 unsigned Msg = 0;
18822 OverloadCandidateDisplayKind DisplayKind;
18823
18824 switch (OCS.BestViableFunction(S, Loc, Best)) {
18825 case OR_Success:
18826 case OR_Deleted:
18827 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18828 break;
18829
18830 case OR_Ambiguous:
18831 Msg = diag::err_ambiguous_destructor;
18832 DisplayKind = OCD_AmbiguousCandidates;
18833 break;
18834
18836 Msg = diag::err_no_viable_destructor;
18837 DisplayKind = OCD_AllCandidates;
18838 break;
18839 }
18840
18841 if (Msg) {
18842 // OpenCL have got their own thing going with destructors. It's slightly broken,
18843 // but we allow it.
18844 if (!S.LangOpts.OpenCL) {
18845 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18846 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18847 Record->setInvalidDecl();
18848 }
18849 // It's a bit hacky: At this point we've raised an error but we want the
18850 // rest of the compiler to continue somehow working. However almost
18851 // everything we'll try to do with the class will depend on there being a
18852 // destructor. So let's pretend the first one is selected and hope for the
18853 // best.
18854 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18855 }
18856}
18857
18858/// [class.mem.special]p5
18859/// Two special member functions are of the same kind if:
18860/// - they are both default constructors,
18861/// - they are both copy or move constructors with the same first parameter
18862/// type, or
18863/// - they are both copy or move assignment operators with the same first
18864/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18866 CXXMethodDecl *M1,
18867 CXXMethodDecl *M2,
18869 // We don't want to compare templates to non-templates: See
18870 // https://github.com/llvm/llvm-project/issues/59206
18872 return bool(M1->getDescribedFunctionTemplate()) ==
18874 // FIXME: better resolve CWG
18875 // https://cplusplus.github.io/CWG/issues/2787.html
18876 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18877 M2->getNonObjectParameter(0)->getType()))
18878 return false;
18881 return false;
18882
18883 return true;
18884}
18885
18886/// [class.mem.special]p6:
18887/// An eligible special member function is a special member function for which:
18888/// - the function is not deleted,
18889/// - the associated constraints, if any, are satisfied, and
18890/// - no special member function of the same kind whose associated constraints
18891/// [CWG2595], if any, are satisfied is more constrained.
18895 SmallVector<bool, 4> SatisfactionStatus;
18896
18897 for (CXXMethodDecl *Method : Methods) {
18898 const Expr *Constraints = Method->getTrailingRequiresClause();
18899 if (!Constraints)
18900 SatisfactionStatus.push_back(true);
18901 else {
18902 ConstraintSatisfaction Satisfaction;
18903 if (S.CheckFunctionConstraints(Method, Satisfaction))
18904 SatisfactionStatus.push_back(false);
18905 else
18906 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18907 }
18908 }
18909
18910 for (size_t i = 0; i < Methods.size(); i++) {
18911 if (!SatisfactionStatus[i])
18912 continue;
18913 CXXMethodDecl *Method = Methods[i];
18914 CXXMethodDecl *OrigMethod = Method;
18915 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18916 OrigMethod = cast<CXXMethodDecl>(MF);
18917
18918 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18919 bool AnotherMethodIsMoreConstrained = false;
18920 for (size_t j = 0; j < Methods.size(); j++) {
18921 if (i == j || !SatisfactionStatus[j])
18922 continue;
18923 CXXMethodDecl *OtherMethod = Methods[j];
18924 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18925 OtherMethod = cast<CXXMethodDecl>(MF);
18926
18927 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18928 CSM))
18929 continue;
18930
18931 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18932 if (!OtherConstraints)
18933 continue;
18934 if (!Constraints) {
18935 AnotherMethodIsMoreConstrained = true;
18936 break;
18937 }
18938 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18939 {Constraints},
18940 AnotherMethodIsMoreConstrained)) {
18941 // There was an error with the constraints comparison. Exit the loop
18942 // and don't consider this function eligible.
18943 AnotherMethodIsMoreConstrained = true;
18944 }
18945 if (AnotherMethodIsMoreConstrained)
18946 break;
18947 }
18948 // FIXME: Do not consider deleted methods as eligible after implementing
18949 // DR1734 and DR1496.
18950 if (!AnotherMethodIsMoreConstrained) {
18951 Method->setIneligibleOrNotSelected(false);
18952 Record->addedEligibleSpecialMemberFunction(Method,
18953 1 << llvm::to_underlying(CSM));
18954 }
18955 }
18956}
18957
18960 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18961 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18962 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18963 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18964 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18965
18966 for (auto *Decl : Record->decls()) {
18967 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18968 if (!MD) {
18969 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18970 if (FTD)
18971 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18972 }
18973 if (!MD)
18974 continue;
18975 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18976 if (CD->isInvalidDecl())
18977 continue;
18978 if (CD->isDefaultConstructor())
18979 DefaultConstructors.push_back(MD);
18980 else if (CD->isCopyConstructor())
18981 CopyConstructors.push_back(MD);
18982 else if (CD->isMoveConstructor())
18983 MoveConstructors.push_back(MD);
18984 } else if (MD->isCopyAssignmentOperator()) {
18985 CopyAssignmentOperators.push_back(MD);
18986 } else if (MD->isMoveAssignmentOperator()) {
18987 MoveAssignmentOperators.push_back(MD);
18988 }
18989 }
18990
18991 SetEligibleMethods(S, Record, DefaultConstructors,
18993 SetEligibleMethods(S, Record, CopyConstructors,
18995 SetEligibleMethods(S, Record, MoveConstructors,
18997 SetEligibleMethods(S, Record, CopyAssignmentOperators,
18999 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19001}
19002
19003void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19004 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19005 SourceLocation RBrac,
19006 const ParsedAttributesView &Attrs) {
19007 assert(EnclosingDecl && "missing record or interface decl");
19008
19009 // If this is an Objective-C @implementation or category and we have
19010 // new fields here we should reset the layout of the interface since
19011 // it will now change.
19012 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19013 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19014 switch (DC->getKind()) {
19015 default: break;
19016 case Decl::ObjCCategory:
19017 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19018 break;
19019 case Decl::ObjCImplementation:
19020 Context.
19021 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19022 break;
19023 }
19024 }
19025
19026 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19027 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19028
19029 // Start counting up the number of named members; make sure to include
19030 // members of anonymous structs and unions in the total.
19031 unsigned NumNamedMembers = 0;
19032 if (Record) {
19033 for (const auto *I : Record->decls()) {
19034 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19035 if (IFD->getDeclName())
19036 ++NumNamedMembers;
19037 }
19038 }
19039
19040 // Verify that all the fields are okay.
19042
19043 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19044 i != end; ++i) {
19045 FieldDecl *FD = cast<FieldDecl>(*i);
19046
19047 // Get the type for the field.
19048 const Type *FDTy = FD->getType().getTypePtr();
19049
19050 if (!FD->isAnonymousStructOrUnion()) {
19051 // Remember all fields written by the user.
19052 RecFields.push_back(FD);
19053 }
19054
19055 // If the field is already invalid for some reason, don't emit more
19056 // diagnostics about it.
19057 if (FD->isInvalidDecl()) {
19058 EnclosingDecl->setInvalidDecl();
19059 continue;
19060 }
19061
19062 // C99 6.7.2.1p2:
19063 // A structure or union shall not contain a member with
19064 // incomplete or function type (hence, a structure shall not
19065 // contain an instance of itself, but may contain a pointer to
19066 // an instance of itself), except that the last member of a
19067 // structure with more than one named member may have incomplete
19068 // array type; such a structure (and any union containing,
19069 // possibly recursively, a member that is such a structure)
19070 // shall not be a member of a structure or an element of an
19071 // array.
19072 bool IsLastField = (i + 1 == Fields.end());
19073 if (FDTy->isFunctionType()) {
19074 // Field declared as a function.
19075 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19076 << FD->getDeclName();
19077 FD->setInvalidDecl();
19078 EnclosingDecl->setInvalidDecl();
19079 continue;
19080 } else if (FDTy->isIncompleteArrayType() &&
19081 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19082 if (Record) {
19083 // Flexible array member.
19084 // Microsoft and g++ is more permissive regarding flexible array.
19085 // It will accept flexible array in union and also
19086 // as the sole element of a struct/class.
19087 unsigned DiagID = 0;
19088 if (!Record->isUnion() && !IsLastField) {
19089 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19090 << FD->getDeclName() << FD->getType()
19091 << llvm::to_underlying(Record->getTagKind());
19092 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19093 FD->setInvalidDecl();
19094 EnclosingDecl->setInvalidDecl();
19095 continue;
19096 } else if (Record->isUnion())
19097 DiagID = getLangOpts().MicrosoftExt
19098 ? diag::ext_flexible_array_union_ms
19099 : diag::ext_flexible_array_union_gnu;
19100 else if (NumNamedMembers < 1)
19101 DiagID = getLangOpts().MicrosoftExt
19102 ? diag::ext_flexible_array_empty_aggregate_ms
19103 : diag::ext_flexible_array_empty_aggregate_gnu;
19104
19105 if (DiagID)
19106 Diag(FD->getLocation(), DiagID)
19107 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19108 // While the layout of types that contain virtual bases is not specified
19109 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19110 // virtual bases after the derived members. This would make a flexible
19111 // array member declared at the end of an object not adjacent to the end
19112 // of the type.
19113 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19114 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19115 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19116 if (!getLangOpts().C99)
19117 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19118 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19119
19120 // If the element type has a non-trivial destructor, we would not
19121 // implicitly destroy the elements, so disallow it for now.
19122 //
19123 // FIXME: GCC allows this. We should probably either implicitly delete
19124 // the destructor of the containing class, or just allow this.
19125 QualType BaseElem = Context.getBaseElementType(FD->getType());
19126 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19127 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19128 << FD->getDeclName() << FD->getType();
19129 FD->setInvalidDecl();
19130 EnclosingDecl->setInvalidDecl();
19131 continue;
19132 }
19133 // Okay, we have a legal flexible array member at the end of the struct.
19134 Record->setHasFlexibleArrayMember(true);
19135 } else {
19136 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19137 // unless they are followed by another ivar. That check is done
19138 // elsewhere, after synthesized ivars are known.
19139 }
19140 } else if (!FDTy->isDependentType() &&
19141 (LangOpts.HLSL // HLSL allows sizeless builtin types
19143 diag::err_incomplete_type)
19145 FD->getLocation(), FD->getType(),
19146 diag::err_field_incomplete_or_sizeless))) {
19147 // Incomplete type
19148 FD->setInvalidDecl();
19149 EnclosingDecl->setInvalidDecl();
19150 continue;
19151 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19152 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19153 // A type which contains a flexible array member is considered to be a
19154 // flexible array member.
19155 Record->setHasFlexibleArrayMember(true);
19156 if (!Record->isUnion()) {
19157 // If this is a struct/class and this is not the last element, reject
19158 // it. Note that GCC supports variable sized arrays in the middle of
19159 // structures.
19160 if (!IsLastField)
19161 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19162 << FD->getDeclName() << FD->getType();
19163 else {
19164 // We support flexible arrays at the end of structs in
19165 // other structs as an extension.
19166 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19167 << FD->getDeclName();
19168 }
19169 }
19170 }
19171 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19173 diag::err_abstract_type_in_decl,
19175 // Ivars can not have abstract class types
19176 FD->setInvalidDecl();
19177 }
19178 if (Record && FDTTy->getDecl()->hasObjectMember())
19179 Record->setHasObjectMember(true);
19180 if (Record && FDTTy->getDecl()->hasVolatileMember())
19181 Record->setHasVolatileMember(true);
19182 } else if (FDTy->isObjCObjectType()) {
19183 /// A field cannot be an Objective-c object
19184 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19187 FD->setType(T);
19188 } else if (Record && Record->isUnion() &&
19190 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19191 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19194 // For backward compatibility, fields of C unions declared in system
19195 // headers that have non-trivial ObjC ownership qualifications are marked
19196 // as unavailable unless the qualifier is explicit and __strong. This can
19197 // break ABI compatibility between programs compiled with ARC and MRR, but
19198 // is a better option than rejecting programs using those unions under
19199 // ARC.
19200 FD->addAttr(UnavailableAttr::CreateImplicit(
19201 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19202 FD->getLocation()));
19203 } else if (getLangOpts().ObjC &&
19204 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19205 !Record->hasObjectMember()) {
19206 if (FD->getType()->isObjCObjectPointerType() ||
19207 FD->getType().isObjCGCStrong())
19208 Record->setHasObjectMember(true);
19209 else if (Context.getAsArrayType(FD->getType())) {
19210 QualType BaseType = Context.getBaseElementType(FD->getType());
19211 if (BaseType->isRecordType() &&
19212 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19213 Record->setHasObjectMember(true);
19214 else if (BaseType->isObjCObjectPointerType() ||
19215 BaseType.isObjCGCStrong())
19216 Record->setHasObjectMember(true);
19217 }
19218 }
19219
19220 if (Record && !getLangOpts().CPlusPlus &&
19221 !shouldIgnoreForRecordTriviality(FD)) {
19222 QualType FT = FD->getType();
19224 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19226 Record->isUnion())
19227 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19228 }
19231 Record->setNonTrivialToPrimitiveCopy(true);
19232 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19233 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19234 }
19235 if (FD->hasAttr<ExplicitInitAttr>())
19236 Record->setHasUninitializedExplicitInitFields(true);
19237 if (FT.isDestructedType()) {
19238 Record->setNonTrivialToPrimitiveDestroy(true);
19239 Record->setParamDestroyedInCallee(true);
19240 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19241 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19242 }
19243
19244 if (const auto *RT = FT->getAs<RecordType>()) {
19245 if (RT->getDecl()->getArgPassingRestrictions() ==
19247 Record->setArgPassingRestrictions(
19250 Record->setArgPassingRestrictions(
19252 }
19253
19254 if (Record && FD->getType().isVolatileQualified())
19255 Record->setHasVolatileMember(true);
19256 // Keep track of the number of named members.
19257 if (FD->getIdentifier())
19258 ++NumNamedMembers;
19259 }
19260
19261 // Okay, we successfully defined 'Record'.
19262 if (Record) {
19263 bool Completed = false;
19264 if (S) {
19265 Scope *Parent = S->getParent();
19266 if (Parent && Parent->isTypeAliasScope() &&
19267 Parent->isTemplateParamScope())
19268 Record->setInvalidDecl();
19269 }
19270
19271 if (CXXRecord) {
19272 if (!CXXRecord->isInvalidDecl()) {
19273 // Set access bits correctly on the directly-declared conversions.
19275 I = CXXRecord->conversion_begin(),
19276 E = CXXRecord->conversion_end(); I != E; ++I)
19277 I.setAccess((*I)->getAccess());
19278 }
19279
19280 // Add any implicitly-declared members to this class.
19282
19283 if (!CXXRecord->isDependentType()) {
19284 if (!CXXRecord->isInvalidDecl()) {
19285 // If we have virtual base classes, we may end up finding multiple
19286 // final overriders for a given virtual function. Check for this
19287 // problem now.
19288 if (CXXRecord->getNumVBases()) {
19289 CXXFinalOverriderMap FinalOverriders;
19290 CXXRecord->getFinalOverriders(FinalOverriders);
19291
19292 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19293 MEnd = FinalOverriders.end();
19294 M != MEnd; ++M) {
19295 for (OverridingMethods::iterator SO = M->second.begin(),
19296 SOEnd = M->second.end();
19297 SO != SOEnd; ++SO) {
19298 assert(SO->second.size() > 0 &&
19299 "Virtual function without overriding functions?");
19300 if (SO->second.size() == 1)
19301 continue;
19302
19303 // C++ [class.virtual]p2:
19304 // In a derived class, if a virtual member function of a base
19305 // class subobject has more than one final overrider the
19306 // program is ill-formed.
19307 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19308 << (const NamedDecl *)M->first << Record;
19309 Diag(M->first->getLocation(),
19310 diag::note_overridden_virtual_function);
19312 OM = SO->second.begin(),
19313 OMEnd = SO->second.end();
19314 OM != OMEnd; ++OM)
19315 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19316 << (const NamedDecl *)M->first << OM->Method->getParent();
19317
19318 Record->setInvalidDecl();
19319 }
19320 }
19321 CXXRecord->completeDefinition(&FinalOverriders);
19322 Completed = true;
19323 }
19324 }
19325 ComputeSelectedDestructor(*this, CXXRecord);
19327 }
19328 }
19329
19330 if (!Completed)
19331 Record->completeDefinition();
19332
19333 // Handle attributes before checking the layout.
19335
19336 // Check to see if a FieldDecl is a pointer to a function.
19337 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19338 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19339 if (!FD) {
19340 // Check whether this is a forward declaration that was inserted by
19341 // Clang. This happens when a non-forward declared / defined type is
19342 // used, e.g.:
19343 //
19344 // struct foo {
19345 // struct bar *(*f)();
19346 // struct bar *(*g)();
19347 // };
19348 //
19349 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19350 // incomplete definition.
19351 if (const auto *TD = dyn_cast<TagDecl>(D))
19352 return !TD->isCompleteDefinition();
19353 return false;
19354 }
19355 QualType FieldType = FD->getType().getDesugaredType(Context);
19356 if (isa<PointerType>(FieldType)) {
19357 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19358 return PointeeType.getDesugaredType(Context)->isFunctionType();
19359 }
19360 return false;
19361 };
19362
19363 // Maybe randomize the record's decls. We automatically randomize a record
19364 // of function pointers, unless it has the "no_randomize_layout" attribute.
19365 if (!getLangOpts().CPlusPlus &&
19366 (Record->hasAttr<RandomizeLayoutAttr>() ||
19367 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19368 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19369 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19370 !Record->isRandomized()) {
19371 SmallVector<Decl *, 32> NewDeclOrdering;
19373 NewDeclOrdering))
19374 Record->reorderDecls(NewDeclOrdering);
19375 }
19376
19377 // We may have deferred checking for a deleted destructor. Check now.
19378 if (CXXRecord) {
19379 auto *Dtor = CXXRecord->getDestructor();
19380 if (Dtor && Dtor->isImplicit() &&
19382 CXXRecord->setImplicitDestructorIsDeleted();
19383 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19384 }
19385 }
19386
19387 if (Record->hasAttrs()) {
19389
19390 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19391 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19392 IA->getRange(), IA->getBestCase(),
19393 IA->getInheritanceModel());
19394 }
19395
19396 // Check if the structure/union declaration is a type that can have zero
19397 // size in C. For C this is a language extension, for C++ it may cause
19398 // compatibility problems.
19399 bool CheckForZeroSize;
19400 if (!getLangOpts().CPlusPlus) {
19401 CheckForZeroSize = true;
19402 } else {
19403 // For C++ filter out types that cannot be referenced in C code.
19404 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19405 CheckForZeroSize =
19406 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19407 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19408 CXXRecord->isCLike();
19409 }
19410 if (CheckForZeroSize) {
19411 bool ZeroSize = true;
19412 bool IsEmpty = true;
19413 unsigned NonBitFields = 0;
19414 for (RecordDecl::field_iterator I = Record->field_begin(),
19415 E = Record->field_end();
19416 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19417 IsEmpty = false;
19418 if (I->isUnnamedBitField()) {
19419 if (!I->isZeroLengthBitField())
19420 ZeroSize = false;
19421 } else {
19422 ++NonBitFields;
19423 QualType FieldType = I->getType();
19424 if (FieldType->isIncompleteType() ||
19425 !Context.getTypeSizeInChars(FieldType).isZero())
19426 ZeroSize = false;
19427 }
19428 }
19429
19430 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19431 // allowed in C++, but warn if its declaration is inside
19432 // extern "C" block.
19433 if (ZeroSize) {
19434 Diag(RecLoc, getLangOpts().CPlusPlus ?
19435 diag::warn_zero_size_struct_union_in_extern_c :
19436 diag::warn_zero_size_struct_union_compat)
19437 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19438 }
19439
19440 // Structs without named members are extension in C (C99 6.7.2.1p7),
19441 // but are accepted by GCC. In C2y, this became implementation-defined
19442 // (C2y 6.7.3.2p10).
19443 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
19444 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
19445 : diag::ext_no_named_members_in_struct_union)
19446 << Record->isUnion();
19447 }
19448 }
19449 } else {
19450 ObjCIvarDecl **ClsFields =
19451 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19452 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19453 ID->setEndOfDefinitionLoc(RBrac);
19454 // Add ivar's to class's DeclContext.
19455 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19456 ClsFields[i]->setLexicalDeclContext(ID);
19457 ID->addDecl(ClsFields[i]);
19458 }
19459 // Must enforce the rule that ivars in the base classes may not be
19460 // duplicates.
19461 if (ID->getSuperClass())
19462 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19463 } else if (ObjCImplementationDecl *IMPDecl =
19464 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19465 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19466 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19467 // Ivar declared in @implementation never belongs to the implementation.
19468 // Only it is in implementation's lexical context.
19469 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19470 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
19471 RBrac);
19472 IMPDecl->setIvarLBraceLoc(LBrac);
19473 IMPDecl->setIvarRBraceLoc(RBrac);
19474 } else if (ObjCCategoryDecl *CDecl =
19475 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19476 // case of ivars in class extension; all other cases have been
19477 // reported as errors elsewhere.
19478 // FIXME. Class extension does not have a LocEnd field.
19479 // CDecl->setLocEnd(RBrac);
19480 // Add ivar's to class extension's DeclContext.
19481 // Diagnose redeclaration of private ivars.
19482 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19483 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19484 if (IDecl) {
19485 if (const ObjCIvarDecl *ClsIvar =
19486 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19487 Diag(ClsFields[i]->getLocation(),
19488 diag::err_duplicate_ivar_declaration);
19489 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19490 continue;
19491 }
19492 for (const auto *Ext : IDecl->known_extensions()) {
19493 if (const ObjCIvarDecl *ClsExtIvar
19494 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19495 Diag(ClsFields[i]->getLocation(),
19496 diag::err_duplicate_ivar_declaration);
19497 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19498 continue;
19499 }
19500 }
19501 }
19502 ClsFields[i]->setLexicalDeclContext(CDecl);
19503 CDecl->addDecl(ClsFields[i]);
19504 }
19505 CDecl->setIvarLBraceLoc(LBrac);
19506 CDecl->setIvarRBraceLoc(RBrac);
19507 }
19508 }
19510}
19511
19512/// Determine whether the given integral value is representable within
19513/// the given type T.
19515 llvm::APSInt &Value,
19516 QualType T) {
19517 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19518 "Integral type required!");
19519 unsigned BitWidth = Context.getIntWidth(T);
19520
19521 if (Value.isUnsigned() || Value.isNonNegative()) {
19523 --BitWidth;
19524 return Value.getActiveBits() <= BitWidth;
19525 }
19526 return Value.getSignificantBits() <= BitWidth;
19527}
19528
19529// Given an integral type, return the next larger integral type
19530// (or a NULL type of no such type exists).
19532 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19533 // enum checking below.
19534 assert((T->isIntegralType(Context) ||
19535 T->isEnumeralType()) && "Integral type required!");
19536 const unsigned NumTypes = 4;
19537 QualType SignedIntegralTypes[NumTypes] = {
19538 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19539 };
19540 QualType UnsignedIntegralTypes[NumTypes] = {
19541 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19542 Context.UnsignedLongLongTy
19543 };
19544
19545 unsigned BitWidth = Context.getTypeSize(T);
19546 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19547 : UnsignedIntegralTypes;
19548 for (unsigned I = 0; I != NumTypes; ++I)
19549 if (Context.getTypeSize(Types[I]) > BitWidth)
19550 return Types[I];
19551
19552 return QualType();
19553}
19554
19556 EnumConstantDecl *LastEnumConst,
19557 SourceLocation IdLoc,
19559 Expr *Val) {
19560 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19561 llvm::APSInt EnumVal(IntWidth);
19562 QualType EltTy;
19563
19565 Val = nullptr;
19566
19567 if (Val)
19568 Val = DefaultLvalueConversion(Val).get();
19569
19570 if (Val) {
19571 if (Enum->isDependentType() || Val->isTypeDependent() ||
19572 Val->containsErrors())
19573 EltTy = Context.DependentTy;
19574 else {
19575 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19576 // underlying type, but do allow it in all other contexts.
19577 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19578 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19579 // constant-expression in the enumerator-definition shall be a converted
19580 // constant expression of the underlying type.
19581 EltTy = Enum->getIntegerType();
19582 ExprResult Converted =
19583 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19585 if (Converted.isInvalid())
19586 Val = nullptr;
19587 else
19588 Val = Converted.get();
19589 } else if (!Val->isValueDependent() &&
19590 !(Val =
19592 .get())) {
19593 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19594 } else {
19595 if (Enum->isComplete()) {
19596 EltTy = Enum->getIntegerType();
19597
19598 // In Obj-C and Microsoft mode, require the enumeration value to be
19599 // representable in the underlying type of the enumeration. In C++11,
19600 // we perform a non-narrowing conversion as part of converted constant
19601 // expression checking.
19602 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19604 .getTriple()
19605 .isWindowsMSVCEnvironment()) {
19606 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19607 } else {
19608 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19609 }
19610 }
19611
19612 // Cast to the underlying type.
19613 Val = ImpCastExprToType(Val, EltTy,
19614 EltTy->isBooleanType() ? CK_IntegralToBoolean
19615 : CK_IntegralCast)
19616 .get();
19617 } else if (getLangOpts().CPlusPlus) {
19618 // C++11 [dcl.enum]p5:
19619 // If the underlying type is not fixed, the type of each enumerator
19620 // is the type of its initializing value:
19621 // - If an initializer is specified for an enumerator, the
19622 // initializing value has the same type as the expression.
19623 EltTy = Val->getType();
19624 } else {
19625 // C99 6.7.2.2p2:
19626 // The expression that defines the value of an enumeration constant
19627 // shall be an integer constant expression that has a value
19628 // representable as an int.
19629
19630 // Complain if the value is not representable in an int.
19632 Diag(IdLoc, getLangOpts().C23
19633 ? diag::warn_c17_compat_enum_value_not_int
19634 : diag::ext_c23_enum_value_not_int)
19635 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
19636 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19637 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19638 // Force the type of the expression to 'int'.
19639 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19640 }
19641 EltTy = Val->getType();
19642 }
19643 }
19644 }
19645 }
19646
19647 if (!Val) {
19648 if (Enum->isDependentType())
19649 EltTy = Context.DependentTy;
19650 else if (!LastEnumConst) {
19651 // C++0x [dcl.enum]p5:
19652 // If the underlying type is not fixed, the type of each enumerator
19653 // is the type of its initializing value:
19654 // - If no initializer is specified for the first enumerator, the
19655 // initializing value has an unspecified integral type.
19656 //
19657 // GCC uses 'int' for its unspecified integral type, as does
19658 // C99 6.7.2.2p3.
19659 if (Enum->isFixed()) {
19660 EltTy = Enum->getIntegerType();
19661 }
19662 else {
19663 EltTy = Context.IntTy;
19664 }
19665 } else {
19666 // Assign the last value + 1.
19667 EnumVal = LastEnumConst->getInitVal();
19668 ++EnumVal;
19669 EltTy = LastEnumConst->getType();
19670
19671 // Check for overflow on increment.
19672 if (EnumVal < LastEnumConst->getInitVal()) {
19673 // C++0x [dcl.enum]p5:
19674 // If the underlying type is not fixed, the type of each enumerator
19675 // is the type of its initializing value:
19676 //
19677 // - Otherwise the type of the initializing value is the same as
19678 // the type of the initializing value of the preceding enumerator
19679 // unless the incremented value is not representable in that type,
19680 // in which case the type is an unspecified integral type
19681 // sufficient to contain the incremented value. If no such type
19682 // exists, the program is ill-formed.
19684 if (T.isNull() || Enum->isFixed()) {
19685 // There is no integral type larger enough to represent this
19686 // value. Complain, then allow the value to wrap around.
19687 EnumVal = LastEnumConst->getInitVal();
19688 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19689 ++EnumVal;
19690 if (Enum->isFixed())
19691 // When the underlying type is fixed, this is ill-formed.
19692 Diag(IdLoc, diag::err_enumerator_wrapped)
19693 << toString(EnumVal, 10)
19694 << EltTy;
19695 else
19696 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19697 << toString(EnumVal, 10);
19698 } else {
19699 EltTy = T;
19700 }
19701
19702 // Retrieve the last enumerator's value, extent that type to the
19703 // type that is supposed to be large enough to represent the incremented
19704 // value, then increment.
19705 EnumVal = LastEnumConst->getInitVal();
19706 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19707 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19708 ++EnumVal;
19709
19710 // If we're not in C++, diagnose the overflow of enumerator values,
19711 // which in C99 means that the enumerator value is not representable in
19712 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
19713 // are representable in some larger integral type and we allow it in
19714 // older language modes as an extension.
19715 // Exclude fixed enumerators since they are diagnosed with an error for
19716 // this case.
19717 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
19718 Diag(IdLoc, getLangOpts().C23
19719 ? diag::warn_c17_compat_enum_value_not_int
19720 : diag::ext_c23_enum_value_not_int)
19721 << 1 << toString(EnumVal, 10) << 1;
19722 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
19723 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19724 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19725 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
19726 : diag::ext_c23_enum_value_not_int)
19727 << 1 << toString(EnumVal, 10) << 1;
19728 }
19729 }
19730 }
19731
19732 if (!EltTy->isDependentType()) {
19733 // Make the enumerator value match the signedness and size of the
19734 // enumerator's type.
19735 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19736 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19737 }
19738
19739 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19740 Val, EnumVal);
19741}
19742
19744 SourceLocation IILoc) {
19745 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19747 return SkipBodyInfo();
19748
19749 // We have an anonymous enum definition. Look up the first enumerator to
19750 // determine if we should merge the definition with an existing one and
19751 // skip the body.
19752 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19754 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19755 if (!PrevECD)
19756 return SkipBodyInfo();
19757
19758 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19759 NamedDecl *Hidden;
19760 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19762 Skip.Previous = Hidden;
19763 return Skip;
19764 }
19765
19766 return SkipBodyInfo();
19767}
19768
19769Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19771 const ParsedAttributesView &Attrs,
19772 SourceLocation EqualLoc, Expr *Val) {
19773 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19774 EnumConstantDecl *LastEnumConst =
19775 cast_or_null<EnumConstantDecl>(lastEnumConst);
19776
19777 // The scope passed in may not be a decl scope. Zip up the scope tree until
19778 // we find one that is.
19779 S = getNonFieldDeclScope(S);
19780
19781 // Verify that there isn't already something declared with this name in this
19782 // scope.
19783 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
19784 RedeclarationKind::ForVisibleRedeclaration);
19785 LookupName(R, S);
19786 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19787
19788 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19789 // Maybe we will complain about the shadowed template parameter.
19790 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19791 // Just pretend that we didn't see the previous declaration.
19792 PrevDecl = nullptr;
19793 }
19794
19795 // C++ [class.mem]p15:
19796 // If T is the name of a class, then each of the following shall have a name
19797 // different from T:
19798 // - every enumerator of every member of class T that is an unscoped
19799 // enumerated type
19800 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19802 DeclarationNameInfo(Id, IdLoc));
19803
19804 EnumConstantDecl *New =
19805 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19806 if (!New)
19807 return nullptr;
19808
19809 if (PrevDecl) {
19810 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19811 // Check for other kinds of shadowing not already handled.
19812 CheckShadow(New, PrevDecl, R);
19813 }
19814
19815 // When in C++, we may get a TagDecl with the same name; in this case the
19816 // enum constant will 'hide' the tag.
19817 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19818 "Received TagDecl when not in C++!");
19819 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19820 if (isa<EnumConstantDecl>(PrevDecl))
19821 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19822 else
19823 Diag(IdLoc, diag::err_redefinition) << Id;
19824 notePreviousDefinition(PrevDecl, IdLoc);
19825 return nullptr;
19826 }
19827 }
19828
19829 // Process attributes.
19830 ProcessDeclAttributeList(S, New, Attrs);
19831 AddPragmaAttributes(S, New);
19832 ProcessAPINotes(New);
19833
19834 // Register this decl in the current scope stack.
19835 New->setAccess(TheEnumDecl->getAccess());
19836 PushOnScopeChains(New, S);
19837
19839
19840 return New;
19841}
19842
19843// Returns true when the enum initial expression does not trigger the
19844// duplicate enum warning. A few common cases are exempted as follows:
19845// Element2 = Element1
19846// Element2 = Element1 + 1
19847// Element2 = Element1 - 1
19848// Where Element2 and Element1 are from the same enum.
19850 Expr *InitExpr = ECD->getInitExpr();
19851 if (!InitExpr)
19852 return true;
19853 InitExpr = InitExpr->IgnoreImpCasts();
19854
19855 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19856 if (!BO->isAdditiveOp())
19857 return true;
19858 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19859 if (!IL)
19860 return true;
19861 if (IL->getValue() != 1)
19862 return true;
19863
19864 InitExpr = BO->getLHS();
19865 }
19866
19867 // This checks if the elements are from the same enum.
19868 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19869 if (!DRE)
19870 return true;
19871
19872 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19873 if (!EnumConstant)
19874 return true;
19875
19876 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19877 Enum)
19878 return true;
19879
19880 return false;
19881}
19882
19883// Emits a warning when an element is implicitly set a value that
19884// a previous element has already been set to.
19887 // Avoid anonymous enums
19888 if (!Enum->getIdentifier())
19889 return;
19890
19891 // Only check for small enums.
19892 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19893 return;
19894
19895 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19896 return;
19897
19898 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19899 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19900
19901 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19902
19903 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19904 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19905
19906 // Use int64_t as a key to avoid needing special handling for map keys.
19907 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19908 llvm::APSInt Val = D->getInitVal();
19909 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19910 };
19911
19912 DuplicatesVector DupVector;
19913 ValueToVectorMap EnumMap;
19914
19915 // Populate the EnumMap with all values represented by enum constants without
19916 // an initializer.
19917 for (auto *Element : Elements) {
19918 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19919
19920 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19921 // this constant. Skip this enum since it may be ill-formed.
19922 if (!ECD) {
19923 return;
19924 }
19925
19926 // Constants with initializers are handled in the next loop.
19927 if (ECD->getInitExpr())
19928 continue;
19929
19930 // Duplicate values are handled in the next loop.
19931 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19932 }
19933
19934 if (EnumMap.size() == 0)
19935 return;
19936
19937 // Create vectors for any values that has duplicates.
19938 for (auto *Element : Elements) {
19939 // The last loop returned if any constant was null.
19940 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19941 if (!ValidDuplicateEnum(ECD, Enum))
19942 continue;
19943
19944 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19945 if (Iter == EnumMap.end())
19946 continue;
19947
19948 DeclOrVector& Entry = Iter->second;
19949 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19950 // Ensure constants are different.
19951 if (D == ECD)
19952 continue;
19953
19954 // Create new vector and push values onto it.
19955 auto Vec = std::make_unique<ECDVector>();
19956 Vec->push_back(D);
19957 Vec->push_back(ECD);
19958
19959 // Update entry to point to the duplicates vector.
19960 Entry = Vec.get();
19961
19962 // Store the vector somewhere we can consult later for quick emission of
19963 // diagnostics.
19964 DupVector.emplace_back(std::move(Vec));
19965 continue;
19966 }
19967
19968 ECDVector *Vec = cast<ECDVector *>(Entry);
19969 // Make sure constants are not added more than once.
19970 if (*Vec->begin() == ECD)
19971 continue;
19972
19973 Vec->push_back(ECD);
19974 }
19975
19976 // Emit diagnostics.
19977 for (const auto &Vec : DupVector) {
19978 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19979
19980 // Emit warning for one enum constant.
19981 auto *FirstECD = Vec->front();
19982 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19983 << FirstECD << toString(FirstECD->getInitVal(), 10)
19984 << FirstECD->getSourceRange();
19985
19986 // Emit one note for each of the remaining enum constants with
19987 // the same value.
19988 for (auto *ECD : llvm::drop_begin(*Vec))
19989 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19990 << ECD << toString(ECD->getInitVal(), 10)
19991 << ECD->getSourceRange();
19992 }
19993}
19994
19995bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19996 bool AllowMask) const {
19997 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19998 assert(ED->isCompleteDefinition() && "expected enum definition");
19999
20000 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
20001 llvm::APInt &FlagBits = R.first->second;
20002
20003 if (R.second) {
20004 for (auto *E : ED->enumerators()) {
20005 const auto &EVal = E->getInitVal();
20006 // Only single-bit enumerators introduce new flag values.
20007 if (EVal.isPowerOf2())
20008 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20009 }
20010 }
20011
20012 // A value is in a flag enum if either its bits are a subset of the enum's
20013 // flag bits (the first condition) or we are allowing masks and the same is
20014 // true of its complement (the second condition). When masks are allowed, we
20015 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20016 //
20017 // While it's true that any value could be used as a mask, the assumption is
20018 // that a mask will have all of the insignificant bits set. Anything else is
20019 // likely a logic error.
20020 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20021 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20022}
20023
20025 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20026 const ParsedAttributesView &Attrs) {
20027 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20029
20030 ProcessDeclAttributeList(S, Enum, Attrs);
20032
20033 if (Enum->isDependentType()) {
20034 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20035 EnumConstantDecl *ECD =
20036 cast_or_null<EnumConstantDecl>(Elements[i]);
20037 if (!ECD) continue;
20038
20039 ECD->setType(EnumType);
20040 }
20041
20042 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20043 return;
20044 }
20045
20046 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20047 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
20048 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
20049
20050 // Verify that all the values are okay, compute the size of the values, and
20051 // reverse the list.
20052 unsigned NumNegativeBits = 0;
20053 unsigned NumPositiveBits = 0;
20054 bool MembersRepresentableByInt = true;
20055
20056 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20057 EnumConstantDecl *ECD =
20058 cast_or_null<EnumConstantDecl>(Elements[i]);
20059 if (!ECD) continue; // Already issued a diagnostic.
20060
20061 llvm::APSInt InitVal = ECD->getInitVal();
20062
20063 // Keep track of the size of positive and negative values.
20064 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20065 // If the enumerator is zero that should still be counted as a positive
20066 // bit since we need a bit to store the value zero.
20067 unsigned ActiveBits = InitVal.getActiveBits();
20068 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
20069 } else {
20070 NumNegativeBits =
20071 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
20072 }
20073 MembersRepresentableByInt &=
20075 }
20076
20077 // If we have an empty set of enumerators we still need one bit.
20078 // From [dcl.enum]p8
20079 // If the enumerator-list is empty, the values of the enumeration are as if
20080 // the enumeration had a single enumerator with value 0
20081 if (!NumPositiveBits && !NumNegativeBits)
20082 NumPositiveBits = 1;
20083
20084 // Figure out the type that should be used for this enum.
20085 QualType BestType;
20086 unsigned BestWidth;
20087
20088 // C++0x N3000 [conv.prom]p3:
20089 // An rvalue of an unscoped enumeration type whose underlying
20090 // type is not fixed can be converted to an rvalue of the first
20091 // of the following types that can represent all the values of
20092 // the enumeration: int, unsigned int, long int, unsigned long
20093 // int, long long int, or unsigned long long int.
20094 // C99 6.4.4.3p2:
20095 // An identifier declared as an enumeration constant has type int.
20096 // The C99 rule is modified by C23.
20097 QualType BestPromotionType;
20098
20099 bool Packed = Enum->hasAttr<PackedAttr>();
20100 // -fshort-enums is the equivalent to specifying the packed attribute on all
20101 // enum definitions.
20102 if (LangOpts.ShortEnums)
20103 Packed = true;
20104
20105 // If the enum already has a type because it is fixed or dictated by the
20106 // target, promote that type instead of analyzing the enumerators.
20107 if (Enum->isComplete()) {
20108 BestType = Enum->getIntegerType();
20109 if (Context.isPromotableIntegerType(BestType))
20110 BestPromotionType = Context.getPromotedIntegerType(BestType);
20111 else
20112 BestPromotionType = BestType;
20113
20114 BestWidth = Context.getIntWidth(BestType);
20115 }
20116 else if (NumNegativeBits) {
20117 // If there is a negative value, figure out the smallest integer type (of
20118 // int/long/longlong) that fits.
20119 // If it's packed, check also if it fits a char or a short.
20120 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
20121 BestType = Context.SignedCharTy;
20122 BestWidth = CharWidth;
20123 } else if (Packed && NumNegativeBits <= ShortWidth &&
20124 NumPositiveBits < ShortWidth) {
20125 BestType = Context.ShortTy;
20126 BestWidth = ShortWidth;
20127 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
20128 BestType = Context.IntTy;
20129 BestWidth = IntWidth;
20130 } else {
20131 BestWidth = Context.getTargetInfo().getLongWidth();
20132
20133 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
20134 BestType = Context.LongTy;
20135 } else {
20136 BestWidth = Context.getTargetInfo().getLongLongWidth();
20137
20138 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
20139 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20140 BestType = Context.LongLongTy;
20141 }
20142 }
20143 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
20144 } else {
20145 // If there is no negative value, figure out the smallest type that fits
20146 // all of the enumerator values.
20147 // If it's packed, check also if it fits a char or a short.
20148 if (Packed && NumPositiveBits <= CharWidth) {
20149 BestType = Context.UnsignedCharTy;
20150 BestPromotionType = Context.IntTy;
20151 BestWidth = CharWidth;
20152 } else if (Packed && NumPositiveBits <= ShortWidth) {
20153 BestType = Context.UnsignedShortTy;
20154 BestPromotionType = Context.IntTy;
20155 BestWidth = ShortWidth;
20156 } else if (NumPositiveBits <= IntWidth) {
20157 BestType = Context.UnsignedIntTy;
20158 BestWidth = IntWidth;
20159 BestPromotionType
20160 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20162 } else if (NumPositiveBits <=
20163 (BestWidth = Context.getTargetInfo().getLongWidth())) {
20164 BestType = Context.UnsignedLongTy;
20165 BestPromotionType
20166 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20168 } else {
20169 BestWidth = Context.getTargetInfo().getLongLongWidth();
20170 if (NumPositiveBits > BestWidth) {
20171 // This can happen with bit-precise integer types, but those are not
20172 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
20173 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
20174 // a 128-bit integer, we should consider doing the same.
20175 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20176 }
20177 BestType = Context.UnsignedLongLongTy;
20178 BestPromotionType
20179 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20181 }
20182 }
20183
20184 // Loop over all of the enumerator constants, changing their types to match
20185 // the type of the enum if needed.
20186 for (auto *D : Elements) {
20187 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20188 if (!ECD) continue; // Already issued a diagnostic.
20189
20190 // C99 says the enumerators have int type, but we allow, as an
20191 // extension, the enumerators to be larger than int size. If each
20192 // enumerator value fits in an int, type it as an int, otherwise type it the
20193 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20194 // that X has type 'int', not 'unsigned'.
20195
20196 // Determine whether the value fits into an int.
20197 llvm::APSInt InitVal = ECD->getInitVal();
20198
20199 // If it fits into an integer type, force it. Otherwise force it to match
20200 // the enum decl type.
20201 QualType NewTy;
20202 unsigned NewWidth;
20203 bool NewSign;
20204 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20205 MembersRepresentableByInt) {
20206 // C23 6.7.3.3.3p15:
20207 // The enumeration member type for an enumerated type without fixed
20208 // underlying type upon completion is:
20209 // - int if all the values of the enumeration are representable as an
20210 // int; or,
20211 // - the enumerated type
20212 NewTy = Context.IntTy;
20213 NewWidth = IntWidth;
20214 NewSign = true;
20215 } else if (ECD->getType() == BestType) {
20216 // Already the right type!
20217 if (getLangOpts().CPlusPlus)
20218 // C++ [dcl.enum]p4: Following the closing brace of an
20219 // enum-specifier, each enumerator has the type of its
20220 // enumeration.
20221 ECD->setType(EnumType);
20222 continue;
20223 } else {
20224 NewTy = BestType;
20225 NewWidth = BestWidth;
20226 NewSign = BestType->isSignedIntegerOrEnumerationType();
20227 }
20228
20229 // Adjust the APSInt value.
20230 InitVal = InitVal.extOrTrunc(NewWidth);
20231 InitVal.setIsSigned(NewSign);
20232 ECD->setInitVal(Context, InitVal);
20233
20234 // Adjust the Expr initializer and type.
20235 if (ECD->getInitExpr() &&
20236 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20237 ECD->setInitExpr(ImplicitCastExpr::Create(
20238 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20239 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20240 if (getLangOpts().CPlusPlus)
20241 // C++ [dcl.enum]p4: Following the closing brace of an
20242 // enum-specifier, each enumerator has the type of its
20243 // enumeration.
20244 ECD->setType(EnumType);
20245 else
20246 ECD->setType(NewTy);
20247 }
20248
20249 Enum->completeDefinition(BestType, BestPromotionType,
20250 NumPositiveBits, NumNegativeBits);
20251
20252 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20253
20254 if (Enum->isClosedFlag()) {
20255 for (Decl *D : Elements) {
20256 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20257 if (!ECD) continue; // Already issued a diagnostic.
20258
20259 llvm::APSInt InitVal = ECD->getInitVal();
20260 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20261 !IsValueInFlagEnum(Enum, InitVal, true))
20262 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20263 << ECD << Enum;
20264 }
20265 }
20266
20267 // Now that the enum type is defined, ensure it's not been underaligned.
20268 if (Enum->hasAttrs())
20270}
20271
20273 SourceLocation StartLoc,
20274 SourceLocation EndLoc) {
20275 StringLiteral *AsmString = cast<StringLiteral>(expr);
20276
20278 AsmString, StartLoc,
20279 EndLoc);
20280 CurContext->addDecl(New);
20281 return New;
20282}
20283
20285 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20286 CurContext->addDecl(New);
20287 PushDeclContext(S, New);
20289 PushCompoundScope(false);
20290 return New;
20291}
20292
20294 D->setStmt(Statement);
20298}
20299
20301 IdentifierInfo* AliasName,
20302 SourceLocation PragmaLoc,
20303 SourceLocation NameLoc,
20304 SourceLocation AliasNameLoc) {
20305 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20307 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20309 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20310 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20311
20312 // If a declaration that:
20313 // 1) declares a function or a variable
20314 // 2) has external linkage
20315 // already exists, add a label attribute to it.
20316 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20317 if (isDeclExternC(PrevDecl))
20318 PrevDecl->addAttr(Attr);
20319 else
20320 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20321 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20322 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20323 } else
20324 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20325}
20326
20328 SourceLocation PragmaLoc,
20329 SourceLocation NameLoc) {
20330 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20331
20332 if (PrevDecl) {
20333 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20334 } else {
20335 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20336 }
20337}
20338
20340 IdentifierInfo* AliasName,
20341 SourceLocation PragmaLoc,
20342 SourceLocation NameLoc,
20343 SourceLocation AliasNameLoc) {
20344 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20346 WeakInfo W = WeakInfo(Name, NameLoc);
20347
20348 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20349 if (!PrevDecl->hasAttr<AliasAttr>())
20350 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20352 } else {
20353 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20354 }
20355}
20356
20358 bool Final) {
20359 assert(FD && "Expected non-null FunctionDecl");
20360
20361 // SYCL functions can be template, so we check if they have appropriate
20362 // attribute prior to checking if it is a template.
20363 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20365
20366 // Templates are emitted when they're instantiated.
20367 if (FD->isDependentContext())
20369
20370 // Check whether this function is an externally visible definition.
20371 auto IsEmittedForExternalSymbol = [this, FD]() {
20372 // We have to check the GVA linkage of the function's *definition* -- if we
20373 // only have a declaration, we don't know whether or not the function will
20374 // be emitted, because (say) the definition could include "inline".
20375 const FunctionDecl *Def = FD->getDefinition();
20376
20377 // We can't compute linkage when we skip function bodies.
20378 return Def && !Def->hasSkippedBody() &&
20380 getASTContext().GetGVALinkageForFunction(Def));
20381 };
20382
20383 if (LangOpts.OpenMPIsTargetDevice) {
20384 // In OpenMP device mode we will not emit host only functions, or functions
20385 // we don't need due to their linkage.
20386 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20387 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20388 // DevTy may be changed later by
20389 // #pragma omp declare target to(*) device_type(*).
20390 // Therefore DevTy having no value does not imply host. The emission status
20391 // will be checked again at the end of compilation unit with Final = true.
20392 if (DevTy)
20393 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20395 // If we have an explicit value for the device type, or we are in a target
20396 // declare context, we need to emit all extern and used symbols.
20397 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20398 if (IsEmittedForExternalSymbol())
20400 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20401 // we'll omit it.
20402 if (Final)
20404 } else if (LangOpts.OpenMP > 45) {
20405 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20406 // function. In 5.0, no_host was introduced which might cause a function to
20407 // be omitted.
20408 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20409 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20410 if (DevTy)
20411 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20413 }
20414
20415 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20417
20418 if (LangOpts.CUDA) {
20419 // When compiling for device, host functions are never emitted. Similarly,
20420 // when compiling for host, device and global functions are never emitted.
20421 // (Technically, we do emit a host-side stub for global functions, but this
20422 // doesn't count for our purposes here.)
20424 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20426 if (!LangOpts.CUDAIsDevice &&
20429
20430 if (IsEmittedForExternalSymbol())
20432 }
20433
20434 // Otherwise, the function is known-emitted if it's in our set of
20435 // known-emitted functions.
20437}
20438
20440 // Host-side references to a __global__ function refer to the stub, so the
20441 // function itself is never emitted and therefore should not be marked.
20442 // If we have host fn calls kernel fn calls host+device, the HD function
20443 // does not get instantiated on the host. We model this by omitting at the
20444 // call to the kernel from the callgraph. This ensures that, when compiling
20445 // for host, only HD functions actually called from the host get marked as
20446 // known-emitted.
20447 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20449}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
#define SM(sm)
Definition: Cuda.cpp:84
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
const Decl * D
enum clang::sema::@1724::IndirectLocalPathEntry::EntryKind Kind
IndirectLocalPath & Path
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
static bool isDeclExternC(const T &D)
Definition: Decl.cpp:2218
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Iter
Definition: HTMLLogger.cpp:153
static const Decl * getCanonicalDecl(const Decl *D)
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition: MachO.h:27
llvm::MachO::Record Record
Definition: MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition: Mangle.cpp:57
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
Definition: Redeclaration.h:18
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
uint32_t Id
Definition: SemaARM.cpp:1134
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:15896
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:15393
static bool isMainVar(DeclarationName Name, VarDecl *VD)
Definition: SemaDecl.cpp:7462
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:11431
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:11833
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:11927
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15377
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
Definition: SemaDecl.cpp:11551
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:15012
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:11440
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:19514
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:19885
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:16930
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:15925
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:17090
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:18865
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:18799
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:16914
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:18892
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:12504
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:18958
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:14820
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:11582
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:11406
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:19849
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:19531
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:11455
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:17127
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:15883
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:15885
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:73
virtual void HandleInlineFunctionDefinition(FunctionDecl *D)
This callback is invoked each time an inline (method or friend) function definition in a class is com...
Definition: ASTConsumer.h:58
virtual bool shouldSkipFunctionBody(Decl *D)
This callback is called for each function if the Parser was initialized with SkipFunctionBodies set t...
Definition: ASTConsumer.h:146
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:113
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
SourceManager & getSourceManager()
Definition: ASTContext.h:741
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2915
QualType getParenType(QualType NamedType) const
CanQualType LongTy
Definition: ASTContext.h:1169
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
ExternCContextDecl * getExternCContextDecl() const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2218
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
QualType getRecordType(const RecordDecl *Decl) const
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
void setObjCIdRedefinitionType(QualType RedefType)
Set the user-written type that redefines id.
Definition: ASTContext.h:1998
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2716
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:2108
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
void setObjCSelRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:2024
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:2086
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2921
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
CanQualType DependentTy
Definition: ASTContext.h:1188
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
IdentifierTable & Idents
Definition: ASTContext.h:680
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:530
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2206
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:2120
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:3014
CanQualType CharTy
Definition: ASTContext.h:1162
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
CanQualType IntTy
Definition: ASTContext.h:1169
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2289
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType SignedCharTy
Definition: ASTContext.h:1169
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
void setNonKeyFunction(const CXXMethodDecl *method)
Observe that the given method cannot be a key function.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2196
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2763
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2482
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1170
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1533
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2918
CanQualType ShortTy
Definition: ASTContext.h:1169
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:2011
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2312
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:2096
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
Definition: ASTContext.h:1169
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
Definition: ASTContext.h:2384
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2390
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2387
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2396
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2393
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2513
The result of parsing/analyzing an expression, statement etc.
Definition: Ownership.h:153
bool isUnset() const
Definition: Ownership.h:167
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3357
Wrapper for source info for arrays.
Definition: TypeLoc.h:1592
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1594
Expr * getSizeExpr() const
Definition: TypeLoc.h:1614
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1622
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1602
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
QualType getElementType() const
Definition: Type.h:3589
Attr - This represents one attribute.
Definition: Attr.h:43
attr::Kind getKind() const
Definition: Attr.h:89
bool isInherited() const
Definition: Attr.h:98
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition: Attr.h:103
SourceLocation getLocation() const
Definition: Attr.h:96
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:637
AttributeFactory & getFactory() const
Definition: ParsedAttr.h:733
Type source information for an attributed type.
Definition: TypeLoc.h:875
const T * getAttrAs()
Definition: TypeLoc.h:905
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:889
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:6132
QualType getModifiedType() const
Definition: Type.h:6162
bool isCallingConv() const
Definition: Type.cpp:4206
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6561
AutoTypeKeyword getKeyword() const
Definition: Type.h:6592
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4324
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
A binding in a decomposition declaration.
Definition: DeclCXX.h:4130
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4496
bool doesNotEscape() const
Definition: Decl.h:4647
This class is used for builtin types like 'int'.
Definition: Type.h:3034
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
bool performsCallback(unsigned ID, llvm::SmallVectorImpl< int > &Encoding) const
Determine whether this builtin has callback behavior (see llvm::AbstractCallSites for details).
Definition: Builtins.cpp:219
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:263
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition: Builtins.h:223
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
bool isReturnsTwice(unsigned ID) const
Return true if we know this builtin can return twice.
Definition: Builtins.h:138
bool isImmediate(unsigned ID) const
Returns true if this is an immediate (consteval) function.
Definition: Builtins.h:285
bool isConstWithoutErrnoAndExceptions(unsigned ID) const
Return true if this function has no side effects and doesn't read memory, except for possibly errno o...
Definition: Builtins.h:248
bool allowTypeMismatch(unsigned ID) const
Determines whether a declaration of this builtin should be recognized even if the type doesn't match ...
Definition: Builtins.h:203
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:112
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition: Builtins.h:168
bool isScanfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like scanf in its formatting rules and, if so, set the index to the...
Definition: Builtins.cpp:214
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:183
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:161
bool isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like printf in its formatting rules and, if so, set the index to th...
Definition: Builtins.cpp:209
bool isConstWithoutExceptions(unsigned ID) const
Definition: Builtins.h:252
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache",...
Definition: Builtins.h:175
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition: Builtins.h:117
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:128
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition: Builtins.h:123
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:194
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclCXX.h:195
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2854
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:3043
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:2289
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:2988
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:2588
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2642
bool isVirtual() const
Definition: DeclCXX.h:2133
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2707
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:2621
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:2407
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2239
bool isConst() const
Definition: DeclCXX.h:2130
bool isStatic() const
Definition: DeclCXX.cpp:2319
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2599
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:2036
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:2003
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1071
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:2007
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1300
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:236
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:123
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:149
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
static CharSourceRange getCharRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Declaration of a class template.
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4262
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:205
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:245
bool isZeroSize() const
Return true if the size is zero.
Definition: Type.h:3685
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3671
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:349
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h: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:2061
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:1408
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1342
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:1862
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:2006
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1695
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1776
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1645
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2024
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1432
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:1293
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1393
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1412
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2097
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1423
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition: DeclGroup.h:68
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:550
ValueDecl * getDecl()
Definition: Expr.h:1333
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool isVirtualSpecified() const
Definition: DeclSpec.h:648
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:829
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:309
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:595
static const TST TST_typename
Definition: DeclSpec.h:306
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition: DeclSpec.cpp:645
bool isNoreturnSpecified() const
Definition: DeclSpec.h:661
TST getTypeSpecType() const
Definition: DeclSpec.h:537
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:510
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:860
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:575
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:574
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:709
static const TST TST_interface
Definition: DeclSpec.h:304
static const TST TST_typeofExpr
Definition: DeclSpec.h:308
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:616
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:708
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:662
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:505
static const TST TST_union
Definition: DeclSpec.h:302
SCS
storage-class-specifier
Definition: DeclSpec.h:251
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:654
static const TST TST_int
Definition: DeclSpec.h:285
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:830
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1504
ParsedType getRepAsType() const
Definition: DeclSpec.h:547
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:788
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:502
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:873
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:626
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:617
Expr * getRepAsExpr() const
Definition: DeclSpec.h:555
static const TST TST_enum
Definition: DeclSpec.h:301
static const TST TST_decltype
Definition: DeclSpec.h:311
static bool isDeclRep(TST T)
Definition: DeclSpec.h:469
bool isInlineSpecified() const
Definition: DeclSpec.h:637
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:618
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:310
static const TST TST_class
Definition: DeclSpec.h:305
static const TST TST_void
Definition: DeclSpec.h:279
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:558
static const TST TST_atomic
Definition: DeclSpec.h:321
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:511
Decl * getRepAsDecl() const
Definition: DeclSpec.h:551
static const TST TST_unspecified
Definition: DeclSpec.h:278
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:620
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:649
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:836
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:582
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:792
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:267
static const TST TST_error
Definition: DeclSpec.h:328
bool isTypeSpecOwned() const
Definition: DeclSpec.h:541
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:640
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:621
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:619
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:821
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:651
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:837
static const TST TST_typeofType
Definition: DeclSpec.h:307
static const TST TST_auto
Definition: DeclSpec.h:318
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:832
static const TST TST_struct
Definition: DeclSpec.h:303
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h: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:1168
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:1018
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:1172
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:1117
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:1011
@ 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:3489
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1792
SourceRange getSourceRange() const
Definition: DeclSpec.h:1839
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1837
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6527
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:6548
bool isDeduced() const
Definition: Type.h:6549
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2454
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2434
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2443
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:939
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:954
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2354
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2368
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3291
llvm::APSInt getInitVal() const
Definition: Decl.h:3311
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5480
const Expr * getInitExpr() const
Definition: Decl.h:3309
Represents an enum.
Definition: Decl.h:3861
enumerator_range enumerators() const
Definition: Decl.h:3994
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4066
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:4030
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:4033
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4080
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4877
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4922
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4075
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4897
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:4016
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4021
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6103
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
This represents one expression.
Definition: Expr.h:110
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3097
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3093
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3077
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:276
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:978
void applyChanges(FPOptionsOverride FPO)
Definition: LangOptions.h:1091
bool isFPConstrained() const
Definition: LangOptions.h:906
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
Definition: LangOptions.h:1085
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3136
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4570
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4555
bool isZeroLengthBitField() const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition: Decl.cpp:4613
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5612
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:101
Represents a function declaration or definition.
Definition: Decl.h:1935
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2565
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2404
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4064
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3609
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4057
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4052
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3262
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2249
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2577
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2556
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3883
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3638
param_iterator param_end()
Definition: Decl.h:2662
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2796
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2571
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3582
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2317
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2305
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3494
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4172
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2376
void setWillHaveBody(bool V=true)
Definition: Decl.h:2562
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2371
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4182
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3623
param_iterator param_begin()
Definition: Decl.h:2661
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2698
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3096
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2468
FunctionEffectsRef getFunctionEffects() const
Definition: Decl.h:3009
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3320
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4116
@ TK_MemberSpecialization
Definition: Decl.h:1947
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2763
bool isStatic() const
Definition: Decl.h:2804
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4382
void setTrivial(bool IT)
Definition: Decl.h:2306
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4003
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
bool isDeletedAsWritten() const
Definition: Decl.h:2472
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition: Decl.h:2393
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2288
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3498
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2292
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2356
bool isImmediateEscalating() const
Definition: Decl.cpp:3275
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2284
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2555
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2217
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3313
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2791
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3372
bool param_empty() const
Definition: Decl.h:2660
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2124
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3187
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2153
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3578
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2349
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4405
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2808
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:3997
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3989
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2401
void setDefaulted(bool D=true)
Definition: Decl.h:2314
bool isConsteval() const
Definition: Decl.h:2410
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition: Decl.h:2737
void setBody(Stmt *B)
Definition: Decl.cpp:3255
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3512
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3133
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition: Decl.h:2387
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4024
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3702
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2146
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3163
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2363
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3210
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2774
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3564
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2561
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:5044
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5373
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4908
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5107
unsigned getNumParams() const
Definition: Type.h:5360
QualType getParamType(unsigned i) const
Definition: Type.h:5362
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:5566
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5393
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5484
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5371
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5367
ArrayRef< QualType > param_types() const
Definition: Type.h:5516
Declaration of a template function.
Definition: DeclTemplate.h:959
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Definition: DeclTemplate.h:541
Wrapper for source info for functions.
Definition: TypeLoc.h:1459
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4432
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4547
CallingConv getCC() const
Definition: Type.h:4494
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4513
unsigned getRegParm() const
Definition: Type.h:4487
bool getNoCallerSavedRegs() const
Definition: Type.h:4483
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4506
bool getHasRegParm() const
Definition: Type.h:4485
bool getNoReturn() const
Definition: Type.h:4480
bool getProducesResult() const
Definition: Type.h:4481
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:4527
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:4541
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4660
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3537
unsigned getRegParmType() const
Definition: Type.h:4651
CallingConv getCallConv() const
Definition: Type.h:4659
QualType getReturnType() const
Definition: Type.h:4648
bool getCmseNSCallAttr() const
Definition: Type.h:4658
@ SME_PStateSMEnabledMask
Definition: Type.h:4587
@ SME_PStateSMCompatibleMask
Definition: Type.h:4588
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
bool isPlaceholder() const
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
iterator begin(DeclarationName Name)
Returns an iterator over decls with the name 'Name'.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
void InsertDeclAfter(iterator Pos, NamedDecl *D)
Insert the given declaration after the given iterator position.
iterator end()
Returns the end iterator.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
bool isDeclInScope(Decl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3724
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2089
Represents a C array with an unspecified size.
Definition: Type.h:3764
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3335
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5508
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:289
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:672
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:816
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:721
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:534
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
Definition: LangOptions.cpp:79
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
Definition: LangOptions.h:591
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
Definition: LangOptions.h:727
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:573
void push_back(const T &LocalValue)
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition: Lexer.cpp:1359
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:3073
void InstantiatedLocal(const Decl *D, Decl *Inst)
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
DeclClass * getAsSingle() const
Definition: Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
bool isAmbiguous() const
Definition: Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition: Lookup.h:670
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition: Lookup.h:146
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
Describes a module or submodule.
Definition: Module.h:115
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:121
Module * Parent
The parent of this module.
Definition: Module.h:164
bool isPrivateModule() const
Definition: Module.h:220
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition: Module.h:619
bool isModuleImplementation() const
Is this a module implementation.
Definition: Module.h:635
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:624
bool isImplicitGlobalModule() const
Definition: Module.h:216
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:240
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:195
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:693
@ ClassId_NSObject
Definition: NSAPI.h:30
This represents a decl that may have a name.
Definition: Decl.h:253
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:466
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Decl.cpp:1079
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition: Decl.h:458
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:408
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:699
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1919
bool isExternallyVisible() const
Definition: Decl.h:412
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:376
Represent a C++ namespace.
Definition: Decl.h:551
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:602
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
SourceRange getLocalSourceRange() const
Retrieve the source range covering just the last part of this nested-name-specifier,...
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool containsErrors() const
Whether this nested name specifier contains an error.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2328
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2774
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition: DeclObjC.cpp:79
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2596
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1761
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
Definition: DeclObjC.cpp:1831
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:941
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
param_const_iterator param_end() const
Definition: DeclObjC.h:358
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
bool isOptional() const
Definition: DeclObjC.h:505
ParmVarDecl *const * param_iterator
Definition: DeclObjC.h:350
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:97
Wrapper for void* pointer.
Definition: Ownership.h:50
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(PtrTy P)
Definition: Ownership.h:60
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
MapType::iterator iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:255
Expr ** getExprs()
Definition: Expr.h:5905
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5894
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1234
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1247
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1230
Sugar for parentheses used when specifying types.
Definition: Type.h:3172
Represents a parameter to a function.
Definition: Decl.h:1725
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1785
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1789
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
QualType getOriginalType() const
Definition: Decl.cpp:2931
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2922
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:836
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:916
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:956
AttributePool & getPool() const
Definition: ParsedAttr.h:963
PipeType - OpenCL20.
Definition: Type.h:7785
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1313
Wrapper for source info for pointers.
Definition: TypeLoc.h:1332
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1338
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
HeaderSearch & getHeaderSearchInfo() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8020
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:8014
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition: Type.h:8083
@ DK_nontrivial_c_struct
Definition: Type.h:1524
PrimitiveDefaultInitializeKind
Definition: Type.h:1452
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2867
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:102
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1209
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1291
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition: Type.cpp:2915
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7936
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8062
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition: Type.h:8077
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7976
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getCanonicalType() const
Definition: Type.h:7988
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8030
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition: Type.cpp:2899
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1428
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8009
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
bool isCanonical() const
Definition: Type.h:7993
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1304
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1437
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2641
NonConstantStorageReason
Definition: Type.h:1013
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: Type.h:1482
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: Type.h:1487
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition: Type.h:8071
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7876
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7883
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4420
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
bool hasConst() const
Definition: Type.h:450
void removeConst()
Definition: Type.h:452
void addConst()
Definition: Type.h:453
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
bool empty() const
Definition: Type.h:640
Represents a struct/union/class.
Definition: Decl.h:4162
bool hasObjectMember() const
Definition: Decl.h:4222
field_range fields() const
Definition: Decl.h:4376
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5041
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5061
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5107
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:5095
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
RecordDecl * getDecl() const
Definition: Type.h:6087
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:7258
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:864
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
redecl_iterator redecls_end() const
Definition: Redeclarable.h:302
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:5003
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:222
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3046
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:3094
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition: Scope.h:382
void RemoveDecl(Decl *D)
Definition: Scope.h:354
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:385
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:582
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:271
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
void CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition: SemaARM.cpp:1334
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
void checkAllowedInitializer(VarDecl *VD)
Definition: SemaCUDA.cpp:656
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
Definition: SemaCUDA.cpp:1068
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
void maybeAddHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition: SemaCUDA.cpp:738
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
Definition: SemaCUDA.cpp:1003
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition: SemaCUDA.cpp:803
void CheckEntryPoint(FunctionDecl *FD)
Definition: SemaHLSL.cpp:365
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition: SemaHLSL.cpp:265
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition: SemaHLSL.cpp:332
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition: SemaHLSL.cpp:299
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition: SemaHLSL.cpp:279
void ActOnVariableDeclarator(VarDecl *VD)
Definition: SemaHLSL.cpp:2520
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
Definition: SemaObjC.cpp:1161
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
void AddCFAuditedAttribute(Decl *D)
AddCFAuditedAttribute - Check whether we're currently within '#pragma clang arc_cf_code_audited' and,...
Definition: SemaObjC.cpp:1447
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: SemaObjC.h:591
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Decl *D, SmallVectorImpl< FunctionDecl * > &Bases)
Register D as specialization of all base functions in Bases in the current omp begin/end declare vari...
void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl< FunctionDecl * > &Bases)
The declarator D defines a function in the scope S which is nested in an omp begin/end declare varian...
void ActOnOpenMPDeclareTargetInitializer(Decl *D)
Adds OMPDeclareTargetDeclAttr to referenced variables in declare target directive.
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D, const llvm::StringMap< bool > &FeatureMap)
Definition: SemaRISCV.cpp:1372
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition: SemaSYCL.cpp:251
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition: SemaSwift.cpp:26
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition: SemaWasm.cpp:266
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition: SemaWasm.cpp:245
bool IsAlignAttr() const
Definition: Sema.h:1507
Mode getAlignMode() const
Definition: Sema.h:1509
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:985
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:997
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition: Sema.h:3254
static NameClassification VarTemplate(TemplateName Name)
Definition: Sema.h:3264
static NameClassification Unknown()
Definition: Sema.h:3234
static NameClassification OverloadSet(ExprResult E)
Definition: Sema.h:3238
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition: Sema.h:3282
static NameClassification FunctionTemplate(TemplateName Name)
Definition: Sema.h:3270
static NameClassification NonType(NamedDecl *D)
Definition: Sema.h:3244
static NameClassification Concept(TemplateName Name)
Definition: Sema.h:3276
static NameClassification UndeclaredNonType()
Definition: Sema.h:3250
static NameClassification TypeTemplate(TemplateName Name)
Definition: Sema.h:3258
static NameClassification Error()
Definition: Sema.h:3232
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12086
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12116
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:14275
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:12643
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition: Sema.cpp:2388
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:732
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls)
MergeTypedefNameDecl - We just parsed a typedef 'New' which has the same name and scope as a previous...
Definition: SemaDecl.cpp:2471
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
Definition: SemaType.cpp:9133
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
Definition: SemaDecl.cpp: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:15168
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:15867
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12922
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:18285
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:18217
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:16425
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:15034
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
Definition: SemaAttr.cpp:1190
SemaCUDA & CUDA()
Definition: Sema.h:1071
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17394
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
void ActOnExitFunctionContext()
Definition: SemaDecl.cpp:1457
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
Definition: SemaAttr.cpp:272
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2292
Preprocessor & getPreprocessor() const
Definition: Sema.h:531
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp: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:17152
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp: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:12336
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:16626
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:18304
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:18402
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:14648
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:15503
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:20272
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15155
ASTContext & Context
Definition: Sema.h:909
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14668
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5821
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:529
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20293
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:15939
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
Definition: SemaDecl.cpp:1715
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17827
PragmaStack< StringLiteral * > ConstSegStack
Definition: Sema.h:1657
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:692
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:667
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3101
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition: SemaAttr.cpp:111
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
Definition: SemaDecl.cpp:4801
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9486
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20439
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:16961
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:11789
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:7962
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition: SemaAttr.cpp:792
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
Definition: SemaDecl.cpp: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:16860
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:19743
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition: Sema.h:13915
@ UPPC_EnumeratorValue
The enumerator value.
Definition: Sema.h:13918
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13930
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:13924
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13903
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:13942
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition: Sema.h:13927
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:13906
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition: Sema.h:13909
const LangOptions & getLangOpts() const
Definition: Sema.h:525
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
SourceLocation CurInitSegLoc
Definition: Sema.h:1697
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:::lifetimebound]] attr for std:: functions and methods.
Definition: SemaAttr.cpp:219
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition: Sema.h:3109
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1390
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
Definition: SemaDecl.cpp: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:14996
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15343
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:11953
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:18497
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
PragmaClangSection PragmaClangRelroSection
Definition: Sema.h:1434
SemaRISCV & RISCV()
Definition: Sema.h:1141
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition: Sema.h:15160
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *RetExpr, const AutoType *AT)
Deduce the return type for a function from a returned expression, per C++1y [dcl.spec....
Definition: SemaStmt.cpp:3717
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:205
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20066
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
SemaSwift & Swift()
Definition: Sema.h:1156
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
Definition: SemaAttr.cpp:1312
PragmaStack< AlignPackInfo > AlignPackStack
Definition: Sema.h:1646
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
Definition: SemaDecl.cpp:15825
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6480
PragmaStack< StringLiteral * > BSSSegStack
Definition: Sema.h:1656
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition: Sema.h:736
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9582
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
Definition: SemaType.cpp:8166
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition: SemaDecl.cpp:862
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
Definition: SemaDecl.cpp:16936
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:12523
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:19769
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:14900
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:20327
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:18695
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:18175
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:14990
StringLiteral * CurInitSeg
Last section used with #pragma init_seg.
Definition: Sema.h:1696
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20357
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:15449
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:18166
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15373
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:14940
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:15210
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:15800
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition: Sema.h:3106
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9241
CodeSegAttr * mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
SectionAttr * mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
Definition: SemaDecl.cpp:15849
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:13490
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3842
@ NTK_Typedef
Definition: Sema.h:3847
@ NTK_NonUnion
Definition: Sema.h:3845
@ NTK_TypeAlias
Definition: Sema.h:3848
@ NTK_NonClass
Definition: Sema.h:3844
@ NTK_NonEnum
Definition: Sema.h:3846
@ NTK_NonStruct
Definition: Sema.h:3843
@ NTK_TemplateTemplateArgument
Definition: Sema.h:3851
@ NTK_TypeAliasTemplate
Definition: Sema.h:3850
@ NTK_Template
Definition: Sema.h:3849
SourceManager & getSourceManager() const
Definition: Sema.h:530
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_bits attribute.
Definition: Sema.h:3059
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
Definition: SemaDecl.cpp: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:20024
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:18152
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
PragmaClangSection PragmaClangTextSection
Definition: Sema.h:1435
@ NTCUK_Destruct
Definition: Sema.h:3654
@ NTCUK_Init
Definition: Sema.h:3653
@ NTCUK_Copy
Definition: Sema.h:3655
PragmaClangSection PragmaClangDataSection
Definition: Sema.h:1432
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20252
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15877
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:13894
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:20300
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:20284
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:14304
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14825
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:18758
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:19555
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12558
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:16557
@ 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:14944
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:14611
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:17145
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:9119
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:15295
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:872
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1338
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20901
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19003
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:17904
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7917
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1310
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:912
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
Definition: SemaDecl.cpp:5779
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15934
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:15930
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:14975
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11283
@ TPC_ClassTemplateMember
Definition: Sema.h:11281
@ TPC_FunctionTemplate
Definition: Sema.h:11280
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11284
@ TPC_VarTemplate
Definition: Sema.h:11279
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
Definition: SemaDecl.cpp: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:16412
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2070
void PopDeclContext()
Definition: SemaDecl.cpp:1317
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6066
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1581
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W)
DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak applied to it,...
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8879
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:13936
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:13104
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:16804
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:13377
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:18394
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:14221
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:284
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition: Sema.h:3074
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1963
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21168
PragmaClangSection PragmaClangBSSSection
Definition: Sema.h:1431
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp: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:20339
@ 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:13070
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:15814
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:13356
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:19995
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:15184
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:16877
SemaARM & ARM()
Definition: Sema.h:1051
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:317
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8268
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Definition: SemaDecl.cpp:1266
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
child_range children()
Definition: Stmt.cpp:294
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:333
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition: Expr.h:1931
StringRef getString() const
Definition: Expr.h:1855
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3578
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3853
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3701
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3676
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3662
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3681
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4762
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4753
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4745
bool isUnion() const
Definition: Decl.h:3784
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4808
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4845
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3802
TagKind getTagKind() const
Definition: Decl.h:3773
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Definition: TargetCXXABI.h:238
Exposes information about the current target.
Definition: TargetInfo.h:220
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1540
unsigned getShortWidth() const
getShortWidth/Align - Return the size of 'signed short' and 'unsigned short' for this target,...
Definition: TargetInfo.h:514
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:519
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
Definition: TargetInfo.h:1826
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:529
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1583
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1591
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1530
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1399
unsigned getCharWidth() const
Definition: TargetInfo.h:509
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:566
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:524
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
Definition: TargetInfo.h:1504
virtual 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:399
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:207
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6666
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4340
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:99
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:101
bool isNot(tok::TokenKind K) const
Definition: Token.h:100
A declaration that models statements at global scope.
Definition: Decl.h:4459
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5627
Represents a declaration of a type.
Definition: Decl.h:3384
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3410
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition: TypeLoc.h:338
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1256
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:206
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition: TypeLoc.cpp:749
SourceLocation getTemplateKeywordLoc() const
Get the SourceLocation of the template keyword (if any).
Definition: TypeLoc.cpp:756
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2715
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7907
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7918
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6929
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3178
The base class of the type hierarchy.
Definition: Type.h:1828
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2511
bool isStructureType() const
Definition: Type.cpp:662
bool isDecltypeType() const
Definition: Type.h:8388
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isDependentSizedArrayType() const
Definition: Type.h:8283
bool isBlockPointerType() const
Definition: Type.h:8205
bool isVoidType() const
Definition: Type.h:8515
bool isBooleanType() const
Definition: Type.h:8643
bool isFunctionReferenceType() const
Definition: Type.h:8238
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2201
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8693
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2937
bool isIncompleteArrayType() const
Definition: Type.h:8271
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8814
bool isDependentAddressSpaceType() const
Definition: Type.h:8329
bool isConstantArrayType() const
Definition: Type.h:8267
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8673
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isArrayType() const
Definition: Type.h:8263
bool isFunctionPointerType() const
Definition: Type.h:8231
bool isPointerType() const
Definition: Type.h:8191
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2517
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
bool isReferenceType() const
Definition: Type.h:8209
bool isEnumeralType() const
Definition: Type.h:8295
bool isScalarType() const
Definition: Type.h:8614
bool isVariableArrayType() const
Definition: Type.h:8275
bool isClkEventT() const
Definition: Type.h:8406
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8630
bool isImageType() const
Definition: Type.h:8418
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
bool isPipeType() const
Definition: Type.h:8425
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isBitIntType() const
Definition: Type.h:8429
bool isOpenCLSpecificType() const
Definition: Type.h:8454
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2372
bool isHalfType() const
Definition: Type.h:8519
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2045
bool isHLSLSpecificType() const
Definition: Type.h:8472
const RecordType * getAsStructureType() const
Definition: Type.cpp:754
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2501
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2700
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8686
bool isAtomicType() const
Definition: Type.h:8346
bool isFunctionProtoType() const
Definition: Type.h:2535
bool isObjCIdType() const
Definition: Type.h:8366
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isObjCObjectType() const
Definition: Type.h:8337
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5048
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8649
bool isEventT() const
Definition: Type.h:8402
bool isPointerOrReferenceType() const
Definition: Type.h:8195
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4991
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:8753
bool isFunctionType() const
Definition: Type.h:8187
bool isObjCObjectPointerType() const
Definition: Type.h:8333
bool isMemberFunctionPointerType() const
Definition: Type.h:8249
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2541
bool isFloatingType() const
Definition: Type.cpp:2283
bool isAnyPointerType() const
Definition: Type.h:8199
TypeClass getTypeClass() const
Definition: Type.h:2341
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:2050
bool isSamplerT() const
Definition: Type.h:8398
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:638
bool isNullPtrType() const
Definition: Type.h:8548
bool isRecordType() const
Definition: Type.h:8291
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4763
bool isUnionType() const
Definition: Type.cpp:704
bool isFunctionNoProtoType() const
Definition: Type.h:2534
bool isReserveIDT() const
Definition: Type.h:8414
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1924
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1920
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3528
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5529
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:5538
TypedefNameDecl * getDecl() const
Definition: Type.h:5745
QualType desugar() const
Definition: Type.cpp:3920
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
decl_iterator end()
decl_iterator begin()
SmallVectorImpl< NamedDecl * >::const_iterator const_decl_iterator
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition: ExprCXX.cpp:419
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3343
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3407
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3243
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:5398
Represents a variable declaration or definition.
Definition: Decl.h:882
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2786
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2140
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1469
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1513
TLSKind getTLSKind() const
Definition: Decl.cpp:2157
bool hasInit() const
Definition: Decl.cpp:2387
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1396
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2249
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2179
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2433
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2246
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1522
bool isCXXCondDecl() const
Definition: Decl.h:1559
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:893
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition: Decl.h:896
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:890
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2152
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1541
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1177
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2355
void setInlineSpecified()
Definition: Decl.h:1502
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1159
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2748
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1293
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1124
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1495
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1128
const Expr * getInit() const
Definition: Decl.h:1319
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1168
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1135
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2418
void setConstexpr(bool IC)
Definition: Decl.h:1516
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:905
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:908
void setInit(Expr *I)
Definition: Decl.cpp:2449
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2334
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1249
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1246
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1252
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2791
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2234
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1204
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1119
void setImplicitlyInline()
Definition: Decl.h:1507
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1420
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1536
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2682
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1213
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2755
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition: Decl.h:1430
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2662
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3808
Expr * getSizeExpr() const
Definition: Type.h:3827
Captures information about a #pragma weak directive.
Definition: Weak.h:25
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
bool isVariableCapture() const
Definition: ScopeInfo.h:650
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:745
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:732
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:755
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1093
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:737
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition: ScopeInfo.h:141
void addByrefBlockVar(VarDecl *VD)
Definition: ScopeInfo.h:498
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition: ScopeInfo.h:150
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition: ScopeInfo.h:167
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition: ScopeInfo.h:145
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition: ScopeInfo.h:158
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:884
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition: ScopeInfo.h:915
ParmVarDecl * ExplicitObjectParameter
Definition: ScopeInfo.h:881
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition: ScopeInfo.h:948
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:871
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:874
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:896
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
Definition: Randstruct.cpp:173
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:32
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_struct
Definition: Specifiers.h:81
@ TST_class
Definition: Specifiers.h:82
@ TST_union
Definition: Specifiers.h:80
@ TST_enum
Definition: Specifiers.h:79
@ TST_interface
Definition: Specifiers.h:83
ImplicitTypenameContext
Definition: DeclSpec.h:1886
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
@ GNUMode
Definition: LangStandard.h:63
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ GVA_AvailableExternally
Definition: Linkage.h:74
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
Definition: AttrIterator.h:30
CUDAFunctionTarget
Definition: Cuda.h:145
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:35
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
OverloadCandidateDisplayKind
Definition: Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
@ LCK_ByRef
Capturing by reference.
Definition: Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition: Lambda.h:35
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:40
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition: Linkage.h:63
@ CLanguageLinkage
Definition: Linkage.h:64
@ CXXLanguageLinkage
Definition: Linkage.h:65
StorageClass
Storage classes.
Definition: Specifiers.h:248
@ SC_Auto
Definition: Specifiers.h:256
@ SC_PrivateExtern
Definition: Specifiers.h:253
@ SC_Extern
Definition: Specifiers.h:251
@ SC_Register
Definition: Specifiers.h:257
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:235
@ TSCS_thread_local
C++11 thread_local.
Definition: Specifiers.h:241
@ TSCS_unspecified
Definition: Specifiers.h:236
@ TSCS__Thread_local
C11 _Thread_local.
Definition: Specifiers.h:244
@ TSCS___thread
GNU __thread.
Definition: Specifiers.h:238
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Parameter
The parameter type of a method or function.
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:50
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:307
TagUseKind
Definition: Sema.h:447
TagTypeKind
The kind of a tag type.
Definition: Type.h:6876
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
@ Union
The "union" keyword.
@ Enum
The "enum" keyword.
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition: CharInfo.h:108
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
ExprResult ExprError()
Definition: Ownership.h:264
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1488
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
@ TU_Complete
The translation unit is a complete translation unit.
Definition: LangOptions.h:1098
int hasAttribute(AttributeCommonInfo::Syntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:34
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:423
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition: Lambda.h:22
@ LCD_ByRef
Definition: Lambda.h:25
@ LCD_None
Definition: Lambda.h:23
@ LCD_ByCopy
Definition: Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:229
const FunctionProtoType * T
MultiVersionKind
Definition: Decl.h:1914
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h: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:5786
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:5192
FunctionEffectsRef FunctionEffects
Definition: Type.h:5202
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:5212
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:58
std::vector< std::string > Features
Definition: TargetInfo.h:59
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
SourceLocation PragmaLocation
Definition: Sema.h:1428
ValueType CurrentValue
Definition: Sema.h:1631
bool CheckSameAsPrevious
Definition: Sema.h:351
NamedDecl * Previous
Definition: Sema.h:352
NamedDecl * New
Definition: Sema.h:353
Information about a template-id annotation token.
unsigned NumArgs
NumArgs - The number of template arguments.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.