clang 22.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"
55#include "clang/Sema/SemaPPC.h"
57#include "clang/Sema/SemaSYCL.h"
59#include "clang/Sema/SemaWasm.h"
60#include "clang/Sema/Template.h"
61#include "llvm/ADT/STLForwardCompat.h"
62#include "llvm/ADT/SmallPtrSet.h"
63#include "llvm/ADT/SmallString.h"
64#include "llvm/ADT/StringExtras.h"
65#include "llvm/Support/SaveAndRestore.h"
66#include "llvm/TargetParser/Triple.h"
67#include <algorithm>
68#include <cstring>
69#include <optional>
70#include <unordered_map>
71
72using namespace clang;
73using namespace sema;
74
76 if (OwnedType) {
77 Decl *Group[2] = { OwnedType, Ptr };
79 }
80
82}
83
84namespace {
85
86class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
87 public:
88 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
89 bool AllowTemplates = false,
90 bool AllowNonTemplates = true)
91 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
92 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
93 WantExpressionKeywords = false;
94 WantCXXNamedCasts = false;
95 WantRemainingKeywords = false;
96 }
97
98 bool ValidateCandidate(const TypoCorrection &candidate) override {
99 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
100 if (!AllowInvalidDecl && ND->isInvalidDecl())
101 return false;
102
103 if (getAsTypeTemplateDecl(ND))
104 return AllowTemplates;
105
106 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
107 if (!IsType)
108 return false;
109
110 if (AllowNonTemplates)
111 return true;
112
113 // An injected-class-name of a class template (specialization) is valid
114 // as a template or as a non-template.
115 if (AllowTemplates) {
116 auto *RD = dyn_cast<CXXRecordDecl>(ND);
117 if (!RD || !RD->isInjectedClassName())
118 return false;
119 RD = cast<CXXRecordDecl>(RD->getDeclContext());
120 return RD->getDescribedClassTemplate() ||
121 isa<ClassTemplateSpecializationDecl>(RD);
122 }
123
124 return false;
125 }
126
127 return !WantClassName && candidate.isKeyword();
128 }
129
130 std::unique_ptr<CorrectionCandidateCallback> clone() override {
131 return std::make_unique<TypeNameValidatorCCC>(*this);
132 }
133
134 private:
135 bool AllowInvalidDecl;
136 bool WantClassName;
137 bool AllowTemplates;
138 bool AllowNonTemplates;
139};
140
141} // end anonymous namespace
142
144 TypeDecl *TD, SourceLocation NameLoc) {
145 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
146 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
147 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
148 FoundRD->isInjectedClassName() &&
149 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
150 Diag(NameLoc,
152 ? diag::ext_out_of_line_qualified_id_type_names_constructor
153 : diag::err_out_of_line_qualified_id_type_names_constructor)
154 << TD->getIdentifier() << /*Type=*/1
155 << 0 /*if any keyword was present, it was 'typename'*/;
156 }
157
158 DiagnoseUseOfDecl(TD, NameLoc);
159 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
160}
161
162namespace {
163enum class UnqualifiedTypeNameLookupResult {
164 NotFound,
165 FoundNonType,
166 FoundType
167};
168} // end anonymous namespace
169
170/// Tries to perform unqualified lookup of the type decls in bases for
171/// dependent class.
172/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
173/// type decl, \a FoundType if only type decls are found.
174static UnqualifiedTypeNameLookupResult
176 SourceLocation NameLoc,
177 const CXXRecordDecl *RD) {
178 if (!RD->hasDefinition())
179 return UnqualifiedTypeNameLookupResult::NotFound;
180 // Look for type decls in base classes.
181 UnqualifiedTypeNameLookupResult FoundTypeDecl =
182 UnqualifiedTypeNameLookupResult::NotFound;
183 for (const auto &Base : RD->bases()) {
184 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
185 if (BaseRD) {
186 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
187 Base.getType().getCanonicalType())) {
188 // Look for type decls in dependent base classes that have known primary
189 // templates.
190 if (!TST->isDependentType())
191 continue;
192 auto *TD = TST->getTemplateName().getAsTemplateDecl();
193 if (!TD)
194 continue;
195 if (auto *BasePrimaryTemplate =
196 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
197 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
198 BaseRD = BasePrimaryTemplate;
199 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
201 CTD->findPartialSpecialization(Base.getType()))
202 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
203 BaseRD = PS;
204 }
205 }
206 }
207 if (BaseRD) {
208 for (NamedDecl *ND : BaseRD->lookup(&II)) {
209 if (!isa<TypeDecl>(ND))
210 return UnqualifiedTypeNameLookupResult::FoundNonType;
211 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
212 }
213 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
214 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
215 case UnqualifiedTypeNameLookupResult::FoundNonType:
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 case UnqualifiedTypeNameLookupResult::FoundType:
218 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
219 break;
220 case UnqualifiedTypeNameLookupResult::NotFound:
221 break;
222 }
223 }
224 }
225 }
226
227 return FoundTypeDecl;
228}
229
231 const IdentifierInfo &II,
232 SourceLocation NameLoc) {
233 // Lookup in the parent class template context, if any.
234 const CXXRecordDecl *RD = nullptr;
235 UnqualifiedTypeNameLookupResult FoundTypeDecl =
236 UnqualifiedTypeNameLookupResult::NotFound;
237 for (DeclContext *DC = S.CurContext;
238 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
239 DC = DC->getParent()) {
240 // Look for type decls in dependent base classes that have known primary
241 // templates.
242 RD = dyn_cast<CXXRecordDecl>(DC);
243 if (RD && RD->getDescribedClassTemplate())
244 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
245 }
246 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
247 return nullptr;
248
249 // We found some types in dependent base classes. Recover as if the user
250 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
251 // allowed. We'll fully resolve the lookup during template instantiation.
252 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
253
254 ASTContext &Context = S.Context;
256 QualType T =
258
259 CXXScopeSpec SS;
260 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
261
262 TypeLocBuilder Builder;
263 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
264 DepTL.setNameLoc(NameLoc);
266 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
267 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
268}
269
271 Scope *S, CXXScopeSpec *SS, bool isClassName,
272 bool HasTrailingDot, ParsedType ObjectTypePtr,
273 bool IsCtorOrDtorName,
274 bool WantNontrivialTypeSourceInfo,
275 bool IsClassTemplateDeductionContext,
276 ImplicitTypenameContext AllowImplicitTypename,
277 IdentifierInfo **CorrectedII) {
278 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
279 // FIXME: Consider allowing this outside C++1z mode as an extension.
280 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
281 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
282 !HasTrailingDot;
283
284 // Determine where we will perform name lookup.
285 DeclContext *LookupCtx = nullptr;
286 if (ObjectTypePtr) {
287 QualType ObjectType = ObjectTypePtr.get();
288 if (ObjectType->isRecordType())
289 LookupCtx = computeDeclContext(ObjectType);
290 } else if (SS && SS->isNotEmpty()) {
291 LookupCtx = computeDeclContext(*SS, false);
292
293 if (!LookupCtx) {
294 if (isDependentScopeSpecifier(*SS)) {
295 // C++ [temp.res]p3:
296 // A qualified-id that refers to a type and in which the
297 // nested-name-specifier depends on a template-parameter (14.6.2)
298 // shall be prefixed by the keyword typename to indicate that the
299 // qualified-id denotes a type, forming an
300 // elaborated-type-specifier (7.1.5.3).
301 //
302 // We therefore do not perform any name lookup if the result would
303 // refer to a member of an unknown specialization.
304 // In C++2a, in several contexts a 'typename' is not required. Also
305 // allow this as an extension.
306 if (IsImplicitTypename) {
307 if (AllowImplicitTypename == ImplicitTypenameContext::No)
308 return nullptr;
309 SourceLocation QualifiedLoc = SS->getRange().getBegin();
310 // FIXME: Defer the diagnostic after we build the type and use it.
311 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
313 SS->getScopeRep(), &II);
315 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
316 }
317
318 // We know from the grammar that this name refers to a type,
319 // so build a dependent node to describe the type.
320 if (WantNontrivialTypeSourceInfo)
321 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
322 (ImplicitTypenameContext)IsImplicitTypename)
323 .get();
324
327 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
329 SourceLocation(), QualifierLoc, II, NameLoc);
330 return ParsedType::make(T);
331 }
332
333 return nullptr;
334 }
335
336 if (!LookupCtx->isDependentContext() &&
337 RequireCompleteDeclContext(*SS, LookupCtx))
338 return nullptr;
339 }
340
341 // In the case where we know that the identifier is a class name, we know that
342 // it is a type declaration (struct, class, union or enum) so we can use tag
343 // name lookup.
344 //
345 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
346 // the component name of the type-name or simple-template-id is type-only.
347 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
348 LookupResult Result(*this, &II, NameLoc, Kind);
349 if (LookupCtx) {
350 // Perform "qualified" name lookup into the declaration context we
351 // computed, which is either the type of the base of a member access
352 // expression or the declaration context associated with a prior
353 // nested-name-specifier.
354 LookupQualifiedName(Result, LookupCtx);
355
356 if (ObjectTypePtr && Result.empty()) {
357 // C++ [basic.lookup.classref]p3:
358 // If the unqualified-id is ~type-name, the type-name is looked up
359 // in the context of the entire postfix-expression. If the type T of
360 // the object expression is of a class type C, the type-name is also
361 // looked up in the scope of class C. At least one of the lookups shall
362 // find a name that refers to (possibly cv-qualified) T.
363 LookupName(Result, S);
364 }
365 } else {
366 // Perform unqualified name lookup.
367 LookupName(Result, S);
368
369 // For unqualified lookup in a class template in MSVC mode, look into
370 // dependent base classes where the primary class template is known.
371 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
372 if (ParsedType TypeInBase =
373 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
374 return TypeInBase;
375 }
376 }
377
378 NamedDecl *IIDecl = nullptr;
379 UsingShadowDecl *FoundUsingShadow = nullptr;
380 switch (Result.getResultKind()) {
382 if (CorrectedII) {
383 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
384 AllowDeducedTemplate);
385 TypoCorrection Correction =
386 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
388 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
390 bool MemberOfUnknownSpecialization;
392 TemplateName.setIdentifier(NewII, NameLoc);
394 CXXScopeSpec NewSS, *NewSSPtr = SS;
395 if (SS && NNS) {
396 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
397 NewSSPtr = &NewSS;
398 }
399 if (Correction && (NNS || NewII != &II) &&
400 // Ignore a correction to a template type as the to-be-corrected
401 // identifier is not a template (typo correction for template names
402 // is handled elsewhere).
403 !(getLangOpts().CPlusPlus && NewSSPtr &&
404 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
405 Template, MemberOfUnknownSpecialization))) {
406 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
407 isClassName, HasTrailingDot, ObjectTypePtr,
408 IsCtorOrDtorName,
409 WantNontrivialTypeSourceInfo,
410 IsClassTemplateDeductionContext);
411 if (Ty) {
412 diagnoseTypo(Correction,
413 PDiag(diag::err_unknown_type_or_class_name_suggest)
414 << Result.getLookupName() << isClassName);
415 if (SS && NNS)
416 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
417 *CorrectedII = NewII;
418 return Ty;
419 }
420 }
421 }
422 Result.suppressDiagnostics();
423 return nullptr;
425 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
427 SS->getScopeRep(), &II);
428 TypeLocBuilder TLB;
432 TL.setNameLoc(NameLoc);
434 }
435 [[fallthrough]];
438 Result.suppressDiagnostics();
439 return nullptr;
440
442 // Recover from type-hiding ambiguities by hiding the type. We'll
443 // do the lookup again when looking for an object, and we can
444 // diagnose the error then. If we don't do this, then the error
445 // about hiding the type will be immediately followed by an error
446 // that only makes sense if the identifier was treated like a type.
447 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
448 Result.suppressDiagnostics();
449 return nullptr;
450 }
451
452 // Look to see if we have a type anywhere in the list of results.
453 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
454 Res != ResEnd; ++Res) {
455 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
456 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
457 RealRes) ||
458 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
459 if (!IIDecl ||
460 // Make the selection of the recovery decl deterministic.
461 RealRes->getLocation() < IIDecl->getLocation()) {
462 IIDecl = RealRes;
463 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
464 }
465 }
466 }
467
468 if (!IIDecl) {
469 // None of the entities we found is a type, so there is no way
470 // to even assume that the result is a type. In this case, don't
471 // complain about the ambiguity. The parser will either try to
472 // perform this lookup again (e.g., as an object name), which
473 // will produce the ambiguity, or will complain that it expected
474 // a type name.
475 Result.suppressDiagnostics();
476 return nullptr;
477 }
478
479 // We found a type within the ambiguous lookup; diagnose the
480 // ambiguity and then return that type. This might be the right
481 // answer, or it might not be, but it suppresses any attempt to
482 // perform the name lookup again.
483 break;
484
486 IIDecl = Result.getFoundDecl();
487 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
488 break;
489 }
490
491 assert(IIDecl && "Didn't find decl");
492
493 TypeLocBuilder TLB;
494 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
495 checkTypeDeclType(LookupCtx,
496 IsImplicitTypename ? DiagCtorKind::Implicit
498 TD, NameLoc);
499 QualType T;
500 if (FoundUsingShadow) {
502 SS ? SS->getScopeRep() : std::nullopt,
503 FoundUsingShadow);
504 if (!WantNontrivialTypeSourceInfo)
505 return ParsedType::make(T);
506 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
509 NameLoc);
510 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
512 SS ? SS->getScopeRep() : std::nullopt, Tag,
513 /*OwnsTag=*/false);
514 if (!WantNontrivialTypeSourceInfo)
515 return ParsedType::make(T);
516 auto TL = TLB.push<TagTypeLoc>(T);
518 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
520 TL.setNameLoc(NameLoc);
521 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
522 TN && !isa<ObjCTypeParamDecl>(TN)) {
524 SS ? SS->getScopeRep() : std::nullopt, TN);
525 if (!WantNontrivialTypeSourceInfo)
526 return ParsedType::make(T);
527 TLB.push<TypedefTypeLoc>(T).set(
528 /*ElaboratedKeywordLoc=*/SourceLocation(),
530 NameLoc);
531 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
533 SS ? SS->getScopeRep() : std::nullopt,
534 UD);
535 if (!WantNontrivialTypeSourceInfo)
536 return ParsedType::make(T);
537 TLB.push<UnresolvedUsingTypeLoc>(T).set(
538 /*ElaboratedKeywordLoc=*/SourceLocation(),
540 NameLoc);
541 } else {
543 if (!WantNontrivialTypeSourceInfo)
544 return ParsedType::make(T);
545 if (isa<ObjCTypeParamType>(T))
546 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
547 else
548 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
549 }
551 }
552 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
553 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
554 if (!HasTrailingDot) {
555 // FIXME: Support UsingType for this case.
557 if (!WantNontrivialTypeSourceInfo)
558 return ParsedType::make(T);
559 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
560 TL.setNameLoc(NameLoc);
561 // FIXME: Pass in this source location.
562 TL.setNameEndLoc(NameLoc);
564 }
565 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
566 (void)DiagnoseUseOfDecl(UD, NameLoc);
567 // Recover with 'int'
569 } else if (AllowDeducedTemplate) {
570 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
571 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
572 // FIXME: Support UsingType here.
574 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
575 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
580 TL.setNameLoc(NameLoc);
581 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
584 }
585 }
586
587 // As it's not plausibly a type, suppress diagnostics.
588 Result.suppressDiagnostics();
589 return nullptr;
590}
591
592// Builds a fake NNS for the given decl context.
595 for (;; DC = DC->getLookupParent()) {
596 DC = DC->getPrimaryContext();
597 auto *ND = dyn_cast<NamespaceDecl>(DC);
598 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
599 return NestedNameSpecifier(Context, ND, std::nullopt);
600 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
602 if (isa<TranslationUnitDecl>(DC))
604 }
605 llvm_unreachable("something isn't in TU scope?");
606}
607
608/// Find the parent class with dependent bases of the innermost enclosing method
609/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
610/// up allowing unqualified dependent type names at class-level, which MSVC
611/// correctly rejects.
612static const CXXRecordDecl *
614 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
615 DC = DC->getPrimaryContext();
616 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
617 if (MD->getParent()->hasAnyDependentBases())
618 return MD->getParent();
619 }
620 return nullptr;
621}
622
624 SourceLocation NameLoc,
625 bool IsTemplateTypeArg) {
626 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
627
628 NestedNameSpecifier NNS = std::nullopt;
629 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
630 // If we weren't able to parse a default template argument, delay lookup
631 // until instantiation time by making a non-dependent DependentTypeName. We
632 // pretend we saw a NestedNameSpecifier referring to the current scope, and
633 // lookup is retried.
634 // FIXME: This hurts our diagnostic quality, since we get errors like "no
635 // type named 'Foo' in 'current_namespace'" when the user didn't write any
636 // name specifiers.
638 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
639 } else if (const CXXRecordDecl *RD =
641 // Build a DependentNameType that will perform lookup into RD at
642 // instantiation time.
644
645 // Diagnose that this identifier was undeclared, and retry the lookup during
646 // template instantiation.
647 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
648 << RD;
649 } else {
650 // This is not a situation that we should recover from.
651 return ParsedType();
652 }
653
654 QualType T =
656
657 // Build type location information. We synthesized the qualifier, so we have
658 // to build a fake NestedNameSpecifierLoc.
659 NestedNameSpecifierLocBuilder NNSLocBuilder;
660 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
661 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
662
663 TypeLocBuilder Builder;
664 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
665 DepTL.setNameLoc(NameLoc);
667 DepTL.setQualifierLoc(QualifierLoc);
668 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
669}
670
672 // Do a tag name lookup in this scope.
673 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
674 LookupName(R, S, false);
677 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
678 switch (TD->getTagKind()) {
684 return DeclSpec::TST_union;
686 return DeclSpec::TST_class;
688 return DeclSpec::TST_enum;
689 }
690 }
691
693}
694
696 if (!CurContext->isRecord())
697 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
698
699 switch (SS->getScopeRep().getKind()) {
701 return true;
703 QualType T(SS->getScopeRep().getAsType(), 0);
704 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
705 if (Context.hasSameUnqualifiedType(T, Base.getType()))
706 return true;
707 [[fallthrough]];
708 }
709 default:
710 return S->isFunctionPrototypeScope();
711 }
712}
713
715 SourceLocation IILoc,
716 Scope *S,
717 CXXScopeSpec *SS,
718 ParsedType &SuggestedType,
719 bool IsTemplateName) {
720 // Don't report typename errors for editor placeholders.
721 if (II->isEditorPlaceholder())
722 return;
723 // We don't have anything to suggest (yet).
724 SuggestedType = nullptr;
725
726 // There may have been a typo in the name of the type. Look up typo
727 // results, in case we have something that we can suggest.
728 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
729 /*AllowTemplates=*/IsTemplateName,
730 /*AllowNonTemplates=*/!IsTemplateName);
731 if (TypoCorrection Corrected =
734 // FIXME: Support error recovery for the template-name case.
735 bool CanRecover = !IsTemplateName;
736 if (Corrected.isKeyword()) {
737 // We corrected to a keyword.
738 diagnoseTypo(Corrected,
739 PDiag(IsTemplateName ? diag::err_no_template_suggest
740 : diag::err_unknown_typename_suggest)
741 << II);
742 II = Corrected.getCorrectionAsIdentifierInfo();
743 } else {
744 // We found a similarly-named type or interface; suggest that.
745 if (!SS || !SS->isSet()) {
746 diagnoseTypo(Corrected,
747 PDiag(IsTemplateName ? diag::err_no_template_suggest
748 : diag::err_unknown_typename_suggest)
749 << II, CanRecover);
750 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
751 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
752 bool DroppedSpecifier =
753 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
754 diagnoseTypo(Corrected,
755 PDiag(IsTemplateName
756 ? diag::err_no_member_template_suggest
757 : diag::err_unknown_nested_typename_suggest)
758 << II << DC << DroppedSpecifier << SS->getRange(),
759 CanRecover);
760 } else {
761 llvm_unreachable("could not have corrected a typo here");
762 }
763
764 if (!CanRecover)
765 return;
766
767 CXXScopeSpec tmpSS;
768 if (Corrected.getCorrectionSpecifier())
769 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
770 SourceRange(IILoc));
771 // FIXME: Support class template argument deduction here.
772 SuggestedType =
773 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
774 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
775 /*IsCtorOrDtorName=*/false,
776 /*WantNontrivialTypeSourceInfo=*/true);
777 }
778 return;
779 }
780
781 if (getLangOpts().CPlusPlus && !IsTemplateName) {
782 // See if II is a class template that the user forgot to pass arguments to.
783 UnqualifiedId Name;
784 Name.setIdentifier(II, IILoc);
785 CXXScopeSpec EmptySS;
786 TemplateTy TemplateResult;
787 bool MemberOfUnknownSpecialization;
788 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
789 Name, nullptr, true, TemplateResult,
790 MemberOfUnknownSpecialization) == TNK_Type_template) {
791 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
792 return;
793 }
794 }
795
796 // FIXME: Should we move the logic that tries to recover from a missing tag
797 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
798
799 if (!SS || (!SS->isSet() && !SS->isInvalid()))
800 Diag(IILoc, IsTemplateName ? diag::err_no_template
801 : diag::err_unknown_typename)
802 << II;
803 else if (DeclContext *DC = computeDeclContext(*SS, false))
804 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
805 : diag::err_typename_nested_not_found)
806 << II << DC << SS->getRange();
807 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
808 SuggestedType =
809 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
810 } else if (isDependentScopeSpecifier(*SS)) {
811 unsigned DiagID = diag::err_typename_missing;
812 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
813 DiagID = diag::ext_typename_missing;
814
815 SuggestedType =
816 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
817
818 Diag(SS->getRange().getBegin(), DiagID)
819 << GetTypeFromParser(SuggestedType)
820 << SourceRange(SS->getRange().getBegin(), IILoc)
821 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
822 } else {
823 assert(SS && SS->isInvalid() &&
824 "Invalid scope specifier has already been diagnosed");
825 }
826}
827
828/// Determine whether the given result set contains either a type name
829/// or
830static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
831 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
832 NextToken.is(tok::less);
833
834 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
835 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
836 return true;
837
838 if (CheckTemplate && isa<TemplateDecl>(*I))
839 return true;
840 }
841
842 return false;
843}
844
846 Scope *S, CXXScopeSpec &SS,
847 IdentifierInfo *&Name,
848 SourceLocation NameLoc) {
849 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
850 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
851 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
852 StringRef FixItTagName;
853 switch (Tag->getTagKind()) {
855 FixItTagName = "class ";
856 break;
857
859 FixItTagName = "enum ";
860 break;
861
863 FixItTagName = "struct ";
864 break;
865
867 FixItTagName = "__interface ";
868 break;
869
871 FixItTagName = "union ";
872 break;
873 }
874
875 StringRef TagName = FixItTagName.drop_back();
876 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
877 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
878 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
879
880 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
881 I != IEnd; ++I)
882 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
883 << Name << TagName;
884
885 // Replace lookup results with just the tag decl.
887 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
888 return true;
889 }
890
891 return false;
892}
893
895 IdentifierInfo *&Name,
896 SourceLocation NameLoc,
897 const Token &NextToken,
899 DeclarationNameInfo NameInfo(Name, NameLoc);
900 ObjCMethodDecl *CurMethod = getCurMethodDecl();
901
902 assert(NextToken.isNot(tok::coloncolon) &&
903 "parse nested name specifiers before calling ClassifyName");
904 if (getLangOpts().CPlusPlus && SS.isSet() &&
905 isCurrentClassName(*Name, S, &SS)) {
906 // Per [class.qual]p2, this names the constructors of SS, not the
907 // injected-class-name. We don't have a classification for that.
908 // There's not much point caching this result, since the parser
909 // will reject it later.
911 }
912
913 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
914 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
915 /*AllowBuiltinCreation=*/!CurMethod);
916
917 if (SS.isInvalid())
919
920 // For unqualified lookup in a class template in MSVC mode, look into
921 // dependent base classes where the primary class template is known.
922 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
923 if (ParsedType TypeInBase =
924 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
925 return TypeInBase;
926 }
927
928 // Perform lookup for Objective-C instance variables (including automatically
929 // synthesized instance variables), if we're in an Objective-C method.
930 // FIXME: This lookup really, really needs to be folded in to the normal
931 // unqualified lookup mechanism.
932 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
933 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
934 if (Ivar.isInvalid())
936 if (Ivar.isUsable())
937 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
938
939 // We defer builtin creation until after ivar lookup inside ObjC methods.
940 if (Result.empty())
942 }
943
944 bool SecondTry = false;
945 bool IsFilteredTemplateName = false;
946
947Corrected:
948 switch (Result.getResultKind()) {
950 // If an unqualified-id is followed by a '(', then we have a function
951 // call.
952 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
953 // In C++, this is an ADL-only call.
954 // FIXME: Reference?
957
958 // C90 6.3.2.2:
959 // If the expression that precedes the parenthesized argument list in a
960 // function call consists solely of an identifier, and if no
961 // declaration is visible for this identifier, the identifier is
962 // implicitly declared exactly as if, in the innermost block containing
963 // the function call, the declaration
964 //
965 // extern int identifier ();
966 //
967 // appeared.
968 //
969 // We also allow this in C99 as an extension. However, this is not
970 // allowed in all language modes as functions without prototypes may not
971 // be supported.
972 if (getLangOpts().implicitFunctionsAllowed()) {
973 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
975 }
976 }
977
978 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
979 // In C++20 onwards, this could be an ADL-only call to a function
980 // template, and we're required to assume that this is a template name.
981 //
982 // FIXME: Find a way to still do typo correction in this case.
986 }
987
988 // In C, we first see whether there is a tag type by the same name, in
989 // which case it's likely that the user just forgot to write "enum",
990 // "struct", or "union".
991 if (!getLangOpts().CPlusPlus && !SecondTry &&
992 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
993 break;
994 }
995
996 // Perform typo correction to determine if there is another name that is
997 // close to this name.
998 if (!SecondTry && CCC) {
999 SecondTry = true;
1000 if (TypoCorrection Corrected =
1001 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1002 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1003 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1004 unsigned QualifiedDiag = diag::err_no_member_suggest;
1005
1006 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1007 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1008 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1009 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1010 UnqualifiedDiag = diag::err_no_template_suggest;
1011 QualifiedDiag = diag::err_no_member_template_suggest;
1012 } else if (UnderlyingFirstDecl &&
1013 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1014 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1015 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1016 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1017 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1018 }
1019
1020 if (SS.isEmpty()) {
1021 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1022 } else {// FIXME: is this even reachable? Test it.
1023 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1024 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1025 Name->getName() == CorrectedStr;
1026 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1027 << Name << computeDeclContext(SS, false)
1028 << DroppedSpecifier << SS.getRange());
1029 }
1030
1031 // Update the name, so that the caller has the new name.
1032 Name = Corrected.getCorrectionAsIdentifierInfo();
1033
1034 // Typo correction corrected to a keyword.
1035 if (Corrected.isKeyword())
1036 return Name;
1037
1038 // Also update the LookupResult...
1039 // FIXME: This should probably go away at some point
1040 Result.clear();
1041 Result.setLookupName(Corrected.getCorrection());
1042 if (FirstDecl)
1043 Result.addDecl(FirstDecl);
1044
1045 // If we found an Objective-C instance variable, let
1046 // LookupInObjCMethod build the appropriate expression to
1047 // reference the ivar.
1048 // FIXME: This is a gross hack.
1049 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1050 DeclResult R =
1051 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1052 if (R.isInvalid())
1054 if (R.isUsable())
1055 return NameClassification::NonType(Ivar);
1056 }
1057
1058 goto Corrected;
1059 }
1060 }
1061
1062 // We failed to correct; just fall through and let the parser deal with it.
1063 Result.suppressDiagnostics();
1065
1067 // We performed name lookup into the current instantiation, and there were
1068 // dependent bases, so we treat this result the same way as any other
1069 // dependent nested-name-specifier.
1070
1071 // C++ [temp.res]p2:
1072 // A name used in a template declaration or definition and that is
1073 // dependent on a template-parameter is assumed not to name a type
1074 // unless the applicable name lookup finds a type name or the name is
1075 // qualified by the keyword typename.
1076 //
1077 // FIXME: If the next token is '<', we might want to ask the parser to
1078 // perform some heroics to see if we actually have a
1079 // template-argument-list, which would indicate a missing 'template'
1080 // keyword here.
1082 }
1083
1087 break;
1088
1090 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1091 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1092 /*AllowDependent=*/false)) {
1093 // C++ [temp.local]p3:
1094 // A lookup that finds an injected-class-name (10.2) can result in an
1095 // ambiguity in certain cases (for example, if it is found in more than
1096 // one base class). If all of the injected-class-names that are found
1097 // refer to specializations of the same class template, and if the name
1098 // is followed by a template-argument-list, the reference refers to the
1099 // class template itself and not a specialization thereof, and is not
1100 // ambiguous.
1101 //
1102 // This filtering can make an ambiguous result into an unambiguous one,
1103 // so try again after filtering out template names.
1105 if (!Result.isAmbiguous()) {
1106 IsFilteredTemplateName = true;
1107 break;
1108 }
1109 }
1110
1111 // Diagnose the ambiguity and return an error.
1113 }
1114
1115 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1116 (IsFilteredTemplateName ||
1118 Result, /*AllowFunctionTemplates=*/true,
1119 /*AllowDependent=*/false,
1120 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1122 // C++ [temp.names]p3:
1123 // After name lookup (3.4) finds that a name is a template-name or that
1124 // an operator-function-id or a literal- operator-id refers to a set of
1125 // overloaded functions any member of which is a function template if
1126 // this is followed by a <, the < is always taken as the delimiter of a
1127 // template-argument-list and never as the less-than operator.
1128 // C++2a [temp.names]p2:
1129 // A name is also considered to refer to a template if it is an
1130 // unqualified-id followed by a < and name lookup finds either one
1131 // or more functions or finds nothing.
1132 if (!IsFilteredTemplateName)
1134
1135 bool IsFunctionTemplate;
1136 bool IsVarTemplate;
1138 if (Result.end() - Result.begin() > 1) {
1139 IsFunctionTemplate = true;
1141 Result.end());
1142 } else if (!Result.empty()) {
1143 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1144 *Result.begin(), /*AllowFunctionTemplates=*/true,
1145 /*AllowDependent=*/false));
1146 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1147 IsVarTemplate = isa<VarTemplateDecl>(TD);
1148
1149 UsingShadowDecl *FoundUsingShadow =
1150 dyn_cast<UsingShadowDecl>(*Result.begin());
1151 assert(!FoundUsingShadow ||
1152 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1154 SS.getScopeRep(),
1155 /*TemplateKeyword=*/false,
1156 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1157 } else {
1158 // All results were non-template functions. This is a function template
1159 // name.
1160 IsFunctionTemplate = true;
1162 }
1163
1164 if (IsFunctionTemplate) {
1165 // Function templates always go through overload resolution, at which
1166 // point we'll perform the various checks (e.g., accessibility) we need
1167 // to based on which function we selected.
1168 Result.suppressDiagnostics();
1169
1171 }
1172
1173 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1175 }
1176
1177 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1178 QualType T;
1179 TypeLocBuilder TLB;
1180 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1182 USD);
1183 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1184 SS.getWithLocInContext(Context), NameLoc);
1185 } else {
1187 Type);
1188 if (isa<TagType>(T)) {
1189 auto TTL = TLB.push<TagTypeLoc>(T);
1191 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1192 TTL.setNameLoc(NameLoc);
1193 } else if (isa<TypedefType>(T)) {
1194 TLB.push<TypedefTypeLoc>(T).set(
1195 /*ElaboratedKeywordLoc=*/SourceLocation(),
1196 SS.getWithLocInContext(Context), NameLoc);
1197 } else if (isa<UnresolvedUsingType>(T)) {
1198 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1199 /*ElaboratedKeywordLoc=*/SourceLocation(),
1200 SS.getWithLocInContext(Context), NameLoc);
1201 } else {
1202 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1203 }
1204 }
1206 };
1207
1208 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1209 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1210 DiagnoseUseOfDecl(Type, NameLoc);
1211 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1212 return BuildTypeFor(Type, *Result.begin());
1213 }
1214
1215 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1216 if (!Class) {
1217 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1218 if (ObjCCompatibleAliasDecl *Alias =
1219 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1220 Class = Alias->getClassInterface();
1221 }
1222
1223 if (Class) {
1224 DiagnoseUseOfDecl(Class, NameLoc);
1225
1226 if (NextToken.is(tok::period)) {
1227 // Interface. <something> is parsed as a property reference expression.
1228 // Just return "unknown" as a fall-through for now.
1229 Result.suppressDiagnostics();
1231 }
1232
1234 return ParsedType::make(T);
1235 }
1236
1237 if (isa<ConceptDecl>(FirstDecl)) {
1238 // We want to preserve the UsingShadowDecl for concepts.
1239 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1242 TemplateName(cast<TemplateDecl>(FirstDecl)));
1243 }
1244
1245 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1246 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1248 }
1249
1250 // We can have a type template here if we're classifying a template argument.
1251 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1252 !isa<VarTemplateDecl>(FirstDecl))
1254 TemplateName(cast<TemplateDecl>(FirstDecl)));
1255
1256 // Check for a tag type hidden by a non-type decl in a few cases where it
1257 // seems likely a type is wanted instead of the non-type that was found.
1258 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1259 if ((NextToken.is(tok::identifier) ||
1260 (NextIsOp &&
1261 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1262 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1263 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1264 DiagnoseUseOfDecl(Type, NameLoc);
1265 return BuildTypeFor(Type, *Result.begin());
1266 }
1267
1268 // If we already know which single declaration is referenced, just annotate
1269 // that declaration directly. Defer resolving even non-overloaded class
1270 // member accesses, as we need to defer certain access checks until we know
1271 // the context.
1272 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1273 if (Result.isSingleResult() && !ADL &&
1274 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1275 return NameClassification::NonType(Result.getRepresentativeDecl());
1276
1277 // Otherwise, this is an overload set that we will need to resolve later.
1278 Result.suppressDiagnostics();
1280 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1281 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1282 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1283}
1284
1287 SourceLocation NameLoc) {
1288 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1289 CXXScopeSpec SS;
1290 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1291 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1292}
1293
1296 IdentifierInfo *Name,
1297 SourceLocation NameLoc,
1298 bool IsAddressOfOperand) {
1299 DeclarationNameInfo NameInfo(Name, NameLoc);
1300 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1301 NameInfo, IsAddressOfOperand,
1302 /*TemplateArgs=*/nullptr);
1303}
1304
1307 SourceLocation NameLoc,
1308 const Token &NextToken) {
1309 if (getCurMethodDecl() && SS.isEmpty())
1310 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1311 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1312
1313 // Reconstruct the lookup result.
1314 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1315 Result.addDecl(Found);
1316 Result.resolveKind();
1317
1318 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1319 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1320}
1321
1323 // For an implicit class member access, transform the result into a member
1324 // access expression if necessary.
1325 auto *ULE = cast<UnresolvedLookupExpr>(E);
1326 if ((*ULE->decls_begin())->isCXXClassMember()) {
1327 CXXScopeSpec SS;
1328 SS.Adopt(ULE->getQualifierLoc());
1329
1330 // Reconstruct the lookup result.
1331 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1333 Result.setNamingClass(ULE->getNamingClass());
1334 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1335 Result.addDecl(*I, I.getAccess());
1336 Result.resolveKind();
1338 nullptr, S);
1339 }
1340
1341 // Otherwise, this is already in the form we needed, and no further checks
1342 // are necessary.
1343 return ULE;
1344}
1345
1348 auto *TD = Name.getAsTemplateDecl();
1349 if (!TD)
1351 if (isa<ClassTemplateDecl>(TD))
1353 if (isa<FunctionTemplateDecl>(TD))
1355 if (isa<VarTemplateDecl>(TD))
1357 if (isa<TypeAliasTemplateDecl>(TD))
1359 if (isa<TemplateTemplateParmDecl>(TD))
1361 if (isa<ConceptDecl>(TD))
1364}
1365
1367 assert(DC->getLexicalParent() == CurContext &&
1368 "The next DeclContext should be lexically contained in the current one.");
1369 CurContext = DC;
1370 S->setEntity(DC);
1371}
1372
1374 assert(CurContext && "DeclContext imbalance!");
1375
1377 assert(CurContext && "Popped translation unit!");
1378}
1379
1381 Decl *D) {
1382 // Unlike PushDeclContext, the context to which we return is not necessarily
1383 // the containing DC of TD, because the new context will be some pre-existing
1384 // TagDecl definition instead of a fresh one.
1385 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1386 CurContext = cast<TagDecl>(D)->getDefinition();
1387 assert(CurContext && "skipping definition of undefined tag");
1388 // Start lookups from the parent of the current context; we don't want to look
1389 // into the pre-existing complete definition.
1390 S->setEntity(CurContext->getLookupParent());
1391 return Result;
1392}
1393
1395 CurContext = static_cast<decltype(CurContext)>(Context);
1396}
1397
1399 // C++0x [basic.lookup.unqual]p13:
1400 // A name used in the definition of a static data member of class
1401 // X (after the qualified-id of the static member) is looked up as
1402 // if the name was used in a member function of X.
1403 // C++0x [basic.lookup.unqual]p14:
1404 // If a variable member of a namespace is defined outside of the
1405 // scope of its namespace then any name used in the definition of
1406 // the variable member (after the declarator-id) is looked up as
1407 // if the definition of the variable member occurred in its
1408 // namespace.
1409 // Both of these imply that we should push a scope whose context
1410 // is the semantic context of the declaration. We can't use
1411 // PushDeclContext here because that context is not necessarily
1412 // lexically contained in the current context. Fortunately,
1413 // the containing scope should have the appropriate information.
1414
1415 assert(!S->getEntity() && "scope already has entity");
1416
1417#ifndef NDEBUG
1418 Scope *Ancestor = S->getParent();
1419 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1420 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1421#endif
1422
1423 CurContext = DC;
1424 S->setEntity(DC);
1425
1426 if (S->getParent()->isTemplateParamScope()) {
1427 // Also set the corresponding entities for all immediately-enclosing
1428 // template parameter scopes.
1429 EnterTemplatedContext(S->getParent(), DC);
1430 }
1431}
1432
1434 assert(S->getEntity() == CurContext && "Context imbalance!");
1435
1436 // Switch back to the lexical context. The safety of this is
1437 // enforced by an assert in EnterDeclaratorContext.
1438 Scope *Ancestor = S->getParent();
1439 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1440 CurContext = Ancestor->getEntity();
1441
1442 // We don't need to do anything with the scope, which is going to
1443 // disappear.
1444}
1445
1447 assert(S->isTemplateParamScope() &&
1448 "expected to be initializing a template parameter scope");
1449
1450 // C++20 [temp.local]p7:
1451 // In the definition of a member of a class template that appears outside
1452 // of the class template definition, the name of a member of the class
1453 // template hides the name of a template-parameter of any enclosing class
1454 // templates (but not a template-parameter of the member if the member is a
1455 // class or function template).
1456 // C++20 [temp.local]p9:
1457 // In the definition of a class template or in the definition of a member
1458 // of such a template that appears outside of the template definition, for
1459 // each non-dependent base class (13.8.2.1), if the name of the base class
1460 // or the name of a member of the base class is the same as the name of a
1461 // template-parameter, the base class name or member name hides the
1462 // template-parameter name (6.4.10).
1463 //
1464 // This means that a template parameter scope should be searched immediately
1465 // after searching the DeclContext for which it is a template parameter
1466 // scope. For example, for
1467 // template<typename T> template<typename U> template<typename V>
1468 // void N::A<T>::B<U>::f(...)
1469 // we search V then B<U> (and base classes) then U then A<T> (and base
1470 // classes) then T then N then ::.
1471 unsigned ScopeDepth = getTemplateDepth(S);
1472 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1473 DeclContext *SearchDCAfterScope = DC;
1474 for (; DC; DC = DC->getLookupParent()) {
1475 if (const TemplateParameterList *TPL =
1476 cast<Decl>(DC)->getDescribedTemplateParams()) {
1477 unsigned DCDepth = TPL->getDepth() + 1;
1478 if (DCDepth > ScopeDepth)
1479 continue;
1480 if (ScopeDepth == DCDepth)
1481 SearchDCAfterScope = DC = DC->getLookupParent();
1482 break;
1483 }
1484 }
1485 S->setLookupEntity(SearchDCAfterScope);
1486 }
1487}
1488
1490 // We assume that the caller has already called
1491 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1492 FunctionDecl *FD = D->getAsFunction();
1493 if (!FD)
1494 return;
1495
1496 // Same implementation as PushDeclContext, but enters the context
1497 // from the lexical parent, rather than the top-level class.
1498 assert(CurContext == FD->getLexicalParent() &&
1499 "The next DeclContext should be lexically contained in the current one.");
1500 CurContext = FD;
1501 S->setEntity(CurContext);
1502
1503 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1504 ParmVarDecl *Param = FD->getParamDecl(P);
1505 // If the parameter has an identifier, then add it to the scope
1506 if (Param->getIdentifier()) {
1507 S->AddDecl(Param);
1508 IdResolver.AddDecl(Param);
1509 }
1510 }
1511}
1512
1514 // Same implementation as PopDeclContext, but returns to the lexical parent,
1515 // rather than the top-level class.
1516 assert(CurContext && "DeclContext imbalance!");
1518 assert(CurContext && "Popped translation unit!");
1519}
1520
1521/// Determine whether overloading is allowed for a new function
1522/// declaration considering prior declarations of the same name.
1523///
1524/// This routine determines whether overloading is possible, not
1525/// whether a new declaration actually overloads a previous one.
1526/// It will return true in C++ (where overloads are always permitted)
1527/// or, as a C extension, when either the new declaration or a
1528/// previous one is declared with the 'overloadable' attribute.
1530 ASTContext &Context,
1531 const FunctionDecl *New) {
1532 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1533 return true;
1534
1535 // Multiversion function declarations are not overloads in the
1536 // usual sense of that term, but lookup will report that an
1537 // overload set was found if more than one multiversion function
1538 // declaration is present for the same name. It is therefore
1539 // inadequate to assume that some prior declaration(s) had
1540 // the overloadable attribute; checking is required. Since one
1541 // declaration is permitted to omit the attribute, it is necessary
1542 // to check at least two; hence the 'any_of' check below. Note that
1543 // the overloadable attribute is implicitly added to declarations
1544 // that were required to have it but did not.
1545 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1546 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1547 return ND->hasAttr<OverloadableAttr>();
1548 });
1549 } else if (Previous.getResultKind() == LookupResultKind::Found)
1550 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1551
1552 return false;
1553}
1554
1555void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1556 // Move up the scope chain until we find the nearest enclosing
1557 // non-transparent context. The declaration will be introduced into this
1558 // scope.
1559 while (S->getEntity() && S->getEntity()->isTransparentContext())
1560 S = S->getParent();
1561
1562 // Add scoped declarations into their context, so that they can be
1563 // found later. Declarations without a context won't be inserted
1564 // into any context.
1565 if (AddToContext)
1567
1568 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1569 // are function-local declarations.
1570 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1571 return;
1572
1573 // Template instantiations should also not be pushed into scope.
1574 if (isa<FunctionDecl>(D) &&
1575 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1576 return;
1577
1578 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1579 S->AddDecl(D);
1580 return;
1581 }
1582 // If this replaces anything in the current scope,
1583 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1584 IEnd = IdResolver.end();
1585 for (; I != IEnd; ++I) {
1586 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1587 S->RemoveDecl(*I);
1589
1590 // Should only need to replace one decl.
1591 break;
1592 }
1593 }
1594
1595 S->AddDecl(D);
1596
1597 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1598 // Implicitly-generated labels may end up getting generated in an order that
1599 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1600 // the label at the appropriate place in the identifier chain.
1601 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1602 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1603 if (IDC == CurContext) {
1604 if (!S->isDeclScope(*I))
1605 continue;
1606 } else if (IDC->Encloses(CurContext))
1607 break;
1608 }
1609
1611 } else {
1613 }
1615}
1616
1618 bool AllowInlineNamespace) const {
1619 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1620}
1621
1623 DeclContext *TargetDC = DC->getPrimaryContext();
1624 do {
1625 if (DeclContext *ScopeDC = S->getEntity())
1626 if (ScopeDC->getPrimaryContext() == TargetDC)
1627 return S;
1628 } while ((S = S->getParent()));
1629
1630 return nullptr;
1631}
1632
1634 DeclContext*,
1635 ASTContext&);
1636
1638 bool ConsiderLinkage,
1639 bool AllowInlineNamespace) {
1641 while (F.hasNext()) {
1642 NamedDecl *D = F.next();
1643
1644 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1645 continue;
1646
1647 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1648 continue;
1649
1650 F.erase();
1651 }
1652
1653 F.done();
1654}
1655
1657 // [module.interface]p7:
1658 // A declaration is attached to a module as follows:
1659 // - If the declaration is a non-dependent friend declaration that nominates a
1660 // function with a declarator-id that is a qualified-id or template-id or that
1661 // nominates a class other than with an elaborated-type-specifier with neither
1662 // a nested-name-specifier nor a simple-template-id, it is attached to the
1663 // module to which the friend is attached ([basic.link]).
1664 if (New->getFriendObjectKind() &&
1665 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1666 New->setLocalOwningModule(Old->getOwningModule());
1668 return false;
1669 }
1670
1671 Module *NewM = New->getOwningModule();
1672 Module *OldM = Old->getOwningModule();
1673
1674 if (NewM && NewM->isPrivateModule())
1675 NewM = NewM->Parent;
1676 if (OldM && OldM->isPrivateModule())
1677 OldM = OldM->Parent;
1678
1679 if (NewM == OldM)
1680 return false;
1681
1682 if (NewM && OldM) {
1683 // A module implementation unit has visibility of the decls in its
1684 // implicitly imported interface.
1685 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1686 return false;
1687
1688 // Partitions are part of the module, but a partition could import another
1689 // module, so verify that the PMIs agree.
1690 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1691 getASTContext().isInSameModule(NewM, OldM))
1692 return false;
1693 }
1694
1695 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1696 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1697 if (NewIsModuleInterface || OldIsModuleInterface) {
1698 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1699 // if a declaration of D [...] appears in the purview of a module, all
1700 // other such declarations shall appear in the purview of the same module
1701 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1702 << New
1703 << NewIsModuleInterface
1704 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1705 << OldIsModuleInterface
1706 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1707 Diag(Old->getLocation(), diag::note_previous_declaration);
1708 New->setInvalidDecl();
1709 return true;
1710 }
1711
1712 return false;
1713}
1714
1716 // [module.interface]p1:
1717 // An export-declaration shall inhabit a namespace scope.
1718 //
1719 // So it is meaningless to talk about redeclaration which is not at namespace
1720 // scope.
1721 if (!New->getLexicalDeclContext()
1722 ->getNonTransparentContext()
1723 ->isFileContext() ||
1724 !Old->getLexicalDeclContext()
1726 ->isFileContext())
1727 return false;
1728
1729 bool IsNewExported = New->isInExportDeclContext();
1730 bool IsOldExported = Old->isInExportDeclContext();
1731
1732 // It should be irrevelant if both of them are not exported.
1733 if (!IsNewExported && !IsOldExported)
1734 return false;
1735
1736 if (IsOldExported)
1737 return false;
1738
1739 // If the Old declaration are not attached to named modules
1740 // and the New declaration are attached to global module.
1741 // It should be fine to allow the export since it doesn't change
1742 // the linkage of declarations. See
1743 // https://github.com/llvm/llvm-project/issues/98583 for details.
1744 if (!Old->isInNamedModule() && New->getOwningModule() &&
1745 New->getOwningModule()->isImplicitGlobalModule())
1746 return false;
1747
1748 assert(IsNewExported);
1749
1750 auto Lk = Old->getFormalLinkage();
1751 int S = 0;
1752 if (Lk == Linkage::Internal)
1753 S = 1;
1754 else if (Lk == Linkage::Module)
1755 S = 2;
1756 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1757 Diag(Old->getLocation(), diag::note_previous_declaration);
1758 return true;
1759}
1760
1763 return true;
1764
1766 return true;
1767
1768 return false;
1769}
1770
1772 const NamedDecl *Old) const {
1773 assert(getASTContext().isSameEntity(New, Old) &&
1774 "New and Old are not the same definition, we should diagnostic it "
1775 "immediately instead of checking it.");
1776 assert(const_cast<Sema *>(this)->isReachable(New) &&
1777 const_cast<Sema *>(this)->isReachable(Old) &&
1778 "We shouldn't see unreachable definitions here.");
1779
1780 Module *NewM = New->getOwningModule();
1781 Module *OldM = Old->getOwningModule();
1782
1783 // We only checks for named modules here. The header like modules is skipped.
1784 // FIXME: This is not right if we import the header like modules in the module
1785 // purview.
1786 //
1787 // For example, assuming "header.h" provides definition for `D`.
1788 // ```C++
1789 // //--- M.cppm
1790 // export module M;
1791 // import "header.h"; // or #include "header.h" but import it by clang modules
1792 // actually.
1793 //
1794 // //--- Use.cpp
1795 // import M;
1796 // import "header.h"; // or uses clang modules.
1797 // ```
1798 //
1799 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1800 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1801 // reject it. But the current implementation couldn't detect the case since we
1802 // don't record the information about the importee modules.
1803 //
1804 // But this might not be painful in practice. Since the design of C++20 Named
1805 // Modules suggests us to use headers in global module fragment instead of
1806 // module purview.
1807 if (NewM && NewM->isHeaderLikeModule())
1808 NewM = nullptr;
1809 if (OldM && OldM->isHeaderLikeModule())
1810 OldM = nullptr;
1811
1812 if (!NewM && !OldM)
1813 return true;
1814
1815 // [basic.def.odr]p14.3
1816 // Each such definition shall not be attached to a named module
1817 // ([module.unit]).
1818 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1819 return true;
1820
1821 // Then New and Old lives in the same TU if their share one same module unit.
1822 if (NewM)
1823 NewM = NewM->getTopLevelModule();
1824 if (OldM)
1825 OldM = OldM->getTopLevelModule();
1826 return OldM == NewM;
1827}
1828
1830 if (D->getDeclContext()->isFileContext())
1831 return false;
1832
1833 return isa<UsingShadowDecl>(D) ||
1834 isa<UnresolvedUsingTypenameDecl>(D) ||
1835 isa<UnresolvedUsingValueDecl>(D);
1836}
1837
1838/// Removes using shadow declarations not at class scope from the lookup
1839/// results.
1842 while (F.hasNext())
1844 F.erase();
1845
1846 F.done();
1847}
1848
1849/// Check for this common pattern:
1850/// @code
1851/// class S {
1852/// S(const S&); // DO NOT IMPLEMENT
1853/// void operator=(const S&); // DO NOT IMPLEMENT
1854/// };
1855/// @endcode
1857 // FIXME: Should check for private access too but access is set after we get
1858 // the decl here.
1859 if (D->doesThisDeclarationHaveABody())
1860 return false;
1861
1862 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1863 return CD->isCopyConstructor();
1864 return D->isCopyAssignmentOperator();
1865}
1866
1867bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1868 const DeclContext *DC = D->getDeclContext();
1869 while (!DC->isTranslationUnit()) {
1870 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1871 if (!RD->hasNameForLinkage())
1872 return true;
1873 }
1874 DC = DC->getParent();
1875 }
1876
1877 return !D->isExternallyVisible();
1878}
1879
1880// FIXME: This needs to be refactored; some other isInMainFile users want
1881// these semantics.
1882static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1884 return false;
1885 return S.SourceMgr.isInMainFile(Loc);
1886}
1887
1889 assert(D);
1890
1891 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1892 return false;
1893
1894 // Ignore all entities declared within templates, and out-of-line definitions
1895 // of members of class templates.
1898 return false;
1899
1900 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1901 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1902 return false;
1903 // A non-out-of-line declaration of a member specialization was implicitly
1904 // instantiated; it's the out-of-line declaration that we're interested in.
1905 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1906 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1907 return false;
1908
1909 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1910 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1911 return false;
1912 } else {
1913 // 'static inline' functions are defined in headers; don't warn.
1914 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1915 return false;
1916 }
1917
1918 if (FD->doesThisDeclarationHaveABody() &&
1920 return false;
1921 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1922 // Constants and utility variables are defined in headers with internal
1923 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1924 // like "inline".)
1925 if (!isMainFileLoc(*this, VD->getLocation()))
1926 return false;
1927
1928 if (Context.DeclMustBeEmitted(VD))
1929 return false;
1930
1931 if (VD->isStaticDataMember() &&
1932 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1933 return false;
1934 if (VD->isStaticDataMember() &&
1935 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1936 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1937 return false;
1938
1939 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1940 return false;
1941 } else {
1942 return false;
1943 }
1944
1945 // Only warn for unused decls internal to the translation unit.
1946 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1947 // for inline functions defined in the main source file, for instance.
1948 return mightHaveNonExternalLinkage(D);
1949}
1950
1952 if (!D)
1953 return;
1954
1955 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1956 const FunctionDecl *First = FD->getFirstDecl();
1958 return; // First should already be in the vector.
1959 }
1960
1961 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1962 const VarDecl *First = VD->getFirstDecl();
1964 return; // First should already be in the vector.
1965 }
1966
1969}
1970
1971static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1972 const NamedDecl *D) {
1973 if (D->isInvalidDecl())
1974 return false;
1975
1976 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1977 // For a decomposition declaration, warn if none of the bindings are
1978 // referenced, instead of if the variable itself is referenced (which
1979 // it is, by the bindings' expressions).
1980 bool IsAllIgnored = true;
1981 for (const auto *BD : DD->bindings()) {
1982 if (BD->isReferenced())
1983 return false;
1984 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
1985 BD->hasAttr<UnusedAttr>());
1986 }
1987 if (IsAllIgnored)
1988 return false;
1989 } else if (!D->getDeclName()) {
1990 return false;
1991 } else if (D->isReferenced() || D->isUsed()) {
1992 return false;
1993 }
1994
1995 if (D->isPlaceholderVar(LangOpts))
1996 return false;
1997
1998 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1999 D->hasAttr<CleanupAttr>())
2000 return false;
2001
2002 if (isa<LabelDecl>(D))
2003 return true;
2004
2005 // Except for labels, we only care about unused decls that are local to
2006 // functions.
2007 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2008 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2009 // For dependent types, the diagnostic is deferred.
2010 WithinFunction =
2011 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2012 if (!WithinFunction)
2013 return false;
2014
2015 if (isa<TypedefNameDecl>(D))
2016 return true;
2017
2018 // White-list anything that isn't a local variable.
2019 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2020 return false;
2021
2022 // Types of valid local variables should be complete, so this should succeed.
2023 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2024
2025 const Expr *Init = VD->getInit();
2026 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2027 Init = Cleanups->getSubExpr();
2028
2029 const auto *Ty = VD->getType().getTypePtr();
2030
2031 // Only look at the outermost level of typedef.
2032 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2033 // Allow anything marked with __attribute__((unused)).
2034 if (TT->getDecl()->hasAttr<UnusedAttr>())
2035 return false;
2036 }
2037
2038 // Warn for reference variables whose initializtion performs lifetime
2039 // extension.
2040 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2041 MTE && MTE->getExtendingDecl()) {
2042 Ty = VD->getType().getNonReferenceType().getTypePtr();
2043 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2044 }
2045
2046 // If we failed to complete the type for some reason, or if the type is
2047 // dependent, don't diagnose the variable.
2048 if (Ty->isIncompleteType() || Ty->isDependentType())
2049 return false;
2050
2051 // Look at the element type to ensure that the warning behaviour is
2052 // consistent for both scalars and arrays.
2053 Ty = Ty->getBaseElementTypeUnsafe();
2054
2055 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2056 if (Tag->hasAttr<UnusedAttr>())
2057 return false;
2058
2059 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2060 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2061 return false;
2062
2063 if (Init) {
2064 const auto *Construct =
2065 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2066 if (Construct && !Construct->isElidable()) {
2067 const CXXConstructorDecl *CD = Construct->getConstructor();
2068 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2069 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2070 return false;
2071 }
2072
2073 // Suppress the warning if we don't know how this is constructed, and
2074 // it could possibly be non-trivial constructor.
2075 if (Init->isTypeDependent()) {
2076 for (const CXXConstructorDecl *Ctor : RD->ctors())
2077 if (!Ctor->isTrivial())
2078 return false;
2079 }
2080
2081 // Suppress the warning if the constructor is unresolved because
2082 // its arguments are dependent.
2083 if (isa<CXXUnresolvedConstructExpr>(Init))
2084 return false;
2085 }
2086 }
2087 }
2088
2089 // TODO: __attribute__((unused)) templates?
2090 }
2091
2092 return true;
2093}
2094
2096 FixItHint &Hint) {
2097 if (isa<LabelDecl>(D)) {
2099 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2100 /*SkipTrailingWhitespaceAndNewline=*/false);
2101 if (AfterColon.isInvalid())
2102 return;
2105 }
2106}
2107
2110 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2111}
2112
2114 DiagReceiverTy DiagReceiver) {
2115 if (D->isDependentType())
2116 return;
2117
2118 for (auto *TmpD : D->decls()) {
2119 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2120 DiagnoseUnusedDecl(T, DiagReceiver);
2121 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2122 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2123 }
2124}
2125
2128 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2129}
2130
2133 return;
2134
2135 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2136 // typedefs can be referenced later on, so the diagnostics are emitted
2137 // at end-of-translation-unit.
2139 return;
2140 }
2141
2142 FixItHint Hint;
2144
2145 unsigned DiagID;
2146 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2147 DiagID = diag::warn_unused_exception_param;
2148 else if (isa<LabelDecl>(D))
2149 DiagID = diag::warn_unused_label;
2150 else
2151 DiagID = diag::warn_unused_variable;
2152
2153 SourceLocation DiagLoc = D->getLocation();
2154 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2155}
2156
2158 DiagReceiverTy DiagReceiver) {
2159 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2160 // it's not really unused.
2161 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2162 return;
2163
2164 // In C++, `_` variables behave as if they were maybe_unused
2165 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2166 return;
2167
2168 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2169
2170 if (Ty->isReferenceType() || Ty->isDependentType())
2171 return;
2172
2173 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2174 if (Tag->hasAttr<UnusedAttr>())
2175 return;
2176 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2177 // mimic gcc's behavior.
2178 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2179 RD && !RD->hasAttr<WarnUnusedAttr>())
2180 return;
2181 }
2182
2183 // Don't warn about __block Objective-C pointer variables, as they might
2184 // be assigned in the block but not used elsewhere for the purpose of lifetime
2185 // extension.
2186 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2187 return;
2188
2189 // Don't warn about Objective-C pointer variables with precise lifetime
2190 // semantics; they can be used to ensure ARC releases the object at a known
2191 // time, which may mean assignment but no other references.
2192 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2193 return;
2194
2195 auto iter = RefsMinusAssignments.find(VD);
2196 if (iter == RefsMinusAssignments.end())
2197 return;
2198
2199 assert(iter->getSecond() >= 0 &&
2200 "Found a negative number of references to a VarDecl");
2201 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2202 // Assume the given VarDecl is "used" if its ref count stored in
2203 // `RefMinusAssignments` is positive, with one exception.
2204 //
2205 // For a C++ variable whose decl (with initializer) entirely consist the
2206 // condition expression of a if/while/for construct,
2207 // Clang creates a DeclRefExpr for the condition expression rather than a
2208 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2209 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2210 // used in the body of the if/while/for construct.
2211 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2212 if (!UnusedCXXCondDecl)
2213 return;
2214 }
2215
2216 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2217 : diag::warn_unused_but_set_variable;
2218 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2219}
2220
2222 Sema::DiagReceiverTy DiagReceiver) {
2223 // Verify that we have no forward references left. If so, there was a goto
2224 // or address of a label taken, but no definition of it. Label fwd
2225 // definitions are indicated with a null substmt which is also not a resolved
2226 // MS inline assembly label name.
2227 bool Diagnose = false;
2228 if (L->isMSAsmLabel())
2229 Diagnose = !L->isResolvedMSAsmLabel();
2230 else
2231 Diagnose = L->getStmt() == nullptr;
2232 if (Diagnose)
2233 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2234 << L);
2235}
2236
2238 S->applyNRVO();
2239
2240 if (S->decl_empty()) return;
2241 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2242 "Scope shouldn't contain decls!");
2243
2244 /// We visit the decls in non-deterministic order, but we want diagnostics
2245 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2246 /// and sort the diagnostics before emitting them, after we visited all decls.
2247 struct LocAndDiag {
2249 std::optional<SourceLocation> PreviousDeclLoc;
2251 };
2253 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2254 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2255 };
2256 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2257 SourceLocation PreviousDeclLoc,
2258 PartialDiagnostic PD) {
2259 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2260 };
2261
2262 for (auto *TmpD : S->decls()) {
2263 assert(TmpD && "This decl didn't get pushed??");
2264
2265 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2266 NamedDecl *D = cast<NamedDecl>(TmpD);
2267
2268 // Diagnose unused variables in this scope.
2269 if (!S->hasUnrecoverableErrorOccurred()) {
2270 DiagnoseUnusedDecl(D, addDiag);
2271 if (const auto *RD = dyn_cast<RecordDecl>(D))
2272 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2273 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2274 DiagnoseUnusedButSetDecl(VD, addDiag);
2275 RefsMinusAssignments.erase(VD);
2276 }
2277 }
2278
2279 if (!D->getDeclName()) continue;
2280
2281 // If this was a forward reference to a label, verify it was defined.
2282 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2283 CheckPoppedLabel(LD, *this, addDiag);
2284
2285 // Partial translation units that are created in incremental processing must
2286 // not clean up the IdResolver because PTUs should take into account the
2287 // declarations that came from previous PTUs.
2291
2292 // Warn on it if we are shadowing a declaration.
2293 auto ShadowI = ShadowingDecls.find(D);
2294 if (ShadowI != ShadowingDecls.end()) {
2295 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2296 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2297 PDiag(diag::warn_ctor_parm_shadows_field)
2298 << D << FD << FD->getParent());
2299 }
2300 ShadowingDecls.erase(ShadowI);
2301 }
2302 }
2303
2304 llvm::sort(DeclDiags,
2305 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2306 // The particular order for diagnostics is not important, as long
2307 // as the order is deterministic. Using the raw location is going
2308 // to generally be in source order unless there are macro
2309 // expansions involved.
2310 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2311 });
2312 for (const LocAndDiag &D : DeclDiags) {
2313 Diag(D.Loc, D.PD);
2314 if (D.PreviousDeclLoc)
2315 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2316 }
2317}
2318
2320 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2321 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2322 (S->isClassScope() && !getLangOpts().CPlusPlus))
2323 S = S->getParent();
2324 return S;
2325}
2326
2327static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2329 switch (Error) {
2331 return "";
2333 return BuiltinInfo.getHeaderName(ID);
2335 return "stdio.h";
2337 return "setjmp.h";
2339 return "ucontext.h";
2340 }
2341 llvm_unreachable("unhandled error kind");
2342}
2343
2345 unsigned ID, SourceLocation Loc) {
2347
2348 if (getLangOpts().CPlusPlus) {
2351 CLinkageDecl->setImplicit();
2352 Parent->addDecl(CLinkageDecl);
2353 Parent = CLinkageDecl;
2354 }
2355
2358 assert(getLangOpts().CPlusPlus20 &&
2359 "consteval builtins should only be available in C++20 mode");
2360 ConstexprKind = ConstexprSpecKind::Consteval;
2361 }
2362
2364 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2365 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2366 Type->isFunctionProtoType(), ConstexprKind);
2367 New->setImplicit();
2368 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2369
2370 // Create Decl objects for each parameter, adding them to the
2371 // FunctionDecl.
2372 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2374 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2376 Context, New, SourceLocation(), SourceLocation(), nullptr,
2377 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2378 parm->setScopeInfo(0, i);
2379 Params.push_back(parm);
2380 }
2381 New->setParams(Params);
2382 }
2383
2385 return New;
2386}
2387
2389 Scope *S, bool ForRedeclaration,
2392
2394 QualType R = Context.GetBuiltinType(ID, Error);
2395 if (Error) {
2396 if (!ForRedeclaration)
2397 return nullptr;
2398
2399 // If we have a builtin without an associated type we should not emit a
2400 // warning when we were not able to find a type for it.
2401 if (Error == ASTContext::GE_Missing_type ||
2403 return nullptr;
2404
2405 // If we could not find a type for setjmp it is because the jmp_buf type was
2406 // not defined prior to the setjmp declaration.
2407 if (Error == ASTContext::GE_Missing_setjmp) {
2408 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2410 return nullptr;
2411 }
2412
2413 // Generally, we emit a warning that the declaration requires the
2414 // appropriate header.
2415 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2416 << getHeaderName(Context.BuiltinInfo, ID, Error)
2418 return nullptr;
2419 }
2420
2421 if (!ForRedeclaration &&
2424 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2425 : diag::ext_implicit_lib_function_decl)
2426 << Context.BuiltinInfo.getName(ID) << R;
2427 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2428 Diag(Loc, diag::note_include_header_or_declare)
2429 << Header << Context.BuiltinInfo.getName(ID);
2430 }
2431
2432 if (R.isNull())
2433 return nullptr;
2434
2435 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2437
2438 // TUScope is the translation-unit scope to insert this function into.
2439 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2440 // relate Scopes to DeclContexts, and probably eliminate CurContext
2441 // entirely, but we're not there yet.
2442 DeclContext *SavedContext = CurContext;
2443 CurContext = New->getDeclContext();
2445 CurContext = SavedContext;
2446 return New;
2447}
2448
2449/// Typedef declarations don't have linkage, but they still denote the same
2450/// entity if their types are the same.
2451/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2452/// isSameEntity.
2453static void
2456 // This is only interesting when modules are enabled.
2457 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2458 return;
2459
2460 // Empty sets are uninteresting.
2461 if (Previous.empty())
2462 return;
2463
2464 LookupResult::Filter Filter = Previous.makeFilter();
2465 while (Filter.hasNext()) {
2466 NamedDecl *Old = Filter.next();
2467
2468 // Non-hidden declarations are never ignored.
2469 if (S.isVisible(Old))
2470 continue;
2471
2472 // Declarations of the same entity are not ignored, even if they have
2473 // different linkages.
2474 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2475 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2476 Decl->getUnderlyingType()))
2477 continue;
2478
2479 // If both declarations give a tag declaration a typedef name for linkage
2480 // purposes, then they declare the same entity.
2481 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2482 Decl->getAnonDeclWithTypedefName())
2483 continue;
2484 }
2485
2486 Filter.erase();
2487 }
2488
2489 Filter.done();
2490}
2491
2493 QualType OldType;
2494 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2495 OldType = OldTypedef->getUnderlyingType();
2496 else
2497 OldType = Context.getTypeDeclType(Old);
2498 QualType NewType = New->getUnderlyingType();
2499
2500 if (NewType->isVariablyModifiedType()) {
2501 // Must not redefine a typedef with a variably-modified type.
2502 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2503 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2504 << Kind << NewType;
2505 if (Old->getLocation().isValid())
2506 notePreviousDefinition(Old, New->getLocation());
2507 New->setInvalidDecl();
2508 return true;
2509 }
2510
2511 if (OldType != NewType &&
2512 !OldType->isDependentType() &&
2513 !NewType->isDependentType() &&
2514 !Context.hasSameType(OldType, NewType)) {
2515 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2516 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2517 << Kind << NewType << OldType;
2518 if (Old->getLocation().isValid())
2519 notePreviousDefinition(Old, New->getLocation());
2520 New->setInvalidDecl();
2521 return true;
2522 }
2523 return false;
2524}
2525
2527 LookupResult &OldDecls) {
2528 // If the new decl is known invalid already, don't bother doing any
2529 // merging checks.
2530 if (New->isInvalidDecl()) return;
2531
2532 // Allow multiple definitions for ObjC built-in typedefs.
2533 // FIXME: Verify the underlying types are equivalent!
2534 if (getLangOpts().ObjC) {
2535 const IdentifierInfo *TypeID = New->getIdentifier();
2536 switch (TypeID->getLength()) {
2537 default: break;
2538 case 2:
2539 {
2540 if (!TypeID->isStr("id"))
2541 break;
2542 QualType T = New->getUnderlyingType();
2543 if (!T->isPointerType())
2544 break;
2545 if (!T->isVoidPointerType()) {
2547 if (!PT->isStructureType())
2548 break;
2549 }
2551 // Install the built-in type for 'id', ignoring the current definition.
2552 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2554 return;
2555 }
2556 case 5:
2557 if (!TypeID->isStr("Class"))
2558 break;
2559 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2560 // Install the built-in type for 'Class', ignoring the current definition.
2561 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2563 return;
2564 case 3:
2565 if (!TypeID->isStr("SEL"))
2566 break;
2567 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2568 // Install the built-in type for 'SEL', ignoring the current definition.
2569 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2571 return;
2572 }
2573 // Fall through - the typedef name was not a builtin type.
2574 }
2575
2576 // Verify the old decl was also a type.
2577 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2578 if (!Old) {
2579 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2580 << New->getDeclName();
2581
2582 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2583 if (OldD->getLocation().isValid())
2584 notePreviousDefinition(OldD, New->getLocation());
2585
2586 return New->setInvalidDecl();
2587 }
2588
2589 // If the old declaration is invalid, just give up here.
2590 if (Old->isInvalidDecl())
2591 return New->setInvalidDecl();
2592
2593 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2594 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2595 auto *NewTag = New->getAnonDeclWithTypedefName();
2596 NamedDecl *Hidden = nullptr;
2597 if (OldTag && NewTag &&
2598 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2599 !hasVisibleDefinition(OldTag, &Hidden)) {
2600 // There is a definition of this tag, but it is not visible. Use it
2601 // instead of our tag.
2602 if (OldTD->isModed())
2603 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2604 OldTD->getUnderlyingType());
2605 else
2606 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2607
2608 // Make the old tag definition visible.
2610
2612 }
2613 }
2614
2615 // If the typedef types are not identical, reject them in all languages and
2616 // with any extensions enabled.
2617 if (isIncompatibleTypedef(Old, New))
2618 return;
2619
2620 // The types match. Link up the redeclaration chain and merge attributes if
2621 // the old declaration was a typedef.
2622 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2623 New->setPreviousDecl(Typedef);
2625 }
2626
2627 if (getLangOpts().MicrosoftExt)
2628 return;
2629
2630 if (getLangOpts().CPlusPlus) {
2631 // C++ [dcl.typedef]p2:
2632 // In a given non-class scope, a typedef specifier can be used to
2633 // redefine the name of any type declared in that scope to refer
2634 // to the type to which it already refers.
2635 if (!isa<CXXRecordDecl>(CurContext))
2636 return;
2637
2638 // C++0x [dcl.typedef]p4:
2639 // In a given class scope, a typedef specifier can be used to redefine
2640 // any class-name declared in that scope that is not also a typedef-name
2641 // to refer to the type to which it already refers.
2642 //
2643 // This wording came in via DR424, which was a correction to the
2644 // wording in DR56, which accidentally banned code like:
2645 //
2646 // struct S {
2647 // typedef struct A { } A;
2648 // };
2649 //
2650 // in the C++03 standard. We implement the C++0x semantics, which
2651 // allow the above but disallow
2652 //
2653 // struct S {
2654 // typedef int I;
2655 // typedef int I;
2656 // };
2657 //
2658 // since that was the intent of DR56.
2659 if (!isa<TypedefNameDecl>(Old))
2660 return;
2661
2662 Diag(New->getLocation(), diag::err_redefinition)
2663 << New->getDeclName();
2664 notePreviousDefinition(Old, New->getLocation());
2665 return New->setInvalidDecl();
2666 }
2667
2668 // Modules always permit redefinition of typedefs, as does C11.
2669 if (getLangOpts().Modules || getLangOpts().C11)
2670 return;
2671
2672 // If we have a redefinition of a typedef in C, emit a warning. This warning
2673 // is normally mapped to an error, but can be controlled with
2674 // -Wtypedef-redefinition. If either the original or the redefinition is
2675 // in a system header, don't emit this for compatibility with GCC.
2676 if (getDiagnostics().getSuppressSystemWarnings() &&
2677 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2678 (Old->isImplicit() ||
2680 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2681 return;
2682
2683 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2684 << New->getDeclName();
2685 notePreviousDefinition(Old, New->getLocation());
2686}
2687
2689 // If this was an unscoped enumeration, yank all of its enumerators
2690 // out of the scope.
2691 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2692 Scope *EnumScope = getNonFieldDeclScope(S);
2693 for (auto *ECD : ED->enumerators()) {
2694 assert(EnumScope->isDeclScope(ECD));
2695 EnumScope->RemoveDecl(ECD);
2697 }
2698 }
2699}
2700
2701/// DeclhasAttr - returns true if decl Declaration already has the target
2702/// attribute.
2703static bool DeclHasAttr(const Decl *D, const Attr *A) {
2704 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2705 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2706 for (const auto *i : D->attrs())
2707 if (i->getKind() == A->getKind()) {
2708 if (Ann) {
2709 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2710 return true;
2711 continue;
2712 }
2713 // FIXME: Don't hardcode this check
2714 if (OA && isa<OwnershipAttr>(i))
2715 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2716 return true;
2717 }
2718
2719 return false;
2720}
2721
2723 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2724 return VD->isThisDeclarationADefinition();
2725 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2726 return TD->isCompleteDefinition() || TD->isBeingDefined();
2727 return true;
2728}
2729
2730/// Merge alignment attributes from \p Old to \p New, taking into account the
2731/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2732///
2733/// \return \c true if any attributes were added to \p New.
2734static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2735 // Look for alignas attributes on Old, and pick out whichever attribute
2736 // specifies the strictest alignment requirement.
2737 AlignedAttr *OldAlignasAttr = nullptr;
2738 AlignedAttr *OldStrictestAlignAttr = nullptr;
2739 unsigned OldAlign = 0;
2740 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2741 // FIXME: We have no way of representing inherited dependent alignments
2742 // in a case like:
2743 // template<int A, int B> struct alignas(A) X;
2744 // template<int A, int B> struct alignas(B) X {};
2745 // For now, we just ignore any alignas attributes which are not on the
2746 // definition in such a case.
2747 if (I->isAlignmentDependent())
2748 return false;
2749
2750 if (I->isAlignas())
2751 OldAlignasAttr = I;
2752
2753 unsigned Align = I->getAlignment(S.Context);
2754 if (Align > OldAlign) {
2755 OldAlign = Align;
2756 OldStrictestAlignAttr = I;
2757 }
2758 }
2759
2760 // Look for alignas attributes on New.
2761 AlignedAttr *NewAlignasAttr = nullptr;
2762 unsigned NewAlign = 0;
2763 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2764 if (I->isAlignmentDependent())
2765 return false;
2766
2767 if (I->isAlignas())
2768 NewAlignasAttr = I;
2769
2770 unsigned Align = I->getAlignment(S.Context);
2771 if (Align > NewAlign)
2772 NewAlign = Align;
2773 }
2774
2775 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2776 // Both declarations have 'alignas' attributes. We require them to match.
2777 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2778 // fall short. (If two declarations both have alignas, they must both match
2779 // every definition, and so must match each other if there is a definition.)
2780
2781 // If either declaration only contains 'alignas(0)' specifiers, then it
2782 // specifies the natural alignment for the type.
2783 if (OldAlign == 0 || NewAlign == 0) {
2784 QualType Ty;
2785 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2786 Ty = VD->getType();
2787 else
2788 Ty = S.Context.getCanonicalTagType(cast<TagDecl>(New));
2789
2790 if (OldAlign == 0)
2791 OldAlign = S.Context.getTypeAlign(Ty);
2792 if (NewAlign == 0)
2793 NewAlign = S.Context.getTypeAlign(Ty);
2794 }
2795
2796 if (OldAlign != NewAlign) {
2797 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2800 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2801 }
2802 }
2803
2804 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2805 // C++11 [dcl.align]p6:
2806 // if any declaration of an entity has an alignment-specifier,
2807 // every defining declaration of that entity shall specify an
2808 // equivalent alignment.
2809 // C11 6.7.5/7:
2810 // If the definition of an object does not have an alignment
2811 // specifier, any other declaration of that object shall also
2812 // have no alignment specifier.
2813 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2814 << OldAlignasAttr;
2815 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2816 << OldAlignasAttr;
2817 }
2818
2819 bool AnyAdded = false;
2820
2821 // Ensure we have an attribute representing the strictest alignment.
2822 if (OldAlign > NewAlign) {
2823 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2824 Clone->setInherited(true);
2825 New->addAttr(Clone);
2826 AnyAdded = true;
2827 }
2828
2829 // Ensure we have an alignas attribute if the old declaration had one.
2830 if (OldAlignasAttr && !NewAlignasAttr &&
2831 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2832 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2833 Clone->setInherited(true);
2834 New->addAttr(Clone);
2835 AnyAdded = true;
2836 }
2837
2838 return AnyAdded;
2839}
2840
2841#define WANT_DECL_MERGE_LOGIC
2842#include "clang/Sema/AttrParsedAttrImpl.inc"
2843#undef WANT_DECL_MERGE_LOGIC
2844
2846 const InheritableAttr *Attr,
2848 // Diagnose any mutual exclusions between the attribute that we want to add
2849 // and attributes that already exist on the declaration.
2850 if (!DiagnoseMutualExclusions(S, D, Attr))
2851 return false;
2852
2853 // This function copies an attribute Attr from a previous declaration to the
2854 // new declaration D if the new declaration doesn't itself have that attribute
2855 // yet or if that attribute allows duplicates.
2856 // If you're adding a new attribute that requires logic different from
2857 // "use explicit attribute on decl if present, else use attribute from
2858 // previous decl", for example if the attribute needs to be consistent
2859 // between redeclarations, you need to call a custom merge function here.
2860 InheritableAttr *NewAttr = nullptr;
2861 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2862 NewAttr = S.mergeAvailabilityAttr(
2863 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2864 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2865 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2866 AA->getPriority(), AA->getEnvironment());
2867 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2868 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2869 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2870 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2871 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2872 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2873 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2874 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2875 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2876 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2877 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2878 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2879 FA->getFirstArg());
2880 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2881 NewAttr = S.mergeFormatMatchesAttr(
2882 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2883 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2884 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2885 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2886 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2887 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2888 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2889 IA->getInheritanceModel());
2890 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2891 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2892 &S.Context.Idents.get(AA->getSpelling()));
2893 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2894 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2895 isa<CUDAGlobalAttr>(Attr))) {
2896 // CUDA target attributes are part of function signature for
2897 // overloading purposes and must not be merged.
2898 return false;
2899 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2900 NewAttr = S.mergeMinSizeAttr(D, *MA);
2901 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2902 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2903 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2904 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2905 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2906 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2907 else if (isa<AlignedAttr>(Attr))
2908 // AlignedAttrs are handled separately, because we need to handle all
2909 // such attributes on a declaration at the same time.
2910 NewAttr = nullptr;
2911 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2915 NewAttr = nullptr;
2916 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2917 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2918 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2919 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2920 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2921 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2922 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2923 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2924 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2925 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2926 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2927 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2928 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2929 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2930 NT->getZ());
2931 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2932 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2933 WS->getPreferred(),
2934 WS->getSpelledArgsCount());
2935 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
2936 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
2937 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2938 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2939 else if (isa<SuppressAttr>(Attr))
2940 // Do nothing. Each redeclaration should be suppressed separately.
2941 NewAttr = nullptr;
2942 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
2943 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
2944 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2945 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2946
2947 if (NewAttr) {
2948 NewAttr->setInherited(true);
2949 D->addAttr(NewAttr);
2950 if (isa<MSInheritanceAttr>(NewAttr))
2951 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2952 return true;
2953 }
2954
2955 return false;
2956}
2957
2958static const NamedDecl *getDefinition(const Decl *D) {
2959 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
2960 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
2961 return Def;
2962 return nullptr;
2963 }
2964 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2965 const VarDecl *Def = VD->getDefinition();
2966 if (Def)
2967 return Def;
2968 return VD->getActingDefinition();
2969 }
2970 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2971 const FunctionDecl *Def = nullptr;
2972 if (FD->isDefined(Def, true))
2973 return Def;
2974 }
2975 return nullptr;
2976}
2977
2978static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2979 for (const auto *Attribute : D->attrs())
2980 if (Attribute->getKind() == Kind)
2981 return true;
2982 return false;
2983}
2984
2985/// checkNewAttributesAfterDef - If we already have a definition, check that
2986/// there are no new attributes in this declaration.
2987static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2988 if (!New->hasAttrs())
2989 return;
2990
2991 const NamedDecl *Def = getDefinition(Old);
2992 if (!Def || Def == New)
2993 return;
2994
2995 AttrVec &NewAttributes = New->getAttrs();
2996 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2997 Attr *NewAttribute = NewAttributes[I];
2998
2999 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3000 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3001 SkipBodyInfo SkipBody;
3002 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3003
3004 // If we're skipping this definition, drop the "alias" attribute.
3005 if (SkipBody.ShouldSkip) {
3006 NewAttributes.erase(NewAttributes.begin() + I);
3007 --E;
3008 continue;
3009 }
3010 } else {
3011 VarDecl *VD = cast<VarDecl>(New);
3012 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3014 ? diag::err_alias_after_tentative
3015 : diag::err_redefinition;
3016 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3017 if (Diag == diag::err_redefinition)
3018 S.notePreviousDefinition(Def, VD->getLocation());
3019 else
3020 S.Diag(Def->getLocation(), diag::note_previous_definition);
3021 VD->setInvalidDecl();
3022 }
3023 ++I;
3024 continue;
3025 }
3026
3027 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3028 // Tentative definitions are only interesting for the alias check above.
3029 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3030 ++I;
3031 continue;
3032 }
3033 }
3034
3035 if (hasAttribute(Def, NewAttribute->getKind())) {
3036 ++I;
3037 continue; // regular attr merging will take care of validating this.
3038 }
3039
3040 if (isa<C11NoReturnAttr>(NewAttribute)) {
3041 // C's _Noreturn is allowed to be added to a function after it is defined.
3042 ++I;
3043 continue;
3044 } else if (isa<UuidAttr>(NewAttribute)) {
3045 // msvc will allow a subsequent definition to add an uuid to a class
3046 ++I;
3047 continue;
3048 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3049 NewAttribute) &&
3050 NewAttribute->isStandardAttributeSyntax()) {
3051 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3052 // deprecated attribute can later be re-declared with the attribute and
3053 // vice-versa.
3054 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3055 // maybe_unused attribute can later be redeclared with the attribute and
3056 // vice versa.
3057 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3058 // nodiscard attribute can later be redeclared with the attribute and
3059 // vice-versa.
3060 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3061 ++I;
3062 continue;
3063 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3064 if (AA->isAlignas()) {
3065 // C++11 [dcl.align]p6:
3066 // if any declaration of an entity has an alignment-specifier,
3067 // every defining declaration of that entity shall specify an
3068 // equivalent alignment.
3069 // C11 6.7.5/7:
3070 // If the definition of an object does not have an alignment
3071 // specifier, any other declaration of that object shall also
3072 // have no alignment specifier.
3073 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3074 << AA;
3075 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3076 << AA;
3077 NewAttributes.erase(NewAttributes.begin() + I);
3078 --E;
3079 continue;
3080 }
3081 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3082 // If there is a C definition followed by a redeclaration with this
3083 // attribute then there are two different definitions. In C++, prefer the
3084 // standard diagnostics.
3085 if (!S.getLangOpts().CPlusPlus) {
3086 S.Diag(NewAttribute->getLocation(),
3087 diag::err_loader_uninitialized_redeclaration);
3088 S.Diag(Def->getLocation(), diag::note_previous_definition);
3089 NewAttributes.erase(NewAttributes.begin() + I);
3090 --E;
3091 continue;
3092 }
3093 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3094 cast<VarDecl>(New)->isInline() &&
3095 !cast<VarDecl>(New)->isInlineSpecified()) {
3096 // Don't warn about applying selectany to implicitly inline variables.
3097 // Older compilers and language modes would require the use of selectany
3098 // to make such variables inline, and it would have no effect if we
3099 // honored it.
3100 ++I;
3101 continue;
3102 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3103 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3104 // declarations after definitions.
3105 ++I;
3106 continue;
3107 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3108 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3109 // error since the definition will have already been created without
3110 // the semantic effects of the attribute having been applied.
3111 S.Diag(NewAttribute->getLocation(),
3112 diag::err_sycl_entry_point_after_definition)
3113 << NewAttribute;
3114 S.Diag(Def->getLocation(), diag::note_previous_definition);
3115 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3116 ++I;
3117 continue;
3118 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3119 // SYCLExternalAttr may be added after a definition.
3120 ++I;
3121 continue;
3122 }
3123
3124 S.Diag(NewAttribute->getLocation(),
3125 diag::warn_attribute_precede_definition);
3126 S.Diag(Def->getLocation(), diag::note_previous_definition);
3127 NewAttributes.erase(NewAttributes.begin() + I);
3128 --E;
3129 }
3130}
3131
3132static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3133 const ConstInitAttr *CIAttr,
3134 bool AttrBeforeInit) {
3135 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3136
3137 // Figure out a good way to write this specifier on the old declaration.
3138 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3139 // enough of the attribute list spelling information to extract that without
3140 // heroics.
3141 std::string SuitableSpelling;
3142 if (S.getLangOpts().CPlusPlus20)
3143 SuitableSpelling = std::string(
3144 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3145 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3146 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3147 InsertLoc, {tok::l_square, tok::l_square,
3148 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3149 S.PP.getIdentifierInfo("require_constant_initialization"),
3150 tok::r_square, tok::r_square}));
3151 if (SuitableSpelling.empty())
3152 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3153 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3154 S.PP.getIdentifierInfo("require_constant_initialization"),
3155 tok::r_paren, tok::r_paren}));
3156 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3157 SuitableSpelling = "constinit";
3158 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3159 SuitableSpelling = "[[clang::require_constant_initialization]]";
3160 if (SuitableSpelling.empty())
3161 SuitableSpelling = "__attribute__((require_constant_initialization))";
3162 SuitableSpelling += " ";
3163
3164 if (AttrBeforeInit) {
3165 // extern constinit int a;
3166 // int a = 0; // error (missing 'constinit'), accepted as extension
3167 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3168 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3169 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3170 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3171 } else {
3172 // int a = 0;
3173 // constinit extern int a; // error (missing 'constinit')
3174 S.Diag(CIAttr->getLocation(),
3175 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3176 : diag::warn_require_const_init_added_too_late)
3177 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3178 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3179 << CIAttr->isConstinit()
3180 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3181 }
3182}
3183
3186 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3187 UsedAttr *NewAttr = OldAttr->clone(Context);
3188 NewAttr->setInherited(true);
3189 New->addAttr(NewAttr);
3190 }
3191 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3192 RetainAttr *NewAttr = OldAttr->clone(Context);
3193 NewAttr->setInherited(true);
3194 New->addAttr(NewAttr);
3195 }
3196
3197 if (!Old->hasAttrs() && !New->hasAttrs())
3198 return;
3199
3200 // [dcl.constinit]p1:
3201 // If the [constinit] specifier is applied to any declaration of a
3202 // variable, it shall be applied to the initializing declaration.
3203 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3204 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3205 if (bool(OldConstInit) != bool(NewConstInit)) {
3206 const auto *OldVD = cast<VarDecl>(Old);
3207 auto *NewVD = cast<VarDecl>(New);
3208
3209 // Find the initializing declaration. Note that we might not have linked
3210 // the new declaration into the redeclaration chain yet.
3211 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3212 if (!InitDecl &&
3213 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3214 InitDecl = NewVD;
3215
3216 if (InitDecl == NewVD) {
3217 // This is the initializing declaration. If it would inherit 'constinit',
3218 // that's ill-formed. (Note that we do not apply this to the attribute
3219 // form).
3220 if (OldConstInit && OldConstInit->isConstinit())
3221 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3222 /*AttrBeforeInit=*/true);
3223 } else if (NewConstInit) {
3224 // This is the first time we've been told that this declaration should
3225 // have a constant initializer. If we already saw the initializing
3226 // declaration, this is too late.
3227 if (InitDecl && InitDecl != NewVD) {
3228 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3229 /*AttrBeforeInit=*/false);
3230 NewVD->dropAttr<ConstInitAttr>();
3231 }
3232 }
3233 }
3234
3235 // Attributes declared post-definition are currently ignored.
3236 checkNewAttributesAfterDef(*this, New, Old);
3237
3238 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3239 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3240 if (!OldA->isEquivalent(NewA)) {
3241 // This redeclaration changes __asm__ label.
3242 Diag(New->getLocation(), diag::err_different_asm_label);
3243 Diag(OldA->getLocation(), diag::note_previous_declaration);
3244 }
3245 } else if (Old->isUsed()) {
3246 // This redeclaration adds an __asm__ label to a declaration that has
3247 // already been ODR-used.
3248 Diag(New->getLocation(), diag::err_late_asm_label_name)
3249 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3250 }
3251 }
3252
3253 // Re-declaration cannot add abi_tag's.
3254 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3255 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3256 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3257 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3258 Diag(NewAbiTagAttr->getLocation(),
3259 diag::err_new_abi_tag_on_redeclaration)
3260 << NewTag;
3261 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3262 }
3263 }
3264 } else {
3265 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3266 Diag(Old->getLocation(), diag::note_previous_declaration);
3267 }
3268 }
3269
3270 // This redeclaration adds a section attribute.
3271 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3272 if (auto *VD = dyn_cast<VarDecl>(New)) {
3273 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3274 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3275 Diag(Old->getLocation(), diag::note_previous_declaration);
3276 }
3277 }
3278 }
3279
3280 // Redeclaration adds code-seg attribute.
3281 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3282 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3283 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3284 Diag(New->getLocation(), diag::warn_mismatched_section)
3285 << 0 /*codeseg*/;
3286 Diag(Old->getLocation(), diag::note_previous_declaration);
3287 }
3288
3289 if (!Old->hasAttrs())
3290 return;
3291
3292 bool foundAny = New->hasAttrs();
3293
3294 // Ensure that any moving of objects within the allocated map is done before
3295 // we process them.
3296 if (!foundAny) New->setAttrs(AttrVec());
3297
3298 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3299 // Ignore deprecated/unavailable/availability attributes if requested.
3301 if (isa<DeprecatedAttr>(I) ||
3302 isa<UnavailableAttr>(I) ||
3303 isa<AvailabilityAttr>(I)) {
3304 switch (AMK) {
3306 continue;
3307
3312 LocalAMK = AMK;
3313 break;
3314 }
3315 }
3316
3317 // Already handled.
3318 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3319 continue;
3320
3321 if (isa<InferredNoReturnAttr>(I)) {
3322 if (auto *FD = dyn_cast<FunctionDecl>(New);
3323 FD &&
3324 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3325 continue; // Don't propagate inferred noreturn attributes to explicit
3326 }
3327
3328 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3329 foundAny = true;
3330 }
3331
3332 if (mergeAlignedAttrs(*this, New, Old))
3333 foundAny = true;
3334
3335 if (!foundAny) New->dropAttrs();
3336}
3337
3338// Returns the number of added attributes.
3339template <class T>
3340static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3341 Sema &S) {
3342 unsigned found = 0;
3343 for (const auto *I : From->specific_attrs<T>()) {
3344 if (!DeclHasAttr(To, I)) {
3345 T *newAttr = cast<T>(I->clone(S.Context));
3346 newAttr->setInherited(true);
3347 To->addAttr(newAttr);
3348 ++found;
3349 }
3350 }
3351 return found;
3352}
3353
3354template <class F>
3355static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3356 F &&propagator) {
3357 if (!From->hasAttrs()) {
3358 return;
3359 }
3360
3361 bool foundAny = To->hasAttrs();
3362
3363 // Ensure that any moving of objects within the allocated map is
3364 // done before we process them.
3365 if (!foundAny)
3366 To->setAttrs(AttrVec());
3367
3368 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3369
3370 if (!foundAny)
3371 To->dropAttrs();
3372}
3373
3374/// mergeParamDeclAttributes - Copy attributes from the old parameter
3375/// to the new one.
3377 const ParmVarDecl *oldDecl,
3378 Sema &S) {
3379 // C++11 [dcl.attr.depend]p2:
3380 // The first declaration of a function shall specify the
3381 // carries_dependency attribute for its declarator-id if any declaration
3382 // of the function specifies the carries_dependency attribute.
3383 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3384 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3385 S.Diag(CDA->getLocation(),
3386 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3387 // Find the first declaration of the parameter.
3388 // FIXME: Should we build redeclaration chains for function parameters?
3389 const FunctionDecl *FirstFD =
3390 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3391 const ParmVarDecl *FirstVD =
3392 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3393 S.Diag(FirstVD->getLocation(),
3394 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3395 }
3396
3398 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3399 unsigned found = 0;
3400 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3401 // Propagate the lifetimebound attribute from parameters to the
3402 // most recent declaration. Note that this doesn't include the implicit
3403 // 'this' parameter, as the attribute is applied to the function type in
3404 // that case.
3405 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3406 return found;
3407 });
3408}
3409
3411 const ASTContext &Ctx) {
3412
3413 auto NoSizeInfo = [&Ctx](QualType Ty) {
3414 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3415 return true;
3416 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3417 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3418 return false;
3419 };
3420
3421 // `type[]` is equivalent to `type *` and `type[*]`.
3422 if (NoSizeInfo(Old) && NoSizeInfo(New))
3423 return true;
3424
3425 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3426 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3427 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3428 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3429 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3430 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3431 return false;
3432 return true;
3433 }
3434
3435 // Only compare size, ignore Size modifiers and CVR.
3436 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3437 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3439 }
3440
3441 // Don't try to compare dependent sized array
3442 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3443 return true;
3444 }
3445
3446 return Old == New;
3447}
3448
3449static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3450 const ParmVarDecl *OldParam,
3451 Sema &S) {
3452 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3453 if (auto Newnullability = NewParam->getType()->getNullability()) {
3454 if (*Oldnullability != *Newnullability) {
3455 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3457 *Newnullability,
3459 != 0))
3461 *Oldnullability,
3463 != 0));
3464 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3465 }
3466 } else {
3467 QualType NewT = NewParam->getType();
3468 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3469 NewParam->setType(NewT);
3470 }
3471 }
3472 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3473 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3474 if (OldParamDT && NewParamDT &&
3475 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3476 QualType OldParamOT = OldParamDT->getOriginalType();
3477 QualType NewParamOT = NewParamDT->getOriginalType();
3478 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3479 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3480 << NewParam << NewParamOT;
3481 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3482 << OldParamOT;
3483 }
3484 }
3485}
3486
3487namespace {
3488
3489/// Used in MergeFunctionDecl to keep track of function parameters in
3490/// C.
3491struct GNUCompatibleParamWarning {
3492 ParmVarDecl *OldParm;
3493 ParmVarDecl *NewParm;
3494 QualType PromotedType;
3495};
3496
3497} // end anonymous namespace
3498
3499// Determine whether the previous declaration was a definition, implicit
3500// declaration, or a declaration.
3501template <typename T>
3502static std::pair<diag::kind, SourceLocation>
3504 diag::kind PrevDiag;
3505 SourceLocation OldLocation = Old->getLocation();
3506 if (Old->isThisDeclarationADefinition())
3507 PrevDiag = diag::note_previous_definition;
3508 else if (Old->isImplicit()) {
3509 PrevDiag = diag::note_previous_implicit_declaration;
3510 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3511 if (FD->getBuiltinID())
3512 PrevDiag = diag::note_previous_builtin_declaration;
3513 }
3514 if (OldLocation.isInvalid())
3515 OldLocation = New->getLocation();
3516 } else
3517 PrevDiag = diag::note_previous_declaration;
3518 return std::make_pair(PrevDiag, OldLocation);
3519}
3520
3521/// canRedefineFunction - checks if a function can be redefined. Currently,
3522/// only extern inline functions can be redefined, and even then only in
3523/// GNU89 mode.
3524static bool canRedefineFunction(const FunctionDecl *FD,
3525 const LangOptions& LangOpts) {
3526 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3527 !LangOpts.CPlusPlus &&
3528 FD->isInlineSpecified() &&
3529 FD->getStorageClass() == SC_Extern);
3530}
3531
3533 const AttributedType *AT = T->getAs<AttributedType>();
3534 while (AT && !AT->isCallingConv())
3535 AT = AT->getModifiedType()->getAs<AttributedType>();
3536 return AT;
3537}
3538
3539template <typename T>
3540static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3541 const DeclContext *DC = Old->getDeclContext();
3542 if (DC->isRecord())
3543 return false;
3544
3545 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3546 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3547 return true;
3548 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3549 return true;
3550 return false;
3551}
3552
3553template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3554static bool isExternC(VarTemplateDecl *) { return false; }
3555static bool isExternC(FunctionTemplateDecl *) { return false; }
3556
3557/// Check whether a redeclaration of an entity introduced by a
3558/// using-declaration is valid, given that we know it's not an overload
3559/// (nor a hidden tag declaration).
3560template<typename ExpectedDecl>
3562 ExpectedDecl *New) {
3563 // C++11 [basic.scope.declarative]p4:
3564 // Given a set of declarations in a single declarative region, each of
3565 // which specifies the same unqualified name,
3566 // -- they shall all refer to the same entity, or all refer to functions
3567 // and function templates; or
3568 // -- exactly one declaration shall declare a class name or enumeration
3569 // name that is not a typedef name and the other declarations shall all
3570 // refer to the same variable or enumerator, or all refer to functions
3571 // and function templates; in this case the class name or enumeration
3572 // name is hidden (3.3.10).
3573
3574 // C++11 [namespace.udecl]p14:
3575 // If a function declaration in namespace scope or block scope has the
3576 // same name and the same parameter-type-list as a function introduced
3577 // by a using-declaration, and the declarations do not declare the same
3578 // function, the program is ill-formed.
3579
3580 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3581 if (Old &&
3582 !Old->getDeclContext()->getRedeclContext()->Equals(
3583 New->getDeclContext()->getRedeclContext()) &&
3584 !(isExternC(Old) && isExternC(New)))
3585 Old = nullptr;
3586
3587 if (!Old) {
3588 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3589 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3590 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3591 return true;
3592 }
3593 return false;
3594}
3595
3597 const FunctionDecl *B) {
3598 assert(A->getNumParams() == B->getNumParams());
3599
3600 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3601 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3602 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3603 if (AttrA == AttrB)
3604 return true;
3605 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3606 AttrA->isDynamic() == AttrB->isDynamic();
3607 };
3608
3609 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3610}
3611
3612/// If necessary, adjust the semantic declaration context for a qualified
3613/// declaration to name the correct inline namespace within the qualifier.
3615 DeclaratorDecl *OldD) {
3616 // The only case where we need to update the DeclContext is when
3617 // redeclaration lookup for a qualified name finds a declaration
3618 // in an inline namespace within the context named by the qualifier:
3619 //
3620 // inline namespace N { int f(); }
3621 // int ::f(); // Sema DC needs adjusting from :: to N::.
3622 //
3623 // For unqualified declarations, the semantic context *can* change
3624 // along the redeclaration chain (for local extern declarations,
3625 // extern "C" declarations, and friend declarations in particular).
3626 if (!NewD->getQualifier())
3627 return;
3628
3629 // NewD is probably already in the right context.
3630 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3631 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3632 if (NamedDC->Equals(SemaDC))
3633 return;
3634
3635 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3636 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3637 "unexpected context for redeclaration");
3638
3639 auto *LexDC = NewD->getLexicalDeclContext();
3640 auto FixSemaDC = [=](NamedDecl *D) {
3641 if (!D)
3642 return;
3643 D->setDeclContext(SemaDC);
3644 D->setLexicalDeclContext(LexDC);
3645 };
3646
3647 FixSemaDC(NewD);
3648 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3649 FixSemaDC(FD->getDescribedFunctionTemplate());
3650 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3651 FixSemaDC(VD->getDescribedVarTemplate());
3652}
3653
3655 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3656 // Verify the old decl was also a function.
3657 FunctionDecl *Old = OldD->getAsFunction();
3658 if (!Old) {
3659 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3660 // We don't need to check the using friend pattern from other module unit
3661 // since we should have diagnosed such cases in its unit already.
3662 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3663 Diag(New->getLocation(), diag::err_using_decl_friend);
3664 Diag(Shadow->getTargetDecl()->getLocation(),
3665 diag::note_using_decl_target);
3666 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3667 << 0;
3668 return true;
3669 }
3670
3671 // Check whether the two declarations might declare the same function or
3672 // function template.
3673 if (FunctionTemplateDecl *NewTemplate =
3674 New->getDescribedFunctionTemplate()) {
3675 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3676 NewTemplate))
3677 return true;
3678 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3679 ->getAsFunction();
3680 } else {
3681 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3682 return true;
3683 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3684 }
3685 } else {
3686 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3687 << New->getDeclName();
3688 notePreviousDefinition(OldD, New->getLocation());
3689 return true;
3690 }
3691 }
3692
3693 // If the old declaration was found in an inline namespace and the new
3694 // declaration was qualified, update the DeclContext to match.
3696
3697 // If the old declaration is invalid, just give up here.
3698 if (Old->isInvalidDecl())
3699 return true;
3700
3701 // Disallow redeclaration of some builtins.
3702 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3703 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3704 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3705 << Old << Old->getType();
3706 return true;
3707 }
3708
3709 diag::kind PrevDiag;
3710 SourceLocation OldLocation;
3711 std::tie(PrevDiag, OldLocation) =
3713
3714 // Don't complain about this if we're in GNU89 mode and the old function
3715 // is an extern inline function.
3716 // Don't complain about specializations. They are not supposed to have
3717 // storage classes.
3718 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3719 New->getStorageClass() == SC_Static &&
3720 Old->hasExternalFormalLinkage() &&
3721 !New->getTemplateSpecializationInfo() &&
3723 if (getLangOpts().MicrosoftExt) {
3724 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3725 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3726 } else {
3727 Diag(New->getLocation(), diag::err_static_non_static) << New;
3728 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3729 return true;
3730 }
3731 }
3732
3733 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3734 if (!Old->hasAttr<InternalLinkageAttr>()) {
3735 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3736 << ILA;
3737 Diag(Old->getLocation(), diag::note_previous_declaration);
3738 New->dropAttr<InternalLinkageAttr>();
3739 }
3740
3741 if (auto *EA = New->getAttr<ErrorAttr>()) {
3742 if (!Old->hasAttr<ErrorAttr>()) {
3743 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3744 Diag(Old->getLocation(), diag::note_previous_declaration);
3745 New->dropAttr<ErrorAttr>();
3746 }
3747 }
3748
3750 return true;
3751
3752 if (!getLangOpts().CPlusPlus) {
3753 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3754 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3755 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3756 << New << OldOvl;
3757
3758 // Try our best to find a decl that actually has the overloadable
3759 // attribute for the note. In most cases (e.g. programs with only one
3760 // broken declaration/definition), this won't matter.
3761 //
3762 // FIXME: We could do this if we juggled some extra state in
3763 // OverloadableAttr, rather than just removing it.
3764 const Decl *DiagOld = Old;
3765 if (OldOvl) {
3766 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3767 const auto *A = D->getAttr<OverloadableAttr>();
3768 return A && !A->isImplicit();
3769 });
3770 // If we've implicitly added *all* of the overloadable attrs to this
3771 // chain, emitting a "previous redecl" note is pointless.
3772 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3773 }
3774
3775 if (DiagOld)
3776 Diag(DiagOld->getLocation(),
3777 diag::note_attribute_overloadable_prev_overload)
3778 << OldOvl;
3779
3780 if (OldOvl)
3781 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3782 else
3783 New->dropAttr<OverloadableAttr>();
3784 }
3785 }
3786
3787 // It is not permitted to redeclare an SME function with different SME
3788 // attributes.
3789 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3790 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3791 << New->getType() << Old->getType();
3792 Diag(OldLocation, diag::note_previous_declaration);
3793 return true;
3794 }
3795
3796 // If a function is first declared with a calling convention, but is later
3797 // declared or defined without one, all following decls assume the calling
3798 // convention of the first.
3799 //
3800 // It's OK if a function is first declared without a calling convention,
3801 // but is later declared or defined with the default calling convention.
3802 //
3803 // To test if either decl has an explicit calling convention, we look for
3804 // AttributedType sugar nodes on the type as written. If they are missing or
3805 // were canonicalized away, we assume the calling convention was implicit.
3806 //
3807 // Note also that we DO NOT return at this point, because we still have
3808 // other tests to run.
3809 QualType OldQType = Context.getCanonicalType(Old->getType());
3810 QualType NewQType = Context.getCanonicalType(New->getType());
3811 const FunctionType *OldType = cast<FunctionType>(OldQType);
3812 const FunctionType *NewType = cast<FunctionType>(NewQType);
3813 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3814 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3815 bool RequiresAdjustment = false;
3816
3817 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3819 const FunctionType *FT =
3820 First->getType().getCanonicalType()->castAs<FunctionType>();
3822 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3823 if (!NewCCExplicit) {
3824 // Inherit the CC from the previous declaration if it was specified
3825 // there but not here.
3826 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3827 RequiresAdjustment = true;
3828 } else if (Old->getBuiltinID()) {
3829 // Builtin attribute isn't propagated to the new one yet at this point,
3830 // so we check if the old one is a builtin.
3831
3832 // Calling Conventions on a Builtin aren't really useful and setting a
3833 // default calling convention and cdecl'ing some builtin redeclarations is
3834 // common, so warn and ignore the calling convention on the redeclaration.
3835 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3836 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3838 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3839 RequiresAdjustment = true;
3840 } else {
3841 // Calling conventions aren't compatible, so complain.
3842 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3843 Diag(New->getLocation(), diag::err_cconv_change)
3844 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3845 << !FirstCCExplicit
3846 << (!FirstCCExplicit ? "" :
3848
3849 // Put the note on the first decl, since it is the one that matters.
3850 Diag(First->getLocation(), diag::note_previous_declaration);
3851 return true;
3852 }
3853 }
3854
3855 // FIXME: diagnose the other way around?
3856 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3857 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3858 RequiresAdjustment = true;
3859 }
3860
3861 // Merge regparm attribute.
3862 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3863 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3864 if (NewTypeInfo.getHasRegParm()) {
3865 Diag(New->getLocation(), diag::err_regparm_mismatch)
3866 << NewType->getRegParmType()
3867 << OldType->getRegParmType();
3868 Diag(OldLocation, diag::note_previous_declaration);
3869 return true;
3870 }
3871
3872 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3873 RequiresAdjustment = true;
3874 }
3875
3876 // Merge ns_returns_retained attribute.
3877 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3878 if (NewTypeInfo.getProducesResult()) {
3879 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3880 << "'ns_returns_retained'";
3881 Diag(OldLocation, diag::note_previous_declaration);
3882 return true;
3883 }
3884
3885 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3886 RequiresAdjustment = true;
3887 }
3888
3889 if (OldTypeInfo.getNoCallerSavedRegs() !=
3890 NewTypeInfo.getNoCallerSavedRegs()) {
3891 if (NewTypeInfo.getNoCallerSavedRegs()) {
3892 AnyX86NoCallerSavedRegistersAttr *Attr =
3893 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3894 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3895 Diag(OldLocation, diag::note_previous_declaration);
3896 return true;
3897 }
3898
3899 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3900 RequiresAdjustment = true;
3901 }
3902
3903 if (RequiresAdjustment) {
3904 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3906 New->setType(QualType(AdjustedType, 0));
3907 NewQType = Context.getCanonicalType(New->getType());
3908 }
3909
3910 // If this redeclaration makes the function inline, we may need to add it to
3911 // UndefinedButUsed.
3912 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3913 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
3914 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3915 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3916 SourceLocation()));
3917
3918 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3919 // about it.
3920 if (New->hasAttr<GNUInlineAttr>() &&
3921 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3922 UndefinedButUsed.erase(Old->getCanonicalDecl());
3923 }
3924
3925 // If pass_object_size params don't match up perfectly, this isn't a valid
3926 // redeclaration.
3927 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3929 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3930 << New->getDeclName();
3931 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3932 return true;
3933 }
3934
3935 QualType OldQTypeForComparison = OldQType;
3937 const auto OldFX = Old->getFunctionEffects();
3938 const auto NewFX = New->getFunctionEffects();
3939 if (OldFX != NewFX) {
3940 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3941 for (const auto &Diff : Diffs) {
3942 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3943 Diag(New->getLocation(),
3944 diag::warn_mismatched_func_effect_redeclaration)
3945 << Diff.effectName();
3946 Diag(Old->getLocation(), diag::note_previous_declaration);
3947 }
3948 }
3949 // Following a warning, we could skip merging effects from the previous
3950 // declaration, but that would trigger an additional "conflicting types"
3951 // error.
3952 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3954 FunctionEffectSet MergedFX =
3955 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3956 if (!MergeErrs.empty())
3957 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
3958 Old->getLocation());
3959
3960 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3961 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3962 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
3963 NewFPT->getParamTypes(), EPI);
3964
3965 New->setType(ModQT);
3966 NewQType = New->getType();
3967
3968 // Revise OldQTForComparison to include the merged effects,
3969 // so as not to fail due to differences later.
3970 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3971 EPI = OldFPT->getExtProtoInfo();
3972 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3973 OldQTypeForComparison = Context.getFunctionType(
3974 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
3975 }
3976 if (OldFX.empty()) {
3977 // A redeclaration may add the attribute to a previously seen function
3978 // body which needs to be verified.
3979 maybeAddDeclWithEffects(Old, MergedFX);
3980 }
3981 }
3982 }
3983 }
3984
3985 if (getLangOpts().CPlusPlus) {
3986 OldQType = Context.getCanonicalType(Old->getType());
3987 NewQType = Context.getCanonicalType(New->getType());
3988
3989 // Go back to the type source info to compare the declared return types,
3990 // per C++1y [dcl.type.auto]p13:
3991 // Redeclarations or specializations of a function or function template
3992 // with a declared return type that uses a placeholder type shall also
3993 // use that placeholder, not a deduced type.
3994 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3995 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3996 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3997 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3998 OldDeclaredReturnType)) {
3999 QualType ResQT;
4000 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4001 OldDeclaredReturnType->isObjCObjectPointerType())
4002 // FIXME: This does the wrong thing for a deduced return type.
4003 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4004 if (ResQT.isNull()) {
4005 if (New->isCXXClassMember() && New->isOutOfLine())
4006 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4007 << New << New->getReturnTypeSourceRange();
4008 else if (Old->isExternC() && New->isExternC() &&
4009 !Old->hasAttr<OverloadableAttr>() &&
4010 !New->hasAttr<OverloadableAttr>())
4011 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4012 else
4013 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4014 << New->getReturnTypeSourceRange();
4015 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4016 << Old->getReturnTypeSourceRange();
4017 return true;
4018 }
4019 else
4020 NewQType = ResQT;
4021 }
4022
4023 QualType OldReturnType = OldType->getReturnType();
4024 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4025 if (OldReturnType != NewReturnType) {
4026 // If this function has a deduced return type and has already been
4027 // defined, copy the deduced value from the old declaration.
4028 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4029 if (OldAT && OldAT->isDeduced()) {
4030 QualType DT = OldAT->getDeducedType();
4031 if (DT.isNull()) {
4032 New->setType(SubstAutoTypeDependent(New->getType()));
4033 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4034 } else {
4035 New->setType(SubstAutoType(New->getType(), DT));
4036 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4037 }
4038 }
4039 }
4040
4041 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4042 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4043 if (OldMethod && NewMethod) {
4044 // Preserve triviality.
4045 NewMethod->setTrivial(OldMethod->isTrivial());
4046
4047 // MSVC allows explicit template specialization at class scope:
4048 // 2 CXXMethodDecls referring to the same function will be injected.
4049 // We don't want a redeclaration error.
4050 bool IsClassScopeExplicitSpecialization =
4051 OldMethod->isFunctionTemplateSpecialization() &&
4053 bool isFriend = NewMethod->getFriendObjectKind();
4054
4055 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4056 !IsClassScopeExplicitSpecialization) {
4057 // -- Member function declarations with the same name and the
4058 // same parameter types cannot be overloaded if any of them
4059 // is a static member function declaration.
4060 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4061 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4062 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4063 return true;
4064 }
4065
4066 // C++ [class.mem]p1:
4067 // [...] A member shall not be declared twice in the
4068 // member-specification, except that a nested class or member
4069 // class template can be declared and then later defined.
4070 if (!inTemplateInstantiation()) {
4071 unsigned NewDiag;
4072 if (isa<CXXConstructorDecl>(OldMethod))
4073 NewDiag = diag::err_constructor_redeclared;
4074 else if (isa<CXXDestructorDecl>(NewMethod))
4075 NewDiag = diag::err_destructor_redeclared;
4076 else if (isa<CXXConversionDecl>(NewMethod))
4077 NewDiag = diag::err_conv_function_redeclared;
4078 else
4079 NewDiag = diag::err_member_redeclared;
4080
4081 Diag(New->getLocation(), NewDiag);
4082 } else {
4083 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4084 << New << New->getType();
4085 }
4086 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4087 return true;
4088
4089 // Complain if this is an explicit declaration of a special
4090 // member that was initially declared implicitly.
4091 //
4092 // As an exception, it's okay to befriend such methods in order
4093 // to permit the implicit constructor/destructor/operator calls.
4094 } else if (OldMethod->isImplicit()) {
4095 if (isFriend) {
4096 NewMethod->setImplicit();
4097 } else {
4098 Diag(NewMethod->getLocation(),
4099 diag::err_definition_of_implicitly_declared_member)
4100 << New << getSpecialMember(OldMethod);
4101 return true;
4102 }
4103 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4104 Diag(NewMethod->getLocation(),
4105 diag::err_definition_of_explicitly_defaulted_member)
4106 << getSpecialMember(OldMethod);
4107 return true;
4108 }
4109 }
4110
4111 // C++1z [over.load]p2
4112 // Certain function declarations cannot be overloaded:
4113 // -- Function declarations that differ only in the return type,
4114 // the exception specification, or both cannot be overloaded.
4115
4116 // Check the exception specifications match. This may recompute the type of
4117 // both Old and New if it resolved exception specifications, so grab the
4118 // types again after this. Because this updates the type, we do this before
4119 // any of the other checks below, which may update the "de facto" NewQType
4120 // but do not necessarily update the type of New.
4122 return true;
4123
4124 // C++11 [dcl.attr.noreturn]p1:
4125 // The first declaration of a function shall specify the noreturn
4126 // attribute if any declaration of that function specifies the noreturn
4127 // attribute.
4128 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4129 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4130 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4131 << NRA;
4132 Diag(Old->getLocation(), diag::note_previous_declaration);
4133 }
4134
4135 // C++11 [dcl.attr.depend]p2:
4136 // The first declaration of a function shall specify the
4137 // carries_dependency attribute for its declarator-id if any declaration
4138 // of the function specifies the carries_dependency attribute.
4139 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4140 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4141 Diag(CDA->getLocation(),
4142 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4143 Diag(Old->getFirstDecl()->getLocation(),
4144 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4145 }
4146
4147 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4148 // When a function is declared with SYCL_EXTERNAL, that macro must be
4149 // used on the first declaration of that function in the translation unit.
4150 // Redeclarations of the function in the same translation unit may
4151 // optionally use SYCL_EXTERNAL, but this is not required.
4152 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4153 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4154 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4155 << SEA;
4156 Diag(Old->getLocation(), diag::note_previous_declaration);
4157 }
4158
4159 // (C++98 8.3.5p3):
4160 // All declarations for a function shall agree exactly in both the
4161 // return type and the parameter-type-list.
4162 // We also want to respect all the extended bits except noreturn.
4163
4164 // noreturn should now match unless the old type info didn't have it.
4165 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4166 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4167 const FunctionType *OldTypeForComparison
4168 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4169 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4170 assert(OldQTypeForComparison.isCanonical());
4171 }
4172
4174 // As a special case, retain the language linkage from previous
4175 // declarations of a friend function as an extension.
4176 //
4177 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4178 // and is useful because there's otherwise no way to specify language
4179 // linkage within class scope.
4180 //
4181 // Check cautiously as the friend object kind isn't yet complete.
4182 if (New->getFriendObjectKind() != Decl::FOK_None) {
4183 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4184 Diag(OldLocation, PrevDiag);
4185 } else {
4186 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4187 Diag(OldLocation, PrevDiag);
4188 return true;
4189 }
4190 }
4191
4192 // HLSL check parameters for matching ABI specifications.
4193 if (getLangOpts().HLSL) {
4194 if (HLSL().CheckCompatibleParameterABI(New, Old))
4195 return true;
4196
4197 // If no errors are generated when checking parameter ABIs we can check if
4198 // the two declarations have the same type ignoring the ABIs and if so,
4199 // the declarations can be merged. This case for merging is only valid in
4200 // HLSL because there are no valid cases of merging mismatched parameter
4201 // ABIs except the HLSL implicit in and explicit in.
4202 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4203 NewQType))
4204 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4205 // Fall through for conflicting redeclarations and redefinitions.
4206 }
4207
4208 // If the function types are compatible, merge the declarations. Ignore the
4209 // exception specifier because it was already checked above in
4210 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4211 // about incompatible types under -fms-compatibility.
4212 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4213 NewQType))
4214 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4215
4216 // If the types are imprecise (due to dependent constructs in friends or
4217 // local extern declarations), it's OK if they differ. We'll check again
4218 // during instantiation.
4219 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4220 return false;
4221
4222 // Fall through for conflicting redeclarations and redefinitions.
4223 }
4224
4225 // C: Function types need to be compatible, not identical. This handles
4226 // duplicate function decls like "void f(int); void f(enum X);" properly.
4227 if (!getLangOpts().CPlusPlus) {
4228 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4229 // type is specified by a function definition that contains a (possibly
4230 // empty) identifier list, both shall agree in the number of parameters
4231 // and the type of each parameter shall be compatible with the type that
4232 // results from the application of default argument promotions to the
4233 // type of the corresponding identifier. ...
4234 // This cannot be handled by ASTContext::typesAreCompatible() because that
4235 // doesn't know whether the function type is for a definition or not when
4236 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4237 // we need to cover here is that the number of arguments agree as the
4238 // default argument promotion rules were already checked by
4239 // ASTContext::typesAreCompatible().
4240 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4241 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4242 if (Old->hasInheritedPrototype())
4243 Old = Old->getCanonicalDecl();
4244 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4245 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4246 return true;
4247 }
4248
4249 // If we are merging two functions where only one of them has a prototype,
4250 // we may have enough information to decide to issue a diagnostic that the
4251 // function without a prototype will change behavior in C23. This handles
4252 // cases like:
4253 // void i(); void i(int j);
4254 // void i(int j); void i();
4255 // void i(); void i(int j) {}
4256 // See ActOnFinishFunctionBody() for other cases of the behavior change
4257 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4258 // type without a prototype.
4259 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4260 !New->isImplicit() && !Old->isImplicit()) {
4261 const FunctionDecl *WithProto, *WithoutProto;
4262 if (New->hasWrittenPrototype()) {
4263 WithProto = New;
4264 WithoutProto = Old;
4265 } else {
4266 WithProto = Old;
4267 WithoutProto = New;
4268 }
4269
4270 if (WithProto->getNumParams() != 0) {
4271 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4272 // The one without the prototype will be changing behavior in C23, so
4273 // warn about that one so long as it's a user-visible declaration.
4274 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4275 if (WithoutProto == New)
4276 IsWithoutProtoADef = NewDeclIsDefn;
4277 else
4278 IsWithProtoADef = NewDeclIsDefn;
4279 Diag(WithoutProto->getLocation(),
4280 diag::warn_non_prototype_changes_behavior)
4281 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4282 << (WithoutProto == Old) << IsWithProtoADef;
4283
4284 // The reason the one without the prototype will be changing behavior
4285 // is because of the one with the prototype, so note that so long as
4286 // it's a user-visible declaration. There is one exception to this:
4287 // when the new declaration is a definition without a prototype, the
4288 // old declaration with a prototype is not the cause of the issue,
4289 // and that does not need to be noted because the one with a
4290 // prototype will not change behavior in C23.
4291 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4292 !IsWithoutProtoADef)
4293 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4294 }
4295 }
4296 }
4297
4298 if (Context.typesAreCompatible(OldQType, NewQType)) {
4299 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4300 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4301 const FunctionProtoType *OldProto = nullptr;
4302 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4303 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4304 // The old declaration provided a function prototype, but the
4305 // new declaration does not. Merge in the prototype.
4306 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4307 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4308 OldProto->getParamTypes(),
4309 OldProto->getExtProtoInfo());
4310 New->setType(NewQType);
4311 New->setHasInheritedPrototype();
4312
4313 // Synthesize parameters with the same types.
4315 for (const auto &ParamType : OldProto->param_types()) {
4317 Context, New, SourceLocation(), SourceLocation(), nullptr,
4318 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4319 Param->setScopeInfo(0, Params.size());
4320 Param->setImplicit();
4321 Params.push_back(Param);
4322 }
4323
4324 New->setParams(Params);
4325 }
4326
4327 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4328 }
4329 }
4330
4331 // Check if the function types are compatible when pointer size address
4332 // spaces are ignored.
4333 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4334 return false;
4335
4336 // GNU C permits a K&R definition to follow a prototype declaration
4337 // if the declared types of the parameters in the K&R definition
4338 // match the types in the prototype declaration, even when the
4339 // promoted types of the parameters from the K&R definition differ
4340 // from the types in the prototype. GCC then keeps the types from
4341 // the prototype.
4342 //
4343 // If a variadic prototype is followed by a non-variadic K&R definition,
4344 // the K&R definition becomes variadic. This is sort of an edge case, but
4345 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4346 // C99 6.9.1p8.
4347 if (!getLangOpts().CPlusPlus &&
4348 Old->hasPrototype() && !New->hasPrototype() &&
4349 New->getType()->getAs<FunctionProtoType>() &&
4350 Old->getNumParams() == New->getNumParams()) {
4353 const FunctionProtoType *OldProto
4354 = Old->getType()->getAs<FunctionProtoType>();
4355 const FunctionProtoType *NewProto
4356 = New->getType()->getAs<FunctionProtoType>();
4357
4358 // Determine whether this is the GNU C extension.
4359 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4360 NewProto->getReturnType());
4361 bool LooseCompatible = !MergedReturn.isNull();
4362 for (unsigned Idx = 0, End = Old->getNumParams();
4363 LooseCompatible && Idx != End; ++Idx) {
4364 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4365 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4366 if (Context.typesAreCompatible(OldParm->getType(),
4367 NewProto->getParamType(Idx))) {
4368 ArgTypes.push_back(NewParm->getType());
4369 } else if (Context.typesAreCompatible(OldParm->getType(),
4370 NewParm->getType(),
4371 /*CompareUnqualified=*/true)) {
4372 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4373 NewProto->getParamType(Idx) };
4374 Warnings.push_back(Warn);
4375 ArgTypes.push_back(NewParm->getType());
4376 } else
4377 LooseCompatible = false;
4378 }
4379
4380 if (LooseCompatible) {
4381 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4382 Diag(Warnings[Warn].NewParm->getLocation(),
4383 diag::ext_param_promoted_not_compatible_with_prototype)
4384 << Warnings[Warn].PromotedType
4385 << Warnings[Warn].OldParm->getType();
4386 if (Warnings[Warn].OldParm->getLocation().isValid())
4387 Diag(Warnings[Warn].OldParm->getLocation(),
4388 diag::note_previous_declaration);
4389 }
4390
4391 if (MergeTypeWithOld)
4392 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4393 OldProto->getExtProtoInfo()));
4394 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4395 }
4396
4397 // Fall through to diagnose conflicting types.
4398 }
4399
4400 // A function that has already been declared has been redeclared or
4401 // defined with a different type; show an appropriate diagnostic.
4402
4403 // If the previous declaration was an implicitly-generated builtin
4404 // declaration, then at the very least we should use a specialized note.
4405 unsigned BuiltinID;
4406 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4407 // If it's actually a library-defined builtin function like 'malloc'
4408 // or 'printf', just warn about the incompatible redeclaration.
4410 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4411 Diag(OldLocation, diag::note_previous_builtin_declaration)
4412 << Old << Old->getType();
4413 return false;
4414 }
4415
4416 PrevDiag = diag::note_previous_builtin_declaration;
4417 }
4418
4419 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4420 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4421 return true;
4422}
4423
4425 Scope *S, bool MergeTypeWithOld) {
4426 // Merge the attributes
4428
4429 // Merge "pure" flag.
4430 if (Old->isPureVirtual())
4431 New->setIsPureVirtual();
4432
4433 // Merge "used" flag.
4434 if (Old->getMostRecentDecl()->isUsed(false))
4435 New->setIsUsed();
4436
4437 // Merge attributes from the parameters. These can mismatch with K&R
4438 // declarations.
4439 if (New->getNumParams() == Old->getNumParams())
4440 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4441 ParmVarDecl *NewParam = New->getParamDecl(i);
4442 ParmVarDecl *OldParam = Old->getParamDecl(i);
4443 mergeParamDeclAttributes(NewParam, OldParam, *this);
4444 mergeParamDeclTypes(NewParam, OldParam, *this);
4445 }
4446
4447 if (getLangOpts().CPlusPlus)
4448 return MergeCXXFunctionDecl(New, Old, S);
4449
4450 // Merge the function types so the we get the composite types for the return
4451 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4452 // was visible.
4453 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4454 if (!Merged.isNull() && MergeTypeWithOld)
4455 New->setType(Merged);
4456
4457 return false;
4458}
4459
4461 ObjCMethodDecl *oldMethod) {
4462 // Merge the attributes, including deprecated/unavailable
4463 AvailabilityMergeKind MergeKind =
4464 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4465 ? (oldMethod->isOptional()
4468 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4471
4472 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4473
4474 // Merge attributes from the parameters.
4476 oe = oldMethod->param_end();
4478 ni = newMethod->param_begin(), ne = newMethod->param_end();
4479 ni != ne && oi != oe; ++ni, ++oi)
4480 mergeParamDeclAttributes(*ni, *oi, *this);
4481
4482 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4483}
4484
4486 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4487
4488 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4489 ? diag::err_redefinition_different_type
4490 : diag::err_redeclaration_different_type)
4491 << New->getDeclName() << New->getType() << Old->getType();
4492
4493 diag::kind PrevDiag;
4494 SourceLocation OldLocation;
4495 std::tie(PrevDiag, OldLocation)
4497 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4498 New->setInvalidDecl();
4499}
4500
4502 bool MergeTypeWithOld) {
4503 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4504 return;
4505
4506 QualType MergedT;
4507 if (getLangOpts().CPlusPlus) {
4508 if (New->getType()->isUndeducedType()) {
4509 // We don't know what the new type is until the initializer is attached.
4510 return;
4511 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4512 // These could still be something that needs exception specs checked.
4513 return MergeVarDeclExceptionSpecs(New, Old);
4514 }
4515 // C++ [basic.link]p10:
4516 // [...] the types specified by all declarations referring to a given
4517 // object or function shall be identical, except that declarations for an
4518 // array object can specify array types that differ by the presence or
4519 // absence of a major array bound (8.3.4).
4520 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4521 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4522 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4523
4524 // We are merging a variable declaration New into Old. If it has an array
4525 // bound, and that bound differs from Old's bound, we should diagnose the
4526 // mismatch.
4527 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4528 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4529 PrevVD = PrevVD->getPreviousDecl()) {
4530 QualType PrevVDTy = PrevVD->getType();
4531 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4532 continue;
4533
4534 if (!Context.hasSameType(New->getType(), PrevVDTy))
4535 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4536 }
4537 }
4538
4539 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4540 if (Context.hasSameType(OldArray->getElementType(),
4541 NewArray->getElementType()))
4542 MergedT = New->getType();
4543 }
4544 // FIXME: Check visibility. New is hidden but has a complete type. If New
4545 // has no array bound, it should not inherit one from Old, if Old is not
4546 // visible.
4547 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4548 if (Context.hasSameType(OldArray->getElementType(),
4549 NewArray->getElementType()))
4550 MergedT = Old->getType();
4551 }
4552 }
4553 else if (New->getType()->isObjCObjectPointerType() &&
4554 Old->getType()->isObjCObjectPointerType()) {
4555 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4556 Old->getType());
4557 }
4558 } else {
4559 // C 6.2.7p2:
4560 // All declarations that refer to the same object or function shall have
4561 // compatible type.
4562 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4563 }
4564 if (MergedT.isNull()) {
4565 // It's OK if we couldn't merge types if either type is dependent, for a
4566 // block-scope variable. In other cases (static data members of class
4567 // templates, variable templates, ...), we require the types to be
4568 // equivalent.
4569 // FIXME: The C++ standard doesn't say anything about this.
4570 if ((New->getType()->isDependentType() ||
4571 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4572 // If the old type was dependent, we can't merge with it, so the new type
4573 // becomes dependent for now. We'll reproduce the original type when we
4574 // instantiate the TypeSourceInfo for the variable.
4575 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4576 New->setType(Context.DependentTy);
4577 return;
4578 }
4579 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4580 }
4581
4582 // Don't actually update the type on the new declaration if the old
4583 // declaration was an extern declaration in a different scope.
4584 if (MergeTypeWithOld)
4585 New->setType(MergedT);
4586}
4587
4588static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4590 // C11 6.2.7p4:
4591 // For an identifier with internal or external linkage declared
4592 // in a scope in which a prior declaration of that identifier is
4593 // visible, if the prior declaration specifies internal or
4594 // external linkage, the type of the identifier at the later
4595 // declaration becomes the composite type.
4596 //
4597 // If the variable isn't visible, we do not merge with its type.
4598 if (Previous.isShadowed())
4599 return false;
4600
4601 if (S.getLangOpts().CPlusPlus) {
4602 // C++11 [dcl.array]p3:
4603 // If there is a preceding declaration of the entity in the same
4604 // scope in which the bound was specified, an omitted array bound
4605 // is taken to be the same as in that earlier declaration.
4606 return NewVD->isPreviousDeclInSameBlockScope() ||
4609 } else {
4610 // If the old declaration was function-local, don't merge with its
4611 // type unless we're in the same function.
4612 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4613 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4614 }
4615}
4616
4618 // If the new decl is already invalid, don't do any other checking.
4619 if (New->isInvalidDecl())
4620 return;
4621
4622 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4623 return;
4624
4625 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4626
4627 // Verify the old decl was also a variable or variable template.
4628 VarDecl *Old = nullptr;
4629 VarTemplateDecl *OldTemplate = nullptr;
4630 if (Previous.isSingleResult()) {
4631 if (NewTemplate) {
4632 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4633 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4634
4635 if (auto *Shadow =
4636 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4637 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4638 return New->setInvalidDecl();
4639 } else {
4640 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4641
4642 if (auto *Shadow =
4643 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4644 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4645 return New->setInvalidDecl();
4646 }
4647 }
4648 if (!Old) {
4649 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4650 << New->getDeclName();
4651 notePreviousDefinition(Previous.getRepresentativeDecl(),
4652 New->getLocation());
4653 return New->setInvalidDecl();
4654 }
4655
4656 // If the old declaration was found in an inline namespace and the new
4657 // declaration was qualified, update the DeclContext to match.
4659
4660 // Ensure the template parameters are compatible.
4661 if (NewTemplate &&
4663 OldTemplate->getTemplateParameters(),
4664 /*Complain=*/true, TPL_TemplateMatch))
4665 return New->setInvalidDecl();
4666
4667 // C++ [class.mem]p1:
4668 // A member shall not be declared twice in the member-specification [...]
4669 //
4670 // Here, we need only consider static data members.
4671 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4672 Diag(New->getLocation(), diag::err_duplicate_member)
4673 << New->getIdentifier();
4674 Diag(Old->getLocation(), diag::note_previous_declaration);
4675 New->setInvalidDecl();
4676 }
4677
4679 // Warn if an already-defined variable is made a weak_import in a subsequent
4680 // declaration
4681 if (New->hasAttr<WeakImportAttr>())
4682 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4683 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4684 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4685 Diag(D->getLocation(), diag::note_previous_definition);
4686 // Remove weak_import attribute on new declaration.
4687 New->dropAttr<WeakImportAttr>();
4688 break;
4689 }
4690 }
4691
4692 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4693 if (!Old->hasAttr<InternalLinkageAttr>()) {
4694 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4695 << ILA;
4696 Diag(Old->getLocation(), diag::note_previous_declaration);
4697 New->dropAttr<InternalLinkageAttr>();
4698 }
4699
4700 // Merge the types.
4701 VarDecl *MostRecent = Old->getMostRecentDecl();
4702 if (MostRecent != Old) {
4703 MergeVarDeclTypes(New, MostRecent,
4704 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4705 if (New->isInvalidDecl())
4706 return;
4707 }
4708
4710 if (New->isInvalidDecl())
4711 return;
4712
4713 diag::kind PrevDiag;
4714 SourceLocation OldLocation;
4715 std::tie(PrevDiag, OldLocation) =
4717
4718 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4719 if (New->getStorageClass() == SC_Static &&
4720 !New->isStaticDataMember() &&
4721 Old->hasExternalFormalLinkage()) {
4722 if (getLangOpts().MicrosoftExt) {
4723 Diag(New->getLocation(), diag::ext_static_non_static)
4724 << New->getDeclName();
4725 Diag(OldLocation, PrevDiag);
4726 } else {
4727 Diag(New->getLocation(), diag::err_static_non_static)
4728 << New->getDeclName();
4729 Diag(OldLocation, PrevDiag);
4730 return New->setInvalidDecl();
4731 }
4732 }
4733 // C99 6.2.2p4:
4734 // For an identifier declared with the storage-class specifier
4735 // extern in a scope in which a prior declaration of that
4736 // identifier is visible,23) if the prior declaration specifies
4737 // internal or external linkage, the linkage of the identifier at
4738 // the later declaration is the same as the linkage specified at
4739 // the prior declaration. If no prior declaration is visible, or
4740 // if the prior declaration specifies no linkage, then the
4741 // identifier has external linkage.
4742 if (New->hasExternalStorage() && Old->hasLinkage())
4743 /* Okay */;
4744 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4745 !New->isStaticDataMember() &&
4747 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4748 Diag(OldLocation, PrevDiag);
4749 return New->setInvalidDecl();
4750 }
4751
4752 // Check if extern is followed by non-extern and vice-versa.
4753 if (New->hasExternalStorage() &&
4754 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4755 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4756 Diag(OldLocation, PrevDiag);
4757 return New->setInvalidDecl();
4758 }
4759 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4760 !New->hasExternalStorage()) {
4761 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4762 Diag(OldLocation, PrevDiag);
4763 return New->setInvalidDecl();
4764 }
4765
4767 return;
4768
4769 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4770
4771 // FIXME: The test for external storage here seems wrong? We still
4772 // need to check for mismatches.
4773 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4774 // Don't complain about out-of-line definitions of static members.
4775 !(Old->getLexicalDeclContext()->isRecord() &&
4776 !New->getLexicalDeclContext()->isRecord())) {
4777 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4778 Diag(OldLocation, PrevDiag);
4779 return New->setInvalidDecl();
4780 }
4781
4782 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4783 if (VarDecl *Def = Old->getDefinition()) {
4784 // C++1z [dcl.fcn.spec]p4:
4785 // If the definition of a variable appears in a translation unit before
4786 // its first declaration as inline, the program is ill-formed.
4787 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4788 Diag(Def->getLocation(), diag::note_previous_definition);
4789 }
4790 }
4791
4792 // If this redeclaration makes the variable inline, we may need to add it to
4793 // UndefinedButUsed.
4794 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4795 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4796 !Old->isInAnotherModuleUnit())
4797 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4798 SourceLocation()));
4799
4800 if (New->getTLSKind() != Old->getTLSKind()) {
4801 if (!Old->getTLSKind()) {
4802 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4803 Diag(OldLocation, PrevDiag);
4804 } else if (!New->getTLSKind()) {
4805 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4806 Diag(OldLocation, PrevDiag);
4807 } else {
4808 // Do not allow redeclaration to change the variable between requiring
4809 // static and dynamic initialization.
4810 // FIXME: GCC allows this, but uses the TLS keyword on the first
4811 // declaration to determine the kind. Do we need to be compatible here?
4812 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4813 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4814 Diag(OldLocation, PrevDiag);
4815 }
4816 }
4817
4818 // C++ doesn't have tentative definitions, so go right ahead and check here.
4819 if (getLangOpts().CPlusPlus) {
4820 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4821 Old->getCanonicalDecl()->isConstexpr()) {
4822 // This definition won't be a definition any more once it's been merged.
4823 Diag(New->getLocation(),
4824 diag::warn_deprecated_redundant_constexpr_static_def);
4825 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4826 VarDecl *Def = Old->getDefinition();
4827 if (Def && checkVarDeclRedefinition(Def, New))
4828 return;
4829 }
4830 } else {
4831 // C++ may not have a tentative definition rule, but it has a different
4832 // rule about what constitutes a definition in the first place. See
4833 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4834 // contains the extern specifier and doesn't have an initializer, it's fine
4835 // in C++.
4836 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4837 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4838 << New;
4839 Diag(Old->getLocation(), diag::note_previous_declaration);
4840 }
4841 }
4842
4844 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4845 Diag(OldLocation, PrevDiag);
4846 New->setInvalidDecl();
4847 return;
4848 }
4849
4850 // Merge "used" flag.
4851 if (Old->getMostRecentDecl()->isUsed(false))
4852 New->setIsUsed();
4853
4854 // Keep a chain of previous declarations.
4855 New->setPreviousDecl(Old);
4856 if (NewTemplate)
4857 NewTemplate->setPreviousDecl(OldTemplate);
4858
4859 // Inherit access appropriately.
4860 New->setAccess(Old->getAccess());
4861 if (NewTemplate)
4862 NewTemplate->setAccess(New->getAccess());
4863
4864 if (Old->isInline())
4865 New->setImplicitlyInline();
4866}
4867
4869 SourceManager &SrcMgr = getSourceManager();
4870 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4871 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4872 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4873 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4874 auto &HSI = PP.getHeaderSearchInfo();
4875 StringRef HdrFilename =
4876 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4877
4878 auto noteFromModuleOrInclude = [&](Module *Mod,
4879 SourceLocation IncLoc) -> bool {
4880 // Redefinition errors with modules are common with non modular mapped
4881 // headers, example: a non-modular header H in module A that also gets
4882 // included directly in a TU. Pointing twice to the same header/definition
4883 // is confusing, try to get better diagnostics when modules is on.
4884 if (IncLoc.isValid()) {
4885 if (Mod) {
4886 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4887 << HdrFilename.str() << Mod->getFullModuleName();
4888 if (!Mod->DefinitionLoc.isInvalid())
4889 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4890 << Mod->getFullModuleName();
4891 } else {
4892 Diag(IncLoc, diag::note_redefinition_include_same_file)
4893 << HdrFilename.str();
4894 }
4895 return true;
4896 }
4897
4898 return false;
4899 };
4900
4901 // Is it the same file and same offset? Provide more information on why
4902 // this leads to a redefinition error.
4903 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4904 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4905 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4906 bool EmittedDiag =
4907 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4908 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4909
4910 // If the header has no guards, emit a note suggesting one.
4911 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4912 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4913
4914 if (EmittedDiag)
4915 return;
4916 }
4917
4918 // Redefinition coming from different files or couldn't do better above.
4919 if (Old->getLocation().isValid())
4920 Diag(Old->getLocation(), diag::note_previous_definition);
4921}
4922
4924 if (!hasVisibleDefinition(Old) &&
4925 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4926 isa<VarTemplateSpecializationDecl>(New) ||
4927 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4928 New->getDeclContext()->isDependentContext() ||
4929 New->hasAttr<SelectAnyAttr>())) {
4930 // The previous definition is hidden, and multiple definitions are
4931 // permitted (in separate TUs). Demote this to a declaration.
4932 New->demoteThisDefinitionToDeclaration();
4933
4934 // Make the canonical definition visible.
4935 if (auto *OldTD = Old->getDescribedVarTemplate())
4938 return false;
4939 } else {
4940 Diag(New->getLocation(), diag::err_redefinition) << New;
4941 notePreviousDefinition(Old, New->getLocation());
4942 New->setInvalidDecl();
4943 return true;
4944 }
4945}
4946
4948 DeclSpec &DS,
4949 const ParsedAttributesView &DeclAttrs,
4950 RecordDecl *&AnonRecord) {
4952 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4953}
4954
4955// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4956// disambiguate entities defined in different scopes.
4957// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4958// compatibility.
4959// We will pick our mangling number depending on which version of MSVC is being
4960// targeted.
4961static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4963 ? S->getMSCurManglingNumber()
4964 : S->getMSLastManglingNumber();
4965}
4966
4967void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4968 if (!Context.getLangOpts().CPlusPlus)
4969 return;
4970
4971 if (isa<CXXRecordDecl>(Tag->getParent())) {
4972 // If this tag is the direct child of a class, number it if
4973 // it is anonymous.
4974 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4975 return;
4977 Context.getManglingNumberContext(Tag->getParent());
4979 Tag, MCtx.getManglingNumber(
4980 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4981 return;
4982 }
4983
4984 // If this tag isn't a direct child of a class, number it if it is local.
4986 Decl *ManglingContextDecl;
4987 std::tie(MCtx, ManglingContextDecl) =
4988 getCurrentMangleNumberContext(Tag->getDeclContext());
4989 if (MCtx) {
4991 Tag, MCtx->getManglingNumber(
4992 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4993 }
4994}
4995
4996namespace {
4997struct NonCLikeKind {
4998 enum {
4999 None,
5000 BaseClass,
5001 DefaultMemberInit,
5002 Lambda,
5003 Friend,
5004 OtherMember,
5005 Invalid,
5006 } Kind = None;
5008
5009 explicit operator bool() { return Kind != None; }
5010};
5011}
5012
5013/// Determine whether a class is C-like, according to the rules of C++
5014/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5015static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5016 if (RD->isInvalidDecl())
5017 return {NonCLikeKind::Invalid, {}};
5018
5019 // C++ [dcl.typedef]p9: [P1766R1]
5020 // An unnamed class with a typedef name for linkage purposes shall not
5021 //
5022 // -- have any base classes
5023 if (RD->getNumBases())
5024 return {NonCLikeKind::BaseClass,
5026 RD->bases_end()[-1].getEndLoc())};
5027 bool Invalid = false;
5028 for (Decl *D : RD->decls()) {
5029 // Don't complain about things we already diagnosed.
5030 if (D->isInvalidDecl()) {
5031 Invalid = true;
5032 continue;
5033 }
5034
5035 // -- have any [...] default member initializers
5036 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5037 if (FD->hasInClassInitializer()) {
5038 auto *Init = FD->getInClassInitializer();
5039 return {NonCLikeKind::DefaultMemberInit,
5040 Init ? Init->getSourceRange() : D->getSourceRange()};
5041 }
5042 continue;
5043 }
5044
5045 // FIXME: We don't allow friend declarations. This violates the wording of
5046 // P1766, but not the intent.
5047 if (isa<FriendDecl>(D))
5048 return {NonCLikeKind::Friend, D->getSourceRange()};
5049
5050 // -- declare any members other than non-static data members, member
5051 // enumerations, or member classes,
5052 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
5053 isa<EnumDecl>(D))
5054 continue;
5055 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5056 if (!MemberRD) {
5057 if (D->isImplicit())
5058 continue;
5059 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5060 }
5061
5062 // -- contain a lambda-expression,
5063 if (MemberRD->isLambda())
5064 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5065
5066 // and all member classes shall also satisfy these requirements
5067 // (recursively).
5068 if (MemberRD->isThisDeclarationADefinition()) {
5069 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5070 return Kind;
5071 }
5072 }
5073
5074 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5075}
5076
5078 TypedefNameDecl *NewTD) {
5079 if (TagFromDeclSpec->isInvalidDecl())
5080 return;
5081
5082 // Do nothing if the tag already has a name for linkage purposes.
5083 if (TagFromDeclSpec->hasNameForLinkage())
5084 return;
5085
5086 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5087 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5088
5089 // The type must match the tag exactly; no qualifiers allowed.
5091 Context.getCanonicalTagType(TagFromDeclSpec))) {
5092 if (getLangOpts().CPlusPlus)
5093 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5094 return;
5095 }
5096
5097 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5098 // An unnamed class with a typedef name for linkage purposes shall [be
5099 // C-like].
5100 //
5101 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5102 // shouldn't happen, but there are constructs that the language rule doesn't
5103 // disallow for which we can't reasonably avoid computing linkage early.
5104 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5105 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5106 : NonCLikeKind();
5107 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5108 if (NonCLike || ChangesLinkage) {
5109 if (NonCLike.Kind == NonCLikeKind::Invalid)
5110 return;
5111
5112 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5113 if (ChangesLinkage) {
5114 // If the linkage changes, we can't accept this as an extension.
5115 if (NonCLike.Kind == NonCLikeKind::None)
5116 DiagID = diag::err_typedef_changes_linkage;
5117 else
5118 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5119 }
5120
5121 SourceLocation FixitLoc =
5122 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5123 llvm::SmallString<40> TextToInsert;
5124 TextToInsert += ' ';
5125 TextToInsert += NewTD->getIdentifier()->getName();
5126
5127 Diag(FixitLoc, DiagID)
5128 << isa<TypeAliasDecl>(NewTD)
5129 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5130 if (NonCLike.Kind != NonCLikeKind::None) {
5131 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5132 << NonCLike.Kind - 1 << NonCLike.Range;
5133 }
5134 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5135 << NewTD << isa<TypeAliasDecl>(NewTD);
5136
5137 if (ChangesLinkage)
5138 return;
5139 }
5140
5141 // Otherwise, set this as the anon-decl typedef for the tag.
5142 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5143
5144 // Now that we have a name for the tag, process API notes again.
5145 ProcessAPINotes(TagFromDeclSpec);
5146}
5147
5148static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5150 switch (T) {
5152 return 0;
5154 return 1;
5156 return 2;
5158 return 3;
5159 case DeclSpec::TST_enum:
5160 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5161 if (ED->isScopedUsingClassTag())
5162 return 5;
5163 if (ED->isScoped())
5164 return 6;
5165 }
5166 return 4;
5167 default:
5168 llvm_unreachable("unexpected type specifier");
5169 }
5170}
5171
5173 DeclSpec &DS,
5174 const ParsedAttributesView &DeclAttrs,
5175 MultiTemplateParamsArg TemplateParams,
5176 bool IsExplicitInstantiation,
5177 RecordDecl *&AnonRecord,
5178 SourceLocation EllipsisLoc) {
5179 Decl *TagD = nullptr;
5180 TagDecl *Tag = nullptr;
5186 TagD = DS.getRepAsDecl();
5187
5188 if (!TagD) // We probably had an error
5189 return nullptr;
5190
5191 // Note that the above type specs guarantee that the
5192 // type rep is a Decl, whereas in many of the others
5193 // it's a Type.
5194 if (isa<TagDecl>(TagD))
5195 Tag = cast<TagDecl>(TagD);
5196 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5197 Tag = CTD->getTemplatedDecl();
5198 }
5199
5200 if (Tag) {
5201 handleTagNumbering(Tag, S);
5202 Tag->setFreeStanding();
5203 if (Tag->isInvalidDecl())
5204 return Tag;
5205 }
5206
5207 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5208 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5209 // or incomplete types shall not be restrict-qualified."
5210 if (TypeQuals & DeclSpec::TQ_restrict)
5212 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5213 << DS.getSourceRange();
5214 }
5215
5216 if (DS.isInlineSpecified())
5217 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5218 << getLangOpts().CPlusPlus17;
5219
5220 if (DS.hasConstexprSpecifier()) {
5221 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5222 // and definitions of functions and variables.
5223 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5224 // the declaration of a function or function template
5225 if (Tag)
5226 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5228 << static_cast<int>(DS.getConstexprSpecifier());
5229 else if (getLangOpts().C23)
5230 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5231 else
5232 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5233 << static_cast<int>(DS.getConstexprSpecifier());
5234 // Don't emit warnings after this error.
5235 return TagD;
5236 }
5237
5239
5240 if (DS.isFriendSpecified()) {
5241 // If we're dealing with a decl but not a TagDecl, assume that
5242 // whatever routines created it handled the friendship aspect.
5243 if (TagD && !Tag)
5244 return nullptr;
5245 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5246 }
5247
5248 assert(EllipsisLoc.isInvalid() &&
5249 "Friend ellipsis but not friend-specified?");
5250
5251 // Track whether this decl-specifier declares anything.
5252 bool DeclaresAnything = true;
5253
5254 // Handle anonymous struct definitions.
5255 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5256 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5258 if (getLangOpts().CPlusPlus ||
5259 Record->getDeclContext()->isRecord()) {
5260 // If CurContext is a DeclContext that can contain statements,
5261 // RecursiveASTVisitor won't visit the decls that
5262 // BuildAnonymousStructOrUnion() will put into CurContext.
5263 // Also store them here so that they can be part of the
5264 // DeclStmt that gets created in this case.
5265 // FIXME: Also return the IndirectFieldDecls created by
5266 // BuildAnonymousStructOr union, for the same reason?
5268 AnonRecord = Record;
5269 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5271 }
5272
5273 DeclaresAnything = false;
5274 }
5275 }
5276
5277 // C11 6.7.2.1p2:
5278 // A struct-declaration that does not declare an anonymous structure or
5279 // anonymous union shall contain a struct-declarator-list.
5280 //
5281 // This rule also existed in C89 and C99; the grammar for struct-declaration
5282 // did not permit a struct-declaration without a struct-declarator-list.
5285 // Check for Microsoft C extension: anonymous struct/union member.
5286 // Handle 2 kinds of anonymous struct/union:
5287 // struct STRUCT;
5288 // union UNION;
5289 // and
5290 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5291 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5292 if ((Tag && Tag->getDeclName()) ||
5294 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5295 : DS.getRepAsType().get()->getAsRecordDecl();
5296 if (Record && getLangOpts().MicrosoftExt) {
5297 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5298 << Record->isUnion() << DS.getSourceRange();
5300 }
5301
5302 DeclaresAnything = false;
5303 }
5304 }
5305
5306 // Skip all the checks below if we have a type error.
5308 (TagD && TagD->isInvalidDecl()))
5309 return TagD;
5310
5311 if (getLangOpts().CPlusPlus &&
5313 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5314 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5315 !Enum->isInvalidDecl())
5316 DeclaresAnything = false;
5317
5318 if (!DS.isMissingDeclaratorOk()) {
5319 // Customize diagnostic for a typedef missing a name.
5321 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5322 << DS.getSourceRange();
5323 else
5324 DeclaresAnything = false;
5325 }
5326
5327 if (DS.isModulePrivateSpecified() &&
5328 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5329 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5330 << Tag->getTagKind()
5332
5334
5335 // C 6.7/2:
5336 // A declaration [...] shall declare at least a declarator [...], a tag,
5337 // or the members of an enumeration.
5338 // C++ [dcl.dcl]p3:
5339 // [If there are no declarators], and except for the declaration of an
5340 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5341 // names into the program, or shall redeclare a name introduced by a
5342 // previous declaration.
5343 if (!DeclaresAnything) {
5344 // In C, we allow this as a (popular) extension / bug. Don't bother
5345 // producing further diagnostics for redundant qualifiers after this.
5346 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5347 ? diag::err_no_declarators
5348 : diag::ext_no_declarators)
5349 << DS.getSourceRange();
5350 return TagD;
5351 }
5352
5353 // C++ [dcl.stc]p1:
5354 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5355 // init-declarator-list of the declaration shall not be empty.
5356 // C++ [dcl.fct.spec]p1:
5357 // If a cv-qualifier appears in a decl-specifier-seq, the
5358 // init-declarator-list of the declaration shall not be empty.
5359 //
5360 // Spurious qualifiers here appear to be valid in C.
5361 unsigned DiagID = diag::warn_standalone_specifier;
5362 if (getLangOpts().CPlusPlus)
5363 DiagID = diag::ext_standalone_specifier;
5364
5365 // Note that a linkage-specification sets a storage class, but
5366 // 'extern "C" struct foo;' is actually valid and not theoretically
5367 // useless.
5368 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5369 if (SCS == DeclSpec::SCS_mutable)
5370 // Since mutable is not a viable storage class specifier in C, there is
5371 // no reason to treat it as an extension. Instead, diagnose as an error.
5372 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5373 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5374 Diag(DS.getStorageClassSpecLoc(), DiagID)
5376 }
5377
5381 if (DS.getTypeQualifiers()) {
5383 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5385 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5386 // Restrict is covered above.
5388 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5390 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5391 }
5392
5393 // Warn about ignored type attributes, for example:
5394 // __attribute__((aligned)) struct A;
5395 // Attributes should be placed after tag to apply to type declaration.
5396 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5397 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5398 if (TypeSpecType == DeclSpec::TST_class ||
5399 TypeSpecType == DeclSpec::TST_struct ||
5400 TypeSpecType == DeclSpec::TST_interface ||
5401 TypeSpecType == DeclSpec::TST_union ||
5402 TypeSpecType == DeclSpec::TST_enum) {
5403
5404 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5405 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5406 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5407 DiagnosticId = diag::warn_attribute_ignored;
5408 else if (AL.isRegularKeywordAttribute())
5409 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5410 else
5411 DiagnosticId = diag::warn_declspec_attribute_ignored;
5412 Diag(AL.getLoc(), DiagnosticId)
5413 << AL << GetDiagnosticTypeSpecifierID(DS);
5414 };
5415
5416 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5417 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5418 }
5419 }
5420
5421 return TagD;
5422}
5423
5424/// We are trying to inject an anonymous member into the given scope;
5425/// check if there's an existing declaration that can't be overloaded.
5426///
5427/// \return true if this is a forbidden redeclaration
5428static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5429 DeclContext *Owner,
5430 DeclarationName Name,
5431 SourceLocation NameLoc, bool IsUnion,
5432 StorageClass SC) {
5433 LookupResult R(SemaRef, Name, NameLoc,
5436 RedeclarationKind::ForVisibleRedeclaration);
5437 if (!SemaRef.LookupName(R, S)) return false;
5438
5439 // Pick a representative declaration.
5441 assert(PrevDecl && "Expected a non-null Decl");
5442
5443 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5444 return false;
5445
5446 if (SC == StorageClass::SC_None &&
5447 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5448 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5449 if (!Owner->isRecord())
5450 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5451 return false;
5452 }
5453
5454 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5455 << IsUnion << Name;
5456 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5457
5458 return true;
5459}
5460
5462 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5464}
5465
5467 if (!getLangOpts().CPlusPlus)
5468 return;
5469
5470 // This function can be parsed before we have validated the
5471 // structure as an anonymous struct
5472 if (Record->isAnonymousStructOrUnion())
5473 return;
5474
5475 const NamedDecl *First = 0;
5476 for (const Decl *D : Record->decls()) {
5477 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5478 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5479 continue;
5480 if (!First)
5481 First = ND;
5482 else
5484 }
5485}
5486
5487/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5488/// anonymous struct or union AnonRecord into the owning context Owner
5489/// and scope S. This routine will be invoked just after we realize
5490/// that an unnamed union or struct is actually an anonymous union or
5491/// struct, e.g.,
5492///
5493/// @code
5494/// union {
5495/// int i;
5496/// float f;
5497/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5498/// // f into the surrounding scope.x
5499/// @endcode
5500///
5501/// This routine is recursive, injecting the names of nested anonymous
5502/// structs/unions into the owning context and scope as well.
5503static bool
5505 RecordDecl *AnonRecord, AccessSpecifier AS,
5506 StorageClass SC,
5507 SmallVectorImpl<NamedDecl *> &Chaining) {
5508 bool Invalid = false;
5509
5510 // Look every FieldDecl and IndirectFieldDecl with a name.
5511 for (auto *D : AnonRecord->decls()) {
5512 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5513 cast<NamedDecl>(D)->getDeclName()) {
5514 ValueDecl *VD = cast<ValueDecl>(D);
5515 // C++ [class.union]p2:
5516 // The names of the members of an anonymous union shall be
5517 // distinct from the names of any other entity in the
5518 // scope in which the anonymous union is declared.
5519
5520 bool FieldInvalid = CheckAnonMemberRedeclaration(
5521 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5522 AnonRecord->isUnion(), SC);
5523 if (FieldInvalid)
5524 Invalid = true;
5525
5526 // Inject the IndirectFieldDecl even if invalid, because later
5527 // diagnostics may depend on it being present, see findDefaultInitializer.
5528
5529 // C++ [class.union]p2:
5530 // For the purpose of name lookup, after the anonymous union
5531 // definition, the members of the anonymous union are
5532 // considered to have been defined in the scope in which the
5533 // anonymous union is declared.
5534 unsigned OldChainingSize = Chaining.size();
5535 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5536 Chaining.append(IF->chain_begin(), IF->chain_end());
5537 else
5538 Chaining.push_back(VD);
5539
5540 assert(Chaining.size() >= 2);
5541 NamedDecl **NamedChain =
5542 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5543 for (unsigned i = 0; i < Chaining.size(); i++)
5544 NamedChain[i] = Chaining[i];
5545
5547 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5548 VD->getType(), {NamedChain, Chaining.size()});
5549
5550 for (const auto *Attr : VD->attrs())
5551 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5552
5553 IndirectField->setAccess(AS);
5554 IndirectField->setImplicit();
5555 IndirectField->setInvalidDecl(FieldInvalid);
5556 SemaRef.PushOnScopeChains(IndirectField, S);
5557
5558 // That includes picking up the appropriate access specifier.
5559 if (AS != AS_none)
5560 IndirectField->setAccess(AS);
5561
5562 Chaining.resize(OldChainingSize);
5563 }
5564 }
5565
5566 return Invalid;
5567}
5568
5569/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5570/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5571/// illegal input values are mapped to SC_None.
5572static StorageClass
5574 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5575 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5576 "Parser allowed 'typedef' as storage class VarDecl.");
5577 switch (StorageClassSpec) {
5580 if (DS.isExternInLinkageSpec())
5581 return SC_None;
5582 return SC_Extern;
5583 case DeclSpec::SCS_static: return SC_Static;
5584 case DeclSpec::SCS_auto: return SC_Auto;
5587 // Illegal SCSs map to None: error reporting is up to the caller.
5588 case DeclSpec::SCS_mutable: // Fall through.
5589 case DeclSpec::SCS_typedef: return SC_None;
5590 }
5591 llvm_unreachable("unknown storage class specifier");
5592}
5593
5595 assert(Record->hasInClassInitializer());
5596
5597 for (const auto *I : Record->decls()) {
5598 const auto *FD = dyn_cast<FieldDecl>(I);
5599 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5600 FD = IFD->getAnonField();
5601 if (FD && FD->hasInClassInitializer())
5602 return FD->getLocation();
5603 }
5604
5605 llvm_unreachable("couldn't find in-class initializer");
5606}
5607
5609 SourceLocation DefaultInitLoc) {
5610 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5611 return;
5612
5613 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5614 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5615}
5616
5618 CXXRecordDecl *AnonUnion) {
5619 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5620 return;
5621
5623}
5624
5626 AccessSpecifier AS,
5628 const PrintingPolicy &Policy) {
5629 DeclContext *Owner = Record->getDeclContext();
5630
5631 // Diagnose whether this anonymous struct/union is an extension.
5632 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5633 Diag(Record->getLocation(), diag::ext_anonymous_union);
5634 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5635 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5636 else if (!Record->isUnion() && !getLangOpts().C11)
5637 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5638
5639 // C and C++ require different kinds of checks for anonymous
5640 // structs/unions.
5641 bool Invalid = false;
5642 if (getLangOpts().CPlusPlus) {
5643 const char *PrevSpec = nullptr;
5644 if (Record->isUnion()) {
5645 // C++ [class.union]p6:
5646 // C++17 [class.union.anon]p2:
5647 // Anonymous unions declared in a named namespace or in the
5648 // global namespace shall be declared static.
5649 unsigned DiagID;
5650 DeclContext *OwnerScope = Owner->getRedeclContext();
5652 (OwnerScope->isTranslationUnit() ||
5653 (OwnerScope->isNamespace() &&
5654 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5655 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5656 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5657
5658 // Recover by adding 'static'.
5660 PrevSpec, DiagID, Policy);
5661 }
5662 // C++ [class.union]p6:
5663 // A storage class is not allowed in a declaration of an
5664 // anonymous union in a class scope.
5666 isa<RecordDecl>(Owner)) {
5668 diag::err_anonymous_union_with_storage_spec)
5670
5671 // Recover by removing the storage specifier.
5674 PrevSpec, DiagID, Context.getPrintingPolicy());
5675 }
5676 }
5677
5678 // Ignore const/volatile/restrict qualifiers.
5679 if (DS.getTypeQualifiers()) {
5681 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5682 << Record->isUnion() << "const"
5686 diag::ext_anonymous_struct_union_qualified)
5687 << Record->isUnion() << "volatile"
5691 diag::ext_anonymous_struct_union_qualified)
5692 << Record->isUnion() << "restrict"
5696 diag::ext_anonymous_struct_union_qualified)
5697 << Record->isUnion() << "_Atomic"
5701 diag::ext_anonymous_struct_union_qualified)
5702 << Record->isUnion() << "__unaligned"
5704
5706 }
5707
5708 // C++ [class.union]p2:
5709 // The member-specification of an anonymous union shall only
5710 // define non-static data members. [Note: nested types and
5711 // functions cannot be declared within an anonymous union. ]
5712 for (auto *Mem : Record->decls()) {
5713 // Ignore invalid declarations; we already diagnosed them.
5714 if (Mem->isInvalidDecl())
5715 continue;
5716
5717 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5718 // C++ [class.union]p3:
5719 // An anonymous union shall not have private or protected
5720 // members (clause 11).
5721 assert(FD->getAccess() != AS_none);
5722 if (FD->getAccess() != AS_public) {
5723 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5724 << Record->isUnion() << (FD->getAccess() == AS_protected);
5725 Invalid = true;
5726 }
5727
5728 // C++ [class.union]p1
5729 // An object of a class with a non-trivial constructor, a non-trivial
5730 // copy constructor, a non-trivial destructor, or a non-trivial copy
5731 // assignment operator cannot be a member of a union, nor can an
5732 // array of such objects.
5733 if (CheckNontrivialField(FD))
5734 Invalid = true;
5735 } else if (Mem->isImplicit()) {
5736 // Any implicit members are fine.
5737 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5738 // This is a type that showed up in an
5739 // elaborated-type-specifier inside the anonymous struct or
5740 // union, but which actually declares a type outside of the
5741 // anonymous struct or union. It's okay.
5742 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5743 if (!MemRecord->isAnonymousStructOrUnion() &&
5744 MemRecord->getDeclName()) {
5745 // Visual C++ allows type definition in anonymous struct or union.
5746 if (getLangOpts().MicrosoftExt)
5747 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5748 << Record->isUnion();
5749 else {
5750 // This is a nested type declaration.
5751 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5752 << Record->isUnion();
5753 Invalid = true;
5754 }
5755 } else {
5756 // This is an anonymous type definition within another anonymous type.
5757 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5758 // not part of standard C++.
5759 Diag(MemRecord->getLocation(),
5760 diag::ext_anonymous_record_with_anonymous_type)
5761 << Record->isUnion();
5762 }
5763 } else if (isa<AccessSpecDecl>(Mem)) {
5764 // Any access specifier is fine.
5765 } else if (isa<StaticAssertDecl>(Mem)) {
5766 // In C++1z, static_assert declarations are also fine.
5767 } else {
5768 // We have something that isn't a non-static data
5769 // member. Complain about it.
5770 unsigned DK = diag::err_anonymous_record_bad_member;
5771 if (isa<TypeDecl>(Mem))
5772 DK = diag::err_anonymous_record_with_type;
5773 else if (isa<FunctionDecl>(Mem))
5774 DK = diag::err_anonymous_record_with_function;
5775 else if (isa<VarDecl>(Mem))
5776 DK = diag::err_anonymous_record_with_static;
5777
5778 // Visual C++ allows type definition in anonymous struct or union.
5779 if (getLangOpts().MicrosoftExt &&
5780 DK == diag::err_anonymous_record_with_type)
5781 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5782 << Record->isUnion();
5783 else {
5784 Diag(Mem->getLocation(), DK) << Record->isUnion();
5785 Invalid = true;
5786 }
5787 }
5788 }
5789
5790 // C++11 [class.union]p8 (DR1460):
5791 // At most one variant member of a union may have a
5792 // brace-or-equal-initializer.
5793 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5794 Owner->isRecord())
5795 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5796 cast<CXXRecordDecl>(Record));
5797 }
5798
5799 if (!Record->isUnion() && !Owner->isRecord()) {
5800 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5801 << getLangOpts().CPlusPlus;
5802 Invalid = true;
5803 }
5804
5805 // C++ [dcl.dcl]p3:
5806 // [If there are no declarators], and except for the declaration of an
5807 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5808 // names into the program
5809 // C++ [class.mem]p2:
5810 // each such member-declaration shall either declare at least one member
5811 // name of the class or declare at least one unnamed bit-field
5812 //
5813 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5814 if (getLangOpts().CPlusPlus && Record->field_empty())
5815 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5816
5817 // Mock up a declarator.
5821 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5822
5823 // Create a declaration for this anonymous struct/union.
5824 NamedDecl *Anon = nullptr;
5825 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5826 Anon = FieldDecl::Create(
5827 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5828 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5829 /*BitWidth=*/nullptr, /*Mutable=*/false,
5830 /*InitStyle=*/ICIS_NoInit);
5831 Anon->setAccess(AS);
5832 ProcessDeclAttributes(S, Anon, Dc);
5833
5834 if (getLangOpts().CPlusPlus)
5835 FieldCollector->Add(cast<FieldDecl>(Anon));
5836 } else {
5837 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5838 if (SCSpec == DeclSpec::SCS_mutable) {
5839 // mutable can only appear on non-static class members, so it's always
5840 // an error here
5841 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5842 Invalid = true;
5843 SC = SC_None;
5844 }
5845
5846 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5847 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5848 Context.getCanonicalTagType(Record), TInfo, SC);
5849 if (Invalid)
5850 Anon->setInvalidDecl();
5851
5852 ProcessDeclAttributes(S, Anon, Dc);
5853
5854 // Default-initialize the implicit variable. This initialization will be
5855 // trivial in almost all cases, except if a union member has an in-class
5856 // initializer:
5857 // union { int n = 0; };
5859 }
5860 Anon->setImplicit();
5861
5862 // Mark this as an anonymous struct/union type.
5863 Record->setAnonymousStructOrUnion(true);
5864
5865 // Add the anonymous struct/union object to the current
5866 // context. We'll be referencing this object when we refer to one of
5867 // its members.
5868 Owner->addDecl(Anon);
5869
5870 // Inject the members of the anonymous struct/union into the owning
5871 // context and into the identifier resolver chain for name lookup
5872 // purposes.
5874 Chain.push_back(Anon);
5875
5876 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5877 Chain))
5878 Invalid = true;
5879
5880 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5881 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5883 Decl *ManglingContextDecl;
5884 std::tie(MCtx, ManglingContextDecl) =
5885 getCurrentMangleNumberContext(NewVD->getDeclContext());
5886 if (MCtx) {
5888 NewVD, MCtx->getManglingNumber(
5889 NewVD, getMSManglingNumber(getLangOpts(), S)));
5891 }
5892 }
5893 }
5894
5895 if (Invalid)
5896 Anon->setInvalidDecl();
5897
5898 return Anon;
5899}
5900
5902 RecordDecl *Record) {
5903 assert(Record && "expected a record!");
5904
5905 // Mock up a declarator.
5908 assert(TInfo && "couldn't build declarator info for anonymous struct");
5909
5910 auto *ParentDecl = cast<RecordDecl>(CurContext);
5912
5913 // Create a declaration for this anonymous struct.
5914 NamedDecl *Anon =
5915 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5916 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5917 /*BitWidth=*/nullptr, /*Mutable=*/false,
5918 /*InitStyle=*/ICIS_NoInit);
5919 Anon->setImplicit();
5920
5921 // Add the anonymous struct object to the current context.
5922 CurContext->addDecl(Anon);
5923
5924 // Inject the members of the anonymous struct into the current
5925 // context and into the identifier resolver chain for name lookup
5926 // purposes.
5928 Chain.push_back(Anon);
5929
5930 RecordDecl *RecordDef = Record->getDefinition();
5931 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5932 diag::err_field_incomplete_or_sizeless) ||
5934 *this, S, CurContext, RecordDef, AS_none,
5936 Anon->setInvalidDecl();
5937 ParentDecl->setInvalidDecl();
5938 }
5939
5940 return Anon;
5941}
5942
5944 return GetNameFromUnqualifiedId(D.getName());
5945}
5946
5949 DeclarationNameInfo NameInfo;
5950 NameInfo.setLoc(Name.StartLocation);
5951
5952 switch (Name.getKind()) {
5953
5956 NameInfo.setName(Name.Identifier);
5957 return NameInfo;
5958
5960 // C++ [temp.deduct.guide]p3:
5961 // The simple-template-id shall name a class template specialization.
5962 // The template-name shall be the same identifier as the template-name
5963 // of the simple-template-id.
5964 // These together intend to imply that the template-name shall name a
5965 // class template.
5966 // FIXME: template<typename T> struct X {};
5967 // template<typename T> using Y = X<T>;
5968 // Y(int) -> Y<int>;
5969 // satisfies these rules but does not name a class template.
5970 TemplateName TN = Name.TemplateName.get().get();
5971 auto *Template = TN.getAsTemplateDecl();
5972 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5973 Diag(Name.StartLocation,
5974 diag::err_deduction_guide_name_not_class_template)
5976 if (Template)
5978 return DeclarationNameInfo();
5979 }
5980
5981 NameInfo.setName(
5983 return NameInfo;
5984 }
5985
5988 Name.OperatorFunctionId.Operator));
5990 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5991 return NameInfo;
5992
5995 Name.Identifier));
5996 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5997 return NameInfo;
5998
6000 TypeSourceInfo *TInfo;
6001 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
6002 if (Ty.isNull())
6003 return DeclarationNameInfo();
6006 NameInfo.setNamedTypeInfo(TInfo);
6007 return NameInfo;
6008 }
6009
6011 TypeSourceInfo *TInfo;
6012 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6013 if (Ty.isNull())
6014 return DeclarationNameInfo();
6017 NameInfo.setNamedTypeInfo(TInfo);
6018 return NameInfo;
6019 }
6020
6022 // In well-formed code, we can only have a constructor
6023 // template-id that refers to the current context, so go there
6024 // to find the actual type being constructed.
6025 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6026 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6027 return DeclarationNameInfo();
6028
6029 // Determine the type of the class being constructed.
6030 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6031
6032 // FIXME: Check two things: that the template-id names the same type as
6033 // CurClassType, and that the template-id does not occur when the name
6034 // was qualified.
6035
6036 NameInfo.setName(
6038 // FIXME: should we retrieve TypeSourceInfo?
6039 NameInfo.setNamedTypeInfo(nullptr);
6040 return NameInfo;
6041 }
6042
6044 TypeSourceInfo *TInfo;
6045 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6046 if (Ty.isNull())
6047 return DeclarationNameInfo();
6050 NameInfo.setNamedTypeInfo(TInfo);
6051 return NameInfo;
6052 }
6053
6055 TemplateName TName = Name.TemplateId->Template.get();
6056 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6057 return Context.getNameForTemplate(TName, TNameLoc);
6058 }
6059
6060 } // switch (Name.getKind())
6061
6062 llvm_unreachable("Unknown name kind");
6063}
6064
6066 do {
6067 if (Ty->isPointerOrReferenceType())
6068 Ty = Ty->getPointeeType();
6069 else if (Ty->isArrayType())
6071 else
6072 return Ty.withoutLocalFastQualifiers();
6073 } while (true);
6074}
6075
6076/// hasSimilarParameters - Determine whether the C++ functions Declaration
6077/// and Definition have "nearly" matching parameters. This heuristic is
6078/// used to improve diagnostics in the case where an out-of-line function
6079/// definition doesn't match any declaration within the class or namespace.
6080/// Also sets Params to the list of indices to the parameters that differ
6081/// between the declaration and the definition. If hasSimilarParameters
6082/// returns true and Params is empty, then all of the parameters match.
6086 SmallVectorImpl<unsigned> &Params) {
6087 Params.clear();
6088 if (Declaration->param_size() != Definition->param_size())
6089 return false;
6090 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6091 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6092 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6093
6094 // The parameter types are identical
6095 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6096 continue;
6097
6098 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6099 QualType DefParamBaseTy = getCoreType(DefParamTy);
6100 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6101 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6102
6103 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6104 (DeclTyName && DeclTyName == DefTyName))
6105 Params.push_back(Idx);
6106 else // The two parameters aren't even close
6107 return false;
6108 }
6109
6110 return true;
6111}
6112
6113/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6114/// declarator needs to be rebuilt in the current instantiation.
6115/// Any bits of declarator which appear before the name are valid for
6116/// consideration here. That's specifically the type in the decl spec
6117/// and the base type in any member-pointer chunks.
6119 DeclarationName Name) {
6120 // The types we specifically need to rebuild are:
6121 // - typenames, typeofs, and decltypes
6122 // - types which will become injected class names
6123 // Of course, we also need to rebuild any type referencing such a
6124 // type. It's safest to just say "dependent", but we call out a
6125 // few cases here.
6126
6127 DeclSpec &DS = D.getMutableDeclSpec();
6128 switch (DS.getTypeSpecType()) {
6132#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6133#include "clang/Basic/TransformTypeTraits.def"
6134 case DeclSpec::TST_atomic: {
6135 // Grab the type from the parser.
6136 TypeSourceInfo *TSI = nullptr;
6137 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6138 if (T.isNull() || !T->isInstantiationDependentType()) break;
6139
6140 // Make sure there's a type source info. This isn't really much
6141 // of a waste; most dependent types should have type source info
6142 // attached already.
6143 if (!TSI)
6145
6146 // Rebuild the type in the current instantiation.
6147 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6148 if (!TSI) return true;
6149
6150 // Store the new type back in the decl spec.
6151 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6152 DS.UpdateTypeRep(LocType);
6153 break;
6154 }
6155
6159 Expr *E = DS.getRepAsExpr();
6161 if (Result.isInvalid()) return true;
6162 DS.UpdateExprRep(Result.get());
6163 break;
6164 }
6165
6166 default:
6167 // Nothing to do for these decl specs.
6168 break;
6169 }
6170
6171 // It doesn't matter what order we do this in.
6172 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6173 DeclaratorChunk &Chunk = D.getTypeObject(I);
6174
6175 // The only type information in the declarator which can come
6176 // before the declaration name is the base type of a member
6177 // pointer.
6179 continue;
6180
6181 // Rebuild the scope specifier in-place.
6182 CXXScopeSpec &SS = Chunk.Mem.Scope();
6184 return true;
6185 }
6186
6187 return false;
6188}
6189
6190/// Returns true if the declaration is declared in a system header or from a
6191/// system macro.
6193 return SM.isInSystemHeader(D->getLocation()) ||
6194 SM.isInSystemMacro(D->getLocation());
6195}
6196
6198 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6199 // of system decl.
6200 if (D->getPreviousDecl() || D->isImplicit())
6201 return;
6202 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6205 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6206 << D << static_cast<int>(Status);
6207 }
6208}
6209
6211 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6212
6213 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6214 // declaration only if the `bind_to_declaration` extension is set.
6216 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6217 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6218 llvm::omp::TraitProperty::
6219 implementation_extension_bind_to_declaration))
6221 S, D, MultiTemplateParamsArg(), Bases);
6222
6224
6226 Dcl && Dcl->getDeclContext()->isFileContext())
6228
6229 if (!Bases.empty())
6231 Bases);
6232
6233 return Dcl;
6234}
6235
6237 DeclarationNameInfo NameInfo) {
6238 DeclarationName Name = NameInfo.getName();
6239
6240 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6241 while (Record && Record->isAnonymousStructOrUnion())
6242 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6243 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6244 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6245 return true;
6246 }
6247
6248 return false;
6249}
6250
6252 DeclarationName Name,
6254 TemplateIdAnnotation *TemplateId,
6255 bool IsMemberSpecialization) {
6256 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6257 "without nested-name-specifier");
6258 DeclContext *Cur = CurContext;
6259 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6260 Cur = Cur->getParent();
6261
6262 // If the user provided a superfluous scope specifier that refers back to the
6263 // class in which the entity is already declared, diagnose and ignore it.
6264 //
6265 // class X {
6266 // void X::f();
6267 // };
6268 //
6269 // Note, it was once ill-formed to give redundant qualification in all
6270 // contexts, but that rule was removed by DR482.
6271 if (Cur->Equals(DC)) {
6272 if (Cur->isRecord()) {
6273 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6274 : diag::err_member_extra_qualification)
6275 << Name << FixItHint::CreateRemoval(SS.getRange());
6276 SS.clear();
6277 } else {
6278 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6279 }
6280 return false;
6281 }
6282
6283 // Check whether the qualifying scope encloses the scope of the original
6284 // declaration. For a template-id, we perform the checks in
6285 // CheckTemplateSpecializationScope.
6286 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6287 if (Cur->isRecord())
6288 Diag(Loc, diag::err_member_qualification)
6289 << Name << SS.getRange();
6290 else if (isa<TranslationUnitDecl>(DC))
6291 Diag(Loc, diag::err_invalid_declarator_global_scope)
6292 << Name << SS.getRange();
6293 else if (isa<FunctionDecl>(Cur))
6294 Diag(Loc, diag::err_invalid_declarator_in_function)
6295 << Name << SS.getRange();
6296 else if (isa<BlockDecl>(Cur))
6297 Diag(Loc, diag::err_invalid_declarator_in_block)
6298 << Name << SS.getRange();
6299 else if (isa<ExportDecl>(Cur)) {
6300 if (!isa<NamespaceDecl>(DC))
6301 Diag(Loc, diag::err_export_non_namespace_scope_name)
6302 << Name << SS.getRange();
6303 else
6304 // The cases that DC is not NamespaceDecl should be handled in
6305 // CheckRedeclarationExported.
6306 return false;
6307 } else
6308 Diag(Loc, diag::err_invalid_declarator_scope)
6309 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6310
6311 return true;
6312 }
6313
6314 if (Cur->isRecord()) {
6315 // Cannot qualify members within a class.
6316 Diag(Loc, diag::err_member_qualification)
6317 << Name << SS.getRange();
6318 SS.clear();
6319
6320 // C++ constructors and destructors with incorrect scopes can break
6321 // our AST invariants by having the wrong underlying types. If
6322 // that's the case, then drop this declaration entirely.
6323 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6324 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6326 Name.getCXXNameType(),
6327 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6328 return true;
6329
6330 return false;
6331 }
6332
6333 // C++23 [temp.names]p5:
6334 // The keyword template shall not appear immediately after a declarative
6335 // nested-name-specifier.
6336 //
6337 // First check the template-id (if any), and then check each component of the
6338 // nested-name-specifier in reverse order.
6339 //
6340 // FIXME: nested-name-specifiers in friend declarations are declarative,
6341 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6342 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6343 Diag(Loc, diag::ext_template_after_declarative_nns)
6345
6347 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6348 TL = std::exchange(NextTL, TypeLoc())) {
6349 SourceLocation TemplateKeywordLoc;
6350 switch (TL.getTypeLocClass()) {
6351 case TypeLoc::TemplateSpecialization: {
6352 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6353 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6354 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6355 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6356 << TST.getLocalSourceRange();
6357 break;
6358 }
6359 case TypeLoc::Decltype:
6360 case TypeLoc::PackIndexing: {
6361 const Type *T = TL.getTypePtr();
6362 // C++23 [expr.prim.id.qual]p2:
6363 // [...] A declarative nested-name-specifier shall not have a
6364 // computed-type-specifier.
6365 //
6366 // CWG2858 changed this from 'decltype-specifier' to
6367 // 'computed-type-specifier'.
6368 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6369 << T->isDecltypeType() << TL.getSourceRange();
6370 break;
6371 }
6372 case TypeLoc::DependentName:
6373 NextTL =
6374 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6375 break;
6376 case TypeLoc::DependentTemplateSpecialization: {
6378 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6379 NextTL = TST.getQualifierLoc().getAsTypeLoc();
6380 break;
6381 }
6382 default:
6383 break;
6384 }
6385 if (TemplateKeywordLoc.isValid())
6386 Diag(Loc, diag::ext_template_after_declarative_nns)
6387 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6388 }
6389
6390 return false;
6391}
6392
6394 MultiTemplateParamsArg TemplateParamLists) {
6395 // TODO: consider using NameInfo for diagnostic.
6397 DeclarationName Name = NameInfo.getName();
6398
6399 // All of these full declarators require an identifier. If it doesn't have
6400 // one, the ParsedFreeStandingDeclSpec action should be used.
6401 if (D.isDecompositionDeclarator()) {
6402 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6403 } else if (!Name) {
6404 if (!D.isInvalidType()) // Reject this if we think it is valid.
6405 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6406 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6407 return nullptr;
6409 return nullptr;
6410
6411 DeclContext *DC = CurContext;
6412 if (D.getCXXScopeSpec().isInvalid())
6413 D.setInvalidType();
6414 else if (D.getCXXScopeSpec().isSet()) {
6415 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6417 return nullptr;
6418
6419 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6420 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6421 if (!DC || isa<EnumDecl>(DC)) {
6422 // If we could not compute the declaration context, it's because the
6423 // declaration context is dependent but does not refer to a class,
6424 // class template, or class template partial specialization. Complain
6425 // and return early, to avoid the coming semantic disaster.
6426 Diag(D.getIdentifierLoc(),
6427 diag::err_template_qualified_declarator_no_match)
6428 << D.getCXXScopeSpec().getScopeRep()
6429 << D.getCXXScopeSpec().getRange();
6430 return nullptr;
6431 }
6432 bool IsDependentContext = DC->isDependentContext();
6433
6434 if (!IsDependentContext &&
6435 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6436 return nullptr;
6437
6438 // If a class is incomplete, do not parse entities inside it.
6439 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6440 Diag(D.getIdentifierLoc(),
6441 diag::err_member_def_undefined_record)
6442 << Name << DC << D.getCXXScopeSpec().getRange();
6443 return nullptr;
6444 }
6445 if (!D.getDeclSpec().isFriendSpecified()) {
6446 TemplateIdAnnotation *TemplateId =
6448 ? D.getName().TemplateId
6449 : nullptr;
6450 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name,
6451 D.getIdentifierLoc(), TemplateId,
6452 /*IsMemberSpecialization=*/false)) {
6453 if (DC->isRecord())
6454 return nullptr;
6455
6456 D.setInvalidType();
6457 }
6458 }
6459
6460 // Check whether we need to rebuild the type of the given
6461 // declaration in the current instantiation.
6462 if (EnteringContext && IsDependentContext &&
6463 TemplateParamLists.size() != 0) {
6464 ContextRAII SavedContext(*this, DC);
6466 D.setInvalidType();
6467 }
6468 }
6469
6471 QualType R = TInfo->getType();
6472
6473 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6475 D.setInvalidType();
6476
6477 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6479
6480 // See if this is a redefinition of a variable in the same scope.
6481 if (!D.getCXXScopeSpec().isSet()) {
6482 bool IsLinkageLookup = false;
6483 bool CreateBuiltins = false;
6484
6485 // If the declaration we're planning to build will be a function
6486 // or object with linkage, then look for another declaration with
6487 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6488 //
6489 // If the declaration we're planning to build will be declared with
6490 // external linkage in the translation unit, create any builtin with
6491 // the same name.
6492 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6493 /* Do nothing*/;
6494 else if (CurContext->isFunctionOrMethod() &&
6495 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6496 R->isFunctionType())) {
6497 IsLinkageLookup = true;
6498 CreateBuiltins =
6501 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6502 CreateBuiltins = true;
6503
6504 if (IsLinkageLookup) {
6506 Previous.setRedeclarationKind(
6507 RedeclarationKind::ForExternalRedeclaration);
6508 }
6509
6510 LookupName(Previous, S, CreateBuiltins);
6511 } else { // Something like "int foo::x;"
6513
6514 // C++ [dcl.meaning]p1:
6515 // When the declarator-id is qualified, the declaration shall refer to a
6516 // previously declared member of the class or namespace to which the
6517 // qualifier refers (or, in the case of a namespace, of an element of the
6518 // inline namespace set of that namespace (7.3.1)) or to a specialization
6519 // thereof; [...]
6520 //
6521 // Note that we already checked the context above, and that we do not have
6522 // enough information to make sure that Previous contains the declaration
6523 // we want to match. For example, given:
6524 //
6525 // class X {
6526 // void f();
6527 // void f(float);
6528 // };
6529 //
6530 // void X::f(int) { } // ill-formed
6531 //
6532 // In this case, Previous will point to the overload set
6533 // containing the two f's declared in X, but neither of them
6534 // matches.
6535
6537 }
6538
6539 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6540 TPD && TPD->isTemplateParameter()) {
6541 // Older versions of clang allowed the names of function/variable templates
6542 // to shadow the names of their template parameters. For the compatibility
6543 // purposes we detect such cases and issue a default-to-error warning that
6544 // can be disabled with -Wno-strict-primary-template-shadow.
6545 if (!D.isInvalidType()) {
6546 bool AllowForCompatibility = false;
6547 if (Scope *DeclParent = S->getDeclParent();
6548 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6549 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6550 TemplateParamParent->isDeclScope(TPD);
6551 }
6552 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
6553 AllowForCompatibility);
6554 }
6555
6556 // Just pretend that we didn't see the previous declaration.
6557 Previous.clear();
6558 }
6559
6560 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6561 // Forget that the previous declaration is the injected-class-name.
6562 Previous.clear();
6563
6564 // In C++, the previous declaration we find might be a tag type
6565 // (class or enum). In this case, the new declaration will hide the
6566 // tag type. Note that this applies to functions, function templates, and
6567 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6568 if (Previous.isSingleTagDecl() &&
6569 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6570 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6571 Previous.clear();
6572
6573 // Check that there are no default arguments other than in the parameters
6574 // of a function declaration (C++ only).
6575 if (getLangOpts().CPlusPlus)
6577
6578 /// Get the innermost enclosing declaration scope.
6579 S = S->getDeclParent();
6580
6581 NamedDecl *New;
6582
6583 bool AddToScope = true;
6584 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6585 if (TemplateParamLists.size()) {
6586 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6587 return nullptr;
6588 }
6589
6590 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6591 } else if (R->isFunctionType()) {
6592 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6593 TemplateParamLists,
6594 AddToScope);
6595 } else {
6596 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6597 AddToScope);
6598 }
6599
6600 if (!New)
6601 return nullptr;
6602
6604
6605 // If this has an identifier and is not a function template specialization,
6606 // add it to the scope stack.
6607 if (New->getDeclName() && AddToScope)
6609
6610 if (OpenMP().isInOpenMPDeclareTargetContext())
6612
6613 return New;
6614}
6615
6616/// Helper method to turn variable array types into constant array
6617/// types in certain situations which would otherwise be errors (for
6618/// GCC compatibility).
6620 ASTContext &Context,
6621 bool &SizeIsNegative,
6622 llvm::APSInt &Oversized) {
6623 // This method tries to turn a variable array into a constant
6624 // array even when the size isn't an ICE. This is necessary
6625 // for compatibility with code that depends on gcc's buggy
6626 // constant expression folding, like struct {char x[(int)(char*)2];}
6627 SizeIsNegative = false;
6628 Oversized = 0;
6629
6630 if (T->isDependentType())
6631 return QualType();
6632
6634 const Type *Ty = Qs.strip(T);
6635
6636 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6637 QualType Pointee = PTy->getPointeeType();
6638 QualType FixedType =
6639 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6640 Oversized);
6641 if (FixedType.isNull()) return FixedType;
6642 FixedType = Context.getPointerType(FixedType);
6643 return Qs.apply(Context, FixedType);
6644 }
6645 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6646 QualType Inner = PTy->getInnerType();
6647 QualType FixedType =
6648 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6649 Oversized);
6650 if (FixedType.isNull()) return FixedType;
6651 FixedType = Context.getParenType(FixedType);
6652 return Qs.apply(Context, FixedType);
6653 }
6654
6655 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6656 if (!VLATy)
6657 return QualType();
6658
6659 QualType ElemTy = VLATy->getElementType();
6660 if (ElemTy->isVariablyModifiedType()) {
6661 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6662 SizeIsNegative, Oversized);
6663 if (ElemTy.isNull())
6664 return QualType();
6665 }
6666
6668 if (!VLATy->getSizeExpr() ||
6669 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6670 return QualType();
6671
6672 llvm::APSInt Res = Result.Val.getInt();
6673
6674 // Check whether the array size is negative.
6675 if (Res.isSigned() && Res.isNegative()) {
6676 SizeIsNegative = true;
6677 return QualType();
6678 }
6679
6680 // Check whether the array is too large to be addressed.
6681 unsigned ActiveSizeBits =
6682 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6683 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6684 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6685 : Res.getActiveBits();
6686 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6687 Oversized = Res;
6688 return QualType();
6689 }
6690
6691 QualType FoldedArrayType = Context.getConstantArrayType(
6692 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6693 return Qs.apply(Context, FoldedArrayType);
6694}
6695
6696static void
6698 SrcTL = SrcTL.getUnqualifiedLoc();
6699 DstTL = DstTL.getUnqualifiedLoc();
6700 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6701 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6702 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6703 DstPTL.getPointeeLoc());
6704 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6705 return;
6706 }
6707 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6708 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6709 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6710 DstPTL.getInnerLoc());
6711 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6712 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6713 return;
6714 }
6715 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6716 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6717 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6718 TypeLoc DstElemTL = DstATL.getElementLoc();
6719 if (VariableArrayTypeLoc SrcElemATL =
6720 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6721 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6722 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6723 } else {
6724 DstElemTL.initializeFullCopy(SrcElemTL);
6725 }
6726 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6727 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6728 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6729}
6730
6731/// Helper method to turn variable array types into constant array
6732/// types in certain situations which would otherwise be errors (for
6733/// GCC compatibility).
6734static TypeSourceInfo*
6736 ASTContext &Context,
6737 bool &SizeIsNegative,
6738 llvm::APSInt &Oversized) {
6739 QualType FixedTy
6740 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6741 SizeIsNegative, Oversized);
6742 if (FixedTy.isNull())
6743 return nullptr;
6744 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6746 FixedTInfo->getTypeLoc());
6747 return FixedTInfo;
6748}
6749
6752 unsigned FailedFoldDiagID) {
6753 bool SizeIsNegative;
6754 llvm::APSInt Oversized;
6756 TInfo, Context, SizeIsNegative, Oversized);
6757 if (FixedTInfo) {
6758 Diag(Loc, diag::ext_vla_folded_to_constant);
6759 TInfo = FixedTInfo;
6760 T = FixedTInfo->getType();
6761 return true;
6762 }
6763
6764 if (SizeIsNegative)
6765 Diag(Loc, diag::err_typecheck_negative_array_size);
6766 else if (Oversized.getBoolValue())
6767 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6768 else if (FailedFoldDiagID)
6769 Diag(Loc, FailedFoldDiagID);
6770 return false;
6771}
6772
6773void
6775 if (!getLangOpts().CPlusPlus &&
6777 // Don't need to track declarations in the TU in C.
6778 return;
6779
6780 // Note that we have a locally-scoped external with this name.
6782}
6783
6785 // FIXME: We can have multiple results via __attribute__((overloadable)).
6787 return Result.empty() ? nullptr : *Result.begin();
6788}
6789
6791 // FIXME: We should probably indicate the identifier in question to avoid
6792 // confusion for constructs like "virtual int a(), b;"
6793 if (DS.isVirtualSpecified())
6795 diag::err_virtual_non_function);
6796
6797 if (DS.hasExplicitSpecifier())
6799 diag::err_explicit_non_function);
6800
6801 if (DS.isNoreturnSpecified())
6803 diag::err_noreturn_non_function);
6804}
6805
6806NamedDecl*
6809 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6810 if (D.getCXXScopeSpec().isSet()) {
6811 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6812 << D.getCXXScopeSpec().getRange();
6813 D.setInvalidType();
6814 // Pretend we didn't see the scope specifier.
6815 DC = CurContext;
6816 Previous.clear();
6817 }
6818
6819 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6820
6821 if (D.getDeclSpec().isInlineSpecified())
6822 Diag(D.getDeclSpec().getInlineSpecLoc(),
6823 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6824 ? diag::warn_ms_inline_non_function
6825 : diag::err_inline_non_function)
6826 << getLangOpts().CPlusPlus17;
6827 if (D.getDeclSpec().hasConstexprSpecifier())
6828 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6829 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6830
6831 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6833 Diag(D.getName().StartLocation,
6834 diag::err_deduction_guide_invalid_specifier)
6835 << "typedef";
6836 else
6837 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6838 << D.getName().getSourceRange();
6839 return nullptr;
6840 }
6841
6842 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6843 if (!NewTD) return nullptr;
6844
6845 // Handle attributes prior to checking for duplicates in MergeVarDecl
6846 ProcessDeclAttributes(S, NewTD, D);
6847
6849
6850 bool Redeclaration = D.isRedeclaration();
6852 D.setRedeclaration(Redeclaration);
6853 return ND;
6854}
6855
6856void
6858 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6859 // then it shall have block scope.
6860 // Note that variably modified types must be fixed before merging the decl so
6861 // that redeclarations will match.
6862 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6863 QualType T = TInfo->getType();
6864 if (T->isVariablyModifiedType()) {
6866
6867 if (S->getFnParent() == nullptr) {
6868 bool SizeIsNegative;
6869 llvm::APSInt Oversized;
6870 TypeSourceInfo *FixedTInfo =
6872 SizeIsNegative,
6873 Oversized);
6874 if (FixedTInfo) {
6875 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6876 NewTD->setTypeSourceInfo(FixedTInfo);
6877 } else {
6878 if (SizeIsNegative)
6879 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6880 else if (T->isVariableArrayType())
6881 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6882 else if (Oversized.getBoolValue())
6883 Diag(NewTD->getLocation(), diag::err_array_too_large)
6884 << toString(Oversized, 10);
6885 else
6886 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6887 NewTD->setInvalidDecl();
6888 }
6889 }
6890 }
6891}
6892
6893NamedDecl*
6896
6897 // Find the shadowed declaration before filtering for scope.
6898 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6899
6900 // Merge the decl with the existing one if appropriate. If the decl is
6901 // in an outer scope, it isn't the same thing.
6902 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6903 /*AllowInlineNamespace*/false);
6905 if (!Previous.empty()) {
6906 Redeclaration = true;
6907 MergeTypedefNameDecl(S, NewTD, Previous);
6908 } else {
6910 }
6911
6912 if (ShadowedDecl && !Redeclaration)
6913 CheckShadow(NewTD, ShadowedDecl, Previous);
6914
6915 // If this is the C FILE type, notify the AST context.
6916 if (IdentifierInfo *II = NewTD->getIdentifier())
6917 if (!NewTD->isInvalidDecl() &&
6919 switch (II->getNotableIdentifierID()) {
6920 case tok::NotableIdentifierKind::FILE:
6921 Context.setFILEDecl(NewTD);
6922 break;
6923 case tok::NotableIdentifierKind::jmp_buf:
6924 Context.setjmp_bufDecl(NewTD);
6925 break;
6926 case tok::NotableIdentifierKind::sigjmp_buf:
6928 break;
6929 case tok::NotableIdentifierKind::ucontext_t:
6931 break;
6932 case tok::NotableIdentifierKind::float_t:
6933 case tok::NotableIdentifierKind::double_t:
6934 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6935 break;
6936 default:
6937 break;
6938 }
6939 }
6940
6941 return NewTD;
6942}
6943
6944/// Determines whether the given declaration is an out-of-scope
6945/// previous declaration.
6946///
6947/// This routine should be invoked when name lookup has found a
6948/// previous declaration (PrevDecl) that is not in the scope where a
6949/// new declaration by the same name is being introduced. If the new
6950/// declaration occurs in a local scope, previous declarations with
6951/// linkage may still be considered previous declarations (C99
6952/// 6.2.2p4-5, C++ [basic.link]p6).
6953///
6954/// \param PrevDecl the previous declaration found by name
6955/// lookup
6956///
6957/// \param DC the context in which the new declaration is being
6958/// declared.
6959///
6960/// \returns true if PrevDecl is an out-of-scope previous declaration
6961/// for a new delcaration with the same name.
6962static bool
6964 ASTContext &Context) {
6965 if (!PrevDecl)
6966 return false;
6967
6968 if (!PrevDecl->hasLinkage())
6969 return false;
6970
6971 if (Context.getLangOpts().CPlusPlus) {
6972 // C++ [basic.link]p6:
6973 // If there is a visible declaration of an entity with linkage
6974 // having the same name and type, ignoring entities declared
6975 // outside the innermost enclosing namespace scope, the block
6976 // scope declaration declares that same entity and receives the
6977 // linkage of the previous declaration.
6978 DeclContext *OuterContext = DC->getRedeclContext();
6979 if (!OuterContext->isFunctionOrMethod())
6980 // This rule only applies to block-scope declarations.
6981 return false;
6982
6983 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6984 if (PrevOuterContext->isRecord())
6985 // We found a member function: ignore it.
6986 return false;
6987
6988 // Find the innermost enclosing namespace for the new and
6989 // previous declarations.
6990 OuterContext = OuterContext->getEnclosingNamespaceContext();
6991 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6992
6993 // The previous declaration is in a different namespace, so it
6994 // isn't the same function.
6995 if (!OuterContext->Equals(PrevOuterContext))
6996 return false;
6997 }
6998
6999 return true;
7000}
7001
7003 CXXScopeSpec &SS = D.getCXXScopeSpec();
7004 if (!SS.isSet()) return;
7006}
7007
7009 if (Decl->getType().hasAddressSpace())
7010 return;
7011 if (Decl->getType()->isDependentType())
7012 return;
7013 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
7014 QualType Type = Var->getType();
7015 if (Type->isSamplerT() || Type->isVoidType())
7016 return;
7018 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7019 // __opencl_c_program_scope_global_variables feature, the address space
7020 // for a variable at program scope or a static or extern variable inside
7021 // a function are inferred to be __global.
7022 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7023 Var->hasGlobalStorage())
7024 ImplAS = LangAS::opencl_global;
7025 // If the original type from a decayed type is an array type and that array
7026 // type has no address space yet, deduce it now.
7027 if (auto DT = dyn_cast<DecayedType>(Type)) {
7028 auto OrigTy = DT->getOriginalType();
7029 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7030 // Add the address space to the original array type and then propagate
7031 // that to the element type through `getAsArrayType`.
7032 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7033 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7034 // Re-generate the decayed type.
7035 Type = Context.getDecayedType(OrigTy);
7036 }
7037 }
7039 // Apply any qualifiers (including address space) from the array type to
7040 // the element type. This implements C99 6.7.3p8: "If the specification of
7041 // an array type includes any type qualifiers, the element type is so
7042 // qualified, not the array type."
7043 if (Type->isArrayType())
7045 Decl->setType(Type);
7046 }
7047}
7048
7049static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7050 // 'weak' only applies to declarations with external linkage.
7051 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7052 if (!ND.isExternallyVisible()) {
7053 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7054 ND.dropAttr<WeakAttr>();
7055 }
7056 }
7057}
7058
7059static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7060 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7061 if (ND.isExternallyVisible()) {
7062 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7063 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7064 }
7065 }
7066}
7067
7068static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7069 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7070 if (VD->hasInit()) {
7071 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7072 assert(VD->isThisDeclarationADefinition() &&
7073 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7074 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7075 VD->dropAttr<AliasAttr>();
7076 }
7077 }
7078 }
7079}
7080
7081static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7082 // 'selectany' only applies to externally visible variable declarations.
7083 // It does not apply to functions.
7084 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7085 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7086 S.Diag(Attr->getLocation(),
7087 diag::err_attribute_selectany_non_extern_data);
7088 ND.dropAttr<SelectAnyAttr>();
7089 }
7090 }
7091}
7092
7094 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7095 if (!ND.isExternallyVisible())
7096 S.Diag(Attr->getLocation(),
7097 diag::warn_attribute_hybrid_patchable_non_extern);
7098 }
7099}
7100
7102 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7103 auto *VD = dyn_cast<VarDecl>(&ND);
7104 bool IsAnonymousNS = false;
7105 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7106 if (VD) {
7107 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7108 while (NS && !IsAnonymousNS) {
7109 IsAnonymousNS = NS->isAnonymousNamespace();
7110 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7111 }
7112 }
7113 // dll attributes require external linkage. Static locals may have external
7114 // linkage but still cannot be explicitly imported or exported.
7115 // In Microsoft mode, a variable defined in anonymous namespace must have
7116 // external linkage in order to be exported.
7117 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7118 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7119 (!AnonNSInMicrosoftMode &&
7120 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7121 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7122 << &ND << Attr;
7123 ND.setInvalidDecl();
7124 }
7125 }
7126}
7127
7129 // Check the attributes on the function type and function params, if any.
7130 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7131 FD = FD->getMostRecentDecl();
7132 // Don't declare this variable in the second operand of the for-statement;
7133 // GCC miscompiles that by ending its lifetime before evaluating the
7134 // third operand. See gcc.gnu.org/PR86769.
7136 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7137 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7138 TL = ATL.getModifiedLoc()) {
7139 // The [[lifetimebound]] attribute can be applied to the implicit object
7140 // parameter of a non-static member function (other than a ctor or dtor)
7141 // by applying it to the function type.
7142 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7143 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7144 int NoImplicitObjectError = -1;
7145 if (!MD)
7146 NoImplicitObjectError = 0;
7147 else if (MD->isStatic())
7148 NoImplicitObjectError = 1;
7149 else if (MD->isExplicitObjectMemberFunction())
7150 NoImplicitObjectError = 2;
7151 if (NoImplicitObjectError != -1) {
7152 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7153 << NoImplicitObjectError << A->getRange();
7154 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7155 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7156 << isa<CXXDestructorDecl>(MD) << A->getRange();
7157 } else if (MD->getReturnType()->isVoidType()) {
7158 S.Diag(
7159 MD->getLocation(),
7160 diag::
7161 err_lifetimebound_implicit_object_parameter_void_return_type);
7162 }
7163 }
7164 }
7165
7166 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7167 const ParmVarDecl *P = FD->getParamDecl(I);
7168
7169 // The [[lifetimebound]] attribute can be applied to a function parameter
7170 // only if the function returns a value.
7171 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7172 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7173 S.Diag(A->getLocation(),
7174 diag::err_lifetimebound_parameter_void_return_type);
7175 }
7176 }
7177 }
7178 }
7179}
7180
7182 // Ensure that an auto decl is deduced otherwise the checks below might cache
7183 // the wrong linkage.
7184 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7185
7186 checkWeakAttr(S, ND);
7187 checkWeakRefAttr(S, ND);
7188 checkAliasAttr(S, ND);
7189 checkSelectAnyAttr(S, ND);
7191 checkInheritableAttr(S, ND);
7193}
7194
7196 NamedDecl *NewDecl,
7197 bool IsSpecialization,
7198 bool IsDefinition) {
7199 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7200 return;
7201
7202 bool IsTemplate = false;
7203 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7204 OldDecl = OldTD->getTemplatedDecl();
7205 IsTemplate = true;
7206 if (!IsSpecialization)
7207 IsDefinition = false;
7208 }
7209 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7210 NewDecl = NewTD->getTemplatedDecl();
7211 IsTemplate = true;
7212 }
7213
7214 if (!OldDecl || !NewDecl)
7215 return;
7216
7217 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7218 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7219 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7220 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7221
7222 // dllimport and dllexport are inheritable attributes so we have to exclude
7223 // inherited attribute instances.
7224 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7225 (NewExportAttr && !NewExportAttr->isInherited());
7226
7227 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7228 // the only exception being explicit specializations.
7229 // Implicitly generated declarations are also excluded for now because there
7230 // is no other way to switch these to use dllimport or dllexport.
7231 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7232
7233 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7234 // Allow with a warning for free functions and global variables.
7235 bool JustWarn = false;
7236 if (!OldDecl->isCXXClassMember()) {
7237 auto *VD = dyn_cast<VarDecl>(OldDecl);
7238 if (VD && !VD->getDescribedVarTemplate())
7239 JustWarn = true;
7240 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7241 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7242 JustWarn = true;
7243 }
7244
7245 // We cannot change a declaration that's been used because IR has already
7246 // been emitted. Dllimported functions will still work though (modulo
7247 // address equality) as they can use the thunk.
7248 if (OldDecl->isUsed())
7249 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7250 JustWarn = false;
7251
7252 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7253 : diag::err_attribute_dll_redeclaration;
7254 S.Diag(NewDecl->getLocation(), DiagID)
7255 << NewDecl
7256 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7257 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7258 if (!JustWarn) {
7259 NewDecl->setInvalidDecl();
7260 return;
7261 }
7262 }
7263
7264 // A redeclaration is not allowed to drop a dllimport attribute, the only
7265 // exceptions being inline function definitions (except for function
7266 // templates), local extern declarations, qualified friend declarations or
7267 // special MSVC extension: in the last case, the declaration is treated as if
7268 // it were marked dllexport.
7269 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7270 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7271 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7272 // Ignore static data because out-of-line definitions are diagnosed
7273 // separately.
7274 IsStaticDataMember = VD->isStaticDataMember();
7275 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7277 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7278 IsInline = FD->isInlined();
7279 IsQualifiedFriend = FD->getQualifier() &&
7280 FD->getFriendObjectKind() == Decl::FOK_Declared;
7281 }
7282
7283 if (OldImportAttr && !HasNewAttr &&
7284 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7285 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7286 if (IsMicrosoftABI && IsDefinition) {
7287 if (IsSpecialization) {
7288 S.Diag(
7289 NewDecl->getLocation(),
7290 diag::err_attribute_dllimport_function_specialization_definition);
7291 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7292 NewDecl->dropAttr<DLLImportAttr>();
7293 } else {
7294 S.Diag(NewDecl->getLocation(),
7295 diag::warn_redeclaration_without_import_attribute)
7296 << NewDecl;
7297 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7298 NewDecl->dropAttr<DLLImportAttr>();
7299 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7300 S.Context, NewImportAttr->getRange()));
7301 }
7302 } else if (IsMicrosoftABI && IsSpecialization) {
7303 assert(!IsDefinition);
7304 // MSVC allows this. Keep the inherited attribute.
7305 } else {
7306 S.Diag(NewDecl->getLocation(),
7307 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7308 << NewDecl << OldImportAttr;
7309 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7310 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7311 OldDecl->dropAttr<DLLImportAttr>();
7312 NewDecl->dropAttr<DLLImportAttr>();
7313 }
7314 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7315 // In MinGW, seeing a function declared inline drops the dllimport
7316 // attribute.
7317 OldDecl->dropAttr<DLLImportAttr>();
7318 NewDecl->dropAttr<DLLImportAttr>();
7319 S.Diag(NewDecl->getLocation(),
7320 diag::warn_dllimport_dropped_from_inline_function)
7321 << NewDecl << OldImportAttr;
7322 }
7323
7324 // A specialization of a class template member function is processed here
7325 // since it's a redeclaration. If the parent class is dllexport, the
7326 // specialization inherits that attribute. This doesn't happen automatically
7327 // since the parent class isn't instantiated until later.
7328 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7329 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7330 !NewImportAttr && !NewExportAttr) {
7331 if (const DLLExportAttr *ParentExportAttr =
7332 MD->getParent()->getAttr<DLLExportAttr>()) {
7333 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7334 NewAttr->setInherited(true);
7335 NewDecl->addAttr(NewAttr);
7336 }
7337 }
7338 }
7339}
7340
7341/// Given that we are within the definition of the given function,
7342/// will that definition behave like C99's 'inline', where the
7343/// definition is discarded except for optimization purposes?
7345 // Try to avoid calling GetGVALinkageForFunction.
7346
7347 // All cases of this require the 'inline' keyword.
7348 if (!FD->isInlined()) return false;
7349
7350 // This is only possible in C++ with the gnu_inline attribute.
7351 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7352 return false;
7353
7354 // Okay, go ahead and call the relatively-more-expensive function.
7356}
7357
7358/// Determine whether a variable is extern "C" prior to attaching
7359/// an initializer. We can't just call isExternC() here, because that
7360/// will also compute and cache whether the declaration is externally
7361/// visible, which might change when we attach the initializer.
7362///
7363/// This can only be used if the declaration is known to not be a
7364/// redeclaration of an internal linkage declaration.
7365///
7366/// For instance:
7367///
7368/// auto x = []{};
7369///
7370/// Attaching the initializer here makes this declaration not externally
7371/// visible, because its type has internal linkage.
7372///
7373/// FIXME: This is a hack.
7374template<typename T>
7375static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7376 if (S.getLangOpts().CPlusPlus) {
7377 // In C++, the overloadable attribute negates the effects of extern "C".
7378 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7379 return false;
7380
7381 // So do CUDA's host/device attributes.
7382 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7383 D->template hasAttr<CUDAHostAttr>()))
7384 return false;
7385 }
7386 return D->isExternC();
7387}
7388
7389static bool shouldConsiderLinkage(const VarDecl *VD) {
7390 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7391 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7392 isa<OMPDeclareMapperDecl>(DC))
7393 return VD->hasExternalStorage();
7394 if (DC->isFileContext())
7395 return true;
7396 if (DC->isRecord())
7397 return false;
7398 if (DC->getDeclKind() == Decl::HLSLBuffer)
7399 return false;
7400
7401 if (isa<RequiresExprBodyDecl>(DC))
7402 return false;
7403 llvm_unreachable("Unexpected context");
7404}
7405
7406static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7407 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7408 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7409 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7410 return true;
7411 if (DC->isRecord())
7412 return false;
7413 llvm_unreachable("Unexpected context");
7414}
7415
7416static bool hasParsedAttr(Scope *S, const Declarator &PD,
7417 ParsedAttr::Kind Kind) {
7418 // Check decl attributes on the DeclSpec.
7419 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7420 return true;
7421
7422 // Walk the declarator structure, checking decl attributes that were in a type
7423 // position to the decl itself.
7424 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7425 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7426 return true;
7427 }
7428
7429 // Finally, check attributes on the decl itself.
7430 return PD.getAttributes().hasAttribute(Kind) ||
7432}
7433
7435 if (!DC->isFunctionOrMethod())
7436 return false;
7437
7438 // If this is a local extern function or variable declared within a function
7439 // template, don't add it into the enclosing namespace scope until it is
7440 // instantiated; it might have a dependent type right now.
7441 if (DC->isDependentContext())
7442 return true;
7443
7444 // C++11 [basic.link]p7:
7445 // When a block scope declaration of an entity with linkage is not found to
7446 // refer to some other declaration, then that entity is a member of the
7447 // innermost enclosing namespace.
7448 //
7449 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7450 // semantically-enclosing namespace, not a lexically-enclosing one.
7451 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7452 DC = DC->getParent();
7453 return true;
7454}
7455
7456/// Returns true if given declaration has external C language linkage.
7457static bool isDeclExternC(const Decl *D) {
7458 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7459 return FD->isExternC();
7460 if (const auto *VD = dyn_cast<VarDecl>(D))
7461 return VD->isExternC();
7462
7463 llvm_unreachable("Unknown type of decl!");
7464}
7465
7466/// Returns true if there hasn't been any invalid type diagnosed.
7467static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7468 DeclContext *DC = NewVD->getDeclContext();
7469 QualType R = NewVD->getType();
7470
7471 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7472 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7473 // argument.
7474 if (R->isImageType() || R->isPipeType()) {
7475 Se.Diag(NewVD->getLocation(),
7476 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7477 << R;
7478 NewVD->setInvalidDecl();
7479 return false;
7480 }
7481
7482 // OpenCL v1.2 s6.9.r:
7483 // The event type cannot be used to declare a program scope variable.
7484 // OpenCL v2.0 s6.9.q:
7485 // The clk_event_t and reserve_id_t types cannot be declared in program
7486 // scope.
7487 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7488 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7489 Se.Diag(NewVD->getLocation(),
7490 diag::err_invalid_type_for_program_scope_var)
7491 << R;
7492 NewVD->setInvalidDecl();
7493 return false;
7494 }
7495 }
7496
7497 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7498 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7499 Se.getLangOpts())) {
7500 QualType NR = R.getCanonicalType();
7501 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7502 NR->isReferenceType()) {
7505 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7506 << NR->isReferenceType();
7507 NewVD->setInvalidDecl();
7508 return false;
7509 }
7510 NR = NR->getPointeeType();
7511 }
7512 }
7513
7514 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7515 Se.getLangOpts())) {
7516 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7517 // half array type (unless the cl_khr_fp16 extension is enabled).
7518 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7519 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7520 NewVD->setInvalidDecl();
7521 return false;
7522 }
7523 }
7524
7525 // OpenCL v1.2 s6.9.r:
7526 // The event type cannot be used with the __local, __constant and __global
7527 // address space qualifiers.
7528 if (R->isEventT()) {
7530 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7531 NewVD->setInvalidDecl();
7532 return false;
7533 }
7534 }
7535
7536 if (R->isSamplerT()) {
7537 // OpenCL v1.2 s6.9.b p4:
7538 // The sampler type cannot be used with the __local and __global address
7539 // space qualifiers.
7542 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7543 NewVD->setInvalidDecl();
7544 }
7545
7546 // OpenCL v1.2 s6.12.14.1:
7547 // A global sampler must be declared with either the constant address
7548 // space qualifier or with the const qualifier.
7549 if (DC->isTranslationUnit() &&
7551 R.isConstQualified())) {
7552 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7553 NewVD->setInvalidDecl();
7554 }
7555 if (NewVD->isInvalidDecl())
7556 return false;
7557 }
7558
7559 return true;
7560}
7561
7562template <typename AttrTy>
7563static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7564 const TypedefNameDecl *TND = TT->getDecl();
7565 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7566 AttrTy *Clone = Attribute->clone(S.Context);
7567 Clone->setInherited(true);
7568 D->addAttr(Clone);
7569 }
7570}
7571
7572// This function emits warning and a corresponding note based on the
7573// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7574// declarations of an annotated type must be const qualified.
7576 QualType VarType = VD->getType().getCanonicalType();
7577
7578 // Ignore local declarations (for now) and those with const qualification.
7579 // TODO: Local variables should not be allowed if their type declaration has
7580 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7581 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7582 return;
7583
7584 if (VarType->isArrayType()) {
7585 // Retrieve element type for array declarations.
7586 VarType = S.getASTContext().getBaseElementType(VarType);
7587 }
7588
7589 const RecordDecl *RD = VarType->getAsRecordDecl();
7590
7591 // Check if the record declaration is present and if it has any attributes.
7592 if (RD == nullptr)
7593 return;
7594
7595 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7596 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7597 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7598 return;
7599 }
7600}
7601
7602// Checks if VD is declared at global scope or with C language linkage.
7603static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7604 return Name.getAsIdentifierInfo() &&
7605 Name.getAsIdentifierInfo()->isStr("main") &&
7606 !VD->getDescribedVarTemplate() &&
7608 VD->isExternC());
7609}
7610
7612 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7613 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7614 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7615 QualType R = TInfo->getType();
7617
7618 IdentifierInfo *II = Name.getAsIdentifierInfo();
7619 bool IsPlaceholderVariable = false;
7620
7621 if (D.isDecompositionDeclarator()) {
7622 // Take the name of the first declarator as our name for diagnostic
7623 // purposes.
7624 auto &Decomp = D.getDecompositionDeclarator();
7625 if (!Decomp.bindings().empty()) {
7626 II = Decomp.bindings()[0].Name;
7627 Name = II;
7628 }
7629 } else if (!II) {
7630 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7631 return nullptr;
7632 }
7633
7634
7635 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7637 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7638 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7639
7640 IsPlaceholderVariable = true;
7641
7642 if (!Previous.empty()) {
7643 NamedDecl *PrevDecl = *Previous.begin();
7644 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7645 DC->getRedeclContext());
7646 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7647 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7648 if (IsPlaceholderVariable)
7649 DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7650 }
7651 }
7652 }
7653
7654 // dllimport globals without explicit storage class are treated as extern. We
7655 // have to change the storage class this early to get the right DeclContext.
7656 if (SC == SC_None && !DC->isRecord() &&
7657 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7658 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7659 SC = SC_Extern;
7660
7661 DeclContext *OriginalDC = DC;
7662 bool IsLocalExternDecl = SC == SC_Extern &&
7664
7665 if (SCSpec == DeclSpec::SCS_mutable) {
7666 // mutable can only appear on non-static class members, so it's always
7667 // an error here
7668 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7669 D.setInvalidType();
7670 SC = SC_None;
7671 }
7672
7673 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7674 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7675 D.getDeclSpec().getStorageClassSpecLoc())) {
7676 // In C++11, the 'register' storage class specifier is deprecated.
7677 // Suppress the warning in system macros, it's used in macros in some
7678 // popular C system headers, such as in glibc's htonl() macro.
7679 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7680 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7681 : diag::warn_deprecated_register)
7682 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7683 }
7684
7685 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7686
7687 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7688 // C99 6.9p2: The storage-class specifiers auto and register shall not
7689 // appear in the declaration specifiers in an external declaration.
7690 // Global Register+Asm is a GNU extension we support.
7691 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7692 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7693 D.setInvalidType();
7694 }
7695 }
7696
7697 // If this variable has a VLA type and an initializer, try to
7698 // fold to a constant-sized type. This is otherwise invalid.
7699 if (D.hasInitializer() && R->isVariableArrayType())
7700 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7701 /*DiagID=*/0);
7702
7703 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7704 const AutoType *AT = TL.getTypePtr();
7705 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7706 }
7707
7708 bool IsMemberSpecialization = false;
7709 bool IsVariableTemplateSpecialization = false;
7710 bool IsPartialSpecialization = false;
7711 bool IsVariableTemplate = false;
7712 VarDecl *NewVD = nullptr;
7713 VarTemplateDecl *NewTemplate = nullptr;
7714 TemplateParameterList *TemplateParams = nullptr;
7715 if (!getLangOpts().CPlusPlus) {
7716 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7717 II, R, TInfo, SC);
7718
7719 if (R->getContainedDeducedType())
7720 ParsingInitForAutoVars.insert(NewVD);
7721
7722 if (D.isInvalidType())
7723 NewVD->setInvalidDecl();
7724
7726 NewVD->hasLocalStorage())
7727 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7729 } else {
7730 bool Invalid = false;
7731 // Match up the template parameter lists with the scope specifier, then
7732 // determine whether we have a template or a template specialization.
7734 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7735 D.getCXXScopeSpec(),
7737 ? D.getName().TemplateId
7738 : nullptr,
7739 TemplateParamLists,
7740 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7741
7742 if (TemplateParams) {
7743 if (DC->isDependentContext()) {
7744 ContextRAII SavedContext(*this, DC);
7746 Invalid = true;
7747 }
7748
7749 if (!TemplateParams->size() &&
7751 // There is an extraneous 'template<>' for this variable. Complain
7752 // about it, but allow the declaration of the variable.
7753 Diag(TemplateParams->getTemplateLoc(),
7754 diag::err_template_variable_noparams)
7755 << II
7756 << SourceRange(TemplateParams->getTemplateLoc(),
7757 TemplateParams->getRAngleLoc());
7758 TemplateParams = nullptr;
7759 } else {
7760 // Check that we can declare a template here.
7761 if (CheckTemplateDeclScope(S, TemplateParams))
7762 return nullptr;
7763
7764 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7765 // This is an explicit specialization or a partial specialization.
7766 IsVariableTemplateSpecialization = true;
7767 IsPartialSpecialization = TemplateParams->size() > 0;
7768 } else { // if (TemplateParams->size() > 0)
7769 // This is a template declaration.
7770 IsVariableTemplate = true;
7771
7772 // Only C++1y supports variable templates (N3651).
7773 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7774 }
7775 }
7776 } else {
7777 // Check that we can declare a member specialization here.
7778 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7779 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7780 return nullptr;
7781 assert((Invalid ||
7782 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7783 "should have a 'template<>' for this decl");
7784 }
7785
7786 bool IsExplicitSpecialization =
7787 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7788
7789 // C++ [temp.expl.spec]p2:
7790 // The declaration in an explicit-specialization shall not be an
7791 // export-declaration. An explicit specialization shall not use a
7792 // storage-class-specifier other than thread_local.
7793 //
7794 // We use the storage-class-specifier from DeclSpec because we may have
7795 // added implicit 'extern' for declarations with __declspec(dllimport)!
7796 if (SCSpec != DeclSpec::SCS_unspecified &&
7797 (IsExplicitSpecialization || IsMemberSpecialization)) {
7798 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7799 diag::ext_explicit_specialization_storage_class)
7800 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7801 }
7802
7803 if (CurContext->isRecord()) {
7804 if (SC == SC_Static) {
7805 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7806 // Walk up the enclosing DeclContexts to check for any that are
7807 // incompatible with static data members.
7808 const DeclContext *FunctionOrMethod = nullptr;
7809 const CXXRecordDecl *AnonStruct = nullptr;
7810 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7811 if (Ctxt->isFunctionOrMethod()) {
7812 FunctionOrMethod = Ctxt;
7813 break;
7814 }
7815 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7816 if (ParentDecl && !ParentDecl->getDeclName()) {
7817 AnonStruct = ParentDecl;
7818 break;
7819 }
7820 }
7821 if (FunctionOrMethod) {
7822 // C++ [class.static.data]p5: A local class shall not have static
7823 // data members.
7824 Diag(D.getIdentifierLoc(),
7825 diag::err_static_data_member_not_allowed_in_local_class)
7826 << Name << RD->getDeclName() << RD->getTagKind();
7827 } else if (AnonStruct) {
7828 // C++ [class.static.data]p4: Unnamed classes and classes contained
7829 // directly or indirectly within unnamed classes shall not contain
7830 // static data members.
7831 Diag(D.getIdentifierLoc(),
7832 diag::err_static_data_member_not_allowed_in_anon_struct)
7833 << Name << AnonStruct->getTagKind();
7834 Invalid = true;
7835 } else if (RD->isUnion()) {
7836 // C++98 [class.union]p1: If a union contains a static data member,
7837 // the program is ill-formed. C++11 drops this restriction.
7838 DiagCompat(D.getIdentifierLoc(),
7839 diag_compat::static_data_member_in_union)
7840 << Name;
7841 }
7842 }
7843 } else if (IsVariableTemplate || IsPartialSpecialization) {
7844 // There is no such thing as a member field template.
7845 Diag(D.getIdentifierLoc(), diag::err_template_member)
7846 << II << TemplateParams->getSourceRange();
7847 // Recover by pretending this is a static data member template.
7848 SC = SC_Static;
7849 }
7850 } else if (DC->isRecord()) {
7851 // This is an out-of-line definition of a static data member.
7852 switch (SC) {
7853 case SC_None:
7854 break;
7855 case SC_Static:
7856 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7857 diag::err_static_out_of_line)
7859 D.getDeclSpec().getStorageClassSpecLoc());
7860 break;
7861 case SC_Auto:
7862 case SC_Register:
7863 case SC_Extern:
7864 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7865 // to names of variables declared in a block or to function parameters.
7866 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7867 // of class members
7868
7869 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7870 diag::err_storage_class_for_static_member)
7872 D.getDeclSpec().getStorageClassSpecLoc());
7873 break;
7874 case SC_PrivateExtern:
7875 llvm_unreachable("C storage class in c++!");
7876 }
7877 }
7878
7879 if (IsVariableTemplateSpecialization) {
7880 SourceLocation TemplateKWLoc =
7881 TemplateParamLists.size() > 0
7882 ? TemplateParamLists[0]->getTemplateLoc()
7883 : SourceLocation();
7885 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7887 if (Res.isInvalid())
7888 return nullptr;
7889 NewVD = cast<VarDecl>(Res.get());
7890 AddToScope = false;
7891 } else if (D.isDecompositionDeclarator()) {
7893 D.getIdentifierLoc(), R, TInfo, SC,
7894 Bindings);
7895 } else
7896 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7897 D.getIdentifierLoc(), II, R, TInfo, SC);
7898
7899 // If this is supposed to be a variable template, create it as such.
7900 if (IsVariableTemplate) {
7901 NewTemplate =
7902 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7903 TemplateParams, NewVD);
7904 NewVD->setDescribedVarTemplate(NewTemplate);
7905 }
7906
7907 // If this decl has an auto type in need of deduction, make a note of the
7908 // Decl so we can diagnose uses of it in its own initializer.
7909 if (R->getContainedDeducedType())
7910 ParsingInitForAutoVars.insert(NewVD);
7911
7912 if (D.isInvalidType() || Invalid) {
7913 NewVD->setInvalidDecl();
7914 if (NewTemplate)
7915 NewTemplate->setInvalidDecl();
7916 }
7917
7918 SetNestedNameSpecifier(*this, NewVD, D);
7919
7920 // If we have any template parameter lists that don't directly belong to
7921 // the variable (matching the scope specifier), store them.
7922 // An explicit variable template specialization does not own any template
7923 // parameter lists.
7924 unsigned VDTemplateParamLists =
7925 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7926 if (TemplateParamLists.size() > VDTemplateParamLists)
7928 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7929 }
7930
7931 if (D.getDeclSpec().isInlineSpecified()) {
7932 if (!getLangOpts().CPlusPlus) {
7933 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7934 << 0;
7935 } else if (CurContext->isFunctionOrMethod()) {
7936 // 'inline' is not allowed on block scope variable declaration.
7937 Diag(D.getDeclSpec().getInlineSpecLoc(),
7938 diag::err_inline_declaration_block_scope) << Name
7939 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7940 } else {
7941 Diag(D.getDeclSpec().getInlineSpecLoc(),
7942 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
7943 : diag::compat_pre_cxx17_inline_variable);
7944 NewVD->setInlineSpecified();
7945 }
7946 }
7947
7948 // Set the lexical context. If the declarator has a C++ scope specifier, the
7949 // lexical context will be different from the semantic context.
7951 if (NewTemplate)
7952 NewTemplate->setLexicalDeclContext(CurContext);
7953
7954 if (IsLocalExternDecl) {
7955 if (D.isDecompositionDeclarator())
7956 for (auto *B : Bindings)
7957 B->setLocalExternDecl();
7958 else
7959 NewVD->setLocalExternDecl();
7960 }
7961
7962 bool EmitTLSUnsupportedError = false;
7963 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7964 // C++11 [dcl.stc]p4:
7965 // When thread_local is applied to a variable of block scope the
7966 // storage-class-specifier static is implied if it does not appear
7967 // explicitly.
7968 // Core issue: 'static' is not implied if the variable is declared
7969 // 'extern'.
7970 if (NewVD->hasLocalStorage() &&
7971 (SCSpec != DeclSpec::SCS_unspecified ||
7973 !DC->isFunctionOrMethod()))
7974 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7975 diag::err_thread_non_global)
7977 else if (!Context.getTargetInfo().isTLSSupported()) {
7978 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
7979 // Postpone error emission until we've collected attributes required to
7980 // figure out whether it's a host or device variable and whether the
7981 // error should be ignored.
7982 EmitTLSUnsupportedError = true;
7983 // We still need to mark the variable as TLS so it shows up in AST with
7984 // proper storage class for other tools to use even if we're not going
7985 // to emit any code for it.
7986 NewVD->setTSCSpec(TSCS);
7987 } else
7988 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7989 diag::err_thread_unsupported);
7990 } else
7991 NewVD->setTSCSpec(TSCS);
7992 }
7993
7994 switch (D.getDeclSpec().getConstexprSpecifier()) {
7996 break;
7997
7999 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8000 diag::err_constexpr_wrong_decl_kind)
8001 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8002 [[fallthrough]];
8003
8005 NewVD->setConstexpr(true);
8006 // C++1z [dcl.spec.constexpr]p1:
8007 // A static data member declared with the constexpr specifier is
8008 // implicitly an inline variable.
8009 if (NewVD->isStaticDataMember() &&
8010 (getLangOpts().CPlusPlus17 ||
8012 NewVD->setImplicitlyInline();
8013 break;
8014
8016 if (!NewVD->hasGlobalStorage())
8017 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8018 diag::err_constinit_local_variable);
8019 else
8020 NewVD->addAttr(
8021 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8022 ConstInitAttr::Keyword_constinit));
8023 break;
8024 }
8025
8026 // C99 6.7.4p3
8027 // An inline definition of a function with external linkage shall
8028 // not contain a definition of a modifiable object with static or
8029 // thread storage duration...
8030 // We only apply this when the function is required to be defined
8031 // elsewhere, i.e. when the function is not 'extern inline'. Note
8032 // that a local variable with thread storage duration still has to
8033 // be marked 'static'. Also note that it's possible to get these
8034 // semantics in C++ using __attribute__((gnu_inline)).
8035 if (SC == SC_Static && S->getFnParent() != nullptr &&
8036 !NewVD->getType().isConstQualified()) {
8038 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8039 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8040 diag::warn_static_local_in_extern_inline);
8042 }
8043 }
8044
8045 if (D.getDeclSpec().isModulePrivateSpecified()) {
8046 if (IsVariableTemplateSpecialization)
8047 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8048 << (IsPartialSpecialization ? 1 : 0)
8050 D.getDeclSpec().getModulePrivateSpecLoc());
8051 else if (IsMemberSpecialization)
8052 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8053 << 2
8054 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
8055 else if (NewVD->hasLocalStorage())
8056 Diag(NewVD->getLocation(), diag::err_module_private_local)
8057 << 0 << NewVD
8058 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8060 D.getDeclSpec().getModulePrivateSpecLoc());
8061 else {
8062 NewVD->setModulePrivate();
8063 if (NewTemplate)
8064 NewTemplate->setModulePrivate();
8065 for (auto *B : Bindings)
8066 B->setModulePrivate();
8067 }
8068 }
8069
8070 if (getLangOpts().OpenCL) {
8072
8073 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8074 if (TSC != TSCS_unspecified) {
8075 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8076 diag::err_opencl_unknown_type_specifier)
8078 << DeclSpec::getSpecifierName(TSC) << 1;
8079 NewVD->setInvalidDecl();
8080 }
8081 }
8082
8083 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8084 // address space if the table has local storage (semantic checks elsewhere
8085 // will produce an error anyway).
8086 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8087 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8088 !NewVD->hasLocalStorage()) {
8091 NewVD->setType(Type);
8092 }
8093 }
8094
8095 // Handle attributes prior to checking for duplicates in MergeVarDecl
8096 ProcessDeclAttributes(S, NewVD, D);
8097
8098 if (getLangOpts().HLSL)
8100
8101 if (getLangOpts().OpenACC)
8103
8104 // FIXME: This is probably the wrong location to be doing this and we should
8105 // probably be doing this for more attributes (especially for function
8106 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8107 // the code to copy attributes would be generated by TableGen.
8108 if (R->isFunctionPointerType())
8109 if (const auto *TT = R->getAs<TypedefType>())
8110 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
8111
8112 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8113 if (EmitTLSUnsupportedError &&
8115 (getLangOpts().OpenMPIsTargetDevice &&
8116 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8117 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8118 diag::err_thread_unsupported);
8119
8120 if (EmitTLSUnsupportedError &&
8121 (LangOpts.SYCLIsDevice ||
8122 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8123 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8124 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8125 // storage [duration]."
8126 if (SC == SC_None && S->getFnParent() != nullptr &&
8127 (NewVD->hasAttr<CUDASharedAttr>() ||
8128 NewVD->hasAttr<CUDAConstantAttr>())) {
8129 NewVD->setStorageClass(SC_Static);
8130 }
8131 }
8132
8133 // Ensure that dllimport globals without explicit storage class are treated as
8134 // extern. The storage class is set above using parsed attributes. Now we can
8135 // check the VarDecl itself.
8136 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8137 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8138 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8139
8140 // In auto-retain/release, infer strong retension for variables of
8141 // retainable type.
8142 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8143 NewVD->setInvalidDecl();
8144
8145 // Handle GNU asm-label extension (encoded as an attribute).
8146 if (Expr *E = D.getAsmLabel()) {
8147 // The parser guarantees this is a string.
8148 StringLiteral *SE = cast<StringLiteral>(E);
8149 StringRef Label = SE->getString();
8150 if (S->getFnParent() != nullptr) {
8151 switch (SC) {
8152 case SC_None:
8153 case SC_Auto:
8154 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8155 break;
8156 case SC_Register:
8157 // Local Named register
8160 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8161 break;
8162 case SC_Static:
8163 case SC_Extern:
8164 case SC_PrivateExtern:
8165 break;
8166 }
8167 } else if (SC == SC_Register) {
8168 // Global Named register
8169 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8170 const auto &TI = Context.getTargetInfo();
8171 bool HasSizeMismatch;
8172
8173 if (!TI.isValidGCCRegisterName(Label))
8174 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8175 else if (!TI.validateGlobalRegisterVariable(Label,
8177 HasSizeMismatch))
8178 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8179 else if (HasSizeMismatch)
8180 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8181 }
8182
8183 if (!R->isIntegralType(Context) && !R->isPointerType()) {
8184 Diag(TInfo->getTypeLoc().getBeginLoc(),
8185 diag::err_asm_unsupported_register_type)
8186 << TInfo->getTypeLoc().getSourceRange();
8187 NewVD->setInvalidDecl(true);
8188 }
8189 }
8190
8191 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8192 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8193 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8195 if (I != ExtnameUndeclaredIdentifiers.end()) {
8196 if (isDeclExternC(NewVD)) {
8197 NewVD->addAttr(I->second);
8199 } else
8200 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8201 << /*Variable*/1 << NewVD;
8202 }
8203 }
8204
8205 // Find the shadowed declaration before filtering for scope.
8206 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8208 : nullptr;
8209
8210 // Don't consider existing declarations that are in a different
8211 // scope and are out-of-semantic-context declarations (if the new
8212 // declaration has linkage).
8214 D.getCXXScopeSpec().isNotEmpty() ||
8215 IsMemberSpecialization ||
8216 IsVariableTemplateSpecialization);
8217
8218 // Check whether the previous declaration is in the same block scope. This
8219 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8220 if (getLangOpts().CPlusPlus &&
8221 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8223 Previous.isSingleResult() && !Previous.isShadowed() &&
8224 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8225
8226 if (!getLangOpts().CPlusPlus) {
8227 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8228 } else {
8229 // If this is an explicit specialization of a static data member, check it.
8230 if (IsMemberSpecialization && !IsVariableTemplate &&
8231 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8233 NewVD->setInvalidDecl();
8234
8235 // Merge the decl with the existing one if appropriate.
8236 if (!Previous.empty()) {
8237 if (Previous.isSingleResult() &&
8238 isa<FieldDecl>(Previous.getFoundDecl()) &&
8239 D.getCXXScopeSpec().isSet()) {
8240 // The user tried to define a non-static data member
8241 // out-of-line (C++ [dcl.meaning]p1).
8242 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8243 << D.getCXXScopeSpec().getRange();
8244 Previous.clear();
8245 NewVD->setInvalidDecl();
8246 }
8247 } else if (D.getCXXScopeSpec().isSet() &&
8248 !IsVariableTemplateSpecialization) {
8249 // No previous declaration in the qualifying scope.
8250 Diag(D.getIdentifierLoc(), diag::err_no_member)
8251 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8252 << D.getCXXScopeSpec().getRange();
8253 NewVD->setInvalidDecl();
8254 }
8255
8256 if (!IsPlaceholderVariable)
8257 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8258
8259 // CheckVariableDeclaration will set NewVD as invalid if something is in
8260 // error like WebAssembly tables being declared as arrays with a non-zero
8261 // size, but then parsing continues and emits further errors on that line.
8262 // To avoid that we check here if it happened and return nullptr.
8263 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8264 return nullptr;
8265
8266 if (NewTemplate) {
8267 VarTemplateDecl *PrevVarTemplate =
8268 NewVD->getPreviousDecl()
8270 : nullptr;
8271
8272 // Check the template parameter list of this declaration, possibly
8273 // merging in the template parameter list from the previous variable
8274 // template declaration.
8276 TemplateParams,
8277 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8278 : nullptr,
8279 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8280 DC->isDependentContext())
8282 : TPC_Other))
8283 NewVD->setInvalidDecl();
8284
8285 // If we are providing an explicit specialization of a static variable
8286 // template, make a note of that.
8287 if (PrevVarTemplate &&
8288 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8289 PrevVarTemplate->setMemberSpecialization();
8290 }
8291 }
8292
8293 // Diagnose shadowed variables iff this isn't a redeclaration.
8294 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8295 CheckShadow(NewVD, ShadowedDecl, Previous);
8296
8297 ProcessPragmaWeak(S, NewVD);
8298
8299 // If this is the first declaration of an extern C variable, update
8300 // the map of such variables.
8301 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8302 isIncompleteDeclExternC(*this, NewVD))
8304
8305 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8307 Decl *ManglingContextDecl;
8308 std::tie(MCtx, ManglingContextDecl) =
8310 if (MCtx) {
8312 NewVD, MCtx->getManglingNumber(
8313 NewVD, getMSManglingNumber(getLangOpts(), S)));
8315 }
8316 }
8317
8318 // Special handling of variable named 'main'.
8319 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8320 // C++ [basic.start.main]p3:
8321 // A program that declares
8322 // - a variable main at global scope, or
8323 // - an entity named main with C language linkage (in any namespace)
8324 // is ill-formed
8325 if (getLangOpts().CPlusPlus)
8326 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8327 << NewVD->isExternC();
8328
8329 // In C, and external-linkage variable named main results in undefined
8330 // behavior.
8331 else if (NewVD->hasExternalFormalLinkage())
8332 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8333 }
8334
8335 if (D.isRedeclaration() && !Previous.empty()) {
8336 NamedDecl *Prev = Previous.getRepresentativeDecl();
8337 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8338 D.isFunctionDefinition());
8339 }
8340
8341 if (NewTemplate) {
8342 if (NewVD->isInvalidDecl())
8343 NewTemplate->setInvalidDecl();
8344 ActOnDocumentableDecl(NewTemplate);
8345 return NewTemplate;
8346 }
8347
8348 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8350
8352
8353 return NewVD;
8354}
8355
8356/// Enum describing the %select options in diag::warn_decl_shadow.
8366
8367/// Determine what kind of declaration we're shadowing.
8369 const DeclContext *OldDC) {
8370 if (isa<TypeAliasDecl>(ShadowedDecl))
8371 return SDK_Using;
8372 else if (isa<TypedefDecl>(ShadowedDecl))
8373 return SDK_Typedef;
8374 else if (isa<BindingDecl>(ShadowedDecl))
8375 return SDK_StructuredBinding;
8376 else if (isa<RecordDecl>(OldDC))
8377 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8378
8379 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8380}
8381
8382/// Return the location of the capture if the given lambda captures the given
8383/// variable \p VD, or an invalid source location otherwise.
8385 const VarDecl *VD) {
8386 for (const Capture &Capture : LSI->Captures) {
8388 return Capture.getLocation();
8389 }
8390 return SourceLocation();
8391}
8392
8394 const LookupResult &R) {
8395 // Only diagnose if we're shadowing an unambiguous field or variable.
8397 return false;
8398
8399 // Return false if warning is ignored.
8400 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8401}
8402
8404 const LookupResult &R) {
8406 return nullptr;
8407
8408 // Don't diagnose declarations at file scope.
8409 if (D->hasGlobalStorage() && !D->isStaticLocal())
8410 return nullptr;
8411
8412 NamedDecl *ShadowedDecl = R.getFoundDecl();
8413 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8414 : nullptr;
8415}
8416
8418 const LookupResult &R) {
8419 // Don't warn if typedef declaration is part of a class
8420 if (D->getDeclContext()->isRecord())
8421 return nullptr;
8422
8424 return nullptr;
8425
8426 NamedDecl *ShadowedDecl = R.getFoundDecl();
8427 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8428}
8429
8431 const LookupResult &R) {
8433 return nullptr;
8434
8435 NamedDecl *ShadowedDecl = R.getFoundDecl();
8436 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8437 : nullptr;
8438}
8439
8441 const LookupResult &R) {
8442 DeclContext *NewDC = D->getDeclContext();
8443
8444 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8445 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) {
8446 // Fields are not shadowed by variables in C++ static methods.
8447 if (MD->isStatic())
8448 return;
8449
8450 if (!MD->getParent()->isLambda() && MD->isExplicitObjectMemberFunction())
8451 return;
8452 }
8453 // Fields shadowed by constructor parameters are a special case. Usually
8454 // the constructor initializes the field with the parameter.
8455 if (isa<CXXConstructorDecl>(NewDC))
8456 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8457 // Remember that this was shadowed so we can either warn about its
8458 // modification or its existence depending on warning settings.
8459 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8460 return;
8461 }
8462 }
8463
8464 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8465 if (shadowedVar->isExternC()) {
8466 // For shadowing external vars, make sure that we point to the global
8467 // declaration, not a locally scoped extern declaration.
8468 for (auto *I : shadowedVar->redecls())
8469 if (I->isFileVarDecl()) {
8470 ShadowedDecl = I;
8471 break;
8472 }
8473 }
8474
8475 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8476
8477 unsigned WarningDiag = diag::warn_decl_shadow;
8478 SourceLocation CaptureLoc;
8479 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8480 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8481 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8482 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8483 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8484 if (RD->getLambdaCaptureDefault() == LCD_None) {
8485 // Try to avoid warnings for lambdas with an explicit capture
8486 // list. Warn only when the lambda captures the shadowed decl
8487 // explicitly.
8488 CaptureLoc = getCaptureLocation(LSI, VD);
8489 if (CaptureLoc.isInvalid())
8490 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8491 } else {
8492 // Remember that this was shadowed so we can avoid the warning if
8493 // the shadowed decl isn't captured and the warning settings allow
8494 // it.
8495 cast<LambdaScopeInfo>(getCurFunction())
8496 ->ShadowingDecls.push_back({D, VD});
8497 return;
8498 }
8499 }
8500 if (isa<FieldDecl>(ShadowedDecl)) {
8501 // If lambda can capture this, then emit default shadowing warning,
8502 // Otherwise it is not really a shadowing case since field is not
8503 // available in lambda's body.
8504 // At this point we don't know that lambda can capture this, so
8505 // remember that this was shadowed and delay until we know.
8506 cast<LambdaScopeInfo>(getCurFunction())
8507 ->ShadowingDecls.push_back({D, ShadowedDecl});
8508 return;
8509 }
8510 }
8511 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8512 VD && VD->hasLocalStorage()) {
8513 // A variable can't shadow a local variable in an enclosing scope, if
8514 // they are separated by a non-capturing declaration context.
8515 for (DeclContext *ParentDC = NewDC;
8516 ParentDC && !ParentDC->Equals(OldDC);
8517 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8518 // Only block literals, captured statements, and lambda expressions
8519 // can capture; other scopes don't.
8520 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8521 !isLambdaCallOperator(ParentDC)) {
8522 return;
8523 }
8524 }
8525 }
8526 }
8527 }
8528
8529 // Never warn about shadowing a placeholder variable.
8530 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8531 return;
8532
8533 // Only warn about certain kinds of shadowing for class members.
8534 if (NewDC) {
8535 // In particular, don't warn about shadowing non-class members.
8536 if (NewDC->isRecord() && !OldDC->isRecord())
8537 return;
8538
8539 // Skip shadowing check if we're in a class scope, dealing with an enum
8540 // constant in a different context.
8541 DeclContext *ReDC = NewDC->getRedeclContext();
8542 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8543 return;
8544
8545 // TODO: should we warn about static data members shadowing
8546 // static data members from base classes?
8547
8548 // TODO: don't diagnose for inaccessible shadowed members.
8549 // This is hard to do perfectly because we might friend the
8550 // shadowing context, but that's just a false negative.
8551 }
8552
8553 DeclarationName Name = R.getLookupName();
8554
8555 // Emit warning and note.
8556 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8557 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8558 if (!CaptureLoc.isInvalid())
8559 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8560 << Name << /*explicitly*/ 1;
8561 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8562}
8563
8565 for (const auto &Shadow : LSI->ShadowingDecls) {
8566 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8567 // Try to avoid the warning when the shadowed decl isn't captured.
8568 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8569 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8570 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8571 Diag(Shadow.VD->getLocation(),
8572 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8573 : diag::warn_decl_shadow)
8574 << Shadow.VD->getDeclName()
8575 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8576 if (CaptureLoc.isValid())
8577 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8578 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8579 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8580 } else if (isa<FieldDecl>(ShadowedDecl)) {
8581 Diag(Shadow.VD->getLocation(),
8582 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8583 : diag::warn_decl_shadow_uncaptured_local)
8584 << Shadow.VD->getDeclName()
8585 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8586 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8587 }
8588 }
8589}
8590
8592 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8593 return;
8594
8595 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8597 RedeclarationKind::ForVisibleRedeclaration);
8598 LookupName(R, S);
8599 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8600 CheckShadow(D, ShadowedDecl, R);
8601}
8602
8603/// Check if 'E', which is an expression that is about to be modified, refers
8604/// to a constructor parameter that shadows a field.
8606 // Quickly ignore expressions that can't be shadowing ctor parameters.
8607 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8608 return;
8609 E = E->IgnoreParenImpCasts();
8610 auto *DRE = dyn_cast<DeclRefExpr>(E);
8611 if (!DRE)
8612 return;
8613 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8614 auto I = ShadowingDecls.find(D);
8615 if (I == ShadowingDecls.end())
8616 return;
8617 const NamedDecl *ShadowedDecl = I->second;
8618 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8619 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8620 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8621 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8622
8623 // Avoid issuing multiple warnings about the same decl.
8624 ShadowingDecls.erase(I);
8625}
8626
8627/// Check for conflict between this global or extern "C" declaration and
8628/// previous global or extern "C" declarations. This is only used in C++.
8629template<typename T>
8631 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8632 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8633 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8634
8635 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8636 // The common case: this global doesn't conflict with any extern "C"
8637 // declaration.
8638 return false;
8639 }
8640
8641 if (Prev) {
8642 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8643 // Both the old and new declarations have C language linkage. This is a
8644 // redeclaration.
8645 Previous.clear();
8646 Previous.addDecl(Prev);
8647 return true;
8648 }
8649
8650 // This is a global, non-extern "C" declaration, and there is a previous
8651 // non-global extern "C" declaration. Diagnose if this is a variable
8652 // declaration.
8653 if (!isa<VarDecl>(ND))
8654 return false;
8655 } else {
8656 // The declaration is extern "C". Check for any declaration in the
8657 // translation unit which might conflict.
8658 if (IsGlobal) {
8659 // We have already performed the lookup into the translation unit.
8660 IsGlobal = false;
8661 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8662 I != E; ++I) {
8663 if (isa<VarDecl>(*I)) {
8664 Prev = *I;
8665 break;
8666 }
8667 }
8668 } else {
8670 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8671 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8672 I != E; ++I) {
8673 if (isa<VarDecl>(*I)) {
8674 Prev = *I;
8675 break;
8676 }
8677 // FIXME: If we have any other entity with this name in global scope,
8678 // the declaration is ill-formed, but that is a defect: it breaks the
8679 // 'stat' hack, for instance. Only variables can have mangled name
8680 // clashes with extern "C" declarations, so only they deserve a
8681 // diagnostic.
8682 }
8683 }
8684
8685 if (!Prev)
8686 return false;
8687 }
8688
8689 // Use the first declaration's location to ensure we point at something which
8690 // is lexically inside an extern "C" linkage-spec.
8691 assert(Prev && "should have found a previous declaration to diagnose");
8692 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8693 Prev = FD->getFirstDecl();
8694 else
8695 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8696
8697 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8698 << IsGlobal << ND;
8699 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8700 << IsGlobal;
8701 return false;
8702}
8703
8704/// Apply special rules for handling extern "C" declarations. Returns \c true
8705/// if we have found that this is a redeclaration of some prior entity.
8706///
8707/// Per C++ [dcl.link]p6:
8708/// Two declarations [for a function or variable] with C language linkage
8709/// with the same name that appear in different scopes refer to the same
8710/// [entity]. An entity with C language linkage shall not be declared with
8711/// the same name as an entity in global scope.
8712template<typename T>
8715 if (!S.getLangOpts().CPlusPlus) {
8716 // In C, when declaring a global variable, look for a corresponding 'extern'
8717 // variable declared in function scope. We don't need this in C++, because
8718 // we find local extern decls in the surrounding file-scope DeclContext.
8719 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8720 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8721 Previous.clear();
8722 Previous.addDecl(Prev);
8723 return true;
8724 }
8725 }
8726 return false;
8727 }
8728
8729 // A declaration in the translation unit can conflict with an extern "C"
8730 // declaration.
8731 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8732 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8733
8734 // An extern "C" declaration can conflict with a declaration in the
8735 // translation unit or can be a redeclaration of an extern "C" declaration
8736 // in another scope.
8737 if (isIncompleteDeclExternC(S,ND))
8738 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8739
8740 // Neither global nor extern "C": nothing to do.
8741 return false;
8742}
8743
8744static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8745 QualType T) {
8746 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8747 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8748 // any of its members, even recursively, shall not have an atomic type, or a
8749 // variably modified type, or a type that is volatile or restrict qualified.
8750 if (CanonT->isVariablyModifiedType()) {
8751 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8752 return true;
8753 }
8754
8755 // Arrays are qualified by their element type, so get the base type (this
8756 // works on non-arrays as well).
8757 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8758
8759 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8760 CanonT.isRestrictQualified()) {
8761 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8762 return true;
8763 }
8764
8765 if (CanonT->isRecordType()) {
8766 const RecordDecl *RD = CanonT->getAsRecordDecl();
8767 if (!RD->isInvalidDecl() &&
8768 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8769 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8770 }))
8771 return true;
8772 }
8773
8774 return false;
8775}
8776
8778 // If the decl is already known invalid, don't check it.
8779 if (NewVD->isInvalidDecl())
8780 return;
8781
8782 QualType T = NewVD->getType();
8783
8784 // Defer checking an 'auto' type until its initializer is attached.
8785 if (T->isUndeducedType())
8786 return;
8787
8788 if (NewVD->hasAttrs())
8790
8791 if (T->isObjCObjectType()) {
8792 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8793 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8795 NewVD->setType(T);
8796 }
8797
8798 // Emit an error if an address space was applied to decl with local storage.
8799 // This includes arrays of objects with address space qualifiers, but not
8800 // automatic variables that point to other address spaces.
8801 // ISO/IEC TR 18037 S5.1.2
8802 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8803 T.getAddressSpace() != LangAS::Default) {
8804 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8805 NewVD->setInvalidDecl();
8806 return;
8807 }
8808
8809 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8810 // scope.
8811 if (getLangOpts().OpenCLVersion == 120 &&
8812 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8813 getLangOpts()) &&
8814 NewVD->isStaticLocal()) {
8815 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8816 NewVD->setInvalidDecl();
8817 return;
8818 }
8819
8820 if (getLangOpts().OpenCL) {
8821 if (!diagnoseOpenCLTypes(*this, NewVD))
8822 return;
8823
8824 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8825 if (NewVD->hasAttr<BlocksAttr>()) {
8826 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8827 return;
8828 }
8829
8830 if (T->isBlockPointerType()) {
8831 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8832 // can't use 'extern' storage class.
8833 if (!T.isConstQualified()) {
8834 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8835 << 0 /*const*/;
8836 NewVD->setInvalidDecl();
8837 return;
8838 }
8839 if (NewVD->hasExternalStorage()) {
8840 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8841 NewVD->setInvalidDecl();
8842 return;
8843 }
8844 }
8845
8846 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8847 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8848 NewVD->hasExternalStorage()) {
8849 if (!T->isSamplerT() && !T->isDependentType() &&
8850 !(T.getAddressSpace() == LangAS::opencl_constant ||
8851 (T.getAddressSpace() == LangAS::opencl_global &&
8852 getOpenCLOptions().areProgramScopeVariablesSupported(
8853 getLangOpts())))) {
8854 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8855 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8856 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8857 << Scope << "global or constant";
8858 else
8859 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8860 << Scope << "constant";
8861 NewVD->setInvalidDecl();
8862 return;
8863 }
8864 } else {
8865 if (T.getAddressSpace() == LangAS::opencl_global) {
8866 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8867 << 1 /*is any function*/ << "global";
8868 NewVD->setInvalidDecl();
8869 return;
8870 }
8871 if (T.getAddressSpace() == LangAS::opencl_constant ||
8872 T.getAddressSpace() == LangAS::opencl_local) {
8874 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8875 // in functions.
8876 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8877 if (T.getAddressSpace() == LangAS::opencl_constant)
8878 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8879 << 0 /*non-kernel only*/ << "constant";
8880 else
8881 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8882 << 0 /*non-kernel only*/ << "local";
8883 NewVD->setInvalidDecl();
8884 return;
8885 }
8886 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8887 // in the outermost scope of a kernel function.
8888 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
8889 if (!getCurScope()->isFunctionScope()) {
8890 if (T.getAddressSpace() == LangAS::opencl_constant)
8891 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8892 << "constant";
8893 else
8894 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8895 << "local";
8896 NewVD->setInvalidDecl();
8897 return;
8898 }
8899 }
8900 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8901 // If we are parsing a template we didn't deduce an addr
8902 // space yet.
8903 T.getAddressSpace() != LangAS::Default) {
8904 // Do not allow other address spaces on automatic variable.
8905 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8906 NewVD->setInvalidDecl();
8907 return;
8908 }
8909 }
8910 }
8911
8912 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8913 && !NewVD->hasAttr<BlocksAttr>()) {
8914 if (getLangOpts().getGC() != LangOptions::NonGC)
8915 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8916 else {
8917 assert(!getLangOpts().ObjCAutoRefCount);
8918 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8919 }
8920 }
8921
8922 // WebAssembly tables must be static with a zero length and can't be
8923 // declared within functions.
8924 if (T->isWebAssemblyTableType()) {
8925 if (getCurScope()->getParent()) { // Parent is null at top-level
8926 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8927 NewVD->setInvalidDecl();
8928 return;
8929 }
8930 if (NewVD->getStorageClass() != SC_Static) {
8931 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8932 NewVD->setInvalidDecl();
8933 return;
8934 }
8935 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8936 if (!ATy || ATy->getZExtSize() != 0) {
8937 Diag(NewVD->getLocation(),
8938 diag::err_typecheck_wasm_table_must_have_zero_length);
8939 NewVD->setInvalidDecl();
8940 return;
8941 }
8942 }
8943
8944 // zero sized static arrays are not allowed in HIP device functions
8945 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
8946 if (FunctionDecl *FD = getCurFunctionDecl();
8947 FD &&
8948 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
8949 if (const ConstantArrayType *ArrayT =
8951 ArrayT && ArrayT->isZeroSize()) {
8952 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
8953 }
8954 }
8955 }
8956
8957 bool isVM = T->isVariablyModifiedType();
8958 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8959 NewVD->hasAttr<BlocksAttr>())
8961
8962 if ((isVM && NewVD->hasLinkage()) ||
8963 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8964 bool SizeIsNegative;
8965 llvm::APSInt Oversized;
8967 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8968 QualType FixedT;
8969 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8970 FixedT = FixedTInfo->getType();
8971 else if (FixedTInfo) {
8972 // Type and type-as-written are canonically different. We need to fix up
8973 // both types separately.
8974 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8975 Oversized);
8976 }
8977 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8979 // FIXME: This won't give the correct result for
8980 // int a[10][n];
8981 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8982
8983 if (NewVD->isFileVarDecl())
8984 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8985 << SizeRange;
8986 else if (NewVD->isStaticLocal())
8987 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8988 << SizeRange;
8989 else
8990 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8991 << SizeRange;
8992 NewVD->setInvalidDecl();
8993 return;
8994 }
8995
8996 if (!FixedTInfo) {
8997 if (NewVD->isFileVarDecl())
8998 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8999 else
9000 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9001 NewVD->setInvalidDecl();
9002 return;
9003 }
9004
9005 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9006 NewVD->setType(FixedT);
9007 NewVD->setTypeSourceInfo(FixedTInfo);
9008 }
9009
9010 if (T->isVoidType()) {
9011 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9012 // of objects and functions.
9014 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9015 << T;
9016 NewVD->setInvalidDecl();
9017 return;
9018 }
9019 }
9020
9021 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9022 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
9023 NewVD->setInvalidDecl();
9024 return;
9025 }
9026
9027 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9028 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9029 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9030 NewVD->setInvalidDecl();
9031 return;
9032 }
9033
9034 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9035 Diag(NewVD->getLocation(), diag::err_block_on_vm);
9036 NewVD->setInvalidDecl();
9037 return;
9038 }
9039
9040 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9041 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9042 NewVD->setInvalidDecl();
9043 return;
9044 }
9045
9046 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9047 !T->isDependentType() &&
9049 diag::err_constexpr_var_non_literal)) {
9050 NewVD->setInvalidDecl();
9051 return;
9052 }
9053
9054 // PPC MMA non-pointer types are not allowed as non-local variable types.
9055 if (Context.getTargetInfo().getTriple().isPPC64() &&
9056 !NewVD->isLocalVarDecl() &&
9057 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9058 NewVD->setInvalidDecl();
9059 return;
9060 }
9061
9062 // Check that SVE types are only used in functions with SVE available.
9063 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9064 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
9065 llvm::StringMap<bool> CallerFeatureMap;
9066 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9067
9068 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
9069 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
9070 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
9071 NewVD->setInvalidDecl();
9072 return;
9073 } else if (!IsArmStreamingFunction(FD,
9074 /*IncludeLocallyStreaming=*/true)) {
9075 Diag(NewVD->getLocation(),
9076 diag::err_sve_vector_in_non_streaming_function)
9077 << T;
9078 NewVD->setInvalidDecl();
9079 return;
9080 }
9081 }
9082 }
9083
9084 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9085 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
9086 llvm::StringMap<bool> CallerFeatureMap;
9087 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9088 RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
9089 CallerFeatureMap);
9090 }
9091}
9092
9095
9096 // If the decl is already known invalid, don't check it.
9097 if (NewVD->isInvalidDecl())
9098 return false;
9099
9100 // If we did not find anything by this name, look for a non-visible
9101 // extern "C" declaration with the same name.
9102 if (Previous.empty() &&
9104 Previous.setShadowed();
9105
9106 if (!Previous.empty()) {
9107 MergeVarDecl(NewVD, Previous);
9108 return true;
9109 }
9110 return false;
9111}
9112
9115
9116 // Look for methods in base classes that this method might override.
9117 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9118 /*DetectVirtual=*/false);
9119 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9120 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9121 DeclarationName Name = MD->getDeclName();
9122
9123 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9124 // We really want to find the base class destructor here.
9126 Context.getCanonicalTagType(BaseRecord));
9127 }
9128
9129 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9130 CXXMethodDecl *BaseMD =
9131 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9132 if (!BaseMD || !BaseMD->isVirtual() ||
9133 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9134 /*ConsiderCudaAttrs=*/true))
9135 continue;
9136 if (!CheckExplicitObjectOverride(MD, BaseMD))
9137 continue;
9138 if (Overridden.insert(BaseMD).second) {
9139 MD->addOverriddenMethod(BaseMD);
9144 }
9145
9146 // A method can only override one function from each base class. We
9147 // don't track indirectly overridden methods from bases of bases.
9148 return true;
9149 }
9150
9151 return false;
9152 };
9153
9154 DC->lookupInBases(VisitBase, Paths);
9155 return !Overridden.empty();
9156}
9157
9158namespace {
9159 // Struct for holding all of the extra arguments needed by
9160 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9161 struct ActOnFDArgs {
9162 Scope *S;
9163 Declarator &D;
9164 MultiTemplateParamsArg TemplateParamLists;
9165 bool AddToScope;
9166 };
9167} // end anonymous namespace
9168
9169namespace {
9170
9171// Callback to only accept typo corrections that have a non-zero edit distance.
9172// Also only accept corrections that have the same parent decl.
9173class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9174 public:
9175 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9177 : Context(Context), OriginalFD(TypoFD),
9178 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9179
9180 bool ValidateCandidate(const TypoCorrection &candidate) override {
9181 if (candidate.getEditDistance() == 0)
9182 return false;
9183
9184 SmallVector<unsigned, 1> MismatchedParams;
9185 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9186 CDeclEnd = candidate.end();
9187 CDecl != CDeclEnd; ++CDecl) {
9188 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9189
9190 if (FD && !FD->hasBody() &&
9191 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9192 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9193 CXXRecordDecl *Parent = MD->getParent();
9194 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9195 return true;
9196 } else if (!ExpectedParent) {
9197 return true;
9198 }
9199 }
9200 }
9201
9202 return false;
9203 }
9204
9205 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9206 return std::make_unique<DifferentNameValidatorCCC>(*this);
9207 }
9208
9209 private:
9210 ASTContext &Context;
9211 FunctionDecl *OriginalFD;
9212 CXXRecordDecl *ExpectedParent;
9213};
9214
9215} // end anonymous namespace
9216
9219}
9220
9221/// Generate diagnostics for an invalid function redeclaration.
9222///
9223/// This routine handles generating the diagnostic messages for an invalid
9224/// function redeclaration, including finding possible similar declarations
9225/// or performing typo correction if there are no previous declarations with
9226/// the same name.
9227///
9228/// Returns a NamedDecl iff typo correction was performed and substituting in
9229/// the new declaration name does not cause new errors.
9231 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9232 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9233 DeclarationName Name = NewFD->getDeclName();
9234 DeclContext *NewDC = NewFD->getDeclContext();
9235 SmallVector<unsigned, 1> MismatchedParams;
9237 TypoCorrection Correction;
9238 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9239 unsigned DiagMsg =
9240 IsLocalFriend ? diag::err_no_matching_local_friend :
9241 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9242 diag::err_member_decl_does_not_match;
9243 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9244 IsLocalFriend ? Sema::LookupLocalFriendName
9246 RedeclarationKind::ForVisibleRedeclaration);
9247
9248 NewFD->setInvalidDecl();
9249 if (IsLocalFriend)
9250 SemaRef.LookupName(Prev, S);
9251 else
9252 SemaRef.LookupQualifiedName(Prev, NewDC);
9253 assert(!Prev.isAmbiguous() &&
9254 "Cannot have an ambiguity in previous-declaration lookup");
9255 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9256 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9257 MD ? MD->getParent() : nullptr);
9258 if (!Prev.empty()) {
9259 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9260 Func != FuncEnd; ++Func) {
9261 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9262 if (FD &&
9263 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9264 // Add 1 to the index so that 0 can mean the mismatch didn't
9265 // involve a parameter
9266 unsigned ParamNum =
9267 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9268 NearMatches.push_back(std::make_pair(FD, ParamNum));
9269 }
9270 }
9271 // If the qualified name lookup yielded nothing, try typo correction
9272 } else if ((Correction = SemaRef.CorrectTypo(
9273 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9274 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9276 IsLocalFriend ? nullptr : NewDC))) {
9277 // Set up everything for the call to ActOnFunctionDeclarator
9278 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9279 ExtraArgs.D.getIdentifierLoc());
9280 Previous.clear();
9281 Previous.setLookupName(Correction.getCorrection());
9282 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9283 CDeclEnd = Correction.end();
9284 CDecl != CDeclEnd; ++CDecl) {
9285 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9286 if (FD && !FD->hasBody() &&
9287 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9288 Previous.addDecl(FD);
9289 }
9290 }
9291 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9292
9294 // Retry building the function declaration with the new previous
9295 // declarations, and with errors suppressed.
9296 {
9297 // Trap errors.
9298 Sema::SFINAETrap Trap(SemaRef);
9299
9300 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9301 // pieces need to verify the typo-corrected C++ declaration and hopefully
9302 // eliminate the need for the parameter pack ExtraArgs.
9304 ExtraArgs.S, ExtraArgs.D,
9305 Correction.getCorrectionDecl()->getDeclContext(),
9306 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9307 ExtraArgs.AddToScope);
9308
9309 if (Trap.hasErrorOccurred())
9310 Result = nullptr;
9311 }
9312
9313 if (Result) {
9314 // Determine which correction we picked.
9315 Decl *Canonical = Result->getCanonicalDecl();
9316 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9317 I != E; ++I)
9318 if ((*I)->getCanonicalDecl() == Canonical)
9319 Correction.setCorrectionDecl(*I);
9320
9321 // Let Sema know about the correction.
9323 SemaRef.diagnoseTypo(
9324 Correction,
9325 SemaRef.PDiag(IsLocalFriend
9326 ? diag::err_no_matching_local_friend_suggest
9327 : diag::err_member_decl_does_not_match_suggest)
9328 << Name << NewDC << IsDefinition);
9329 return Result;
9330 }
9331
9332 // Pretend the typo correction never occurred
9333 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9334 ExtraArgs.D.getIdentifierLoc());
9335 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9336 Previous.clear();
9337 Previous.setLookupName(Name);
9338 }
9339
9340 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9341 << Name << NewDC << IsDefinition << NewFD->getLocation();
9342
9343 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9344 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9345 CXXRecordDecl *RD = NewMD->getParent();
9346 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9347 << RD->getName() << RD->getLocation();
9348 }
9349
9350 bool NewFDisConst = NewMD && NewMD->isConst();
9351
9352 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9353 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9354 NearMatch != NearMatchEnd; ++NearMatch) {
9355 FunctionDecl *FD = NearMatch->first;
9356 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9357 bool FDisConst = MD && MD->isConst();
9358 bool IsMember = MD || !IsLocalFriend;
9359
9360 // FIXME: These notes are poorly worded for the local friend case.
9361 if (unsigned Idx = NearMatch->second) {
9362 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9364 if (Loc.isInvalid()) Loc = FD->getLocation();
9365 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9366 : diag::note_local_decl_close_param_match)
9367 << Idx << FDParam->getType()
9368 << NewFD->getParamDecl(Idx - 1)->getType();
9369 } else if (FDisConst != NewFDisConst) {
9370 auto DB = SemaRef.Diag(FD->getLocation(),
9371 diag::note_member_def_close_const_match)
9372 << NewFDisConst << FD->getSourceRange().getEnd();
9373 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9374 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9375 " const");
9376 else if (FTI.hasMethodTypeQualifiers() &&
9377 FTI.getConstQualifierLoc().isValid())
9378 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9379 } else {
9380 SemaRef.Diag(FD->getLocation(),
9381 IsMember ? diag::note_member_def_close_match
9382 : diag::note_local_decl_close_match);
9383 }
9384 }
9385 return nullptr;
9386}
9387
9389 switch (D.getDeclSpec().getStorageClassSpec()) {
9390 default: llvm_unreachable("Unknown storage class!");
9391 case DeclSpec::SCS_auto:
9394 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9395 diag::err_typecheck_sclass_func);
9396 D.getMutableDeclSpec().ClearStorageClassSpecs();
9397 D.setInvalidType();
9398 break;
9399 case DeclSpec::SCS_unspecified: break;
9401 if (D.getDeclSpec().isExternInLinkageSpec())
9402 return SC_None;
9403 return SC_Extern;
9404 case DeclSpec::SCS_static: {
9406 // C99 6.7.1p5:
9407 // The declaration of an identifier for a function that has
9408 // block scope shall have no explicit storage-class specifier
9409 // other than extern
9410 // See also (C++ [dcl.stc]p4).
9411 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9412 diag::err_static_block_func);
9413 break;
9414 } else
9415 return SC_Static;
9416 }
9418 }
9419
9420 // No explicit storage class has already been returned
9421 return SC_None;
9422}
9423
9425 DeclContext *DC, QualType &R,
9426 TypeSourceInfo *TInfo,
9427 StorageClass SC,
9428 bool &IsVirtualOkay) {
9429 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9430 DeclarationName Name = NameInfo.getName();
9431
9432 FunctionDecl *NewFD = nullptr;
9433 bool isInline = D.getDeclSpec().isInlineSpecified();
9434
9435 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9436 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9437 (SemaRef.getLangOpts().C23 &&
9438 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9439
9440 if (SemaRef.getLangOpts().C23)
9441 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9442 diag::err_c23_constexpr_not_variable);
9443 else
9444 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9445 diag::err_constexpr_wrong_decl_kind)
9446 << static_cast<int>(ConstexprKind);
9447 ConstexprKind = ConstexprSpecKind::Unspecified;
9448 D.getMutableDeclSpec().ClearConstexprSpec();
9449 }
9450
9451 if (!SemaRef.getLangOpts().CPlusPlus) {
9452 // Determine whether the function was written with a prototype. This is
9453 // true when:
9454 // - there is a prototype in the declarator, or
9455 // - the type R of the function is some kind of typedef or other non-
9456 // attributed reference to a type name (which eventually refers to a
9457 // function type). Note, we can't always look at the adjusted type to
9458 // check this case because attributes may cause a non-function
9459 // declarator to still have a function type. e.g.,
9460 // typedef void func(int a);
9461 // __attribute__((noreturn)) func other_func; // This has a prototype
9462 bool HasPrototype =
9463 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9464 (D.getDeclSpec().isTypeRep() &&
9465 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9466 ->isFunctionProtoType()) ||
9468 assert(
9469 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9470 "Strict prototypes are required");
9471
9472 NewFD = FunctionDecl::Create(
9473 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9474 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9476 /*TrailingRequiresClause=*/{});
9477 if (D.isInvalidType())
9478 NewFD->setInvalidDecl();
9479
9480 return NewFD;
9481 }
9482
9483 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9484 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9485
9486 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9487
9488 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9489 // This is a C++ constructor declaration.
9490 assert(DC->isRecord() &&
9491 "Constructors can only be declared in a member context");
9492
9493 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9495 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9497 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9498 InheritedConstructor(), TrailingRequiresClause);
9499
9500 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9501 // This is a C++ destructor declaration.
9502 if (DC->isRecord()) {
9503 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9504 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9506 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9507 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9508 /*isImplicitlyDeclared=*/false, ConstexprKind,
9509 TrailingRequiresClause);
9510 // User defined destructors start as not selected if the class definition is still
9511 // not done.
9512 if (Record->isBeingDefined())
9513 NewDD->setIneligibleOrNotSelected(true);
9514
9515 // If the destructor needs an implicit exception specification, set it
9516 // now. FIXME: It'd be nice to be able to create the right type to start
9517 // with, but the type needs to reference the destructor declaration.
9518 if (SemaRef.getLangOpts().CPlusPlus11)
9519 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9520
9521 IsVirtualOkay = true;
9522 return NewDD;
9523
9524 } else {
9525 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9526 D.setInvalidType();
9527
9528 // Create a FunctionDecl to satisfy the function definition parsing
9529 // code path.
9530 return FunctionDecl::Create(
9531 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9532 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9533 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9534 }
9535
9536 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9537 if (!DC->isRecord()) {
9538 SemaRef.Diag(D.getIdentifierLoc(),
9539 diag::err_conv_function_not_member);
9540 return nullptr;
9541 }
9542
9543 SemaRef.CheckConversionDeclarator(D, R, SC);
9544 if (D.isInvalidType())
9545 return nullptr;
9546
9547 IsVirtualOkay = true;
9549 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9550 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9551 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9552 TrailingRequiresClause);
9553
9554 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9555 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9556 return nullptr;
9558 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9559 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9560 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9561 } else if (DC->isRecord()) {
9562 // If the name of the function is the same as the name of the record,
9563 // then this must be an invalid constructor that has a return type.
9564 // (The parser checks for a return type and makes the declarator a
9565 // constructor if it has no return type).
9566 if (Name.getAsIdentifierInfo() &&
9567 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9568 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9569 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9570 << SourceRange(D.getIdentifierLoc());
9571 return nullptr;
9572 }
9573
9574 // This is a C++ method declaration.
9576 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9577 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9578 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9579 IsVirtualOkay = !Ret->isStatic();
9580 return Ret;
9581 } else {
9582 bool isFriend =
9583 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9584 if (!isFriend && SemaRef.CurContext->isRecord())
9585 return nullptr;
9586
9587 // Determine whether the function was written with a
9588 // prototype. This true when:
9589 // - we're in C++ (where every function has a prototype),
9590 return FunctionDecl::Create(
9591 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9592 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9593 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9594 }
9595}
9596
9605
9607 // Size dependent types are just typedefs to normal integer types
9608 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9609 // integers other than by their names.
9610 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9611
9612 // Remove typedefs one by one until we reach a typedef
9613 // for a size dependent type.
9614 QualType DesugaredTy = Ty;
9615 do {
9616 ArrayRef<StringRef> Names(SizeTypeNames);
9617 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9618 if (Names.end() != Match)
9619 return true;
9620
9621 Ty = DesugaredTy;
9622 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9623 } while (DesugaredTy != Ty);
9624
9625 return false;
9626}
9627
9629 if (PT->isDependentType())
9630 return InvalidKernelParam;
9631
9632 if (PT->isPointerOrReferenceType()) {
9633 QualType PointeeType = PT->getPointeeType();
9634 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9635 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9636 PointeeType.getAddressSpace() == LangAS::Default)
9638
9639 if (PointeeType->isPointerType()) {
9640 // This is a pointer to pointer parameter.
9641 // Recursively check inner type.
9642 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9643 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9644 ParamKind == InvalidKernelParam)
9645 return ParamKind;
9646
9647 // OpenCL v3.0 s6.11.a:
9648 // A restriction to pass pointers to pointers only applies to OpenCL C
9649 // v1.2 or below.
9651 return ValidKernelParam;
9652
9653 return PtrPtrKernelParam;
9654 }
9655
9656 // C++ for OpenCL v1.0 s2.4:
9657 // Moreover the types used in parameters of the kernel functions must be:
9658 // Standard layout types for pointer parameters. The same applies to
9659 // reference if an implementation supports them in kernel parameters.
9660 if (S.getLangOpts().OpenCLCPlusPlus &&
9662 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9663 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9664 bool IsStandardLayoutType = true;
9665 if (CXXRec) {
9666 // If template type is not ODR-used its definition is only available
9667 // in the template definition not its instantiation.
9668 // FIXME: This logic doesn't work for types that depend on template
9669 // parameter (PR58590).
9670 if (!CXXRec->hasDefinition())
9671 CXXRec = CXXRec->getTemplateInstantiationPattern();
9672 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9673 IsStandardLayoutType = false;
9674 }
9675 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9676 !IsStandardLayoutType)
9677 return InvalidKernelParam;
9678 }
9679
9680 // OpenCL v1.2 s6.9.p:
9681 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9683 return ValidKernelParam;
9684
9685 return PtrKernelParam;
9686 }
9687
9688 // OpenCL v1.2 s6.9.k:
9689 // Arguments to kernel functions in a program cannot be declared with the
9690 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9691 // uintptr_t or a struct and/or union that contain fields declared to be one
9692 // of these built-in scalar types.
9694 return InvalidKernelParam;
9695
9696 if (PT->isImageType())
9697 return PtrKernelParam;
9698
9699 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9700 return InvalidKernelParam;
9701
9702 // OpenCL extension spec v1.2 s9.5:
9703 // This extension adds support for half scalar and vector types as built-in
9704 // types that can be used for arithmetic operations, conversions etc.
9705 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9706 PT->isHalfType())
9707 return InvalidKernelParam;
9708
9709 // Look into an array argument to check if it has a forbidden type.
9710 if (PT->isArrayType()) {
9711 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9712 // Call ourself to check an underlying type of an array. Since the
9713 // getPointeeOrArrayElementType returns an innermost type which is not an
9714 // array, this recursive call only happens once.
9715 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9716 }
9717
9718 // C++ for OpenCL v1.0 s2.4:
9719 // Moreover the types used in parameters of the kernel functions must be:
9720 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9721 // types) for parameters passed by value;
9722 if (S.getLangOpts().OpenCLCPlusPlus &&
9724 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9725 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9726 return InvalidKernelParam;
9727
9728 if (PT->isRecordType())
9729 return RecordKernelParam;
9730
9731 return ValidKernelParam;
9732}
9733
9735 Sema &S,
9736 Declarator &D,
9737 ParmVarDecl *Param,
9738 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9739 QualType PT = Param->getType();
9740
9741 // Cache the valid types we encounter to avoid rechecking structs that are
9742 // used again
9743 if (ValidTypes.count(PT.getTypePtr()))
9744 return;
9745
9746 switch (getOpenCLKernelParameterType(S, PT)) {
9747 case PtrPtrKernelParam:
9748 // OpenCL v3.0 s6.11.a:
9749 // A kernel function argument cannot be declared as a pointer to a pointer
9750 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9751 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9752 D.setInvalidType();
9753 return;
9754
9756 // OpenCL v1.0 s6.5:
9757 // __kernel function arguments declared to be a pointer of a type can point
9758 // to one of the following address spaces only : __global, __local or
9759 // __constant.
9760 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9761 D.setInvalidType();
9762 return;
9763
9764 // OpenCL v1.2 s6.9.k:
9765 // Arguments to kernel functions in a program cannot be declared with the
9766 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9767 // uintptr_t or a struct and/or union that contain fields declared to be
9768 // one of these built-in scalar types.
9769
9770 case InvalidKernelParam:
9771 // OpenCL v1.2 s6.8 n:
9772 // A kernel function argument cannot be declared
9773 // of event_t type.
9774 // Do not diagnose half type since it is diagnosed as invalid argument
9775 // type for any function elsewhere.
9776 if (!PT->isHalfType()) {
9777 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9778
9779 // Explain what typedefs are involved.
9780 const TypedefType *Typedef = nullptr;
9781 while ((Typedef = PT->getAs<TypedefType>())) {
9782 SourceLocation Loc = Typedef->getDecl()->getLocation();
9783 // SourceLocation may be invalid for a built-in type.
9784 if (Loc.isValid())
9785 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9786 PT = Typedef->desugar();
9787 }
9788 }
9789
9790 D.setInvalidType();
9791 return;
9792
9793 case PtrKernelParam:
9794 case ValidKernelParam:
9795 ValidTypes.insert(PT.getTypePtr());
9796 return;
9797
9798 case RecordKernelParam:
9799 break;
9800 }
9801
9802 // Track nested structs we will inspect
9804
9805 // Track where we are in the nested structs. Items will migrate from
9806 // VisitStack to HistoryStack as we do the DFS for bad field.
9808 HistoryStack.push_back(nullptr);
9809
9810 // At this point we already handled everything except of a RecordType.
9811 assert(PT->isRecordType() && "Unexpected type.");
9812 const auto *PD = PT->castAsRecordDecl();
9813 VisitStack.push_back(PD);
9814 assert(VisitStack.back() && "First decl null?");
9815
9816 do {
9817 const Decl *Next = VisitStack.pop_back_val();
9818 if (!Next) {
9819 assert(!HistoryStack.empty());
9820 // Found a marker, we have gone up a level
9821 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9822 ValidTypes.insert(Hist->getType().getTypePtr());
9823
9824 continue;
9825 }
9826
9827 // Adds everything except the original parameter declaration (which is not a
9828 // field itself) to the history stack.
9829 const RecordDecl *RD;
9830 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9831 HistoryStack.push_back(Field);
9832
9833 QualType FieldTy = Field->getType();
9834 // Other field types (known to be valid or invalid) are handled while we
9835 // walk around RecordDecl::fields().
9836 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9837 "Unexpected type.");
9838 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9839
9840 RD = FieldRecTy->castAsRecordDecl();
9841 } else {
9842 RD = cast<RecordDecl>(Next);
9843 }
9844
9845 // Add a null marker so we know when we've gone back up a level
9846 VisitStack.push_back(nullptr);
9847
9848 for (const auto *FD : RD->fields()) {
9849 QualType QT = FD->getType();
9850
9851 if (ValidTypes.count(QT.getTypePtr()))
9852 continue;
9853
9855 if (ParamType == ValidKernelParam)
9856 continue;
9857
9858 if (ParamType == RecordKernelParam) {
9859 VisitStack.push_back(FD);
9860 continue;
9861 }
9862
9863 // OpenCL v1.2 s6.9.p:
9864 // Arguments to kernel functions that are declared to be a struct or union
9865 // do not allow OpenCL objects to be passed as elements of the struct or
9866 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9867 // of SVM.
9868 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9869 ParamType == InvalidAddrSpacePtrKernelParam) {
9870 S.Diag(Param->getLocation(),
9871 diag::err_record_with_pointers_kernel_param)
9872 << PT->isUnionType()
9873 << PT;
9874 } else {
9875 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9876 }
9877
9878 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
9879 << PD->getDeclName();
9880
9881 // We have an error, now let's go back up through history and show where
9882 // the offending field came from
9884 I = HistoryStack.begin() + 1,
9885 E = HistoryStack.end();
9886 I != E; ++I) {
9887 const FieldDecl *OuterField = *I;
9888 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9889 << OuterField->getType();
9890 }
9891
9892 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9893 << QT->isPointerType()
9894 << QT;
9895 D.setInvalidType();
9896 return;
9897 }
9898 } while (!VisitStack.empty());
9899}
9900
9901/// Find the DeclContext in which a tag is implicitly declared if we see an
9902/// elaborated type specifier in the specified context, and lookup finds
9903/// nothing.
9905 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9906 DC = DC->getParent();
9907 return DC;
9908}
9909
9910/// Find the Scope in which a tag is implicitly declared if we see an
9911/// elaborated type specifier in the specified context, and lookup finds
9912/// nothing.
9913static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9914 while (S->isClassScope() ||
9915 (LangOpts.CPlusPlus &&
9916 S->isFunctionPrototypeScope()) ||
9917 ((S->getFlags() & Scope::DeclScope) == 0) ||
9918 (S->getEntity() && S->getEntity()->isTransparentContext()))
9919 S = S->getParent();
9920 return S;
9921}
9922
9923/// Determine whether a declaration matches a known function in namespace std.
9925 unsigned BuiltinID) {
9926 switch (BuiltinID) {
9927 case Builtin::BI__GetExceptionInfo:
9928 // No type checking whatsoever.
9929 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9930
9931 case Builtin::BIaddressof:
9932 case Builtin::BI__addressof:
9933 case Builtin::BIforward:
9934 case Builtin::BIforward_like:
9935 case Builtin::BImove:
9936 case Builtin::BImove_if_noexcept:
9937 case Builtin::BIas_const: {
9938 // Ensure that we don't treat the algorithm
9939 // OutputIt std::move(InputIt, InputIt, OutputIt)
9940 // as the builtin std::move.
9941 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9942 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9943 }
9944
9945 default:
9946 return false;
9947 }
9948}
9949
9950NamedDecl*
9953 MultiTemplateParamsArg TemplateParamListsRef,
9954 bool &AddToScope) {
9955 QualType R = TInfo->getType();
9956
9957 assert(R->isFunctionType());
9959 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9960
9961 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9962 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9963 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9964 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9965 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9966 TemplateParamLists.back() = Invented;
9967 else
9968 TemplateParamLists.push_back(Invented);
9969 }
9970
9971 // TODO: consider using NameInfo for diagnostic.
9973 DeclarationName Name = NameInfo.getName();
9975
9976 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9977 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9978 diag::err_invalid_thread)
9980
9981 if (D.isFirstDeclarationOfMember())
9983 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9984 D.isCtorOrDtor(), D.getIdentifierLoc());
9985
9986 bool isFriend = false;
9988 bool isMemberSpecialization = false;
9989 bool isFunctionTemplateSpecialization = false;
9990
9991 bool HasExplicitTemplateArgs = false;
9992 TemplateArgumentListInfo TemplateArgs;
9993
9994 bool isVirtualOkay = false;
9995
9996 DeclContext *OriginalDC = DC;
9997 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9998
9999 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10000 isVirtualOkay);
10001 if (!NewFD) return nullptr;
10002
10005
10006 // Set the lexical context. If this is a function-scope declaration, or has a
10007 // C++ scope specifier, or is the object of a friend declaration, the lexical
10008 // context will be different from the semantic context.
10010
10011 if (IsLocalExternDecl)
10012 NewFD->setLocalExternDecl();
10013
10014 if (getLangOpts().CPlusPlus) {
10015 // The rules for implicit inlines changed in C++20 for methods and friends
10016 // with an in-class definition (when such a definition is not attached to
10017 // the global module). This does not affect declarations that are already
10018 // inline (whether explicitly or implicitly by being declared constexpr,
10019 // consteval, etc).
10020 // FIXME: We need a better way to separate C++ standard and clang modules.
10021 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10022 !NewFD->getOwningModule() ||
10023 NewFD->isFromGlobalModule() ||
10025 bool isInline = D.getDeclSpec().isInlineSpecified();
10026 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10027 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10028 isFriend = D.getDeclSpec().isFriendSpecified();
10029 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10030 // Pre-C++20 [class.friend]p5
10031 // A function can be defined in a friend declaration of a
10032 // class . . . . Such a function is implicitly inline.
10033 // Post C++20 [class.friend]p7
10034 // Such a function is implicitly an inline function if it is attached
10035 // to the global module.
10036 NewFD->setImplicitlyInline();
10037 }
10038
10039 // If this is a method defined in an __interface, and is not a constructor
10040 // or an overloaded operator, then set the pure flag (isVirtual will already
10041 // return true).
10042 if (const CXXRecordDecl *Parent =
10043 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10044 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10045 NewFD->setIsPureVirtual(true);
10046
10047 // C++ [class.union]p2
10048 // A union can have member functions, but not virtual functions.
10049 if (isVirtual && Parent->isUnion()) {
10050 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10051 NewFD->setInvalidDecl();
10052 }
10053 if ((Parent->isClass() || Parent->isStruct()) &&
10054 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10055 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10056 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10057 if (auto *Def = Parent->getDefinition())
10058 Def->setInitMethod(true);
10059 }
10060 }
10061
10062 SetNestedNameSpecifier(*this, NewFD, D);
10063 isMemberSpecialization = false;
10064 isFunctionTemplateSpecialization = false;
10065 if (D.isInvalidType())
10066 NewFD->setInvalidDecl();
10067
10068 // Match up the template parameter lists with the scope specifier, then
10069 // determine whether we have a template or a template specialization.
10070 bool Invalid = false;
10071 TemplateIdAnnotation *TemplateId =
10073 ? D.getName().TemplateId
10074 : nullptr;
10075 TemplateParameterList *TemplateParams =
10077 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
10078 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10079 isMemberSpecialization, Invalid);
10080 if (TemplateParams) {
10081 // Check that we can declare a template here.
10082 if (CheckTemplateDeclScope(S, TemplateParams))
10083 NewFD->setInvalidDecl();
10084
10085 if (TemplateParams->size() > 0) {
10086 // This is a function template
10087
10088 // A destructor cannot be a template.
10089 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10090 Diag(NewFD->getLocation(), diag::err_destructor_template);
10091 NewFD->setInvalidDecl();
10092 // Function template with explicit template arguments.
10093 } else if (TemplateId) {
10094 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10095 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10096 NewFD->setInvalidDecl();
10097 }
10098
10099 // If we're adding a template to a dependent context, we may need to
10100 // rebuilding some of the types used within the template parameter list,
10101 // now that we know what the current instantiation is.
10102 if (DC->isDependentContext()) {
10103 ContextRAII SavedContext(*this, DC);
10105 Invalid = true;
10106 }
10107
10109 NewFD->getLocation(),
10110 Name, TemplateParams,
10111 NewFD);
10112 FunctionTemplate->setLexicalDeclContext(CurContext);
10114
10115 // For source fidelity, store the other template param lists.
10116 if (TemplateParamLists.size() > 1) {
10118 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10119 .drop_back(1));
10120 }
10121 } else {
10122 // This is a function template specialization.
10123 isFunctionTemplateSpecialization = true;
10124 // For source fidelity, store all the template param lists.
10125 if (TemplateParamLists.size() > 0)
10126 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10127
10128 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10129 if (isFriend) {
10130 // We want to remove the "template<>", found here.
10131 SourceRange RemoveRange = TemplateParams->getSourceRange();
10132
10133 // If we remove the template<> and the name is not a
10134 // template-id, we're actually silently creating a problem:
10135 // the friend declaration will refer to an untemplated decl,
10136 // and clearly the user wants a template specialization. So
10137 // we need to insert '<>' after the name.
10138 SourceLocation InsertLoc;
10139 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10140 InsertLoc = D.getName().getSourceRange().getEnd();
10141 InsertLoc = getLocForEndOfToken(InsertLoc);
10142 }
10143
10144 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10145 << Name << RemoveRange
10146 << FixItHint::CreateRemoval(RemoveRange)
10147 << FixItHint::CreateInsertion(InsertLoc, "<>");
10148 Invalid = true;
10149
10150 // Recover by faking up an empty template argument list.
10151 HasExplicitTemplateArgs = true;
10152 TemplateArgs.setLAngleLoc(InsertLoc);
10153 TemplateArgs.setRAngleLoc(InsertLoc);
10154 }
10155 }
10156 } else {
10157 // Check that we can declare a template here.
10158 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10159 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10160 NewFD->setInvalidDecl();
10161
10162 // All template param lists were matched against the scope specifier:
10163 // this is NOT (an explicit specialization of) a template.
10164 if (TemplateParamLists.size() > 0)
10165 // For source fidelity, store all the template param lists.
10166 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10167
10168 // "friend void foo<>(int);" is an implicit specialization decl.
10169 if (isFriend && TemplateId)
10170 isFunctionTemplateSpecialization = true;
10171 }
10172
10173 // If this is a function template specialization and the unqualified-id of
10174 // the declarator-id is a template-id, convert the template argument list
10175 // into our AST format and check for unexpanded packs.
10176 if (isFunctionTemplateSpecialization && TemplateId) {
10177 HasExplicitTemplateArgs = true;
10178
10179 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10180 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10181 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10182 TemplateId->NumArgs);
10183 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10184
10185 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10186 // declaration of a function template partial specialization? Should we
10187 // consider the unexpanded pack context to be a partial specialization?
10188 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10190 ArgLoc, isFriend ? UPPC_FriendDeclaration
10192 NewFD->setInvalidDecl();
10193 }
10194 }
10195
10196 if (Invalid) {
10197 NewFD->setInvalidDecl();
10198 if (FunctionTemplate)
10199 FunctionTemplate->setInvalidDecl();
10200 }
10201
10202 // C++ [dcl.fct.spec]p5:
10203 // The virtual specifier shall only be used in declarations of
10204 // nonstatic class member functions that appear within a
10205 // member-specification of a class declaration; see 10.3.
10206 //
10207 if (isVirtual && !NewFD->isInvalidDecl()) {
10208 if (!isVirtualOkay) {
10209 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10210 diag::err_virtual_non_function);
10211 } else if (!CurContext->isRecord()) {
10212 // 'virtual' was specified outside of the class.
10213 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10214 diag::err_virtual_out_of_class)
10215 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10216 } else if (NewFD->getDescribedFunctionTemplate()) {
10217 // C++ [temp.mem]p3:
10218 // A member function template shall not be virtual.
10219 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10220 diag::err_virtual_member_function_template)
10221 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10222 } else {
10223 // Okay: Add virtual to the method.
10224 NewFD->setVirtualAsWritten(true);
10225 }
10226
10227 if (getLangOpts().CPlusPlus14 &&
10228 NewFD->getReturnType()->isUndeducedType())
10229 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10230 }
10231
10232 // C++ [dcl.fct.spec]p3:
10233 // The inline specifier shall not appear on a block scope function
10234 // declaration.
10235 if (isInline && !NewFD->isInvalidDecl()) {
10237 // 'inline' is not allowed on block scope function declaration.
10238 Diag(D.getDeclSpec().getInlineSpecLoc(),
10239 diag::err_inline_declaration_block_scope) << Name
10240 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10241 }
10242 }
10243
10244 // C++ [dcl.fct.spec]p6:
10245 // The explicit specifier shall be used only in the declaration of a
10246 // constructor or conversion function within its class definition;
10247 // see 12.3.1 and 12.3.2.
10248 if (hasExplicit && !NewFD->isInvalidDecl() &&
10249 !isa<CXXDeductionGuideDecl>(NewFD)) {
10250 if (!CurContext->isRecord()) {
10251 // 'explicit' was specified outside of the class.
10252 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10253 diag::err_explicit_out_of_class)
10254 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10255 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10256 !isa<CXXConversionDecl>(NewFD)) {
10257 // 'explicit' was specified on a function that wasn't a constructor
10258 // or conversion function.
10259 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10260 diag::err_explicit_non_ctor_or_conv_function)
10261 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10262 }
10263 }
10264
10265 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10266 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10267 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10268 // are implicitly inline.
10269 NewFD->setImplicitlyInline();
10270
10271 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10272 // be either constructors or to return a literal type. Therefore,
10273 // destructors cannot be declared constexpr.
10274 if (isa<CXXDestructorDecl>(NewFD) &&
10276 ConstexprKind == ConstexprSpecKind::Consteval)) {
10277 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10278 << static_cast<int>(ConstexprKind);
10279 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10282 }
10283 // C++20 [dcl.constexpr]p2: An allocation function, or a
10284 // deallocation function shall not be declared with the consteval
10285 // specifier.
10286 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10288 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10289 diag::err_invalid_consteval_decl_kind)
10290 << NewFD;
10292 }
10293 }
10294
10295 // If __module_private__ was specified, mark the function accordingly.
10296 if (D.getDeclSpec().isModulePrivateSpecified()) {
10297 if (isFunctionTemplateSpecialization) {
10298 SourceLocation ModulePrivateLoc
10299 = D.getDeclSpec().getModulePrivateSpecLoc();
10300 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10301 << 0
10302 << FixItHint::CreateRemoval(ModulePrivateLoc);
10303 } else {
10304 NewFD->setModulePrivate();
10305 if (FunctionTemplate)
10306 FunctionTemplate->setModulePrivate();
10307 }
10308 }
10309
10310 if (isFriend) {
10311 if (FunctionTemplate) {
10312 FunctionTemplate->setObjectOfFriendDecl();
10313 FunctionTemplate->setAccess(AS_public);
10314 }
10315 NewFD->setObjectOfFriendDecl();
10316 NewFD->setAccess(AS_public);
10317 }
10318
10319 // If a function is defined as defaulted or deleted, mark it as such now.
10320 // We'll do the relevant checks on defaulted / deleted functions later.
10321 switch (D.getFunctionDefinitionKind()) {
10324 break;
10325
10327 NewFD->setDefaulted();
10328 break;
10329
10331 NewFD->setDeletedAsWritten();
10332 break;
10333 }
10334
10335 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10336 D.isFunctionDefinition()) {
10337 // Pre C++20 [class.mfct]p2:
10338 // A member function may be defined (8.4) in its class definition, in
10339 // which case it is an inline member function (7.1.2)
10340 // Post C++20 [class.mfct]p1:
10341 // If a member function is attached to the global module and is defined
10342 // in its class definition, it is inline.
10343 NewFD->setImplicitlyInline();
10344 }
10345
10346 if (!isFriend && SC != SC_None) {
10347 // C++ [temp.expl.spec]p2:
10348 // The declaration in an explicit-specialization shall not be an
10349 // export-declaration. An explicit specialization shall not use a
10350 // storage-class-specifier other than thread_local.
10351 //
10352 // We diagnose friend declarations with storage-class-specifiers
10353 // elsewhere.
10354 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10355 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10356 diag::ext_explicit_specialization_storage_class)
10358 D.getDeclSpec().getStorageClassSpecLoc());
10359 }
10360
10361 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10362 assert(isa<CXXMethodDecl>(NewFD) &&
10363 "Out-of-line member function should be a CXXMethodDecl");
10364 // C++ [class.static]p1:
10365 // A data or function member of a class may be declared static
10366 // in a class definition, in which case it is a static member of
10367 // the class.
10368
10369 // Complain about the 'static' specifier if it's on an out-of-line
10370 // member function definition.
10371
10372 // MSVC permits the use of a 'static' storage specifier on an
10373 // out-of-line member function template declaration and class member
10374 // template declaration (MSVC versions before 2015), warn about this.
10375 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10376 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10377 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10378 (getLangOpts().MSVCCompat &&
10380 ? diag::ext_static_out_of_line
10381 : diag::err_static_out_of_line)
10383 D.getDeclSpec().getStorageClassSpecLoc());
10384 }
10385 }
10386
10387 // C++11 [except.spec]p15:
10388 // A deallocation function with no exception-specification is treated
10389 // as if it were specified with noexcept(true).
10390 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10391 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10392 !FPT->hasExceptionSpec())
10394 FPT->getReturnType(), FPT->getParamTypes(),
10396
10397 // C++20 [dcl.inline]/7
10398 // If an inline function or variable that is attached to a named module
10399 // is declared in a definition domain, it shall be defined in that
10400 // domain.
10401 // So, if the current declaration does not have a definition, we must
10402 // check at the end of the TU (or when the PMF starts) to see that we
10403 // have a definition at that point.
10404 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10405 NewFD->isInNamedModule()) {
10406 PendingInlineFuncDecls.insert(NewFD);
10407 }
10408 }
10409
10410 // Filter out previous declarations that don't match the scope.
10412 D.getCXXScopeSpec().isNotEmpty() ||
10413 isMemberSpecialization ||
10414 isFunctionTemplateSpecialization);
10415
10416 // Handle GNU asm-label extension (encoded as an attribute).
10417 if (Expr *E = D.getAsmLabel()) {
10418 // The parser guarantees this is a string.
10419 StringLiteral *SE = cast<StringLiteral>(E);
10420 NewFD->addAttr(
10421 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10422 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10423 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10425 if (I != ExtnameUndeclaredIdentifiers.end()) {
10426 if (isDeclExternC(NewFD)) {
10427 NewFD->addAttr(I->second);
10429 } else
10430 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10431 << /*Variable*/0 << NewFD;
10432 }
10433 }
10434
10435 // Copy the parameter declarations from the declarator D to the function
10436 // declaration NewFD, if they are available. First scavenge them into Params.
10438 unsigned FTIIdx;
10439 if (D.isFunctionDeclarator(FTIIdx)) {
10440 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10441
10442 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10443 // function that takes no arguments, not a function that takes a
10444 // single void argument.
10445 // We let through "const void" here because Sema::GetTypeForDeclarator
10446 // already checks for that case.
10447 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10448 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10449 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10450 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10451 Param->setDeclContext(NewFD);
10452 Params.push_back(Param);
10453
10454 if (Param->isInvalidDecl())
10455 NewFD->setInvalidDecl();
10456 }
10457 }
10458
10459 if (!getLangOpts().CPlusPlus) {
10460 // In C, find all the tag declarations from the prototype and move them
10461 // into the function DeclContext. Remove them from the surrounding tag
10462 // injection context of the function, which is typically but not always
10463 // the TU.
10464 DeclContext *PrototypeTagContext =
10466 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10467 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10468
10469 // We don't want to reparent enumerators. Look at their parent enum
10470 // instead.
10471 if (!TD) {
10472 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10473 TD = cast<EnumDecl>(ECD->getDeclContext());
10474 }
10475 if (!TD)
10476 continue;
10477 DeclContext *TagDC = TD->getLexicalDeclContext();
10478 if (!TagDC->containsDecl(TD))
10479 continue;
10480 TagDC->removeDecl(TD);
10481 TD->setDeclContext(NewFD);
10482 NewFD->addDecl(TD);
10483
10484 // Preserve the lexical DeclContext if it is not the surrounding tag
10485 // injection context of the FD. In this example, the semantic context of
10486 // E will be f and the lexical context will be S, while both the
10487 // semantic and lexical contexts of S will be f:
10488 // void f(struct S { enum E { a } f; } s);
10489 if (TagDC != PrototypeTagContext)
10490 TD->setLexicalDeclContext(TagDC);
10491 }
10492 }
10493 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10494 // When we're declaring a function with a typedef, typeof, etc as in the
10495 // following example, we'll need to synthesize (unnamed)
10496 // parameters for use in the declaration.
10497 //
10498 // @code
10499 // typedef void fn(int);
10500 // fn f;
10501 // @endcode
10502
10503 // Synthesize a parameter for each argument type.
10504 for (const auto &AI : FT->param_types()) {
10505 ParmVarDecl *Param =
10506 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10507 Param->setScopeInfo(0, Params.size());
10508 Params.push_back(Param);
10509 }
10510 } else {
10511 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10512 "Should not need args for typedef of non-prototype fn");
10513 }
10514
10515 // Finally, we know we have the right number of parameters, install them.
10516 NewFD->setParams(Params);
10517
10518 // If this declarator is a declaration and not a definition, its parameters
10519 // will not be pushed onto a scope chain. That means we will not issue any
10520 // reserved identifier warnings for the declaration, but we will for the
10521 // definition. Handle those here.
10522 if (!D.isFunctionDefinition()) {
10523 for (const ParmVarDecl *PVD : Params)
10525 }
10526
10527 if (D.getDeclSpec().isNoreturnSpecified())
10528 NewFD->addAttr(
10529 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10530
10531 // Functions returning a variably modified type violate C99 6.7.5.2p2
10532 // because all functions have linkage.
10533 if (!NewFD->isInvalidDecl() &&
10535 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10536 NewFD->setInvalidDecl();
10537 }
10538
10539 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10540 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10541 !NewFD->hasAttr<SectionAttr>())
10542 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10545
10546 // Apply an implicit SectionAttr if #pragma code_seg is active.
10547 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10548 !NewFD->hasAttr<SectionAttr>()) {
10549 NewFD->addAttr(SectionAttr::CreateImplicit(
10550 Context, CodeSegStack.CurrentValue->getString(),
10551 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10552 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10555 NewFD))
10556 NewFD->dropAttr<SectionAttr>();
10557 }
10558
10559 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10560 // active.
10561 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10562 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10563 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10565
10566 // Apply an implicit CodeSegAttr from class declspec or
10567 // apply an implicit SectionAttr from #pragma code_seg if active.
10568 if (!NewFD->hasAttr<CodeSegAttr>()) {
10570 D.isFunctionDefinition())) {
10571 NewFD->addAttr(SAttr);
10572 }
10573 }
10574
10575 // Handle attributes.
10576 ProcessDeclAttributes(S, NewFD, D);
10577 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10578 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10579 !NewTVA->isDefaultVersion() &&
10580 !Context.getTargetInfo().hasFeature("fmv")) {
10581 // Don't add to scope fmv functions declarations if fmv disabled
10582 AddToScope = false;
10583 return NewFD;
10584 }
10585
10586 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10587 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10588 // type.
10589 //
10590 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10591 // type declaration will generate a compilation error.
10592 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10593 if (AddressSpace != LangAS::Default) {
10594 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10595 NewFD->setInvalidDecl();
10596 }
10597 }
10598
10599 if (!getLangOpts().CPlusPlus) {
10600 // Perform semantic checking on the function declaration.
10601 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10602 CheckMain(NewFD, D.getDeclSpec());
10603
10604 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10605 CheckMSVCRTEntryPoint(NewFD);
10606
10607 if (!NewFD->isInvalidDecl())
10608 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10609 isMemberSpecialization,
10610 D.isFunctionDefinition()));
10611 else if (!Previous.empty())
10612 // Recover gracefully from an invalid redeclaration.
10613 D.setRedeclaration(true);
10614 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10615 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10616 "previous declaration set still overloaded");
10617
10618 // Diagnose no-prototype function declarations with calling conventions that
10619 // don't support variadic calls. Only do this in C and do it after merging
10620 // possibly prototyped redeclarations.
10621 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10622 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10623 CallingConv CC = FT->getExtInfo().getCC();
10624 if (!supportsVariadicCall(CC)) {
10625 // Windows system headers sometimes accidentally use stdcall without
10626 // (void) parameters, so we relax this to a warning.
10627 int DiagID =
10628 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10629 Diag(NewFD->getLocation(), DiagID)
10631 }
10632 }
10633
10637 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10639 } else {
10640 // C++11 [replacement.functions]p3:
10641 // The program's definitions shall not be specified as inline.
10642 //
10643 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10644 //
10645 // Suppress the diagnostic if the function is __attribute__((used)), since
10646 // that forces an external definition to be emitted.
10647 if (D.getDeclSpec().isInlineSpecified() &&
10649 !NewFD->hasAttr<UsedAttr>())
10650 Diag(D.getDeclSpec().getInlineSpecLoc(),
10651 diag::ext_operator_new_delete_declared_inline)
10652 << NewFD->getDeclName();
10653
10654 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10655 // C++20 [dcl.decl.general]p4:
10656 // The optional requires-clause in an init-declarator or
10657 // member-declarator shall be present only if the declarator declares a
10658 // templated function.
10659 //
10660 // C++20 [temp.pre]p8:
10661 // An entity is templated if it is
10662 // - a template,
10663 // - an entity defined or created in a templated entity,
10664 // - a member of a templated entity,
10665 // - an enumerator for an enumeration that is a templated entity, or
10666 // - the closure type of a lambda-expression appearing in the
10667 // declaration of a templated entity.
10668 //
10669 // [Note 6: A local class, a local or block variable, or a friend
10670 // function defined in a templated entity is a templated entity.
10671 // — end note]
10672 //
10673 // A templated function is a function template or a function that is
10674 // templated. A templated class is a class template or a class that is
10675 // templated. A templated variable is a variable template or a variable
10676 // that is templated.
10677 if (!FunctionTemplate) {
10678 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10679 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10680 // An explicit specialization shall not have a trailing
10681 // requires-clause unless it declares a function template.
10682 //
10683 // Since a friend function template specialization cannot be
10684 // definition, and since a non-template friend declaration with a
10685 // trailing requires-clause must be a definition, we diagnose
10686 // friend function template specializations with trailing
10687 // requires-clauses on the same path as explicit specializations
10688 // even though they aren't necessarily prohibited by the same
10689 // language rule.
10690 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10691 << isFriend;
10692 } else if (isFriend && NewFD->isTemplated() &&
10693 !D.isFunctionDefinition()) {
10694 // C++ [temp.friend]p9:
10695 // A non-template friend declaration with a requires-clause shall be
10696 // a definition.
10697 Diag(NewFD->getBeginLoc(),
10698 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10699 NewFD->setInvalidDecl();
10700 } else if (!NewFD->isTemplated() ||
10701 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10702 Diag(TRC->getBeginLoc(),
10703 diag::err_constrained_non_templated_function);
10704 }
10705 }
10706 }
10707
10708 // We do not add HD attributes to specializations here because
10709 // they may have different constexpr-ness compared to their
10710 // templates and, after maybeAddHostDeviceAttrs() is applied,
10711 // may end up with different effective targets. Instead, a
10712 // specialization inherits its target attributes from its template
10713 // in the CheckFunctionTemplateSpecialization() call below.
10714 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10716
10717 // Handle explicit specializations of function templates
10718 // and friend function declarations with an explicit
10719 // template argument list.
10720 if (isFunctionTemplateSpecialization) {
10721 bool isDependentSpecialization = false;
10722 if (isFriend) {
10723 // For friend function specializations, this is a dependent
10724 // specialization if its semantic context is dependent, its
10725 // type is dependent, or if its template-id is dependent.
10726 isDependentSpecialization =
10727 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10728 (HasExplicitTemplateArgs &&
10731 TemplateArgs.arguments()));
10732 assert((!isDependentSpecialization ||
10733 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10734 "dependent friend function specialization without template "
10735 "args");
10736 } else {
10737 // For class-scope explicit specializations of function templates,
10738 // if the lexical context is dependent, then the specialization
10739 // is dependent.
10740 isDependentSpecialization =
10742 }
10743
10744 TemplateArgumentListInfo *ExplicitTemplateArgs =
10745 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10746 if (isDependentSpecialization) {
10747 // If it's a dependent specialization, it may not be possible
10748 // to determine the primary template (for explicit specializations)
10749 // or befriended declaration (for friends) until the enclosing
10750 // template is instantiated. In such cases, we store the declarations
10751 // found by name lookup and defer resolution until instantiation.
10753 NewFD, ExplicitTemplateArgs, Previous))
10754 NewFD->setInvalidDecl();
10755 } else if (!NewFD->isInvalidDecl()) {
10756 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10757 Previous))
10758 NewFD->setInvalidDecl();
10759 }
10760 } else if (isMemberSpecialization && !FunctionTemplate) {
10762 NewFD->setInvalidDecl();
10763 }
10764
10765 // Perform semantic checking on the function declaration.
10766 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10767 CheckMain(NewFD, D.getDeclSpec());
10768
10769 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10770 CheckMSVCRTEntryPoint(NewFD);
10771
10772 if (!NewFD->isInvalidDecl())
10773 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10774 isMemberSpecialization,
10775 D.isFunctionDefinition()));
10776 else if (!Previous.empty())
10777 // Recover gracefully from an invalid redeclaration.
10778 D.setRedeclaration(true);
10779
10780 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10781 !D.isRedeclaration() ||
10782 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10783 "previous declaration set still overloaded");
10784
10785 NamedDecl *PrincipalDecl = (FunctionTemplate
10786 ? cast<NamedDecl>(FunctionTemplate)
10787 : NewFD);
10788
10789 if (isFriend && NewFD->getPreviousDecl()) {
10790 AccessSpecifier Access = AS_public;
10791 if (!NewFD->isInvalidDecl())
10792 Access = NewFD->getPreviousDecl()->getAccess();
10793
10794 NewFD->setAccess(Access);
10795 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10796 }
10797
10798 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10800 PrincipalDecl->setNonMemberOperator();
10801
10802 // If we have a function template, check the template parameter
10803 // list. This will check and merge default template arguments.
10804 if (FunctionTemplate) {
10805 FunctionTemplateDecl *PrevTemplate =
10806 FunctionTemplate->getPreviousDecl();
10807 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10808 PrevTemplate ? PrevTemplate->getTemplateParameters()
10809 : nullptr,
10810 D.getDeclSpec().isFriendSpecified()
10811 ? (D.isFunctionDefinition()
10814 : (D.getCXXScopeSpec().isSet() &&
10815 DC && DC->isRecord() &&
10816 DC->isDependentContext())
10819 }
10820
10821 if (NewFD->isInvalidDecl()) {
10822 // Ignore all the rest of this.
10823 } else if (!D.isRedeclaration()) {
10824 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10825 AddToScope };
10826 // Fake up an access specifier if it's supposed to be a class member.
10827 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10828 NewFD->setAccess(AS_public);
10829
10830 // Qualified decls generally require a previous declaration.
10831 if (D.getCXXScopeSpec().isSet()) {
10832 // ...with the major exception of templated-scope or
10833 // dependent-scope friend declarations.
10834
10835 // TODO: we currently also suppress this check in dependent
10836 // contexts because (1) the parameter depth will be off when
10837 // matching friend templates and (2) we might actually be
10838 // selecting a friend based on a dependent factor. But there
10839 // are situations where these conditions don't apply and we
10840 // can actually do this check immediately.
10841 //
10842 // Unless the scope is dependent, it's always an error if qualified
10843 // redeclaration lookup found nothing at all. Diagnose that now;
10844 // nothing will diagnose that error later.
10845 if (isFriend &&
10846 (D.getCXXScopeSpec().getScopeRep().isDependent() ||
10847 (!Previous.empty() && CurContext->isDependentContext()))) {
10848 // ignore these
10849 } else if (NewFD->isCPUDispatchMultiVersion() ||
10850 NewFD->isCPUSpecificMultiVersion()) {
10851 // ignore this, we allow the redeclaration behavior here to create new
10852 // versions of the function.
10853 } else {
10854 // The user tried to provide an out-of-line definition for a
10855 // function that is a member of a class or namespace, but there
10856 // was no such member function declared (C++ [class.mfct]p2,
10857 // C++ [namespace.memdef]p2). For example:
10858 //
10859 // class X {
10860 // void f() const;
10861 // };
10862 //
10863 // void X::f() { } // ill-formed
10864 //
10865 // Complain about this problem, and attempt to suggest close
10866 // matches (e.g., those that differ only in cv-qualifiers and
10867 // whether the parameter types are references).
10868
10870 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10871 AddToScope = ExtraArgs.AddToScope;
10872 return Result;
10873 }
10874 }
10875
10876 // Unqualified local friend declarations are required to resolve
10877 // to something.
10878 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10880 *this, Previous, NewFD, ExtraArgs, true, S)) {
10881 AddToScope = ExtraArgs.AddToScope;
10882 return Result;
10883 }
10884 }
10885 } else if (!D.isFunctionDefinition() &&
10886 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10887 !isFriend && !isFunctionTemplateSpecialization &&
10888 !isMemberSpecialization) {
10889 // An out-of-line member function declaration must also be a
10890 // definition (C++ [class.mfct]p2).
10891 // Note that this is not the case for explicit specializations of
10892 // function templates or member functions of class templates, per
10893 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10894 // extension for compatibility with old SWIG code which likes to
10895 // generate them.
10896 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10897 << D.getCXXScopeSpec().getRange();
10898 }
10899 }
10900
10901 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10902 // Any top level function could potentially be specified as an entry.
10903 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10904 HLSL().ActOnTopLevelFunction(NewFD);
10905
10906 if (NewFD->hasAttr<HLSLShaderAttr>())
10907 HLSL().CheckEntryPoint(NewFD);
10908 }
10909
10910 // If this is the first declaration of a library builtin function, add
10911 // attributes as appropriate.
10912 if (!D.isRedeclaration()) {
10913 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10914 if (unsigned BuiltinID = II->getBuiltinID()) {
10915 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10916 if (!InStdNamespace &&
10918 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10919 // Validate the type matches unless this builtin is specified as
10920 // matching regardless of its declared type.
10921 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10922 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10923 } else {
10925 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10926 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10927
10928 if (!Error && !BuiltinType.isNull() &&
10930 NewFD->getType(), BuiltinType))
10931 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10932 }
10933 }
10934 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10935 isStdBuiltin(Context, NewFD, BuiltinID)) {
10936 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10937 }
10938 }
10939 }
10940 }
10941
10942 ProcessPragmaWeak(S, NewFD);
10943 checkAttributesAfterMerging(*this, *NewFD);
10944
10946
10947 if (NewFD->hasAttr<OverloadableAttr>() &&
10948 !NewFD->getType()->getAs<FunctionProtoType>()) {
10949 Diag(NewFD->getLocation(),
10950 diag::err_attribute_overloadable_no_prototype)
10951 << NewFD;
10952 NewFD->dropAttr<OverloadableAttr>();
10953 }
10954
10955 // If there's a #pragma GCC visibility in scope, and this isn't a class
10956 // member, set the visibility of this function.
10957 if (!DC->isRecord() && NewFD->isExternallyVisible())
10959
10960 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10961 // marking the function.
10962 ObjC().AddCFAuditedAttribute(NewFD);
10963
10964 // If this is a function definition, check if we have to apply any
10965 // attributes (i.e. optnone and no_builtin) due to a pragma.
10966 if (D.isFunctionDefinition()) {
10967 AddRangeBasedOptnone(NewFD);
10969 AddSectionMSAllocText(NewFD);
10971 }
10972
10973 // If this is the first declaration of an extern C variable, update
10974 // the map of such variables.
10975 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10976 isIncompleteDeclExternC(*this, NewFD))
10978
10979 // Set this FunctionDecl's range up to the right paren.
10980 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10981
10982 if (D.isRedeclaration() && !Previous.empty()) {
10983 NamedDecl *Prev = Previous.getRepresentativeDecl();
10984 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10985 isMemberSpecialization ||
10986 isFunctionTemplateSpecialization,
10987 D.isFunctionDefinition());
10988 }
10989
10990 if (getLangOpts().CUDA) {
10991 IdentifierInfo *II = NewFD->getIdentifier();
10992 if (II && II->isStr(CUDA().getConfigureFuncName()) &&
10993 !NewFD->isInvalidDecl() &&
10996 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10999 }
11000
11001 // Variadic functions, other than a *declaration* of printf, are not allowed
11002 // in device-side CUDA code, unless someone passed
11003 // -fcuda-allow-variadic-functions.
11004 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
11005 (NewFD->hasAttr<CUDADeviceAttr>() ||
11006 NewFD->hasAttr<CUDAGlobalAttr>()) &&
11007 !(II && II->isStr("printf") && NewFD->isExternC() &&
11008 !D.isFunctionDefinition())) {
11009 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
11010 }
11011 }
11012
11014
11015 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11016 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11017 if (SC == SC_Static) {
11018 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11019 D.setInvalidType();
11020 }
11021
11022 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11023 if (!NewFD->getReturnType()->isVoidType()) {
11024 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11025 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11026 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11027 : FixItHint());
11028 D.setInvalidType();
11029 }
11030
11032 for (auto *Param : NewFD->parameters())
11033 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11034
11035 if (getLangOpts().OpenCLCPlusPlus) {
11036 if (DC->isRecord()) {
11037 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11038 D.setInvalidType();
11039 }
11040 if (FunctionTemplate) {
11041 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11042 D.setInvalidType();
11043 }
11044 }
11045 }
11046
11047 if (getLangOpts().CPlusPlus) {
11048 // Precalculate whether this is a friend function template with a constraint
11049 // that depends on an enclosing template, per [temp.friend]p9.
11050 if (isFriend && FunctionTemplate &&
11053
11054 // C++ [temp.friend]p9:
11055 // A friend function template with a constraint that depends on a
11056 // template parameter from an enclosing template shall be a definition.
11057 if (!D.isFunctionDefinition()) {
11058 Diag(NewFD->getBeginLoc(),
11059 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11060 NewFD->setInvalidDecl();
11061 }
11062 }
11063
11064 if (FunctionTemplate) {
11065 if (NewFD->isInvalidDecl())
11066 FunctionTemplate->setInvalidDecl();
11067 return FunctionTemplate;
11068 }
11069
11070 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11072 }
11073
11074 for (const ParmVarDecl *Param : NewFD->parameters()) {
11075 QualType PT = Param->getType();
11076
11077 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11078 // types.
11079 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11080 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11081 QualType ElemTy = PipeTy->getElementType();
11082 if (ElemTy->isPointerOrReferenceType()) {
11083 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11084 D.setInvalidType();
11085 }
11086 }
11087 }
11088 // WebAssembly tables can't be used as function parameters.
11089 if (Context.getTargetInfo().getTriple().isWasm()) {
11091 Diag(Param->getTypeSpecStartLoc(),
11092 diag::err_wasm_table_as_function_parameter);
11093 D.setInvalidType();
11094 }
11095 }
11096 }
11097
11098 // Diagnose availability attributes. Availability cannot be used on functions
11099 // that are run during load/unload.
11100 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11101 if (NewFD->hasAttr<ConstructorAttr>()) {
11102 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11103 << 1;
11104 NewFD->dropAttr<AvailabilityAttr>();
11105 }
11106 if (NewFD->hasAttr<DestructorAttr>()) {
11107 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11108 << 2;
11109 NewFD->dropAttr<AvailabilityAttr>();
11110 }
11111 }
11112
11113 // Diagnose no_builtin attribute on function declaration that are not a
11114 // definition.
11115 // FIXME: We should really be doing this in
11116 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11117 // the FunctionDecl and at this point of the code
11118 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11119 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11120 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11121 switch (D.getFunctionDefinitionKind()) {
11124 Diag(NBA->getLocation(),
11125 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11126 << NBA->getSpelling();
11127 break;
11129 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11130 << NBA->getSpelling();
11131 break;
11133 break;
11134 }
11135
11136 // Similar to no_builtin logic above, at this point of the code
11137 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11138 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11140 !NewFD->isInvalidDecl() &&
11141 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11142 ExternalDeclarations.push_back(NewFD);
11143
11144 // Used for a warning on the 'next' declaration when used with a
11145 // `routine(name)`.
11146 if (getLangOpts().OpenACC)
11148
11149 return NewFD;
11150}
11151
11152/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11153/// when __declspec(code_seg) "is applied to a class, all member functions of
11154/// the class and nested classes -- this includes compiler-generated special
11155/// member functions -- are put in the specified segment."
11156/// The actual behavior is a little more complicated. The Microsoft compiler
11157/// won't check outer classes if there is an active value from #pragma code_seg.
11158/// The CodeSeg is always applied from the direct parent but only from outer
11159/// classes when the #pragma code_seg stack is empty. See:
11160/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11161/// available since MS has removed the page.
11163 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11164 if (!Method)
11165 return nullptr;
11166 const CXXRecordDecl *Parent = Method->getParent();
11167 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11168 Attr *NewAttr = SAttr->clone(S.getASTContext());
11169 NewAttr->setImplicit(true);
11170 return NewAttr;
11171 }
11172
11173 // The Microsoft compiler won't check outer classes for the CodeSeg
11174 // when the #pragma code_seg stack is active.
11175 if (S.CodeSegStack.CurrentValue)
11176 return nullptr;
11177
11178 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11179 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11180 Attr *NewAttr = SAttr->clone(S.getASTContext());
11181 NewAttr->setImplicit(true);
11182 return NewAttr;
11183 }
11184 }
11185 return nullptr;
11186}
11187
11189 bool IsDefinition) {
11190 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11191 return A;
11192 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11193 CodeSegStack.CurrentValue)
11194 return SectionAttr::CreateImplicit(
11195 getASTContext(), CodeSegStack.CurrentValue->getString(),
11196 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11197 return nullptr;
11198}
11199
11201 QualType NewT, QualType OldT) {
11203 return true;
11204
11205 // For dependently-typed local extern declarations and friends, we can't
11206 // perform a correct type check in general until instantiation:
11207 //
11208 // int f();
11209 // template<typename T> void g() { T f(); }
11210 //
11211 // (valid if g() is only instantiated with T = int).
11212 if (NewT->isDependentType() &&
11213 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11214 return false;
11215
11216 // Similarly, if the previous declaration was a dependent local extern
11217 // declaration, we don't really know its type yet.
11218 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11219 return false;
11220
11221 return true;
11222}
11223
11226 return true;
11227
11228 // Don't chain dependent friend function definitions until instantiation, to
11229 // permit cases like
11230 //
11231 // void func();
11232 // template<typename T> class C1 { friend void func() {} };
11233 // template<typename T> class C2 { friend void func() {} };
11234 //
11235 // ... which is valid if only one of C1 and C2 is ever instantiated.
11236 //
11237 // FIXME: This need only apply to function definitions. For now, we proxy
11238 // this by checking for a file-scope function. We do not want this to apply
11239 // to friend declarations nominating member functions, because that gets in
11240 // the way of access checks.
11242 return false;
11243
11244 auto *VD = dyn_cast<ValueDecl>(D);
11245 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11246 return !VD || !PrevVD ||
11247 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11248 PrevVD->getType());
11249}
11250
11251/// Check the target or target_version attribute of the function for
11252/// MultiVersion validity.
11253///
11254/// Returns true if there was an error, false otherwise.
11255static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11256 const auto *TA = FD->getAttr<TargetAttr>();
11257 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11258
11259 assert((TA || TVA) && "Expecting target or target_version attribute");
11260
11262 enum ErrType { Feature = 0, Architecture = 1 };
11263
11264 if (TA) {
11265 ParsedTargetAttr ParseInfo =
11266 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11267 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11268 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11269 << Architecture << ParseInfo.CPU;
11270 return true;
11271 }
11272 for (const auto &Feat : ParseInfo.Features) {
11273 auto BareFeat = StringRef{Feat}.substr(1);
11274 if (Feat[0] == '-') {
11275 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11276 << Feature << ("no-" + BareFeat).str();
11277 return true;
11278 }
11279
11280 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11281 !TargetInfo.isValidFeatureName(BareFeat) ||
11282 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11283 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11284 << Feature << BareFeat;
11285 return true;
11286 }
11287 }
11288 }
11289
11290 if (TVA) {
11292 ParsedTargetAttr ParseInfo;
11293 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11294 ParseInfo =
11295 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11296 for (auto &Feat : ParseInfo.Features)
11297 Feats.push_back(StringRef{Feat}.substr(1));
11298 } else {
11299 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11300 TVA->getFeatures(Feats);
11301 }
11302 for (const auto &Feat : Feats) {
11303 if (!TargetInfo.validateCpuSupports(Feat)) {
11304 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11305 << Feature << Feat;
11306 return true;
11307 }
11308 }
11309 }
11310 return false;
11311}
11312
11313// Provide a white-list of attributes that are allowed to be combined with
11314// multiversion functions.
11316 MultiVersionKind MVKind) {
11317 // Note: this list/diagnosis must match the list in
11318 // checkMultiversionAttributesAllSame.
11319 switch (Kind) {
11320 default:
11321 return false;
11322 case attr::ArmLocallyStreaming:
11323 return MVKind == MultiVersionKind::TargetVersion ||
11325 case attr::Used:
11326 return MVKind == MultiVersionKind::Target;
11327 case attr::NonNull:
11328 case attr::NoThrow:
11329 return true;
11330 }
11331}
11332
11334 const FunctionDecl *FD,
11335 const FunctionDecl *CausedFD,
11336 MultiVersionKind MVKind) {
11337 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11338 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11339 << static_cast<unsigned>(MVKind) << A;
11340 if (CausedFD)
11341 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11342 return true;
11343 };
11344
11345 for (const Attr *A : FD->attrs()) {
11346 switch (A->getKind()) {
11347 case attr::CPUDispatch:
11348 case attr::CPUSpecific:
11349 if (MVKind != MultiVersionKind::CPUDispatch &&
11351 return Diagnose(S, A);
11352 break;
11353 case attr::Target:
11354 if (MVKind != MultiVersionKind::Target)
11355 return Diagnose(S, A);
11356 break;
11357 case attr::TargetVersion:
11358 if (MVKind != MultiVersionKind::TargetVersion &&
11360 return Diagnose(S, A);
11361 break;
11362 case attr::TargetClones:
11363 if (MVKind != MultiVersionKind::TargetClones &&
11365 return Diagnose(S, A);
11366 break;
11367 default:
11368 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11369 return Diagnose(S, A);
11370 break;
11371 }
11372 }
11373 return false;
11374}
11375
11377 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11378 const PartialDiagnostic &NoProtoDiagID,
11379 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11380 const PartialDiagnosticAt &NoSupportDiagIDAt,
11381 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11382 bool ConstexprSupported, bool CLinkageMayDiffer) {
11383 enum DoesntSupport {
11384 FuncTemplates = 0,
11385 VirtFuncs = 1,
11386 DeducedReturn = 2,
11387 Constructors = 3,
11388 Destructors = 4,
11389 DeletedFuncs = 5,
11390 DefaultedFuncs = 6,
11391 ConstexprFuncs = 7,
11392 ConstevalFuncs = 8,
11393 Lambda = 9,
11394 };
11395 enum Different {
11396 CallingConv = 0,
11397 ReturnType = 1,
11398 ConstexprSpec = 2,
11399 InlineSpec = 3,
11400 Linkage = 4,
11401 LanguageLinkage = 5,
11402 };
11403
11404 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11405 !OldFD->getType()->getAs<FunctionProtoType>()) {
11406 Diag(OldFD->getLocation(), NoProtoDiagID);
11407 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11408 return true;
11409 }
11410
11411 if (NoProtoDiagID.getDiagID() != 0 &&
11412 !NewFD->getType()->getAs<FunctionProtoType>())
11413 return Diag(NewFD->getLocation(), NoProtoDiagID);
11414
11415 if (!TemplatesSupported &&
11417 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11418 << FuncTemplates;
11419
11420 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11421 if (NewCXXFD->isVirtual())
11422 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11423 << VirtFuncs;
11424
11425 if (isa<CXXConstructorDecl>(NewCXXFD))
11426 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11427 << Constructors;
11428
11429 if (isa<CXXDestructorDecl>(NewCXXFD))
11430 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11431 << Destructors;
11432 }
11433
11434 if (NewFD->isDeleted())
11435 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11436 << DeletedFuncs;
11437
11438 if (NewFD->isDefaulted())
11439 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11440 << DefaultedFuncs;
11441
11442 if (!ConstexprSupported && NewFD->isConstexpr())
11443 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11444 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11445
11446 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11447 const auto *NewType = cast<FunctionType>(NewQType);
11448 QualType NewReturnType = NewType->getReturnType();
11449
11450 if (NewReturnType->isUndeducedType())
11451 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11452 << DeducedReturn;
11453
11454 // Ensure the return type is identical.
11455 if (OldFD) {
11456 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11457 const auto *OldType = cast<FunctionType>(OldQType);
11458 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11459 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11460
11461 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11462 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11463
11464 bool ArmStreamingCCMismatched = false;
11465 if (OldFPT && NewFPT) {
11466 unsigned Diff =
11468 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11469 // cannot be mixed.
11472 ArmStreamingCCMismatched = true;
11473 }
11474
11475 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11476 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11477
11478 QualType OldReturnType = OldType->getReturnType();
11479
11480 if (OldReturnType != NewReturnType)
11481 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11482
11483 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11484 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11485
11486 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11487 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11488
11489 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11490 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11491
11492 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11493 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11494
11495 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11496 NewFD->getLocation()))
11497 return true;
11498 }
11499 return false;
11500}
11501
11503 const FunctionDecl *NewFD,
11504 bool CausesMV,
11505 MultiVersionKind MVKind) {
11507 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11508 if (OldFD)
11509 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11510 return true;
11511 }
11512
11513 bool IsCPUSpecificCPUDispatchMVKind =
11516
11517 if (CausesMV && OldFD &&
11518 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11519 return true;
11520
11521 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11522 return true;
11523
11524 // Only allow transition to MultiVersion if it hasn't been used.
11525 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11526 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11527 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11528 return true;
11529 }
11530
11532 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11534 S.PDiag(diag::note_multiversioning_caused_here)),
11536 S.PDiag(diag::err_multiversion_doesnt_support)
11537 << static_cast<unsigned>(MVKind)),
11539 S.PDiag(diag::err_multiversion_diff)),
11540 /*TemplatesSupported=*/false,
11541 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11542 /*CLinkageMayDiffer=*/false);
11543}
11544
11545/// Check the validity of a multiversion function declaration that is the
11546/// first of its kind. Also sets the multiversion'ness' of the function itself.
11547///
11548/// This sets NewFD->isInvalidDecl() to true if there was an error.
11549///
11550/// Returns true if there was an error, false otherwise.
11553 assert(MVKind != MultiVersionKind::None &&
11554 "Function lacks multiversion attribute");
11555 const auto *TA = FD->getAttr<TargetAttr>();
11556 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11557 // The target attribute only causes MV if this declaration is the default,
11558 // otherwise it is treated as a normal function.
11559 if (TA && !TA->isDefaultVersion())
11560 return false;
11561
11562 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11563 FD->setInvalidDecl();
11564 return true;
11565 }
11566
11567 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11568 FD->setInvalidDecl();
11569 return true;
11570 }
11571
11572 FD->setIsMultiVersion();
11573 return false;
11574}
11575
11577 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11579 return true;
11580 }
11581
11582 return false;
11583}
11584
11586 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11587 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11588 return;
11589
11590 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11591 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11592
11593 if (MVKindTo == MultiVersionKind::None &&
11594 (MVKindFrom == MultiVersionKind::TargetVersion ||
11595 MVKindFrom == MultiVersionKind::TargetClones))
11596 To->addAttr(TargetVersionAttr::CreateImplicit(
11597 To->getASTContext(), "default", To->getSourceRange()));
11598}
11599
11601 FunctionDecl *NewFD,
11602 bool &Redeclaration,
11603 NamedDecl *&OldDecl,
11605 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11606
11607 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11608 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11609 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11610 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11611
11612 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11613
11614 // The definitions should be allowed in any order. If we have discovered
11615 // a new target version and the preceeding was the default, then add the
11616 // corresponding attribute to it.
11617 patchDefaultTargetVersion(NewFD, OldFD);
11618
11619 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11620 // to change, this is a simple redeclaration.
11621 if (NewTA && !NewTA->isDefaultVersion() &&
11622 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11623 return false;
11624
11625 // Otherwise, this decl causes MultiVersioning.
11626 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11629 NewFD->setInvalidDecl();
11630 return true;
11631 }
11632
11633 if (CheckMultiVersionValue(S, NewFD)) {
11634 NewFD->setInvalidDecl();
11635 return true;
11636 }
11637
11638 // If this is 'default', permit the forward declaration.
11639 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11640 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11641 Redeclaration = true;
11642 OldDecl = OldFD;
11643 OldFD->setIsMultiVersion();
11644 NewFD->setIsMultiVersion();
11645 return false;
11646 }
11647
11648 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11649 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11650 NewFD->setInvalidDecl();
11651 return true;
11652 }
11653
11654 if (NewTA) {
11655 ParsedTargetAttr OldParsed =
11657 OldTA->getFeaturesStr());
11658 llvm::sort(OldParsed.Features);
11659 ParsedTargetAttr NewParsed =
11661 NewTA->getFeaturesStr());
11662 // Sort order doesn't matter, it just needs to be consistent.
11663 llvm::sort(NewParsed.Features);
11664 if (OldParsed == NewParsed) {
11665 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11666 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11667 NewFD->setInvalidDecl();
11668 return true;
11669 }
11670 }
11671
11672 for (const auto *FD : OldFD->redecls()) {
11673 const auto *CurTA = FD->getAttr<TargetAttr>();
11674 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11675 // We allow forward declarations before ANY multiversioning attributes, but
11676 // nothing after the fact.
11678 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11679 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11680 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11681 << (NewTA ? 0 : 2);
11682 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11683 NewFD->setInvalidDecl();
11684 return true;
11685 }
11686 }
11687
11688 OldFD->setIsMultiVersion();
11689 NewFD->setIsMultiVersion();
11690 Redeclaration = false;
11691 OldDecl = nullptr;
11692 Previous.clear();
11693 return false;
11694}
11695
11697 MultiVersionKind OldKind = Old->getMultiVersionKind();
11698 MultiVersionKind NewKind = New->getMultiVersionKind();
11699
11700 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11701 NewKind == MultiVersionKind::None)
11702 return true;
11703
11704 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11705 switch (OldKind) {
11707 return NewKind == MultiVersionKind::TargetClones;
11709 return NewKind == MultiVersionKind::TargetVersion;
11710 default:
11711 return false;
11712 }
11713 } else {
11714 switch (OldKind) {
11716 return NewKind == MultiVersionKind::CPUSpecific;
11718 return NewKind == MultiVersionKind::CPUDispatch;
11719 default:
11720 return false;
11721 }
11722 }
11723}
11724
11725/// Check the validity of a new function declaration being added to an existing
11726/// multiversioned declaration collection.
11728 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11729 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11730 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11732
11733 // Disallow mixing of multiversioning types.
11734 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11735 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11736 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11737 NewFD->setInvalidDecl();
11738 return true;
11739 }
11740
11741 // Add the default target_version attribute if it's missing.
11742 patchDefaultTargetVersion(OldFD, NewFD);
11743 patchDefaultTargetVersion(NewFD, OldFD);
11744
11745 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11746 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11747 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11748 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11749
11750 ParsedTargetAttr NewParsed;
11751 if (NewTA) {
11753 NewTA->getFeaturesStr());
11754 llvm::sort(NewParsed.Features);
11755 }
11757 if (NewTVA) {
11758 NewTVA->getFeatures(NewFeats);
11759 llvm::sort(NewFeats);
11760 }
11761
11762 bool UseMemberUsingDeclRules =
11763 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11764
11765 bool MayNeedOverloadableChecks =
11767
11768 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11769 // of a previous member of the MultiVersion set.
11770 for (NamedDecl *ND : Previous) {
11771 FunctionDecl *CurFD = ND->getAsFunction();
11772 if (!CurFD || CurFD->isInvalidDecl())
11773 continue;
11774 if (MayNeedOverloadableChecks &&
11775 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11776 continue;
11777
11778 switch (NewMVKind) {
11780 assert(OldMVKind == MultiVersionKind::TargetClones &&
11781 "Only target_clones can be omitted in subsequent declarations");
11782 break;
11784 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11785 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11786 NewFD->setIsMultiVersion();
11787 Redeclaration = true;
11788 OldDecl = ND;
11789 return false;
11790 }
11791
11792 ParsedTargetAttr CurParsed =
11794 CurTA->getFeaturesStr());
11795 llvm::sort(CurParsed.Features);
11796 if (CurParsed == NewParsed) {
11797 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11798 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11799 NewFD->setInvalidDecl();
11800 return true;
11801 }
11802 break;
11803 }
11805 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11806 if (CurTVA->getName() == NewTVA->getName()) {
11807 NewFD->setIsMultiVersion();
11808 Redeclaration = true;
11809 OldDecl = ND;
11810 return false;
11811 }
11813 CurTVA->getFeatures(CurFeats);
11814 llvm::sort(CurFeats);
11815
11816 if (CurFeats == NewFeats) {
11817 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11818 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11819 NewFD->setInvalidDecl();
11820 return true;
11821 }
11822 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11823 // Default
11824 if (NewFeats.empty())
11825 break;
11826
11827 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11829 CurClones->getFeatures(CurFeats, I);
11830 llvm::sort(CurFeats);
11831
11832 if (CurFeats == NewFeats) {
11833 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11834 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11835 NewFD->setInvalidDecl();
11836 return true;
11837 }
11838 }
11839 }
11840 break;
11841 }
11843 assert(NewClones && "MultiVersionKind does not match attribute type");
11844 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11845 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11846 !std::equal(CurClones->featuresStrs_begin(),
11847 CurClones->featuresStrs_end(),
11848 NewClones->featuresStrs_begin())) {
11849 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11850 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11851 NewFD->setInvalidDecl();
11852 return true;
11853 }
11854 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11856 CurTVA->getFeatures(CurFeats);
11857 llvm::sort(CurFeats);
11858
11859 // Default
11860 if (CurFeats.empty())
11861 break;
11862
11863 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11864 NewFeats.clear();
11865 NewClones->getFeatures(NewFeats, I);
11866 llvm::sort(NewFeats);
11867
11868 if (CurFeats == NewFeats) {
11869 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11870 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11871 NewFD->setInvalidDecl();
11872 return true;
11873 }
11874 }
11875 break;
11876 }
11877 Redeclaration = true;
11878 OldDecl = CurFD;
11879 NewFD->setIsMultiVersion();
11880 return false;
11881 }
11884 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11885 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11886 // Handle CPUDispatch/CPUSpecific versions.
11887 // Only 1 CPUDispatch function is allowed, this will make it go through
11888 // the redeclaration errors.
11889 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11890 CurFD->hasAttr<CPUDispatchAttr>()) {
11891 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11892 std::equal(
11893 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11894 NewCPUDisp->cpus_begin(),
11895 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11896 return Cur->getName() == New->getName();
11897 })) {
11898 NewFD->setIsMultiVersion();
11899 Redeclaration = true;
11900 OldDecl = ND;
11901 return false;
11902 }
11903
11904 // If the declarations don't match, this is an error condition.
11905 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11906 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11907 NewFD->setInvalidDecl();
11908 return true;
11909 }
11910 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11911 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11912 std::equal(
11913 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11914 NewCPUSpec->cpus_begin(),
11915 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11916 return Cur->getName() == New->getName();
11917 })) {
11918 NewFD->setIsMultiVersion();
11919 Redeclaration = true;
11920 OldDecl = ND;
11921 return false;
11922 }
11923
11924 // Only 1 version of CPUSpecific is allowed for each CPU.
11925 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11926 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11927 if (CurII == NewII) {
11928 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11929 << NewII;
11930 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11931 NewFD->setInvalidDecl();
11932 return true;
11933 }
11934 }
11935 }
11936 }
11937 break;
11938 }
11939 }
11940 }
11941
11942 // Else, this is simply a non-redecl case. Checking the 'value' is only
11943 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11944 // handled in the attribute adding step.
11945 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
11946 NewFD->setInvalidDecl();
11947 return true;
11948 }
11949
11950 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11951 !OldFD->isMultiVersion(), NewMVKind)) {
11952 NewFD->setInvalidDecl();
11953 return true;
11954 }
11955
11956 // Permit forward declarations in the case where these two are compatible.
11957 if (!OldFD->isMultiVersion()) {
11958 OldFD->setIsMultiVersion();
11959 NewFD->setIsMultiVersion();
11960 Redeclaration = true;
11961 OldDecl = OldFD;
11962 return false;
11963 }
11964
11965 NewFD->setIsMultiVersion();
11966 Redeclaration = false;
11967 OldDecl = nullptr;
11968 Previous.clear();
11969 return false;
11970}
11971
11972/// Check the validity of a mulitversion function declaration.
11973/// Also sets the multiversion'ness' of the function itself.
11974///
11975/// This sets NewFD->isInvalidDecl() to true if there was an error.
11976///
11977/// Returns true if there was an error, false otherwise.
11979 bool &Redeclaration, NamedDecl *&OldDecl,
11981 const TargetInfo &TI = S.getASTContext().getTargetInfo();
11982
11983 // Check if FMV is disabled.
11984 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
11985 return false;
11986
11987 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11988 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11989 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11990 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11991 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11992 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11993
11994 // Main isn't allowed to become a multiversion function, however it IS
11995 // permitted to have 'main' be marked with the 'target' optimization hint,
11996 // for 'target_version' only default is allowed.
11997 if (NewFD->isMain()) {
11998 if (MVKind != MultiVersionKind::None &&
11999 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12000 !(MVKind == MultiVersionKind::TargetVersion &&
12001 NewTVA->isDefaultVersion())) {
12002 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12003 NewFD->setInvalidDecl();
12004 return true;
12005 }
12006 return false;
12007 }
12008
12009 // Target attribute on AArch64 is not used for multiversioning
12010 if (NewTA && TI.getTriple().isAArch64())
12011 return false;
12012
12013 // Target attribute on RISCV is not used for multiversioning
12014 if (NewTA && TI.getTriple().isRISCV())
12015 return false;
12016
12017 if (!OldDecl || !OldDecl->getAsFunction() ||
12018 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12019 NewFD->getDeclContext()->getRedeclContext())) {
12020 // If there's no previous declaration, AND this isn't attempting to cause
12021 // multiversioning, this isn't an error condition.
12022 if (MVKind == MultiVersionKind::None)
12023 return false;
12024 return CheckMultiVersionFirstFunction(S, NewFD);
12025 }
12026
12027 FunctionDecl *OldFD = OldDecl->getAsFunction();
12028
12029 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12030 return false;
12031
12032 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12033 // for target_clones and target_version.
12034 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12037 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12039 NewFD->setInvalidDecl();
12040 return true;
12041 }
12042
12043 if (!OldFD->isMultiVersion()) {
12044 switch (MVKind) {
12048 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12050 if (OldFD->isUsed(false)) {
12051 NewFD->setInvalidDecl();
12052 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12053 }
12054 OldFD->setIsMultiVersion();
12055 break;
12056
12060 break;
12061 }
12062 }
12063
12064 // At this point, we have a multiversion function decl (in OldFD) AND an
12065 // appropriate attribute in the current function decl. Resolve that these are
12066 // still compatible with previous declarations.
12067 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12068 NewCPUSpec, NewClones, Redeclaration,
12069 OldDecl, Previous);
12070}
12071
12073 bool IsPure = NewFD->hasAttr<PureAttr>();
12074 bool IsConst = NewFD->hasAttr<ConstAttr>();
12075
12076 // If there are no pure or const attributes, there's nothing to check.
12077 if (!IsPure && !IsConst)
12078 return;
12079
12080 // If the function is marked both pure and const, we retain the const
12081 // attribute because it makes stronger guarantees than the pure attribute, and
12082 // we drop the pure attribute explicitly to prevent later confusion about
12083 // semantics.
12084 if (IsPure && IsConst) {
12085 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12086 NewFD->dropAttrs<PureAttr>();
12087 }
12088
12089 // Constructors and destructors are functions which return void, so are
12090 // handled here as well.
12091 if (NewFD->getReturnType()->isVoidType()) {
12092 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12093 << IsConst;
12094 NewFD->dropAttrs<PureAttr, ConstAttr>();
12095 }
12096}
12097
12100 bool IsMemberSpecialization,
12101 bool DeclIsDefn) {
12102 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12103 "Variably modified return types are not handled here");
12104
12105 // Determine whether the type of this function should be merged with
12106 // a previous visible declaration. This never happens for functions in C++,
12107 // and always happens in C if the previous declaration was visible.
12108 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12109 !Previous.isShadowed();
12110
12111 bool Redeclaration = false;
12112 NamedDecl *OldDecl = nullptr;
12113 bool MayNeedOverloadableChecks = false;
12114
12116 // Merge or overload the declaration with an existing declaration of
12117 // the same name, if appropriate.
12118 if (!Previous.empty()) {
12119 // Determine whether NewFD is an overload of PrevDecl or
12120 // a declaration that requires merging. If it's an overload,
12121 // there's no more work to do here; we'll just add the new
12122 // function to the scope.
12124 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12125 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12126 Redeclaration = true;
12127 OldDecl = Candidate;
12128 }
12129 } else {
12130 MayNeedOverloadableChecks = true;
12131 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12132 /*NewIsUsingDecl*/ false)) {
12134 Redeclaration = true;
12135 break;
12136
12138 Redeclaration = true;
12139 break;
12140
12142 Redeclaration = false;
12143 break;
12144 }
12145 }
12146 }
12147
12148 // Check for a previous extern "C" declaration with this name.
12149 if (!Redeclaration &&
12151 if (!Previous.empty()) {
12152 // This is an extern "C" declaration with the same name as a previous
12153 // declaration, and thus redeclares that entity...
12154 Redeclaration = true;
12155 OldDecl = Previous.getFoundDecl();
12156 MergeTypeWithPrevious = false;
12157
12158 // ... except in the presence of __attribute__((overloadable)).
12159 if (OldDecl->hasAttr<OverloadableAttr>() ||
12160 NewFD->hasAttr<OverloadableAttr>()) {
12161 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12162 MayNeedOverloadableChecks = true;
12163 Redeclaration = false;
12164 OldDecl = nullptr;
12165 }
12166 }
12167 }
12168 }
12169
12170 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12171 return Redeclaration;
12172
12173 // PPC MMA non-pointer types are not allowed as function return types.
12174 if (Context.getTargetInfo().getTriple().isPPC64() &&
12175 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12176 NewFD->setInvalidDecl();
12177 }
12178
12179 CheckConstPureAttributesUsage(*this, NewFD);
12180
12181 // C++ [dcl.spec.auto.general]p12:
12182 // Return type deduction for a templated function with a placeholder in its
12183 // declared type occurs when the definition is instantiated even if the
12184 // function body contains a return statement with a non-type-dependent
12185 // operand.
12186 //
12187 // C++ [temp.dep.expr]p3:
12188 // An id-expression is type-dependent if it is a template-id that is not a
12189 // concept-id and is dependent; or if its terminal name is:
12190 // - [...]
12191 // - associated by name lookup with one or more declarations of member
12192 // functions of a class that is the current instantiation declared with a
12193 // return type that contains a placeholder type,
12194 // - [...]
12195 //
12196 // If this is a templated function with a placeholder in its return type,
12197 // make the placeholder type dependent since it won't be deduced until the
12198 // definition is instantiated. We do this here because it needs to happen
12199 // for implicitly instantiated member functions/member function templates.
12200 if (getLangOpts().CPlusPlus14 &&
12201 (NewFD->isDependentContext() &&
12202 NewFD->getReturnType()->isUndeducedType())) {
12203 const FunctionProtoType *FPT =
12204 NewFD->getType()->castAs<FunctionProtoType>();
12205 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12206 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12207 FPT->getExtProtoInfo()));
12208 }
12209
12210 // C++11 [dcl.constexpr]p8:
12211 // A constexpr specifier for a non-static member function that is not
12212 // a constructor declares that member function to be const.
12213 //
12214 // This needs to be delayed until we know whether this is an out-of-line
12215 // definition of a static member function.
12216 //
12217 // This rule is not present in C++1y, so we produce a backwards
12218 // compatibility warning whenever it happens in C++11.
12219 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12220 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12221 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12222 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
12223 CXXMethodDecl *OldMD = nullptr;
12224 if (OldDecl)
12225 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12226 if (!OldMD || !OldMD->isStatic()) {
12227 const FunctionProtoType *FPT =
12230 EPI.TypeQuals.addConst();
12232 FPT->getParamTypes(), EPI));
12233
12234 // Warn that we did this, if we're not performing template instantiation.
12235 // In that case, we'll have warned already when the template was defined.
12236 if (!inTemplateInstantiation()) {
12237 SourceLocation AddConstLoc;
12240 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12241
12242 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12243 << FixItHint::CreateInsertion(AddConstLoc, " const");
12244 }
12245 }
12246 }
12247
12248 if (Redeclaration) {
12249 // NewFD and OldDecl represent declarations that need to be
12250 // merged.
12251 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12252 DeclIsDefn)) {
12253 NewFD->setInvalidDecl();
12254 return Redeclaration;
12255 }
12256
12257 Previous.clear();
12258 Previous.addDecl(OldDecl);
12259
12260 if (FunctionTemplateDecl *OldTemplateDecl =
12261 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12262 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12263 FunctionTemplateDecl *NewTemplateDecl
12265 assert(NewTemplateDecl && "Template/non-template mismatch");
12266
12267 // The call to MergeFunctionDecl above may have created some state in
12268 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12269 // can add it as a redeclaration.
12270 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12271
12272 NewFD->setPreviousDeclaration(OldFD);
12273 if (NewFD->isCXXClassMember()) {
12274 NewFD->setAccess(OldTemplateDecl->getAccess());
12275 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12276 }
12277
12278 // If this is an explicit specialization of a member that is a function
12279 // template, mark it as a member specialization.
12280 if (IsMemberSpecialization &&
12281 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12282 NewTemplateDecl->setMemberSpecialization();
12283 assert(OldTemplateDecl->isMemberSpecialization());
12284 // Explicit specializations of a member template do not inherit deleted
12285 // status from the parent member template that they are specializing.
12286 if (OldFD->isDeleted()) {
12287 // FIXME: This assert will not hold in the presence of modules.
12288 assert(OldFD->getCanonicalDecl() == OldFD);
12289 // FIXME: We need an update record for this AST mutation.
12290 OldFD->setDeletedAsWritten(false);
12291 }
12292 }
12293
12294 } else {
12295 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12296 auto *OldFD = cast<FunctionDecl>(OldDecl);
12297 // This needs to happen first so that 'inline' propagates.
12298 NewFD->setPreviousDeclaration(OldFD);
12299 if (NewFD->isCXXClassMember())
12300 NewFD->setAccess(OldFD->getAccess());
12301 }
12302 }
12303 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12304 !NewFD->getAttr<OverloadableAttr>()) {
12305 assert((Previous.empty() ||
12306 llvm::any_of(Previous,
12307 [](const NamedDecl *ND) {
12308 return ND->hasAttr<OverloadableAttr>();
12309 })) &&
12310 "Non-redecls shouldn't happen without overloadable present");
12311
12312 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12313 const auto *FD = dyn_cast<FunctionDecl>(ND);
12314 return FD && !FD->hasAttr<OverloadableAttr>();
12315 });
12316
12317 if (OtherUnmarkedIter != Previous.end()) {
12318 Diag(NewFD->getLocation(),
12319 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12320 Diag((*OtherUnmarkedIter)->getLocation(),
12321 diag::note_attribute_overloadable_prev_overload)
12322 << false;
12323
12324 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12325 }
12326 }
12327
12328 if (LangOpts.OpenMP)
12330
12331 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12333
12334 if (NewFD->hasAttr<SYCLExternalAttr>())
12336
12337 // Semantic checking for this function declaration (in isolation).
12338
12339 if (getLangOpts().CPlusPlus) {
12340 // C++-specific checks.
12341 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12343 } else if (CXXDestructorDecl *Destructor =
12344 dyn_cast<CXXDestructorDecl>(NewFD)) {
12345 // We check here for invalid destructor names.
12346 // If we have a friend destructor declaration that is dependent, we can't
12347 // diagnose right away because cases like this are still valid:
12348 // template <class T> struct A { friend T::X::~Y(); };
12349 // struct B { struct Y { ~Y(); }; using X = Y; };
12350 // template struct A<B>;
12352 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12353 CanQualType ClassType =
12355
12356 DeclarationName Name =
12358 if (NewFD->getDeclName() != Name) {
12359 Diag(NewFD->getLocation(), diag::err_destructor_name);
12360 NewFD->setInvalidDecl();
12361 return Redeclaration;
12362 }
12363 }
12364 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12365 if (auto *TD = Guide->getDescribedFunctionTemplate())
12367
12368 // A deduction guide is not on the list of entities that can be
12369 // explicitly specialized.
12370 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12371 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12372 << /*explicit specialization*/ 1;
12373 }
12374
12375 // Find any virtual functions that this function overrides.
12376 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12377 if (!Method->isFunctionTemplateSpecialization() &&
12378 !Method->getDescribedFunctionTemplate() &&
12379 Method->isCanonicalDecl()) {
12380 AddOverriddenMethods(Method->getParent(), Method);
12381 }
12382 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12383 // C++2a [class.virtual]p6
12384 // A virtual method shall not have a requires-clause.
12386 diag::err_constrained_virtual_method);
12387
12388 if (Method->isStatic())
12390 }
12391
12392 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12393 ActOnConversionDeclarator(Conversion);
12394
12395 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12396 if (NewFD->isOverloadedOperator() &&
12398 NewFD->setInvalidDecl();
12399 return Redeclaration;
12400 }
12401
12402 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12403 if (NewFD->getLiteralIdentifier() &&
12405 NewFD->setInvalidDecl();
12406 return Redeclaration;
12407 }
12408
12409 // In C++, check default arguments now that we have merged decls. Unless
12410 // the lexical context is the class, because in this case this is done
12411 // during delayed parsing anyway.
12412 if (!CurContext->isRecord())
12414
12415 // If this function is declared as being extern "C", then check to see if
12416 // the function returns a UDT (class, struct, or union type) that is not C
12417 // compatible, and if it does, warn the user.
12418 // But, issue any diagnostic on the first declaration only.
12419 if (Previous.empty() && NewFD->isExternC()) {
12420 QualType R = NewFD->getReturnType();
12421 if (R->isIncompleteType() && !R->isVoidType())
12422 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12423 << NewFD << R;
12424 else if (!R.isPODType(Context) && !R->isVoidType() &&
12426 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12427 }
12428
12429 // C++1z [dcl.fct]p6:
12430 // [...] whether the function has a non-throwing exception-specification
12431 // [is] part of the function type
12432 //
12433 // This results in an ABI break between C++14 and C++17 for functions whose
12434 // declared type includes an exception-specification in a parameter or
12435 // return type. (Exception specifications on the function itself are OK in
12436 // most cases, and exception specifications are not permitted in most other
12437 // contexts where they could make it into a mangling.)
12438 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12439 auto HasNoexcept = [&](QualType T) -> bool {
12440 // Strip off declarator chunks that could be between us and a function
12441 // type. We don't need to look far, exception specifications are very
12442 // restricted prior to C++17.
12443 if (auto *RT = T->getAs<ReferenceType>())
12444 T = RT->getPointeeType();
12445 else if (T->isAnyPointerType())
12446 T = T->getPointeeType();
12447 else if (auto *MPT = T->getAs<MemberPointerType>())
12448 T = MPT->getPointeeType();
12449 if (auto *FPT = T->getAs<FunctionProtoType>())
12450 if (FPT->isNothrow())
12451 return true;
12452 return false;
12453 };
12454
12455 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12456 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12457 for (QualType T : FPT->param_types())
12458 AnyNoexcept |= HasNoexcept(T);
12459 if (AnyNoexcept)
12460 Diag(NewFD->getLocation(),
12461 diag::warn_cxx17_compat_exception_spec_in_signature)
12462 << NewFD;
12463 }
12464
12465 if (!Redeclaration && LangOpts.CUDA) {
12466 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12467 for (auto *Parm : NewFD->parameters()) {
12468 if (!Parm->getType()->isDependentType() &&
12469 Parm->hasAttr<CUDAGridConstantAttr>() &&
12470 !(IsKernel && Parm->getType().isConstQualified()))
12471 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12472 diag::err_cuda_grid_constant_not_allowed);
12473 }
12475 }
12476 }
12477
12478 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12480
12481 return Redeclaration;
12482}
12483
12485 // [basic.start.main]p3
12486 // The main function shall not be declared with C linkage-specification.
12487 if (FD->isExternCContext())
12488 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12489
12490 // C++11 [basic.start.main]p3:
12491 // A program that [...] declares main to be inline, static or
12492 // constexpr is ill-formed.
12493 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12494 // appear in a declaration of main.
12495 // static main is not an error under C99, but we should warn about it.
12496 // We accept _Noreturn main as an extension.
12497 if (FD->getStorageClass() == SC_Static)
12499 ? diag::err_static_main : diag::warn_static_main)
12501 if (FD->isInlineSpecified())
12502 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12504 if (DS.isNoreturnSpecified()) {
12505 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12506 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12507 Diag(NoreturnLoc, diag::ext_noreturn_main);
12508 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12509 << FixItHint::CreateRemoval(NoreturnRange);
12510 }
12511 if (FD->isConstexpr()) {
12512 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12513 << FD->isConsteval()
12516 }
12517
12518 if (getLangOpts().OpenCL) {
12519 Diag(FD->getLocation(), diag::err_opencl_no_main)
12520 << FD->hasAttr<DeviceKernelAttr>();
12521 FD->setInvalidDecl();
12522 return;
12523 }
12524
12525 if (FD->hasAttr<SYCLExternalAttr>()) {
12526 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12527 << FD->getAttr<SYCLExternalAttr>();
12528 FD->setInvalidDecl();
12529 return;
12530 }
12531
12532 // Functions named main in hlsl are default entries, but don't have specific
12533 // signatures they are required to conform to.
12534 if (getLangOpts().HLSL)
12535 return;
12536
12537 QualType T = FD->getType();
12538 assert(T->isFunctionType() && "function decl is not of function type");
12539 const FunctionType* FT = T->castAs<FunctionType>();
12540
12541 // Set default calling convention for main()
12542 if (FT->getCallConv() != CC_C) {
12544 FD->setType(QualType(FT, 0));
12546 }
12547
12548 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12549 // In C with GNU extensions we allow main() to have non-integer return
12550 // type, but we should warn about the extension, and we disable the
12551 // implicit-return-zero rule.
12552
12553 // GCC in C mode accepts qualified 'int'.
12555 FD->setHasImplicitReturnZero(true);
12556 else {
12557 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12558 SourceRange RTRange = FD->getReturnTypeSourceRange();
12559 if (RTRange.isValid())
12560 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12561 << FixItHint::CreateReplacement(RTRange, "int");
12562 }
12563 } else {
12564 // In C and C++, main magically returns 0 if you fall off the end;
12565 // set the flag which tells us that.
12566 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12567
12568 // All the standards say that main() should return 'int'.
12570 FD->setHasImplicitReturnZero(true);
12571 else {
12572 // Otherwise, this is just a flat-out error.
12573 SourceRange RTRange = FD->getReturnTypeSourceRange();
12574 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12575 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12576 : FixItHint());
12577 FD->setInvalidDecl(true);
12578 }
12579
12580 // [basic.start.main]p3:
12581 // A program that declares a function main that belongs to the global scope
12582 // and is attached to a named module is ill-formed.
12583 if (FD->isInNamedModule()) {
12584 const SourceLocation start = FD->getTypeSpecStartLoc();
12585 Diag(start, diag::warn_main_in_named_module)
12586 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12587 }
12588 }
12589
12590 // Treat protoless main() as nullary.
12591 if (isa<FunctionNoProtoType>(FT)) return;
12592
12593 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12594 unsigned nparams = FTP->getNumParams();
12595 assert(FD->getNumParams() == nparams);
12596
12597 bool HasExtraParameters = (nparams > 3);
12598
12599 if (FTP->isVariadic()) {
12600 Diag(FD->getLocation(), diag::ext_variadic_main);
12601 // FIXME: if we had information about the location of the ellipsis, we
12602 // could add a FixIt hint to remove it as a parameter.
12603 }
12604
12605 // Darwin passes an undocumented fourth argument of type char**. If
12606 // other platforms start sprouting these, the logic below will start
12607 // getting shifty.
12608 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12609 HasExtraParameters = false;
12610
12611 if (HasExtraParameters) {
12612 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12613 FD->setInvalidDecl(true);
12614 nparams = 3;
12615 }
12616
12617 // FIXME: a lot of the following diagnostics would be improved
12618 // if we had some location information about types.
12619
12620 QualType CharPP =
12622 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12623
12624 for (unsigned i = 0; i < nparams; ++i) {
12625 QualType AT = FTP->getParamType(i);
12626
12627 bool mismatch = true;
12628
12630 mismatch = false;
12631 else if (Expected[i] == CharPP) {
12632 // As an extension, the following forms are okay:
12633 // char const **
12634 // char const * const *
12635 // char * const *
12636
12638 const PointerType* PT;
12639 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12640 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12642 Context.CharTy)) {
12643 qs.removeConst();
12644 mismatch = !qs.empty();
12645 }
12646 }
12647
12648 if (mismatch) {
12649 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12650 // TODO: suggest replacing given type with expected type
12651 FD->setInvalidDecl(true);
12652 }
12653 }
12654
12655 if (nparams == 1 && !FD->isInvalidDecl()) {
12656 Diag(FD->getLocation(), diag::warn_main_one_arg);
12657 }
12658
12659 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12660 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12661 FD->setInvalidDecl();
12662 }
12663}
12664
12665static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12666
12667 // Default calling convention for main and wmain is __cdecl
12668 if (FD->getName() == "main" || FD->getName() == "wmain")
12669 return false;
12670
12671 // Default calling convention for MinGW and Cygwin is __cdecl
12672 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12673 if (T.isOSCygMing())
12674 return false;
12675
12676 // Default calling convention for WinMain, wWinMain and DllMain
12677 // is __stdcall on 32 bit Windows
12678 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12679 return true;
12680
12681 return false;
12682}
12683
12685 QualType T = FD->getType();
12686 assert(T->isFunctionType() && "function decl is not of function type");
12687 const FunctionType *FT = T->castAs<FunctionType>();
12688
12689 // Set an implicit return of 'zero' if the function can return some integral,
12690 // enumeration, pointer or nullptr type.
12694 // DllMain is exempt because a return value of zero means it failed.
12695 if (FD->getName() != "DllMain")
12696 FD->setHasImplicitReturnZero(true);
12697
12698 // Explicitly specified calling conventions are applied to MSVC entry points
12699 if (!hasExplicitCallingConv(T)) {
12700 if (isDefaultStdCall(FD, *this)) {
12701 if (FT->getCallConv() != CC_X86StdCall) {
12704 FD->setType(QualType(FT, 0));
12705 }
12706 } else if (FT->getCallConv() != CC_C) {
12709 FD->setType(QualType(FT, 0));
12710 }
12711 }
12712
12713 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12714 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12715 FD->setInvalidDecl();
12716 }
12717}
12718
12720 // FIXME: Need strict checking. In C89, we need to check for
12721 // any assignment, increment, decrement, function-calls, or
12722 // commas outside of a sizeof. In C99, it's the same list,
12723 // except that the aforementioned are allowed in unevaluated
12724 // expressions. Everything else falls under the
12725 // "may accept other forms of constant expressions" exception.
12726 //
12727 // Regular C++ code will not end up here (exceptions: language extensions,
12728 // OpenCL C++ etc), so the constant expression rules there don't matter.
12729 if (Init->isValueDependent()) {
12730 assert(Init->containsErrors() &&
12731 "Dependent code should only occur in error-recovery path.");
12732 return true;
12733 }
12734 const Expr *Culprit;
12735 if (Init->isConstantInitializer(Context, false, &Culprit))
12736 return false;
12737 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12738 return true;
12739}
12740
12741namespace {
12742 // Visits an initialization expression to see if OrigDecl is evaluated in
12743 // its own initialization and throws a warning if it does.
12744 class SelfReferenceChecker
12745 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12746 Sema &S;
12747 Decl *OrigDecl;
12748 bool isRecordType;
12749 bool isPODType;
12750 bool isReferenceType;
12751 bool isInCXXOperatorCall;
12752
12753 bool isInitList;
12754 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12755
12756 public:
12758
12759 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12760 S(S), OrigDecl(OrigDecl) {
12761 isPODType = false;
12762 isRecordType = false;
12763 isReferenceType = false;
12764 isInCXXOperatorCall = false;
12765 isInitList = false;
12766 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12767 isPODType = VD->getType().isPODType(S.Context);
12768 isRecordType = VD->getType()->isRecordType();
12769 isReferenceType = VD->getType()->isReferenceType();
12770 }
12771 }
12772
12773 // For most expressions, just call the visitor. For initializer lists,
12774 // track the index of the field being initialized since fields are
12775 // initialized in order allowing use of previously initialized fields.
12776 void CheckExpr(Expr *E) {
12777 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12778 if (!InitList) {
12779 Visit(E);
12780 return;
12781 }
12782
12783 // Track and increment the index here.
12784 isInitList = true;
12785 InitFieldIndex.push_back(0);
12786 for (auto *Child : InitList->children()) {
12787 CheckExpr(cast<Expr>(Child));
12788 ++InitFieldIndex.back();
12789 }
12790 InitFieldIndex.pop_back();
12791 }
12792
12793 // Returns true if MemberExpr is checked and no further checking is needed.
12794 // Returns false if additional checking is required.
12795 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12797 Expr *Base = E;
12798 bool ReferenceField = false;
12799
12800 // Get the field members used.
12801 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12802 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12803 if (!FD)
12804 return false;
12805 Fields.push_back(FD);
12806 if (FD->getType()->isReferenceType())
12807 ReferenceField = true;
12808 Base = ME->getBase()->IgnoreParenImpCasts();
12809 }
12810
12811 // Keep checking only if the base Decl is the same.
12812 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12813 if (!DRE || DRE->getDecl() != OrigDecl)
12814 return false;
12815
12816 // A reference field can be bound to an unininitialized field.
12817 if (CheckReference && !ReferenceField)
12818 return true;
12819
12820 // Convert FieldDecls to their index number.
12821 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12822 for (const FieldDecl *I : llvm::reverse(Fields))
12823 UsedFieldIndex.push_back(I->getFieldIndex());
12824
12825 // See if a warning is needed by checking the first difference in index
12826 // numbers. If field being used has index less than the field being
12827 // initialized, then the use is safe.
12828 for (auto UsedIter = UsedFieldIndex.begin(),
12829 UsedEnd = UsedFieldIndex.end(),
12830 OrigIter = InitFieldIndex.begin(),
12831 OrigEnd = InitFieldIndex.end();
12832 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12833 if (*UsedIter < *OrigIter)
12834 return true;
12835 if (*UsedIter > *OrigIter)
12836 break;
12837 }
12838
12839 // TODO: Add a different warning which will print the field names.
12840 HandleDeclRefExpr(DRE);
12841 return true;
12842 }
12843
12844 // For most expressions, the cast is directly above the DeclRefExpr.
12845 // For conditional operators, the cast can be outside the conditional
12846 // operator if both expressions are DeclRefExpr's.
12847 void HandleValue(Expr *E) {
12848 E = E->IgnoreParens();
12849 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12850 HandleDeclRefExpr(DRE);
12851 return;
12852 }
12853
12854 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12855 Visit(CO->getCond());
12856 HandleValue(CO->getTrueExpr());
12857 HandleValue(CO->getFalseExpr());
12858 return;
12859 }
12860
12861 if (BinaryConditionalOperator *BCO =
12862 dyn_cast<BinaryConditionalOperator>(E)) {
12863 Visit(BCO->getCond());
12864 HandleValue(BCO->getFalseExpr());
12865 return;
12866 }
12867
12868 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12869 if (Expr *SE = OVE->getSourceExpr())
12870 HandleValue(SE);
12871 return;
12872 }
12873
12874 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12875 if (BO->getOpcode() == BO_Comma) {
12876 Visit(BO->getLHS());
12877 HandleValue(BO->getRHS());
12878 return;
12879 }
12880 }
12881
12882 if (isa<MemberExpr>(E)) {
12883 if (isInitList) {
12884 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12885 false /*CheckReference*/))
12886 return;
12887 }
12888
12890 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12891 // Check for static member variables and don't warn on them.
12892 if (!isa<FieldDecl>(ME->getMemberDecl()))
12893 return;
12894 Base = ME->getBase()->IgnoreParenImpCasts();
12895 }
12896 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12897 HandleDeclRefExpr(DRE);
12898 return;
12899 }
12900
12901 Visit(E);
12902 }
12903
12904 // Reference types not handled in HandleValue are handled here since all
12905 // uses of references are bad, not just r-value uses.
12906 void VisitDeclRefExpr(DeclRefExpr *E) {
12907 if (isReferenceType)
12908 HandleDeclRefExpr(E);
12909 }
12910
12911 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12912 if (E->getCastKind() == CK_LValueToRValue) {
12913 HandleValue(E->getSubExpr());
12914 return;
12915 }
12916
12917 Inherited::VisitImplicitCastExpr(E);
12918 }
12919
12920 void VisitMemberExpr(MemberExpr *E) {
12921 if (isInitList) {
12922 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12923 return;
12924 }
12925
12926 // Don't warn on arrays since they can be treated as pointers.
12927 if (E->getType()->canDecayToPointerType()) return;
12928
12929 // Warn when a non-static method call is followed by non-static member
12930 // field accesses, which is followed by a DeclRefExpr.
12931 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12932 bool Warn = (MD && !MD->isStatic());
12933 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12934 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12935 if (!isa<FieldDecl>(ME->getMemberDecl()))
12936 Warn = false;
12937 Base = ME->getBase()->IgnoreParenImpCasts();
12938 }
12939
12940 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12941 if (Warn)
12942 HandleDeclRefExpr(DRE);
12943 return;
12944 }
12945
12946 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12947 // Visit that expression.
12948 Visit(Base);
12949 }
12950
12951 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12952 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
12953 Expr *Callee = E->getCallee();
12954
12955 if (isa<UnresolvedLookupExpr>(Callee))
12956 return Inherited::VisitCXXOperatorCallExpr(E);
12957
12958 Visit(Callee);
12959 for (auto Arg: E->arguments())
12960 HandleValue(Arg->IgnoreParenImpCasts());
12961 }
12962
12963 void VisitLambdaExpr(LambdaExpr *E) {
12964 if (!isInCXXOperatorCall) {
12965 Inherited::VisitLambdaExpr(E);
12966 return;
12967 }
12968
12969 for (Expr *Init : E->capture_inits())
12970 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
12971 HandleDeclRefExpr(DRE);
12972 else if (Init)
12973 Visit(Init);
12974 }
12975
12976 void VisitUnaryOperator(UnaryOperator *E) {
12977 // For POD record types, addresses of its own members are well-defined.
12978 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12979 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12980 if (!isPODType)
12981 HandleValue(E->getSubExpr());
12982 return;
12983 }
12984
12985 if (E->isIncrementDecrementOp()) {
12986 HandleValue(E->getSubExpr());
12987 return;
12988 }
12989
12990 Inherited::VisitUnaryOperator(E);
12991 }
12992
12993 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12994
12995 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12996 if (E->getConstructor()->isCopyConstructor()) {
12997 Expr *ArgExpr = E->getArg(0);
12998 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12999 if (ILE->getNumInits() == 1)
13000 ArgExpr = ILE->getInit(0);
13001 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13002 if (ICE->getCastKind() == CK_NoOp)
13003 ArgExpr = ICE->getSubExpr();
13004 HandleValue(ArgExpr);
13005 return;
13006 }
13007 Inherited::VisitCXXConstructExpr(E);
13008 }
13009
13010 void VisitCallExpr(CallExpr *E) {
13011 // Treat std::move as a use.
13012 if (E->isCallToStdMove()) {
13013 HandleValue(E->getArg(0));
13014 return;
13015 }
13016
13017 Inherited::VisitCallExpr(E);
13018 }
13019
13020 void VisitBinaryOperator(BinaryOperator *E) {
13021 if (E->isCompoundAssignmentOp()) {
13022 HandleValue(E->getLHS());
13023 Visit(E->getRHS());
13024 return;
13025 }
13026
13027 Inherited::VisitBinaryOperator(E);
13028 }
13029
13030 // A custom visitor for BinaryConditionalOperator is needed because the
13031 // regular visitor would check the condition and true expression separately
13032 // but both point to the same place giving duplicate diagnostics.
13033 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13034 Visit(E->getCond());
13035 Visit(E->getFalseExpr());
13036 }
13037
13038 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13039 Decl* ReferenceDecl = DRE->getDecl();
13040 if (OrigDecl != ReferenceDecl) return;
13041 unsigned diag;
13042 if (isReferenceType) {
13043 diag = diag::warn_uninit_self_reference_in_reference_init;
13044 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13045 diag = diag::warn_static_self_reference_in_init;
13046 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13047 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13048 DRE->getDecl()->getType()->isRecordType()) {
13049 diag = diag::warn_uninit_self_reference_in_init;
13050 } else {
13051 // Local variables will be handled by the CFG analysis.
13052 return;
13053 }
13054
13055 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13056 S.PDiag(diag)
13057 << DRE->getDecl() << OrigDecl->getLocation()
13058 << DRE->getSourceRange());
13059 }
13060 };
13061
13062 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13063 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13064 bool DirectInit) {
13065 // Parameters arguments are occassionially constructed with itself,
13066 // for instance, in recursive functions. Skip them.
13067 if (isa<ParmVarDecl>(OrigDecl))
13068 return;
13069
13070 E = E->IgnoreParens();
13071
13072 // Skip checking T a = a where T is not a record or reference type.
13073 // Doing so is a way to silence uninitialized warnings.
13074 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13075 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13076 if (ICE->getCastKind() == CK_LValueToRValue)
13077 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13078 if (DRE->getDecl() == OrigDecl)
13079 return;
13080
13081 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13082 }
13083} // end anonymous namespace
13084
13085namespace {
13086 // Simple wrapper to add the name of a variable or (if no variable is
13087 // available) a DeclarationName into a diagnostic.
13088 struct VarDeclOrName {
13089 VarDecl *VDecl;
13090 DeclarationName Name;
13091
13092 friend const Sema::SemaDiagnosticBuilder &
13093 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13094 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13095 }
13096 };
13097} // end anonymous namespace
13098
13101 TypeSourceInfo *TSI,
13103 Expr *Init) {
13104 bool IsInitCapture = !VDecl;
13105 assert((!VDecl || !VDecl->isInitCapture()) &&
13106 "init captures are expected to be deduced prior to initialization");
13107
13108 VarDeclOrName VN{VDecl, Name};
13109
13111 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13112
13113 // Diagnose auto array declarations in C23, unless it's a supported extension.
13114 if (getLangOpts().C23 && Type->isArrayType() &&
13115 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13116 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13117 << (int)Deduced->getContainedAutoType()->getKeyword()
13118 << /*in array decl*/ 23 << Range;
13119 return QualType();
13120 }
13121
13122 // C++11 [dcl.spec.auto]p3
13123 if (!Init) {
13124 assert(VDecl && "no init for init capture deduction?");
13125
13126 // Except for class argument deduction, and then for an initializing
13127 // declaration only, i.e. no static at class scope or extern.
13128 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
13129 VDecl->hasExternalStorage() ||
13130 VDecl->isStaticDataMember()) {
13131 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13132 << VDecl->getDeclName() << Type;
13133 return QualType();
13134 }
13135 }
13136
13137 ArrayRef<Expr*> DeduceInits;
13138 if (Init)
13139 DeduceInits = Init;
13140
13141 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13142 if (DirectInit && PL)
13143 DeduceInits = PL->exprs();
13144
13145 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
13146 assert(VDecl && "non-auto type for init capture deduction?");
13149 VDecl->getLocation(), DirectInit, Init);
13150 // FIXME: Initialization should not be taking a mutable list of inits.
13151 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13152 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13153 InitsCopy);
13154 }
13155
13156 if (DirectInit) {
13157 if (auto *IL = dyn_cast<InitListExpr>(Init))
13158 DeduceInits = IL->inits();
13159 }
13160
13161 // Deduction only works if we have exactly one source expression.
13162 if (DeduceInits.empty()) {
13163 // It isn't possible to write this directly, but it is possible to
13164 // end up in this situation with "auto x(some_pack...);"
13165 Diag(Init->getBeginLoc(), IsInitCapture
13166 ? diag::err_init_capture_no_expression
13167 : diag::err_auto_var_init_no_expression)
13168 << VN << Type << Range;
13169 return QualType();
13170 }
13171
13172 if (DeduceInits.size() > 1) {
13173 Diag(DeduceInits[1]->getBeginLoc(),
13174 IsInitCapture ? diag::err_init_capture_multiple_expressions
13175 : diag::err_auto_var_init_multiple_expressions)
13176 << VN << Type << Range;
13177 return QualType();
13178 }
13179
13180 Expr *DeduceInit = DeduceInits[0];
13181 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13182 Diag(Init->getBeginLoc(), IsInitCapture
13183 ? diag::err_init_capture_paren_braces
13184 : diag::err_auto_var_init_paren_braces)
13185 << isa<InitListExpr>(Init) << VN << Type << Range;
13186 return QualType();
13187 }
13188
13189 // Expressions default to 'id' when we're in a debugger.
13190 bool DefaultedAnyToId = false;
13191 if (getLangOpts().DebuggerCastResultToId &&
13192 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13194 if (Result.isInvalid()) {
13195 return QualType();
13196 }
13197 Init = Result.get();
13198 DefaultedAnyToId = true;
13199 }
13200
13201 // C++ [dcl.decomp]p1:
13202 // If the assignment-expression [...] has array type A and no ref-qualifier
13203 // is present, e has type cv A
13204 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13206 DeduceInit->getType()->isConstantArrayType())
13207 return Context.getQualifiedType(DeduceInit->getType(),
13208 Type.getQualifiers());
13209
13211 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13213 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13216 if (!IsInitCapture)
13217 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13218 else if (isa<InitListExpr>(Init))
13220 diag::err_init_capture_deduction_failure_from_init_list)
13221 << VN
13222 << (DeduceInit->getType().isNull() ? TSI->getType()
13223 : DeduceInit->getType())
13224 << DeduceInit->getSourceRange();
13225 else
13226 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13227 << VN << TSI->getType()
13228 << (DeduceInit->getType().isNull() ? TSI->getType()
13229 : DeduceInit->getType())
13230 << DeduceInit->getSourceRange();
13231 }
13232
13233 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13234 // 'id' instead of a specific object type prevents most of our usual
13235 // checks.
13236 // We only want to warn outside of template instantiations, though:
13237 // inside a template, the 'id' could have come from a parameter.
13238 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13239 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13241 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13242 }
13243
13244 return DeducedType;
13245}
13246
13248 Expr *Init) {
13249 assert(!Init || !Init->containsErrors());
13251 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13252 VDecl->getSourceRange(), DirectInit, Init);
13253 if (DeducedType.isNull()) {
13254 VDecl->setInvalidDecl();
13255 return true;
13256 }
13257
13258 VDecl->setType(DeducedType);
13259 assert(VDecl->isLinkageValid());
13260
13261 // In ARC, infer lifetime.
13262 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13263 VDecl->setInvalidDecl();
13264
13265 if (getLangOpts().OpenCL)
13267
13268 if (getLangOpts().HLSL)
13269 HLSL().deduceAddressSpace(VDecl);
13270
13271 // If this is a redeclaration, check that the type we just deduced matches
13272 // the previously declared type.
13273 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13274 // We never need to merge the type, because we cannot form an incomplete
13275 // array of auto, nor deduce such a type.
13276 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13277 }
13278
13279 // Check the deduced type is valid for a variable declaration.
13281 return VDecl->isInvalidDecl();
13282}
13283
13286 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13287 Init = EWC->getSubExpr();
13288
13289 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13290 Init = CE->getSubExpr();
13291
13292 QualType InitType = Init->getType();
13295 "shouldn't be called if type doesn't have a non-trivial C struct");
13296 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13297 for (auto *I : ILE->inits()) {
13298 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13299 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13300 continue;
13301 SourceLocation SL = I->getExprLoc();
13303 }
13304 return;
13305 }
13306
13307 if (isa<ImplicitValueInitExpr>(Init)) {
13309 checkNonTrivialCUnion(InitType, Loc,
13311 NTCUK_Init);
13312 } else {
13313 // Assume all other explicit initializers involving copying some existing
13314 // object.
13315 // TODO: ignore any explicit initializers where we can guarantee
13316 // copy-elision.
13319 NTCUK_Copy);
13320 }
13321}
13322
13323namespace {
13324
13325bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13326 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13327 // in the source code or implicitly by the compiler if it is in a union
13328 // defined in a system header and has non-trivial ObjC ownership
13329 // qualifications. We don't want those fields to participate in determining
13330 // whether the containing union is non-trivial.
13331 return FD->hasAttr<UnavailableAttr>();
13332}
13333
13334struct DiagNonTrivalCUnionDefaultInitializeVisitor
13335 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13336 void> {
13337 using Super =
13338 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13339 void>;
13340
13341 DiagNonTrivalCUnionDefaultInitializeVisitor(
13342 QualType OrigTy, SourceLocation OrigLoc,
13343 NonTrivialCUnionContext UseContext, Sema &S)
13344 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13345
13346 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13347 const FieldDecl *FD, bool InNonTrivialUnion) {
13348 if (const auto *AT = S.Context.getAsArrayType(QT))
13349 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13350 InNonTrivialUnion);
13351 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13352 }
13353
13354 void visitARCStrong(QualType QT, const FieldDecl *FD,
13355 bool InNonTrivialUnion) {
13356 if (InNonTrivialUnion)
13357 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13358 << 1 << 0 << QT << FD->getName();
13359 }
13360
13361 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13362 if (InNonTrivialUnion)
13363 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13364 << 1 << 0 << QT << FD->getName();
13365 }
13366
13367 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13368 const auto *RD = QT->castAsRecordDecl();
13369 if (RD->isUnion()) {
13370 if (OrigLoc.isValid()) {
13371 bool IsUnion = false;
13372 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13373 IsUnion = OrigRD->isUnion();
13374 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13375 << 0 << OrigTy << IsUnion << UseContext;
13376 // Reset OrigLoc so that this diagnostic is emitted only once.
13377 OrigLoc = SourceLocation();
13378 }
13379 InNonTrivialUnion = true;
13380 }
13381
13382 if (InNonTrivialUnion)
13383 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13384 << 0 << 0 << QT.getUnqualifiedType() << "";
13385
13386 for (const FieldDecl *FD : RD->fields())
13387 if (!shouldIgnoreForRecordTriviality(FD))
13388 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13389 }
13390
13391 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13392
13393 // The non-trivial C union type or the struct/union type that contains a
13394 // non-trivial C union.
13395 QualType OrigTy;
13396 SourceLocation OrigLoc;
13397 NonTrivialCUnionContext UseContext;
13398 Sema &S;
13399};
13400
13401struct DiagNonTrivalCUnionDestructedTypeVisitor
13402 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13403 using Super =
13405
13406 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13407 SourceLocation OrigLoc,
13408 NonTrivialCUnionContext UseContext,
13409 Sema &S)
13410 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13411
13412 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13413 const FieldDecl *FD, bool InNonTrivialUnion) {
13414 if (const auto *AT = S.Context.getAsArrayType(QT))
13415 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13416 InNonTrivialUnion);
13417 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13418 }
13419
13420 void visitARCStrong(QualType QT, const FieldDecl *FD,
13421 bool InNonTrivialUnion) {
13422 if (InNonTrivialUnion)
13423 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13424 << 1 << 1 << QT << FD->getName();
13425 }
13426
13427 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13428 if (InNonTrivialUnion)
13429 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13430 << 1 << 1 << QT << FD->getName();
13431 }
13432
13433 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13434 const auto *RD = QT->castAsRecordDecl();
13435 if (RD->isUnion()) {
13436 if (OrigLoc.isValid()) {
13437 bool IsUnion = false;
13438 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13439 IsUnion = OrigRD->isUnion();
13440 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13441 << 1 << OrigTy << IsUnion << UseContext;
13442 // Reset OrigLoc so that this diagnostic is emitted only once.
13443 OrigLoc = SourceLocation();
13444 }
13445 InNonTrivialUnion = true;
13446 }
13447
13448 if (InNonTrivialUnion)
13449 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13450 << 0 << 1 << QT.getUnqualifiedType() << "";
13451
13452 for (const FieldDecl *FD : RD->fields())
13453 if (!shouldIgnoreForRecordTriviality(FD))
13454 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13455 }
13456
13457 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13458 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13459 bool InNonTrivialUnion) {}
13460
13461 // The non-trivial C union type or the struct/union type that contains a
13462 // non-trivial C union.
13463 QualType OrigTy;
13464 SourceLocation OrigLoc;
13465 NonTrivialCUnionContext UseContext;
13466 Sema &S;
13467};
13468
13469struct DiagNonTrivalCUnionCopyVisitor
13470 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13472
13473 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13474 NonTrivialCUnionContext UseContext, Sema &S)
13475 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13476
13477 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13478 const FieldDecl *FD, bool InNonTrivialUnion) {
13479 if (const auto *AT = S.Context.getAsArrayType(QT))
13480 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13481 InNonTrivialUnion);
13482 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13483 }
13484
13485 void visitARCStrong(QualType QT, const FieldDecl *FD,
13486 bool InNonTrivialUnion) {
13487 if (InNonTrivialUnion)
13488 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13489 << 1 << 2 << QT << FD->getName();
13490 }
13491
13492 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13493 if (InNonTrivialUnion)
13494 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13495 << 1 << 2 << QT << FD->getName();
13496 }
13497
13498 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13499 const auto *RD = QT->castAsRecordDecl();
13500 if (RD->isUnion()) {
13501 if (OrigLoc.isValid()) {
13502 bool IsUnion = false;
13503 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13504 IsUnion = OrigRD->isUnion();
13505 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13506 << 2 << OrigTy << IsUnion << UseContext;
13507 // Reset OrigLoc so that this diagnostic is emitted only once.
13508 OrigLoc = SourceLocation();
13509 }
13510 InNonTrivialUnion = true;
13511 }
13512
13513 if (InNonTrivialUnion)
13514 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13515 << 0 << 2 << QT.getUnqualifiedType() << "";
13516
13517 for (const FieldDecl *FD : RD->fields())
13518 if (!shouldIgnoreForRecordTriviality(FD))
13519 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13520 }
13521
13522 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13523 if (InNonTrivialUnion)
13524 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13525 << 1 << 2 << QT << FD->getName();
13526 }
13527
13528 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13529 const FieldDecl *FD, bool InNonTrivialUnion) {}
13530 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13531 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13532 bool InNonTrivialUnion) {}
13533
13534 // The non-trivial C union type or the struct/union type that contains a
13535 // non-trivial C union.
13536 QualType OrigTy;
13537 SourceLocation OrigLoc;
13538 NonTrivialCUnionContext UseContext;
13539 Sema &S;
13540};
13541
13542} // namespace
13543
13545 NonTrivialCUnionContext UseContext,
13546 unsigned NonTrivialKind) {
13550 "shouldn't be called if type doesn't have a non-trivial C union");
13551
13552 if ((NonTrivialKind & NTCUK_Init) &&
13554 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13555 .visit(QT, nullptr, false);
13556 if ((NonTrivialKind & NTCUK_Destruct) &&
13558 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13559 .visit(QT, nullptr, false);
13560 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13561 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13562 .visit(QT, nullptr, false);
13563}
13564
13566 const VarDecl *Dcl) {
13567 if (!getLangOpts().CPlusPlus)
13568 return false;
13569
13570 // We only need to warn if the definition is in a header file, so wait to
13571 // diagnose until we've seen the definition.
13572 if (!Dcl->isThisDeclarationADefinition())
13573 return false;
13574
13575 // If an object is defined in a source file, its definition can't get
13576 // duplicated since it will never appear in more than one TU.
13578 return false;
13579
13580 // If the variable we're looking at is a static local, then we actually care
13581 // about the properties of the function containing it.
13582 const ValueDecl *Target = Dcl;
13583 // VarDecls and FunctionDecls have different functions for checking
13584 // inline-ness, and whether they were originally templated, so we have to
13585 // call the appropriate functions manually.
13586 bool TargetIsInline = Dcl->isInline();
13587 bool TargetWasTemplated =
13589
13590 // Update the Target and TargetIsInline property if necessary
13591 if (Dcl->isStaticLocal()) {
13592 const DeclContext *Ctx = Dcl->getDeclContext();
13593 if (!Ctx)
13594 return false;
13595
13596 const FunctionDecl *FunDcl =
13597 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
13598 if (!FunDcl)
13599 return false;
13600
13601 Target = FunDcl;
13602 // IsInlined() checks for the C++ inline property
13603 TargetIsInline = FunDcl->isInlined();
13604 TargetWasTemplated =
13606 }
13607
13608 // Non-inline functions/variables can only legally appear in one TU
13609 // unless they were part of a template. Unfortunately, making complex
13610 // template instantiations visible is infeasible in practice, since
13611 // everything the template depends on also has to be visible. To avoid
13612 // giving impractical-to-fix warnings, don't warn if we're inside
13613 // something that was templated, even on inline stuff.
13614 if (!TargetIsInline || TargetWasTemplated)
13615 return false;
13616
13617 // If the object isn't hidden, the dynamic linker will prevent duplication.
13618 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13619
13620 // The target is "hidden" (from the dynamic linker) if:
13621 // 1. On posix, it has hidden visibility, or
13622 // 2. On windows, it has no import/export annotation, and neither does the
13623 // class which directly contains it.
13625 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13626 return false;
13627
13628 // If the variable isn't directly annotated, check to see if it's a member
13629 // of an annotated class.
13630 const CXXRecordDecl *Ctx =
13631 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
13632 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13633 return false;
13634
13635 } else if (Lnk.getVisibility() != HiddenVisibility) {
13636 // Posix case
13637 return false;
13638 }
13639
13640 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13642 return false;
13643
13644 return true;
13645}
13646
13647// Determine whether the object seems mutable for the purpose of diagnosing
13648// possible unique object duplication, i.e. non-const-qualified, and
13649// not an always-constant type like a function.
13650// Not perfect: doesn't account for mutable members, for example, or
13651// elements of container types.
13652// For nested pointers, any individual level being non-const is sufficient.
13653static bool looksMutable(QualType T, const ASTContext &Ctx) {
13654 T = T.getNonReferenceType();
13655 if (T->isFunctionType())
13656 return false;
13657 if (!T.isConstant(Ctx))
13658 return true;
13659 if (T->isPointerType())
13660 return looksMutable(T->getPointeeType(), Ctx);
13661 return false;
13662}
13663
13665 // If this object has external linkage and hidden visibility, it might be
13666 // duplicated when built into a shared library, which causes problems if it's
13667 // mutable (since the copies won't be in sync) or its initialization has side
13668 // effects (since it will run once per copy instead of once globally).
13669
13670 // Don't diagnose if we're inside a template, because it's not practical to
13671 // fix the warning in most cases.
13672 if (!VD->isTemplated() &&
13674
13675 QualType Type = VD->getType();
13676 if (looksMutable(Type, VD->getASTContext())) {
13677 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13679 }
13680
13681 // To keep false positives low, only warn if we're certain that the
13682 // initializer has side effects. Don't warn on operator new, since a mutable
13683 // pointer will trigger the previous warning, and an immutable pointer
13684 // getting duplicated just results in a little extra memory usage.
13685 const Expr *Init = VD->getAnyInitializer();
13686 if (Init &&
13687 Init->HasSideEffects(VD->getASTContext(),
13688 /*IncludePossibleEffects=*/false) &&
13689 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
13690 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13692 }
13693 }
13694}
13695
13697 // If there is no declaration, there was an error parsing it. Just ignore
13698 // the initializer.
13699 if (!RealDecl) {
13700 return;
13701 }
13702
13703 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13704 if (!Method->isInvalidDecl()) {
13705 // Pure-specifiers are handled in ActOnPureSpecifier.
13706 Diag(Method->getLocation(), diag::err_member_function_initialization)
13707 << Method->getDeclName() << Init->getSourceRange();
13708 Method->setInvalidDecl();
13709 }
13710 return;
13711 }
13712
13713 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13714 if (!VDecl) {
13715 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13716 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13717 RealDecl->setInvalidDecl();
13718 return;
13719 }
13720
13721 if (VDecl->isInvalidDecl()) {
13722 ExprResult Recovery =
13723 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13724 if (Expr *E = Recovery.get())
13725 VDecl->setInit(E);
13726 return;
13727 }
13728
13729 // WebAssembly tables can't be used to initialise a variable.
13730 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13731 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13732 VDecl->setInvalidDecl();
13733 return;
13734 }
13735
13736 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13737 if (VDecl->getType()->isUndeducedType()) {
13738 if (Init->containsErrors()) {
13739 // Invalidate the decl as we don't know the type for recovery-expr yet.
13740 RealDecl->setInvalidDecl();
13741 VDecl->setInit(Init);
13742 return;
13743 }
13744
13746 return;
13747 }
13748
13749 // dllimport cannot be used on variable definitions.
13750 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13751 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13752 VDecl->setInvalidDecl();
13753 return;
13754 }
13755
13756 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13757 // the identifier has external or internal linkage, the declaration shall
13758 // have no initializer for the identifier.
13759 // C++14 [dcl.init]p5 is the same restriction for C++.
13760 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13761 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13762 VDecl->setInvalidDecl();
13763 return;
13764 }
13765
13766 if (!VDecl->getType()->isDependentType()) {
13767 // A definition must end up with a complete type, which means it must be
13768 // complete with the restriction that an array type might be completed by
13769 // the initializer; note that later code assumes this restriction.
13770 QualType BaseDeclType = VDecl->getType();
13771 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13772 BaseDeclType = Array->getElementType();
13773 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13774 diag::err_typecheck_decl_incomplete_type)) {
13775 RealDecl->setInvalidDecl();
13776 return;
13777 }
13778
13779 // The variable can not have an abstract class type.
13780 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13781 diag::err_abstract_type_in_decl,
13783 VDecl->setInvalidDecl();
13784 }
13785
13786 // C++ [module.import/6] external definitions are not permitted in header
13787 // units.
13788 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13789 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13790 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13791 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13793 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13794 VDecl->setInvalidDecl();
13795 }
13796
13797 // If adding the initializer will turn this declaration into a definition,
13798 // and we already have a definition for this variable, diagnose or otherwise
13799 // handle the situation.
13800 if (VarDecl *Def = VDecl->getDefinition())
13801 if (Def != VDecl &&
13802 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13804 checkVarDeclRedefinition(Def, VDecl))
13805 return;
13806
13807 if (getLangOpts().CPlusPlus) {
13808 // C++ [class.static.data]p4
13809 // If a static data member is of const integral or const
13810 // enumeration type, its declaration in the class definition can
13811 // specify a constant-initializer which shall be an integral
13812 // constant expression (5.19). In that case, the member can appear
13813 // in integral constant expressions. The member shall still be
13814 // defined in a namespace scope if it is used in the program and the
13815 // namespace scope definition shall not contain an initializer.
13816 //
13817 // We already performed a redefinition check above, but for static
13818 // data members we also need to check whether there was an in-class
13819 // declaration with an initializer.
13820 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13821 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13822 << VDecl->getDeclName();
13823 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13824 diag::note_previous_initializer)
13825 << 0;
13826 return;
13827 }
13828
13830 VDecl->setInvalidDecl();
13831 return;
13832 }
13833 }
13834
13835 // If the variable has an initializer and local storage, check whether
13836 // anything jumps over the initialization.
13837 if (VDecl->hasLocalStorage())
13839
13840 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13841 // a kernel function cannot be initialized."
13842 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13843 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13844 VDecl->setInvalidDecl();
13845 return;
13846 }
13847
13848 // The LoaderUninitialized attribute acts as a definition (of undef).
13849 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13850 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13851 VDecl->setInvalidDecl();
13852 return;
13853 }
13854
13855 if (getLangOpts().HLSL)
13856 if (!HLSL().handleInitialization(VDecl, Init))
13857 return;
13858
13859 // Get the decls type and save a reference for later, since
13860 // CheckInitializerTypes may change it.
13861 QualType DclT = VDecl->getType(), SavT = DclT;
13862
13863 // Expressions default to 'id' when we're in a debugger
13864 // and we are assigning it to a variable of Objective-C pointer type.
13865 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13866 Init->getType() == Context.UnknownAnyTy) {
13868 if (!Result.isUsable()) {
13869 VDecl->setInvalidDecl();
13870 return;
13871 }
13872 Init = Result.get();
13873 }
13874
13875 // Perform the initialization.
13876 bool InitializedFromParenListExpr = false;
13877 bool IsParenListInit = false;
13878 if (!VDecl->isInvalidDecl()) {
13881 VDecl->getLocation(), DirectInit, Init);
13882
13883 MultiExprArg Args = Init;
13884 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
13885 Args =
13886 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
13887 InitializedFromParenListExpr = true;
13888 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
13889 Args = CXXDirectInit->getInitExprs();
13890 InitializedFromParenListExpr = true;
13891 }
13892
13893 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13894 /*TopLevelOfInitList=*/false,
13895 /*TreatUnavailableAsInvalid=*/false);
13896 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13897 if (!Result.isUsable()) {
13898 // If the provided initializer fails to initialize the var decl,
13899 // we attach a recovery expr for better recovery.
13900 auto RecoveryExpr =
13901 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13902 if (RecoveryExpr.get())
13903 VDecl->setInit(RecoveryExpr.get());
13904 // In general, for error recovery purposes, the initializer doesn't play
13905 // part in the valid bit of the declaration. There are a few exceptions:
13906 // 1) if the var decl has a deduced auto type, and the type cannot be
13907 // deduced by an invalid initializer;
13908 // 2) if the var decl is a decomposition decl with a non-deduced type,
13909 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13910 // Case 1) was already handled elsewhere.
13911 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13912 VDecl->setInvalidDecl();
13913 return;
13914 }
13915
13916 Init = Result.getAs<Expr>();
13917 IsParenListInit = !InitSeq.steps().empty() &&
13918 InitSeq.step_begin()->Kind ==
13920 QualType VDeclType = VDecl->getType();
13921 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
13922 !VDeclType->isDependentType() &&
13923 Context.getAsIncompleteArrayType(VDeclType) &&
13925 // Bail out if it is not possible to deduce array size from the
13926 // initializer.
13927 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13928 << VDeclType;
13929 VDecl->setInvalidDecl();
13930 return;
13931 }
13932 }
13933
13934 // Check for self-references within variable initializers.
13935 // Variables declared within a function/method body (except for references)
13936 // are handled by a dataflow analysis.
13937 // This is undefined behavior in C++, but valid in C.
13938 if (getLangOpts().CPlusPlus)
13939 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13940 VDecl->getType()->isReferenceType())
13941 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13942
13943 // If the type changed, it means we had an incomplete type that was
13944 // completed by the initializer. For example:
13945 // int ary[] = { 1, 3, 5 };
13946 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13947 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13948 VDecl->setType(DclT);
13949
13950 if (!VDecl->isInvalidDecl()) {
13951 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13952
13953 if (VDecl->hasAttr<BlocksAttr>())
13954 ObjC().checkRetainCycles(VDecl, Init);
13955
13956 // It is safe to assign a weak reference into a strong variable.
13957 // Although this code can still have problems:
13958 // id x = self.weakProp;
13959 // id y = self.weakProp;
13960 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13961 // paths through the function. This should be revisited if
13962 // -Wrepeated-use-of-weak is made flow-sensitive.
13963 if (FunctionScopeInfo *FSI = getCurFunction())
13964 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13966 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13967 Init->getBeginLoc()))
13968 FSI->markSafeWeakUse(Init);
13969 }
13970
13971 // The initialization is usually a full-expression.
13972 //
13973 // FIXME: If this is a braced initialization of an aggregate, it is not
13974 // an expression, and each individual field initializer is a separate
13975 // full-expression. For instance, in:
13976 //
13977 // struct Temp { ~Temp(); };
13978 // struct S { S(Temp); };
13979 // struct T { S a, b; } t = { Temp(), Temp() }
13980 //
13981 // we should destroy the first Temp before constructing the second.
13984 /*DiscardedValue*/ false, VDecl->isConstexpr());
13985 if (!Result.isUsable()) {
13986 VDecl->setInvalidDecl();
13987 return;
13988 }
13989 Init = Result.get();
13990
13991 // Attach the initializer to the decl.
13992 VDecl->setInit(Init);
13993
13994 if (VDecl->isLocalVarDecl()) {
13995 // Don't check the initializer if the declaration is malformed.
13996 if (VDecl->isInvalidDecl()) {
13997 // do nothing
13998
13999 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14000 // This is true even in C++ for OpenCL.
14001 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14003
14004 // Otherwise, C++ does not restrict the initializer.
14005 } else if (getLangOpts().CPlusPlus) {
14006 // do nothing
14007
14008 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14009 // static storage duration shall be constant expressions or string literals.
14010 } else if (VDecl->getStorageClass() == SC_Static) {
14012
14013 // C89 is stricter than C99 for aggregate initializers.
14014 // C89 6.5.7p3: All the expressions [...] in an initializer list
14015 // for an object that has aggregate or union type shall be
14016 // constant expressions.
14017 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14018 isa<InitListExpr>(Init)) {
14019 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14020 }
14021
14022 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14023 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14024 if (VDecl->hasLocalStorage())
14025 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14026 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14027 VDecl->getLexicalDeclContext()->isRecord()) {
14028 // This is an in-class initialization for a static data member, e.g.,
14029 //
14030 // struct S {
14031 // static const int value = 17;
14032 // };
14033
14034 // C++ [class.mem]p4:
14035 // A member-declarator can contain a constant-initializer only
14036 // if it declares a static member (9.4) of const integral or
14037 // const enumeration type, see 9.4.2.
14038 //
14039 // C++11 [class.static.data]p3:
14040 // If a non-volatile non-inline const static data member is of integral
14041 // or enumeration type, its declaration in the class definition can
14042 // specify a brace-or-equal-initializer in which every initializer-clause
14043 // that is an assignment-expression is a constant expression. A static
14044 // data member of literal type can be declared in the class definition
14045 // with the constexpr specifier; if so, its declaration shall specify a
14046 // brace-or-equal-initializer in which every initializer-clause that is
14047 // an assignment-expression is a constant expression.
14048
14049 // Do nothing on dependent types.
14050 if (DclT->isDependentType()) {
14051
14052 // Allow any 'static constexpr' members, whether or not they are of literal
14053 // type. We separately check that every constexpr variable is of literal
14054 // type.
14055 } else if (VDecl->isConstexpr()) {
14056
14057 // Require constness.
14058 } else if (!DclT.isConstQualified()) {
14059 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14060 << Init->getSourceRange();
14061 VDecl->setInvalidDecl();
14062
14063 // We allow integer constant expressions in all cases.
14064 } else if (DclT->isIntegralOrEnumerationType()) {
14066 // In C++11, a non-constexpr const static data member with an
14067 // in-class initializer cannot be volatile.
14068 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14069
14070 // We allow foldable floating-point constants as an extension.
14071 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14072 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14073 // it anyway and provide a fixit to add the 'constexpr'.
14074 if (getLangOpts().CPlusPlus11) {
14075 Diag(VDecl->getLocation(),
14076 diag::ext_in_class_initializer_float_type_cxx11)
14077 << DclT << Init->getSourceRange();
14078 Diag(VDecl->getBeginLoc(),
14079 diag::note_in_class_initializer_float_type_cxx11)
14080 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14081 } else {
14082 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14083 << DclT << Init->getSourceRange();
14084
14085 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14086 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14087 << Init->getSourceRange();
14088 VDecl->setInvalidDecl();
14089 }
14090 }
14091
14092 // Suggest adding 'constexpr' in C++11 for literal types.
14093 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14094 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14095 << DclT << Init->getSourceRange()
14096 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14097 VDecl->setConstexpr(true);
14098
14099 } else {
14100 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14101 << DclT << Init->getSourceRange();
14102 VDecl->setInvalidDecl();
14103 }
14104 } else if (VDecl->isFileVarDecl()) {
14105 // In C, extern is typically used to avoid tentative definitions when
14106 // declaring variables in headers, but adding an initializer makes it a
14107 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14108 // In C++, extern is often used to give implicitly static const variables
14109 // external linkage, so don't warn in that case. If selectany is present,
14110 // this might be header code intended for C and C++ inclusion, so apply the
14111 // C++ rules.
14112 if (VDecl->getStorageClass() == SC_Extern &&
14113 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14115 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14117 Diag(VDecl->getLocation(), diag::warn_extern_init);
14118
14119 // In Microsoft C++ mode, a const variable defined in namespace scope has
14120 // external linkage by default if the variable is declared with
14121 // __declspec(dllexport).
14124 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14125 VDecl->setStorageClass(SC_Extern);
14126
14127 // C99 6.7.8p4. All file scoped initializers need to be constant.
14128 // Avoid duplicate diagnostics for constexpr variables.
14129 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14130 !VDecl->isConstexpr())
14132 }
14133
14134 QualType InitType = Init->getType();
14135 if (!InitType.isNull() &&
14139
14140 // We will represent direct-initialization similarly to copy-initialization:
14141 // int x(1); -as-> int x = 1;
14142 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14143 //
14144 // Clients that want to distinguish between the two forms, can check for
14145 // direct initializer using VarDecl::getInitStyle().
14146 // A major benefit is that clients that don't particularly care about which
14147 // exactly form was it (like the CodeGen) can handle both cases without
14148 // special case code.
14149
14150 // C++ 8.5p11:
14151 // The form of initialization (using parentheses or '=') matters
14152 // when the entity being initialized has class type.
14153 if (InitializedFromParenListExpr) {
14154 assert(DirectInit && "Call-style initializer must be direct init.");
14155 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14157 } else if (DirectInit) {
14158 // This must be list-initialization. No other way is direct-initialization.
14160 }
14161
14162 if (LangOpts.OpenMP &&
14163 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14164 VDecl->isFileVarDecl())
14165 DeclsToCheckForDeferredDiags.insert(VDecl);
14167
14168 if (LangOpts.OpenACC && !InitType.isNull())
14169 OpenACC().ActOnVariableInit(VDecl, InitType);
14170}
14171
14173 // Our main concern here is re-establishing invariants like "a
14174 // variable's type is either dependent or complete".
14175 if (!D || D->isInvalidDecl()) return;
14176
14177 VarDecl *VD = dyn_cast<VarDecl>(D);
14178 if (!VD) return;
14179
14180 // Bindings are not usable if we can't make sense of the initializer.
14181 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14182 for (auto *BD : DD->bindings())
14183 BD->setInvalidDecl();
14184
14185 // Auto types are meaningless if we can't make sense of the initializer.
14186 if (VD->getType()->isUndeducedType()) {
14187 D->setInvalidDecl();
14188 return;
14189 }
14190
14191 QualType Ty = VD->getType();
14192 if (Ty->isDependentType()) return;
14193
14194 // Require a complete type.
14197 diag::err_typecheck_decl_incomplete_type)) {
14198 VD->setInvalidDecl();
14199 return;
14200 }
14201
14202 // Require a non-abstract type.
14203 if (RequireNonAbstractType(VD->getLocation(), Ty,
14204 diag::err_abstract_type_in_decl,
14206 VD->setInvalidDecl();
14207 return;
14208 }
14209
14210 // Don't bother complaining about constructors or destructors,
14211 // though.
14212}
14213
14215 // If there is no declaration, there was an error parsing it. Just ignore it.
14216 if (!RealDecl)
14217 return;
14218
14219 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14220 QualType Type = Var->getType();
14221
14222 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14223 if (isa<DecompositionDecl>(RealDecl)) {
14224 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14225 Var->setInvalidDecl();
14226 return;
14227 }
14228
14229 if (Type->isUndeducedType() &&
14230 DeduceVariableDeclarationType(Var, false, nullptr))
14231 return;
14232
14233 // C++11 [class.static.data]p3: A static data member can be declared with
14234 // the constexpr specifier; if so, its declaration shall specify
14235 // a brace-or-equal-initializer.
14236 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14237 // the definition of a variable [...] or the declaration of a static data
14238 // member.
14239 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14240 !Var->isThisDeclarationADemotedDefinition()) {
14241 if (Var->isStaticDataMember()) {
14242 // C++1z removes the relevant rule; the in-class declaration is always
14243 // a definition there.
14244 if (!getLangOpts().CPlusPlus17 &&
14246 Diag(Var->getLocation(),
14247 diag::err_constexpr_static_mem_var_requires_init)
14248 << Var;
14249 Var->setInvalidDecl();
14250 return;
14251 }
14252 } else {
14253 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14254 Var->setInvalidDecl();
14255 return;
14256 }
14257 }
14258
14259 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14260 // be initialized.
14261 if (!Var->isInvalidDecl() &&
14262 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14263 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14264 bool HasConstExprDefaultConstructor = false;
14265 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14266 for (auto *Ctor : RD->ctors()) {
14267 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14268 Ctor->getMethodQualifiers().getAddressSpace() ==
14270 HasConstExprDefaultConstructor = true;
14271 }
14272 }
14273 }
14274 if (!HasConstExprDefaultConstructor) {
14275 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14276 Var->setInvalidDecl();
14277 return;
14278 }
14279 }
14280
14281 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14282 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14283 Diag(Var->getLocation(), diag::err_specialization_const);
14284 Var->setInvalidDecl();
14285 return;
14286 }
14287
14288 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14289 if (Var->getStorageClass() == SC_Extern) {
14290 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14291 << Var;
14292 Var->setInvalidDecl();
14293 return;
14294 }
14295 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14296 diag::err_typecheck_decl_incomplete_type)) {
14297 Var->setInvalidDecl();
14298 return;
14299 }
14300 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14301 if (!RD->hasTrivialDefaultConstructor()) {
14302 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14303 Var->setInvalidDecl();
14304 return;
14305 }
14306 }
14307 // The declaration is uninitialized, no need for further checks.
14308 return;
14309 }
14310
14311 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14312 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14313 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14314 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14316 NTCUK_Init);
14317
14318 switch (DefKind) {
14320 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14321 break;
14322
14323 // We have an out-of-line definition of a static data member
14324 // that has an in-class initializer, so we type-check this like
14325 // a declaration.
14326 //
14327 [[fallthrough]];
14328
14330 // It's only a declaration.
14331
14332 // Block scope. C99 6.7p7: If an identifier for an object is
14333 // declared with no linkage (C99 6.2.2p6), the type for the
14334 // object shall be complete.
14335 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14336 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14337 RequireCompleteType(Var->getLocation(), Type,
14338 diag::err_typecheck_decl_incomplete_type))
14339 Var->setInvalidDecl();
14340
14341 // Make sure that the type is not abstract.
14342 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14343 RequireNonAbstractType(Var->getLocation(), Type,
14344 diag::err_abstract_type_in_decl,
14346 Var->setInvalidDecl();
14347 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14348 Var->getStorageClass() == SC_PrivateExtern) {
14349 Diag(Var->getLocation(), diag::warn_private_extern);
14350 Diag(Var->getLocation(), diag::note_private_extern);
14351 }
14352
14354 !Var->isInvalidDecl())
14355 ExternalDeclarations.push_back(Var);
14356
14357 return;
14358
14360 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14361 // object that has file scope without an initializer, and without a
14362 // storage-class specifier or with the storage-class specifier "static",
14363 // constitutes a tentative definition. Note: A tentative definition with
14364 // external linkage is valid (C99 6.2.2p5).
14365 if (!Var->isInvalidDecl()) {
14366 if (const IncompleteArrayType *ArrayT
14369 Var->getLocation(), ArrayT->getElementType(),
14370 diag::err_array_incomplete_or_sizeless_type))
14371 Var->setInvalidDecl();
14372 }
14373 if (Var->getStorageClass() == SC_Static) {
14374 // C99 6.9.2p3: If the declaration of an identifier for an object is
14375 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14376 // declared type shall not be an incomplete type.
14377 // NOTE: code such as the following
14378 // static struct s;
14379 // struct s { int a; };
14380 // is accepted by gcc. Hence here we issue a warning instead of
14381 // an error and we do not invalidate the static declaration.
14382 // NOTE: to avoid multiple warnings, only check the first declaration.
14383 if (Var->isFirstDecl())
14384 RequireCompleteType(Var->getLocation(), Type,
14385 diag::ext_typecheck_decl_incomplete_type,
14386 Type->isArrayType());
14387 }
14388 }
14389
14390 // Record the tentative definition; we're done.
14391 if (!Var->isInvalidDecl())
14393 return;
14394 }
14395
14396 // Provide a specific diagnostic for uninitialized variable
14397 // definitions with incomplete array type.
14398 if (Type->isIncompleteArrayType()) {
14399 if (Var->isConstexpr())
14400 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14401 << Var;
14402 else
14403 Diag(Var->getLocation(),
14404 diag::err_typecheck_incomplete_array_needs_initializer);
14405 Var->setInvalidDecl();
14406 return;
14407 }
14408
14409 // Provide a specific diagnostic for uninitialized variable
14410 // definitions with reference type.
14411 if (Type->isReferenceType()) {
14412 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14413 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14414 return;
14415 }
14416
14417 // Do not attempt to type-check the default initializer for a
14418 // variable with dependent type.
14419 if (Type->isDependentType())
14420 return;
14421
14422 if (Var->isInvalidDecl())
14423 return;
14424
14425 if (!Var->hasAttr<AliasAttr>()) {
14426 if (RequireCompleteType(Var->getLocation(),
14428 diag::err_typecheck_decl_incomplete_type)) {
14429 Var->setInvalidDecl();
14430 return;
14431 }
14432 } else {
14433 return;
14434 }
14435
14436 // The variable can not have an abstract class type.
14437 if (RequireNonAbstractType(Var->getLocation(), Type,
14438 diag::err_abstract_type_in_decl,
14440 Var->setInvalidDecl();
14441 return;
14442 }
14443
14444 // In C, if the definition is const-qualified and has no initializer, it
14445 // is left uninitialized unless it has static or thread storage duration.
14446 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14447 unsigned DiagID = diag::warn_default_init_const_unsafe;
14448 if (Var->getStorageDuration() == SD_Static ||
14449 Var->getStorageDuration() == SD_Thread)
14450 DiagID = diag::warn_default_init_const;
14451
14452 bool EmitCppCompat = !Diags.isIgnored(
14453 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14454 Var->getLocation());
14455
14456 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14457 }
14458
14459 // Check for jumps past the implicit initializer. C++0x
14460 // clarifies that this applies to a "variable with automatic
14461 // storage duration", not a "local variable".
14462 // C++11 [stmt.dcl]p3
14463 // A program that jumps from a point where a variable with automatic
14464 // storage duration is not in scope to a point where it is in scope is
14465 // ill-formed unless the variable has scalar type, class type with a
14466 // trivial default constructor and a trivial destructor, a cv-qualified
14467 // version of one of these types, or an array of one of the preceding
14468 // types and is declared without an initializer.
14469 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14470 if (const auto *CXXRecord =
14472 // Mark the function (if we're in one) for further checking even if the
14473 // looser rules of C++11 do not require such checks, so that we can
14474 // diagnose incompatibilities with C++98.
14475 if (!CXXRecord->isPOD())
14477 }
14478 }
14479 // In OpenCL, we can't initialize objects in the __local address space,
14480 // even implicitly, so don't synthesize an implicit initializer.
14481 if (getLangOpts().OpenCL &&
14482 Var->getType().getAddressSpace() == LangAS::opencl_local)
14483 return;
14484
14485 // Handle HLSL uninitialized decls
14486 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14487 return;
14488
14489 // HLSL input variables are expected to be externally initialized, even
14490 // when marked `static`.
14491 if (getLangOpts().HLSL &&
14492 Var->getType().getAddressSpace() == LangAS::hlsl_input)
14493 return;
14494
14495 // C++03 [dcl.init]p9:
14496 // If no initializer is specified for an object, and the
14497 // object is of (possibly cv-qualified) non-POD class type (or
14498 // array thereof), the object shall be default-initialized; if
14499 // the object is of const-qualified type, the underlying class
14500 // type shall have a user-declared default
14501 // constructor. Otherwise, if no initializer is specified for
14502 // a non- static object, the object and its subobjects, if
14503 // any, have an indeterminate initial value); if the object
14504 // or any of its subobjects are of const-qualified type, the
14505 // program is ill-formed.
14506 // C++0x [dcl.init]p11:
14507 // If no initializer is specified for an object, the object is
14508 // default-initialized; [...].
14511 = InitializationKind::CreateDefault(Var->getLocation());
14512
14513 InitializationSequence InitSeq(*this, Entity, Kind, {});
14514 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14515
14516 if (Init.get()) {
14517 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14518 // This is important for template substitution.
14519 Var->setInitStyle(VarDecl::CallInit);
14520 } else if (Init.isInvalid()) {
14521 // If default-init fails, attach a recovery-expr initializer to track
14522 // that initialization was attempted and failed.
14523 auto RecoveryExpr =
14524 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14525 if (RecoveryExpr.get())
14526 Var->setInit(RecoveryExpr.get());
14527 }
14528
14530 }
14531}
14532
14534 // If there is no declaration, there was an error parsing it. Ignore it.
14535 if (!D)
14536 return;
14537
14538 VarDecl *VD = dyn_cast<VarDecl>(D);
14539 if (!VD) {
14540 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14541 D->setInvalidDecl();
14542 return;
14543 }
14544
14545 VD->setCXXForRangeDecl(true);
14546
14547 // for-range-declaration cannot be given a storage class specifier.
14548 int Error = -1;
14549 switch (VD->getStorageClass()) {
14550 case SC_None:
14551 break;
14552 case SC_Extern:
14553 Error = 0;
14554 break;
14555 case SC_Static:
14556 Error = 1;
14557 break;
14558 case SC_PrivateExtern:
14559 Error = 2;
14560 break;
14561 case SC_Auto:
14562 Error = 3;
14563 break;
14564 case SC_Register:
14565 Error = 4;
14566 break;
14567 }
14568
14569 // for-range-declaration cannot be given a storage class specifier con't.
14570 switch (VD->getTSCSpec()) {
14571 case TSCS_thread_local:
14572 Error = 6;
14573 break;
14574 case TSCS___thread:
14575 case TSCS__Thread_local:
14576 case TSCS_unspecified:
14577 break;
14578 }
14579
14580 if (Error != -1) {
14581 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14582 << VD << Error;
14583 D->setInvalidDecl();
14584 }
14585}
14586
14588 IdentifierInfo *Ident,
14589 ParsedAttributes &Attrs) {
14590 // C++1y [stmt.iter]p1:
14591 // A range-based for statement of the form
14592 // for ( for-range-identifier : for-range-initializer ) statement
14593 // is equivalent to
14594 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14595 DeclSpec DS(Attrs.getPool().getFactory());
14596
14597 const char *PrevSpec;
14598 unsigned DiagID;
14599 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14601
14603 D.SetIdentifier(Ident, IdentLoc);
14604 D.takeAttributes(Attrs);
14605
14606 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14607 IdentLoc);
14608 Decl *Var = ActOnDeclarator(S, D);
14609 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14611 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14612 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14613 : IdentLoc);
14614}
14615
14617 if (var->isInvalidDecl()) return;
14618
14620
14621 if (getLangOpts().OpenCL) {
14622 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14623 // initialiser
14624 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14625 !var->hasInit()) {
14626 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14627 << 1 /*Init*/;
14628 var->setInvalidDecl();
14629 return;
14630 }
14631 }
14632
14633 // In Objective-C, don't allow jumps past the implicit initialization of a
14634 // local retaining variable.
14635 if (getLangOpts().ObjC &&
14636 var->hasLocalStorage()) {
14637 switch (var->getType().getObjCLifetime()) {
14641 break;
14642
14646 break;
14647 }
14648 }
14649
14650 if (var->hasLocalStorage() &&
14651 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14653
14654 // Warn about externally-visible variables being defined without a
14655 // prior declaration. We only want to do this for global
14656 // declarations, but we also specifically need to avoid doing it for
14657 // class members because the linkage of an anonymous class can
14658 // change if it's later given a typedef name.
14659 if (var->isThisDeclarationADefinition() &&
14660 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14661 var->isExternallyVisible() && var->hasLinkage() &&
14662 !var->isInline() && !var->getDescribedVarTemplate() &&
14663 var->getStorageClass() != SC_Register &&
14664 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14665 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14666 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14667 var->getLocation())) {
14668 // Find a previous declaration that's not a definition.
14669 VarDecl *prev = var->getPreviousDecl();
14670 while (prev && prev->isThisDeclarationADefinition())
14671 prev = prev->getPreviousDecl();
14672
14673 if (!prev) {
14674 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14675 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14676 << /* variable */ 0;
14677 }
14678 }
14679
14680 // Cache the result of checking for constant initialization.
14681 std::optional<bool> CacheHasConstInit;
14682 const Expr *CacheCulprit = nullptr;
14683 auto checkConstInit = [&]() mutable {
14684 const Expr *Init = var->getInit();
14685 if (Init->isInstantiationDependent())
14686 return true;
14687
14688 if (!CacheHasConstInit)
14689 CacheHasConstInit = var->getInit()->isConstantInitializer(
14690 Context, var->getType()->isReferenceType(), &CacheCulprit);
14691 return *CacheHasConstInit;
14692 };
14693
14694 if (var->getTLSKind() == VarDecl::TLS_Static) {
14695 if (var->getType().isDestructedType()) {
14696 // GNU C++98 edits for __thread, [basic.start.term]p3:
14697 // The type of an object with thread storage duration shall not
14698 // have a non-trivial destructor.
14699 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14701 Diag(var->getLocation(), diag::note_use_thread_local);
14702 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14703 if (!checkConstInit()) {
14704 // GNU C++98 edits for __thread, [basic.start.init]p4:
14705 // An object of thread storage duration shall not require dynamic
14706 // initialization.
14707 // FIXME: Need strict checking here.
14708 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14709 << CacheCulprit->getSourceRange();
14711 Diag(var->getLocation(), diag::note_use_thread_local);
14712 }
14713 }
14714 }
14715
14716
14717 if (!var->getType()->isStructureType() && var->hasInit() &&
14718 isa<InitListExpr>(var->getInit())) {
14719 const auto *ILE = cast<InitListExpr>(var->getInit());
14720 unsigned NumInits = ILE->getNumInits();
14721 if (NumInits > 2)
14722 for (unsigned I = 0; I < NumInits; ++I) {
14723 const auto *Init = ILE->getInit(I);
14724 if (!Init)
14725 break;
14726 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14727 if (!SL)
14728 break;
14729
14730 unsigned NumConcat = SL->getNumConcatenated();
14731 // Diagnose missing comma in string array initialization.
14732 // Do not warn when all the elements in the initializer are concatenated
14733 // together. Do not warn for macros too.
14734 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14735 bool OnlyOneMissingComma = true;
14736 for (unsigned J = I + 1; J < NumInits; ++J) {
14737 const auto *Init = ILE->getInit(J);
14738 if (!Init)
14739 break;
14740 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14741 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14742 OnlyOneMissingComma = false;
14743 break;
14744 }
14745 }
14746
14747 if (OnlyOneMissingComma) {
14749 for (unsigned i = 0; i < NumConcat - 1; ++i)
14750 Hints.push_back(FixItHint::CreateInsertion(
14751 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14752
14753 Diag(SL->getStrTokenLoc(1),
14754 diag::warn_concatenated_literal_array_init)
14755 << Hints;
14756 Diag(SL->getBeginLoc(),
14757 diag::note_concatenated_string_literal_silence);
14758 }
14759 // In any case, stop now.
14760 break;
14761 }
14762 }
14763 }
14764
14765
14766 QualType type = var->getType();
14767
14768 if (var->hasAttr<BlocksAttr>())
14770
14771 Expr *Init = var->getInit();
14772 bool GlobalStorage = var->hasGlobalStorage();
14773 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14775 bool HasConstInit = true;
14776
14777 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14778 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14779 << var;
14780
14781 // Check whether the initializer is sufficiently constant.
14782 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14783 !type->isDependentType() && Init && !Init->isValueDependent() &&
14784 (GlobalStorage || var->isConstexpr() ||
14785 var->mightBeUsableInConstantExpressions(Context))) {
14786 // If this variable might have a constant initializer or might be usable in
14787 // constant expressions, check whether or not it actually is now. We can't
14788 // do this lazily, because the result might depend on things that change
14789 // later, such as which constexpr functions happen to be defined.
14791 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14792 // Prior to C++11, in contexts where a constant initializer is required,
14793 // the set of valid constant initializers is described by syntactic rules
14794 // in [expr.const]p2-6.
14795 // FIXME: Stricter checking for these rules would be useful for constinit /
14796 // -Wglobal-constructors.
14797 HasConstInit = checkConstInit();
14798
14799 // Compute and cache the constant value, and remember that we have a
14800 // constant initializer.
14801 if (HasConstInit) {
14802 if (var->isStaticDataMember() && !var->isInline() &&
14803 var->getLexicalDeclContext()->isRecord() &&
14804 type->isIntegralOrEnumerationType()) {
14805 // In C++98, in-class initialization for a static data member must
14806 // be an integer constant expression.
14807 if (!Init->isIntegerConstantExpr(Context)) {
14808 Diag(Init->getExprLoc(),
14809 diag::ext_in_class_initializer_non_constant)
14810 << Init->getSourceRange();
14811 }
14812 }
14813 (void)var->checkForConstantInitialization(Notes);
14814 Notes.clear();
14815 } else if (CacheCulprit) {
14816 Notes.emplace_back(CacheCulprit->getExprLoc(),
14817 PDiag(diag::note_invalid_subexpr_in_const_expr));
14818 Notes.back().second << CacheCulprit->getSourceRange();
14819 }
14820 } else {
14821 // Evaluate the initializer to see if it's a constant initializer.
14822 HasConstInit = var->checkForConstantInitialization(Notes);
14823 }
14824
14825 if (HasConstInit) {
14826 // FIXME: Consider replacing the initializer with a ConstantExpr.
14827 } else if (var->isConstexpr()) {
14828 SourceLocation DiagLoc = var->getLocation();
14829 // If the note doesn't add any useful information other than a source
14830 // location, fold it into the primary diagnostic.
14831 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14832 diag::note_invalid_subexpr_in_const_expr) {
14833 DiagLoc = Notes[0].first;
14834 Notes.clear();
14835 }
14836 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14837 << var << Init->getSourceRange();
14838 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14839 Diag(Notes[I].first, Notes[I].second);
14840 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14841 auto *Attr = var->getAttr<ConstInitAttr>();
14842 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14843 << Init->getSourceRange();
14844 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14845 << Attr->getRange() << Attr->isConstinit();
14846 for (auto &it : Notes)
14847 Diag(it.first, it.second);
14848 } else if (var->isStaticDataMember() && !var->isInline() &&
14849 var->getLexicalDeclContext()->isRecord()) {
14850 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
14851 << Init->getSourceRange();
14852 for (auto &it : Notes)
14853 Diag(it.first, it.second);
14854 var->setInvalidDecl();
14855 } else if (IsGlobal &&
14856 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14857 var->getLocation())) {
14858 // Warn about globals which don't have a constant initializer. Don't
14859 // warn about globals with a non-trivial destructor because we already
14860 // warned about them.
14861 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14862 if (!(RD && !RD->hasTrivialDestructor())) {
14863 // checkConstInit() here permits trivial default initialization even in
14864 // C++11 onwards, where such an initializer is not a constant initializer
14865 // but nonetheless doesn't require a global constructor.
14866 if (!checkConstInit())
14867 Diag(var->getLocation(), diag::warn_global_constructor)
14868 << Init->getSourceRange();
14869 }
14870 }
14871 }
14872
14873 // Apply section attributes and pragmas to global variables.
14874 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14876 PragmaStack<StringLiteral *> *Stack = nullptr;
14877 int SectionFlags = ASTContext::PSF_Read;
14878 bool MSVCEnv =
14879 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14880 std::optional<QualType::NonConstantStorageReason> Reason;
14881 if (HasConstInit &&
14882 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14883 Stack = &ConstSegStack;
14884 } else {
14885 SectionFlags |= ASTContext::PSF_Write;
14886 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14887 }
14888 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14889 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14890 SectionFlags |= ASTContext::PSF_Implicit;
14891 UnifySection(SA->getName(), SectionFlags, var);
14892 } else if (Stack->CurrentValue) {
14893 if (Stack != &ConstSegStack && MSVCEnv &&
14894 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14895 var->getType().isConstQualified()) {
14896 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14897 NonConstNonReferenceType) &&
14898 "This case should've already been handled elsewhere");
14899 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14900 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14902 : *Reason);
14903 }
14904 SectionFlags |= ASTContext::PSF_Implicit;
14905 auto SectionName = Stack->CurrentValue->getString();
14906 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14907 Stack->CurrentPragmaLocation,
14908 SectionAttr::Declspec_allocate));
14909 if (UnifySection(SectionName, SectionFlags, var))
14910 var->dropAttr<SectionAttr>();
14911 }
14912
14913 // Apply the init_seg attribute if this has an initializer. If the
14914 // initializer turns out to not be dynamic, we'll end up ignoring this
14915 // attribute.
14916 if (CurInitSeg && var->getInit())
14917 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14918 CurInitSegLoc));
14919 }
14920
14921 // All the following checks are C++ only.
14922 if (!getLangOpts().CPlusPlus) {
14923 // If this variable must be emitted, add it as an initializer for the
14924 // current module.
14925 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14926 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14927 return;
14928 }
14929
14931
14932 // Require the destructor.
14933 if (!type->isDependentType())
14934 if (auto *RD = baseType->getAsCXXRecordDecl())
14936
14937 // If this variable must be emitted, add it as an initializer for the current
14938 // module.
14939 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14940 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14941
14942 // Build the bindings if this is a structured binding declaration.
14943 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14945}
14946
14948 assert(VD->isStaticLocal());
14949
14950 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14951
14952 // Find outermost function when VD is in lambda function.
14953 while (FD && !getDLLAttr(FD) &&
14954 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14955 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14956 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14957 }
14958
14959 if (!FD)
14960 return;
14961
14962 // Static locals inherit dll attributes from their function.
14963 if (Attr *A = getDLLAttr(FD)) {
14964 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14965 NewAttr->setInherited(true);
14966 VD->addAttr(NewAttr);
14967 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14968 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14969 NewAttr->setInherited(true);
14970 VD->addAttr(NewAttr);
14971
14972 // Export this function to enforce exporting this static variable even
14973 // if it is not used in this compilation unit.
14974 if (!FD->hasAttr<DLLExportAttr>())
14975 FD->addAttr(NewAttr);
14976
14977 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14978 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14979 NewAttr->setInherited(true);
14980 VD->addAttr(NewAttr);
14981 }
14982}
14983
14985 assert(VD->getTLSKind());
14986
14987 // Perform TLS alignment check here after attributes attached to the variable
14988 // which may affect the alignment have been processed. Only perform the check
14989 // if the target has a maximum TLS alignment (zero means no constraints).
14990 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14991 // Protect the check so that it's not performed on dependent types and
14992 // dependent alignments (we can't determine the alignment in that case).
14993 if (!VD->hasDependentAlignment()) {
14994 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14995 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14996 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14998 << (unsigned)MaxAlignChars.getQuantity();
14999 }
15000 }
15001 }
15002}
15003
15005 // Note that we are no longer parsing the initializer for this declaration.
15006 ParsingInitForAutoVars.erase(ThisDecl);
15007
15008 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15009 if (!VD)
15010 return;
15011
15012 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15014 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15016 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15020 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15024 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15028 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15031 }
15032
15033 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15034 for (auto *BD : DD->bindings()) {
15036 }
15037 }
15038
15039 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15041
15042 checkAttributesAfterMerging(*this, *VD);
15043
15044 if (VD->isStaticLocal())
15046
15047 if (VD->getTLSKind())
15049
15050 // Perform check for initializers of device-side global variables.
15051 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15052 // 7.5). We must also apply the same checks to all __shared__
15053 // variables whether they are local or not. CUDA also allows
15054 // constant initializers for __constant__ and __device__ variables.
15055 if (getLangOpts().CUDA)
15057
15058 // Grab the dllimport or dllexport attribute off of the VarDecl.
15059 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15060
15061 // Imported static data members cannot be defined out-of-line.
15062 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15063 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15065 // We allow definitions of dllimport class template static data members
15066 // with a warning.
15068 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
15069 bool IsClassTemplateMember =
15070 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
15071 Context->getDescribedClassTemplate();
15072
15073 Diag(VD->getLocation(),
15074 IsClassTemplateMember
15075 ? diag::warn_attribute_dllimport_static_field_definition
15076 : diag::err_attribute_dllimport_static_field_definition);
15077 Diag(IA->getLocation(), diag::note_attribute);
15078 if (!IsClassTemplateMember)
15079 VD->setInvalidDecl();
15080 }
15081 }
15082
15083 // dllimport/dllexport variables cannot be thread local, their TLS index
15084 // isn't exported with the variable.
15085 if (DLLAttr && VD->getTLSKind()) {
15086 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15087 if (F && getDLLAttr(F)) {
15088 assert(VD->isStaticLocal());
15089 // But if this is a static local in a dlimport/dllexport function, the
15090 // function will never be inlined, which means the var would never be
15091 // imported, so having it marked import/export is safe.
15092 } else {
15093 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15094 << DLLAttr;
15095 VD->setInvalidDecl();
15096 }
15097 }
15098
15099 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15100 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15101 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15102 << Attr;
15103 VD->dropAttr<UsedAttr>();
15104 }
15105 }
15106 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15107 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15108 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15109 << Attr;
15110 VD->dropAttr<RetainAttr>();
15111 }
15112 }
15113
15114 const DeclContext *DC = VD->getDeclContext();
15115 // If there's a #pragma GCC visibility in scope, and this isn't a class
15116 // member, set the visibility of this variable.
15119
15120 // FIXME: Warn on unused var template partial specializations.
15121 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
15123
15124 // Now we have parsed the initializer and can update the table of magic
15125 // tag values.
15126 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15128 return;
15129
15130 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15131 const Expr *MagicValueExpr = VD->getInit();
15132 if (!MagicValueExpr) {
15133 continue;
15134 }
15135 std::optional<llvm::APSInt> MagicValueInt;
15136 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15137 Diag(I->getRange().getBegin(),
15138 diag::err_type_tag_for_datatype_not_ice)
15139 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15140 continue;
15141 }
15142 if (MagicValueInt->getActiveBits() > 64) {
15143 Diag(I->getRange().getBegin(),
15144 diag::err_type_tag_for_datatype_too_large)
15145 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15146 continue;
15147 }
15148 uint64_t MagicValue = MagicValueInt->getZExtValue();
15149 RegisterTypeTagForDatatype(I->getArgumentKind(),
15150 MagicValue,
15151 I->getMatchingCType(),
15152 I->getLayoutCompatible(),
15153 I->getMustBeNull());
15154 }
15155}
15156
15158 auto *VD = dyn_cast<VarDecl>(DD);
15159 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15160}
15161
15163 ArrayRef<Decl *> Group) {
15165
15166 if (DS.isTypeSpecOwned())
15167 Decls.push_back(DS.getRepAsDecl());
15168
15169 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15170 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15171 bool DiagnosedMultipleDecomps = false;
15172 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15173 bool DiagnosedNonDeducedAuto = false;
15174
15175 for (Decl *D : Group) {
15176 if (!D)
15177 continue;
15178 // Check if the Decl has been declared in '#pragma omp declare target'
15179 // directive and has static storage duration.
15180 if (auto *VD = dyn_cast<VarDecl>(D);
15181 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15182 VD->hasGlobalStorage())
15184 // For declarators, there are some additional syntactic-ish checks we need
15185 // to perform.
15186 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15187 if (!FirstDeclaratorInGroup)
15188 FirstDeclaratorInGroup = DD;
15189 if (!FirstDecompDeclaratorInGroup)
15190 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15191 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15192 !hasDeducedAuto(DD))
15193 FirstNonDeducedAutoInGroup = DD;
15194
15195 if (FirstDeclaratorInGroup != DD) {
15196 // A decomposition declaration cannot be combined with any other
15197 // declaration in the same group.
15198 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15199 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15200 diag::err_decomp_decl_not_alone)
15201 << FirstDeclaratorInGroup->getSourceRange()
15202 << DD->getSourceRange();
15203 DiagnosedMultipleDecomps = true;
15204 }
15205
15206 // A declarator that uses 'auto' in any way other than to declare a
15207 // variable with a deduced type cannot be combined with any other
15208 // declarator in the same group.
15209 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15210 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15211 diag::err_auto_non_deduced_not_alone)
15212 << FirstNonDeducedAutoInGroup->getType()
15214 << FirstDeclaratorInGroup->getSourceRange()
15215 << DD->getSourceRange();
15216 DiagnosedNonDeducedAuto = true;
15217 }
15218 }
15219 }
15220
15221 Decls.push_back(D);
15222 }
15223
15225 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15226 handleTagNumbering(Tag, S);
15227 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15229 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15230 }
15231 }
15232
15233 return BuildDeclaratorGroup(Decls);
15234}
15235
15238 // C++14 [dcl.spec.auto]p7: (DR1347)
15239 // If the type that replaces the placeholder type is not the same in each
15240 // deduction, the program is ill-formed.
15241 if (Group.size() > 1) {
15242 QualType Deduced;
15243 VarDecl *DeducedDecl = nullptr;
15244 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15245 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15246 if (!D || D->isInvalidDecl())
15247 break;
15248 DeducedType *DT = D->getType()->getContainedDeducedType();
15249 if (!DT || DT->getDeducedType().isNull())
15250 continue;
15251 if (Deduced.isNull()) {
15252 Deduced = DT->getDeducedType();
15253 DeducedDecl = D;
15254 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15255 auto *AT = dyn_cast<AutoType>(DT);
15256 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15257 diag::err_auto_different_deductions)
15258 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15259 << DeducedDecl->getDeclName() << DT->getDeducedType()
15260 << D->getDeclName();
15261 if (DeducedDecl->hasInit())
15262 Dia << DeducedDecl->getInit()->getSourceRange();
15263 if (D->getInit())
15264 Dia << D->getInit()->getSourceRange();
15265 D->setInvalidDecl();
15266 break;
15267 }
15268 }
15269 }
15270
15272
15273 return DeclGroupPtrTy::make(
15274 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15275}
15276
15279}
15280
15282 // Don't parse the comment if Doxygen diagnostics are ignored.
15283 if (Group.empty() || !Group[0])
15284 return;
15285
15286 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15287 Group[0]->getLocation()) &&
15288 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15289 Group[0]->getLocation()))
15290 return;
15291
15292 if (Group.size() >= 2) {
15293 // This is a decl group. Normally it will contain only declarations
15294 // produced from declarator list. But in case we have any definitions or
15295 // additional declaration references:
15296 // 'typedef struct S {} S;'
15297 // 'typedef struct S *S;'
15298 // 'struct S *pS;'
15299 // FinalizeDeclaratorGroup adds these as separate declarations.
15300 Decl *MaybeTagDecl = Group[0];
15301 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15302 Group = Group.slice(1);
15303 }
15304 }
15305
15306 // FIMXE: We assume every Decl in the group is in the same file.
15307 // This is false when preprocessor constructs the group from decls in
15308 // different files (e. g. macros or #include).
15310}
15311
15313 // Check that there are no default arguments inside the type of this
15314 // parameter.
15315 if (getLangOpts().CPlusPlus)
15317
15318 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15319 if (D.getCXXScopeSpec().isSet()) {
15320 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15321 << D.getCXXScopeSpec().getRange();
15322 }
15323
15324 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15325 // simple identifier except [...irrelevant cases...].
15326 switch (D.getName().getKind()) {
15328 break;
15329
15337 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15339 break;
15340
15343 // GetNameForDeclarator would not produce a useful name in this case.
15344 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15345 break;
15346 }
15347}
15348
15350 // This only matters in C.
15351 if (getLangOpts().CPlusPlus)
15352 return;
15353
15354 // This only matters if the declaration has a type.
15355 const auto *VD = dyn_cast<ValueDecl>(D);
15356 if (!VD)
15357 return;
15358
15359 // Get the type, this only matters for tag types.
15360 QualType QT = VD->getType();
15361 const auto *TD = QT->getAsTagDecl();
15362 if (!TD)
15363 return;
15364
15365 // Check if the tag declaration is lexically declared somewhere different
15366 // from the lexical declaration of the given object, then it will be hidden
15367 // in C++ and we should warn on it.
15368 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15369 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15370 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15371 Diag(TD->getLocation(), diag::note_declared_at);
15372 }
15373}
15374
15376 SourceLocation ExplicitThisLoc) {
15377 if (!ExplicitThisLoc.isValid())
15378 return;
15379 assert(S.getLangOpts().CPlusPlus &&
15380 "explicit parameter in non-cplusplus mode");
15381 if (!S.getLangOpts().CPlusPlus23)
15382 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15383 << P->getSourceRange();
15384
15385 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15386 // parameter pack.
15387 if (P->isParameterPack()) {
15388 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15389 << P->getSourceRange();
15390 return;
15391 }
15392 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15393 if (LambdaScopeInfo *LSI = S.getCurLambda())
15394 LSI->ExplicitObjectParameter = P;
15395}
15396
15398 SourceLocation ExplicitThisLoc) {
15399 const DeclSpec &DS = D.getDeclSpec();
15400
15401 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15402 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15403 // except for the special case of a single unnamed parameter of type void
15404 // with no storage class specifier, no type qualifier, and no following
15405 // ellipsis terminator.
15406 // Clang applies the C2y rules for 'register void' in all C language modes,
15407 // same as GCC, because it's questionable what that could possibly mean.
15408
15409 // C++03 [dcl.stc]p2 also permits 'auto'.
15410 StorageClass SC = SC_None;
15412 SC = SC_Register;
15413 // In C++11, the 'register' storage class specifier is deprecated.
15414 // In C++17, it is not allowed, but we tolerate it as an extension.
15415 if (getLangOpts().CPlusPlus11) {
15417 ? diag::ext_register_storage_class
15418 : diag::warn_deprecated_register)
15420 } else if (!getLangOpts().CPlusPlus &&
15422 D.getNumTypeObjects() == 0) {
15424 diag::err_invalid_storage_class_in_func_decl)
15426 D.getMutableDeclSpec().ClearStorageClassSpecs();
15427 }
15428 } else if (getLangOpts().CPlusPlus &&
15430 SC = SC_Auto;
15433 diag::err_invalid_storage_class_in_func_decl);
15434 D.getMutableDeclSpec().ClearStorageClassSpecs();
15435 }
15436
15438 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15440 if (DS.isInlineSpecified())
15441 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15442 << getLangOpts().CPlusPlus17;
15443 if (DS.hasConstexprSpecifier())
15444 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15445 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15446
15448
15450
15452 QualType parmDeclType = TInfo->getType();
15453
15454 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15455 const IdentifierInfo *II = D.getIdentifier();
15456 if (II) {
15457 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15458 RedeclarationKind::ForVisibleRedeclaration);
15459 LookupName(R, S);
15460 if (!R.empty()) {
15461 NamedDecl *PrevDecl = *R.begin();
15462 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15463 // Maybe we will complain about the shadowed template parameter.
15464 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15465 // Just pretend that we didn't see the previous declaration.
15466 PrevDecl = nullptr;
15467 }
15468 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15469 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15470 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15471 // Recover by removing the name
15472 II = nullptr;
15473 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15474 D.setInvalidType(true);
15475 }
15476 }
15477 }
15478
15479 // Temporarily put parameter variables in the translation unit, not
15480 // the enclosing context. This prevents them from accidentally
15481 // looking like class members in C++.
15482 ParmVarDecl *New =
15484 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15485
15486 if (D.isInvalidType())
15487 New->setInvalidDecl();
15488
15489 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15490
15491 assert(S->isFunctionPrototypeScope());
15492 assert(S->getFunctionPrototypeDepth() >= 1);
15493 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15494 S->getNextFunctionPrototypeIndex());
15495
15497
15498 // Add the parameter declaration into this scope.
15499 S->AddDecl(New);
15500 if (II)
15502
15504
15505 if (D.getDeclSpec().isModulePrivateSpecified())
15506 Diag(New->getLocation(), diag::err_module_private_local)
15507 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15508 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15509
15510 if (New->hasAttr<BlocksAttr>()) {
15511 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15512 }
15513
15514 if (getLangOpts().OpenCL)
15516
15517 return New;
15518}
15519
15522 QualType T) {
15523 /* FIXME: setting StartLoc == Loc.
15524 Would it be worth to modify callers so as to provide proper source
15525 location for the unnamed parameters, embedding the parameter's type? */
15526 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15528 SC_None, nullptr);
15529 Param->setImplicit();
15530 return Param;
15531}
15532
15534 // Don't diagnose unused-parameter errors in template instantiations; we
15535 // will already have done so in the template itself.
15537 return;
15538
15539 for (const ParmVarDecl *Parameter : Parameters) {
15540 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15541 !Parameter->hasAttr<UnusedAttr>() &&
15542 !Parameter->getIdentifier()->isPlaceholder()) {
15543 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15544 << Parameter->getDeclName();
15545 }
15546 }
15547}
15548
15550 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15551 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15552 return;
15553
15554 // Warn if the return value is pass-by-value and larger than the specified
15555 // threshold.
15556 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15557 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15558 if (Size > LangOpts.NumLargeByValueCopy)
15559 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15560 }
15561
15562 // Warn if any parameter is pass-by-value and larger than the specified
15563 // threshold.
15564 for (const ParmVarDecl *Parameter : Parameters) {
15565 QualType T = Parameter->getType();
15566 if (T->isDependentType() || !T.isPODType(Context))
15567 continue;
15568 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15569 if (Size > LangOpts.NumLargeByValueCopy)
15570 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15571 << Parameter << Size;
15572 }
15573}
15574
15576 SourceLocation NameLoc,
15577 const IdentifierInfo *Name, QualType T,
15578 TypeSourceInfo *TSInfo, StorageClass SC) {
15579 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15580 if (getLangOpts().ObjCAutoRefCount &&
15581 T.getObjCLifetime() == Qualifiers::OCL_None &&
15582 T->isObjCLifetimeType()) {
15583
15584 Qualifiers::ObjCLifetime lifetime;
15585
15586 // Special cases for arrays:
15587 // - if it's const, use __unsafe_unretained
15588 // - otherwise, it's an error
15589 if (T->isArrayType()) {
15590 if (!T.isConstQualified()) {
15594 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15595 else
15596 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15597 << TSInfo->getTypeLoc().getSourceRange();
15598 }
15600 } else {
15601 lifetime = T->getObjCARCImplicitLifetime();
15602 }
15603 T = Context.getLifetimeQualifiedType(T, lifetime);
15604 }
15605
15606 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15608 TSInfo, SC, nullptr);
15609
15610 // Make a note if we created a new pack in the scope of a lambda, so that
15611 // we know that references to that pack must also be expanded within the
15612 // lambda scope.
15613 if (New->isParameterPack())
15614 if (auto *CSI = getEnclosingLambdaOrBlock())
15615 CSI->LocalPacks.push_back(New);
15616
15617 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15618 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15619 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15622
15623 // Parameter declarators cannot be interface types. All ObjC objects are
15624 // passed by reference.
15625 if (T->isObjCObjectType()) {
15626 SourceLocation TypeEndLoc =
15628 Diag(NameLoc,
15629 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15630 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15632 New->setType(T);
15633 }
15634
15635 // __ptrauth is forbidden on parameters.
15636 if (T.getPointerAuth()) {
15637 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
15638 New->setInvalidDecl();
15639 }
15640
15641 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15642 // duration shall not be qualified by an address-space qualifier."
15643 // Since all parameters have automatic store duration, they can not have
15644 // an address space.
15645 if (T.getAddressSpace() != LangAS::Default &&
15646 // OpenCL allows function arguments declared to be an array of a type
15647 // to be qualified with an address space.
15648 !(getLangOpts().OpenCL &&
15649 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15650 // WebAssembly allows reference types as parameters. Funcref in particular
15651 // lives in a different address space.
15652 !(T->isFunctionPointerType() &&
15653 T.getAddressSpace() == LangAS::wasm_funcref)) {
15654 Diag(NameLoc, diag::err_arg_with_address_space);
15655 New->setInvalidDecl();
15656 }
15657
15658 // PPC MMA non-pointer types are not allowed as function argument types.
15659 if (Context.getTargetInfo().getTriple().isPPC64() &&
15660 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15661 New->setInvalidDecl();
15662 }
15663
15664 return New;
15665}
15666
15668 SourceLocation LocAfterDecls) {
15669 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15670
15671 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15672 // in the declaration list shall have at least one declarator, those
15673 // declarators shall only declare identifiers from the identifier list, and
15674 // every identifier in the identifier list shall be declared.
15675 //
15676 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15677 // identifiers it names shall be declared in the declaration list."
15678 //
15679 // This is why we only diagnose in C99 and later. Note, the other conditions
15680 // listed are checked elsewhere.
15681 if (!FTI.hasPrototype) {
15682 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15683 --i;
15684 if (FTI.Params[i].Param == nullptr) {
15685 if (getLangOpts().C99) {
15686 SmallString<256> Code;
15687 llvm::raw_svector_ostream(Code)
15688 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15689 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15690 << FTI.Params[i].Ident
15691 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15692 }
15693
15694 // Implicitly declare the argument as type 'int' for lack of a better
15695 // type.
15696 AttributeFactory attrs;
15697 DeclSpec DS(attrs);
15698 const char* PrevSpec; // unused
15699 unsigned DiagID; // unused
15700 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15701 DiagID, Context.getPrintingPolicy());
15702 // Use the identifier location for the type source range.
15703 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15704 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15707 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15708 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15709 }
15710 }
15711 }
15712}
15713
15714Decl *
15716 MultiTemplateParamsArg TemplateParameterLists,
15717 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15718 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15719 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15720 Scope *ParentScope = FnBodyScope->getParent();
15721
15722 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15723 // we define a non-templated function definition, we will create a declaration
15724 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15725 // The base function declaration will have the equivalent of an `omp declare
15726 // variant` annotation which specifies the mangled definition as a
15727 // specialization function under the OpenMP context defined as part of the
15728 // `omp begin declare variant`.
15730 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15732 ParentScope, D, TemplateParameterLists, Bases);
15733
15734 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15735 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15736 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15737
15738 if (!Bases.empty())
15740 Bases);
15741
15742 return Dcl;
15743}
15744
15747}
15748
15750 const FunctionDecl *&PossiblePrototype) {
15751 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15752 Prev = Prev->getPreviousDecl()) {
15753 // Ignore any declarations that occur in function or method
15754 // scope, because they aren't visible from the header.
15755 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15756 continue;
15757
15758 PossiblePrototype = Prev;
15759 return Prev->getType()->isFunctionProtoType();
15760 }
15761 return false;
15762}
15763
15764static bool
15766 const FunctionDecl *&PossiblePrototype) {
15767 // Don't warn about invalid declarations.
15768 if (FD->isInvalidDecl())
15769 return false;
15770
15771 // Or declarations that aren't global.
15772 if (!FD->isGlobal())
15773 return false;
15774
15775 // Don't warn about C++ member functions.
15776 if (isa<CXXMethodDecl>(FD))
15777 return false;
15778
15779 // Don't warn about 'main'.
15780 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15781 if (IdentifierInfo *II = FD->getIdentifier())
15782 if (II->isStr("main") || II->isStr("efi_main"))
15783 return false;
15784
15785 if (FD->isMSVCRTEntryPoint())
15786 return false;
15787
15788 // Don't warn about inline functions.
15789 if (FD->isInlined())
15790 return false;
15791
15792 // Don't warn about function templates.
15794 return false;
15795
15796 // Don't warn about function template specializations.
15798 return false;
15799
15800 // Don't warn for OpenCL kernels.
15801 if (FD->hasAttr<DeviceKernelAttr>())
15802 return false;
15803
15804 // Don't warn on explicitly deleted functions.
15805 if (FD->isDeleted())
15806 return false;
15807
15808 // Don't warn on implicitly local functions (such as having local-typed
15809 // parameters).
15810 if (!FD->isExternallyVisible())
15811 return false;
15812
15813 // If we were able to find a potential prototype, don't warn.
15814 if (FindPossiblePrototype(FD, PossiblePrototype))
15815 return false;
15816
15817 return true;
15818}
15819
15820void
15822 const FunctionDecl *EffectiveDefinition,
15823 SkipBodyInfo *SkipBody) {
15824 const FunctionDecl *Definition = EffectiveDefinition;
15825 if (!Definition &&
15826 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15827 return;
15828
15829 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15830 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15831 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15832 // A merged copy of the same function, instantiated as a member of
15833 // the same class, is OK.
15834 if (declaresSameEntity(OrigFD, OrigDef) &&
15835 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15836 cast<Decl>(FD->getLexicalDeclContext())))
15837 return;
15838 }
15839 }
15840 }
15841
15843 return;
15844
15845 // Don't emit an error when this is redefinition of a typo-corrected
15846 // definition.
15848 return;
15849
15850 bool DefinitionVisible = false;
15851 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&
15852 (Definition->getFormalLinkage() == Linkage::Internal ||
15853 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15854 Definition->getNumTemplateParameterLists())) {
15855 SkipBody->ShouldSkip = true;
15856 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15857 if (!DefinitionVisible) {
15858 if (auto *TD = Definition->getDescribedFunctionTemplate())
15861 }
15862 return;
15863 }
15864
15865 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15866 Definition->getStorageClass() == SC_Extern)
15867 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15868 << FD << getLangOpts().CPlusPlus;
15869 else
15870 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15871
15872 Diag(Definition->getLocation(), diag::note_previous_definition);
15873 FD->setInvalidDecl();
15874}
15875
15877 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15878
15880 LSI->CallOperator = CallOperator;
15881 LSI->Lambda = LambdaClass;
15882 LSI->ReturnType = CallOperator->getReturnType();
15883 // When this function is called in situation where the context of the call
15884 // operator is not entered, we set AfterParameterList to false, so that
15885 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15886 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
15887 // where we would set the CurContext to the lambda operator before
15888 // substituting into it. In this case the flag needs to be true such that
15889 // tryCaptureVariable can correctly handle potential captures thereof.
15890 LSI->AfterParameterList = CurContext == CallOperator;
15891
15892 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
15893 // used at the point of dealing with potential captures.
15894 //
15895 // We don't use LambdaClass->isGenericLambda() because this value doesn't
15896 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
15897 // associated. (Technically, we could recover that list from their
15898 // instantiation patterns, but for now, the GLTemplateParameterList seems
15899 // unnecessary in these cases.)
15900 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
15901 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
15902 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15903
15904 if (LCD == LCD_None)
15906 else if (LCD == LCD_ByCopy)
15908 else if (LCD == LCD_ByRef)
15910 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15911
15913 LSI->Mutable = !CallOperator->isConst();
15914 if (CallOperator->isExplicitObjectMemberFunction())
15915 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15916
15917 // Add the captures to the LSI so they can be noted as already
15918 // captured within tryCaptureVar.
15919 auto I = LambdaClass->field_begin();
15920 for (const auto &C : LambdaClass->captures()) {
15921 if (C.capturesVariable()) {
15922 ValueDecl *VD = C.getCapturedVar();
15923 if (VD->isInitCapture())
15925 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15926 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15927 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15928 /*EllipsisLoc*/C.isPackExpansion()
15929 ? C.getEllipsisLoc() : SourceLocation(),
15930 I->getType(), /*Invalid*/false);
15931
15932 } else if (C.capturesThis()) {
15933 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15934 C.getCaptureKind() == LCK_StarThis);
15935 } else {
15936 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15937 I->getType());
15938 }
15939 ++I;
15940 }
15941 return LSI;
15942}
15943
15945 SkipBodyInfo *SkipBody,
15946 FnBodyKind BodyKind) {
15947 if (!D) {
15948 // Parsing the function declaration failed in some way. Push on a fake scope
15949 // anyway so we can try to parse the function body.
15952 return D;
15953 }
15954
15955 FunctionDecl *FD = nullptr;
15956
15957 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15958 FD = FunTmpl->getTemplatedDecl();
15959 else
15960 FD = cast<FunctionDecl>(D);
15961
15962 // Do not push if it is a lambda because one is already pushed when building
15963 // the lambda in ActOnStartOfLambdaDefinition().
15964 if (!isLambdaCallOperator(FD))
15966 FD);
15967
15968 // Check for defining attributes before the check for redefinition.
15969 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15970 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15971 FD->dropAttr<AliasAttr>();
15972 FD->setInvalidDecl();
15973 }
15974 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15975 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15976 FD->dropAttr<IFuncAttr>();
15977 FD->setInvalidDecl();
15978 }
15979 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15980 if (Context.getTargetInfo().getTriple().isAArch64() &&
15981 !Context.getTargetInfo().hasFeature("fmv") &&
15982 !Attr->isDefaultVersion()) {
15983 // If function multi versioning disabled skip parsing function body
15984 // defined with non-default target_version attribute
15985 if (SkipBody)
15986 SkipBody->ShouldSkip = true;
15987 return nullptr;
15988 }
15989 }
15990
15991 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15992 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15993 Ctor->isDefaultConstructor() &&
15995 // If this is an MS ABI dllexport default constructor, instantiate any
15996 // default arguments.
15998 }
15999 }
16000
16001 // See if this is a redefinition. If 'will have body' (or similar) is already
16002 // set, then these checks were already performed when it was set.
16003 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16005 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16006
16007 // If we're skipping the body, we're done. Don't enter the scope.
16008 if (SkipBody && SkipBody->ShouldSkip)
16009 return D;
16010 }
16011
16012 // Mark this function as "will have a body eventually". This lets users to
16013 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16014 // this function.
16015 FD->setWillHaveBody();
16016
16017 // If we are instantiating a generic lambda call operator, push
16018 // a LambdaScopeInfo onto the function stack. But use the information
16019 // that's already been calculated (ActOnLambdaExpr) to prime the current
16020 // LambdaScopeInfo.
16021 // When the template operator is being specialized, the LambdaScopeInfo,
16022 // has to be properly restored so that tryCaptureVariable doesn't try
16023 // and capture any new variables. In addition when calculating potential
16024 // captures during transformation of nested lambdas, it is necessary to
16025 // have the LSI properly restored.
16027 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16028 // instantiated, explicitly specialized.
16031 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
16032 FD->setInvalidDecl();
16034 } else {
16035 assert(inTemplateInstantiation() &&
16036 "There should be an active template instantiation on the stack "
16037 "when instantiating a generic lambda!");
16038 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
16039 }
16040 } else {
16041 // Enter a new function scope
16043 }
16044
16045 // Builtin functions cannot be defined.
16046 if (unsigned BuiltinID = FD->getBuiltinID()) {
16049 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16050 FD->setInvalidDecl();
16051 }
16052 }
16053
16054 // The return type of a function definition must be complete (C99 6.9.1p3).
16055 // C++23 [dcl.fct.def.general]/p2
16056 // The type of [...] the return for a function definition
16057 // shall not be a (possibly cv-qualified) class type that is incomplete
16058 // or abstract within the function body unless the function is deleted.
16059 QualType ResultType = FD->getReturnType();
16060 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16061 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16062 (RequireCompleteType(FD->getLocation(), ResultType,
16063 diag::err_func_def_incomplete_result) ||
16065 diag::err_abstract_type_in_decl,
16067 FD->setInvalidDecl();
16068
16069 if (FnBodyScope)
16070 PushDeclContext(FnBodyScope, FD);
16071
16072 // Check the validity of our function parameters
16073 if (BodyKind != FnBodyKind::Delete)
16075 /*CheckParameterNames=*/true);
16076
16077 // Add non-parameter declarations already in the function to the current
16078 // scope.
16079 if (FnBodyScope) {
16080 for (Decl *NPD : FD->decls()) {
16081 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16082 if (!NonParmDecl)
16083 continue;
16084 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16085 "parameters should not be in newly created FD yet");
16086
16087 // If the decl has a name, make it accessible in the current scope.
16088 if (NonParmDecl->getDeclName())
16089 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16090
16091 // Similarly, dive into enums and fish their constants out, making them
16092 // accessible in this scope.
16093 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16094 for (auto *EI : ED->enumerators())
16095 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16096 }
16097 }
16098 }
16099
16100 // Introduce our parameters into the function scope
16101 for (auto *Param : FD->parameters()) {
16102 Param->setOwningFunction(FD);
16103
16104 // If this has an identifier, add it to the scope stack.
16105 if (Param->getIdentifier() && FnBodyScope) {
16106 CheckShadow(FnBodyScope, Param);
16107
16108 PushOnScopeChains(Param, FnBodyScope);
16109 }
16110 }
16111
16112 // C++ [module.import/6] external definitions are not permitted in header
16113 // units. Deleted and Defaulted functions are implicitly inline (but the
16114 // inline state is not set at this point, so check the BodyKind explicitly).
16115 // FIXME: Consider an alternate location for the test where the inlined()
16116 // state is complete.
16117 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16118 !FD->isInvalidDecl() && !FD->isInlined() &&
16119 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16120 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16121 !FD->isTemplateInstantiation()) {
16122 assert(FD->isThisDeclarationADefinition());
16123 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16124 FD->setInvalidDecl();
16125 }
16126
16127 // Ensure that the function's exception specification is instantiated.
16128 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16130
16131 // dllimport cannot be applied to non-inline function definitions.
16132 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16133 !FD->isTemplateInstantiation()) {
16134 assert(!FD->hasAttr<DLLExportAttr>());
16135 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16136 FD->setInvalidDecl();
16137 return D;
16138 }
16139
16140 // Some function attributes (like OptimizeNoneAttr) need actions before
16141 // parsing body started.
16143
16144 // We want to attach documentation to original Decl (which might be
16145 // a function template).
16147 if (getCurLexicalContext()->isObjCContainer() &&
16148 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16149 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16150 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16151
16153
16154 return D;
16155}
16156
16158 if (!FD || FD->isInvalidDecl())
16159 return;
16160 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16161 FD = TD->getTemplatedDecl();
16162 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16166 FpPragmaStack.CurrentValue =
16168 }
16169}
16170
16172 ReturnStmt **Returns = Scope->Returns.data();
16173
16174 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16175 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16176 if (!NRVOCandidate->isNRVOVariable()) {
16177 Diag(Returns[I]->getRetValue()->getExprLoc(),
16178 diag::warn_not_eliding_copy_on_return);
16179 Returns[I]->setNRVOCandidate(nullptr);
16180 }
16181 }
16182 }
16183}
16184
16186 // We can't delay parsing the body of a constexpr function template (yet).
16187 if (D.getDeclSpec().hasConstexprSpecifier())
16188 return false;
16189
16190 // We can't delay parsing the body of a function template with a deduced
16191 // return type (yet).
16192 if (D.getDeclSpec().hasAutoTypeSpec()) {
16193 // If the placeholder introduces a non-deduced trailing return type,
16194 // we can still delay parsing it.
16195 if (D.getNumTypeObjects()) {
16196 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16197 if (Outer.Kind == DeclaratorChunk::Function &&
16198 Outer.Fun.hasTrailingReturnType()) {
16199 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16200 return Ty.isNull() || !Ty->isUndeducedType();
16201 }
16202 }
16203 return false;
16204 }
16205
16206 return true;
16207}
16208
16210 // We cannot skip the body of a function (or function template) which is
16211 // constexpr, since we may need to evaluate its body in order to parse the
16212 // rest of the file.
16213 // We cannot skip the body of a function with an undeduced return type,
16214 // because any callers of that function need to know the type.
16215 if (const FunctionDecl *FD = D->getAsFunction()) {
16216 if (FD->isConstexpr())
16217 return false;
16218 // We can't simply call Type::isUndeducedType here, because inside template
16219 // auto can be deduced to a dependent type, which is not considered
16220 // "undeduced".
16221 if (FD->getReturnType()->getContainedDeducedType())
16222 return false;
16223 }
16225}
16226
16228 if (!Decl)
16229 return nullptr;
16230 if (FunctionDecl *FD = Decl->getAsFunction())
16231 FD->setHasSkippedBody();
16232 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16233 MD->setHasSkippedBody();
16234 return Decl;
16235}
16236
16237/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16238/// body.
16240public:
16241 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16243 if (!IsLambda)
16245 }
16246
16247private:
16248 Sema &S;
16249 bool IsLambda = false;
16250};
16251
16253 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16254
16255 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16256 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16257 if (!Inserted)
16258 return It->second;
16259
16260 bool R = false;
16261 const BlockDecl *CurBD = BD;
16262
16263 do {
16264 R = !CurBD->doesNotEscape();
16265 if (R)
16266 break;
16267 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16268 } while (CurBD);
16269
16270 return It->second = R;
16271 };
16272
16273 // If the location where 'self' is implicitly retained is inside a escaping
16274 // block, emit a diagnostic.
16275 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16277 if (IsOrNestedInEscapingBlock(P.second))
16278 S.Diag(P.first, diag::warn_implicitly_retains_self)
16279 << FixItHint::CreateInsertion(P.first, "self->");
16280}
16281
16282static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16283 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16284 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16285}
16286
16288 return methodHasName(FD, "get_return_object");
16289}
16290
16292 return FD->isStatic() &&
16293 methodHasName(FD, "get_return_object_on_allocation_failure");
16294}
16295
16298 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16299 return;
16300 // Allow some_promise_type::get_return_object().
16302 return;
16303 if (!FD->hasAttr<CoroWrapperAttr>())
16304 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16305}
16306
16307Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16308 bool RetainFunctionScopeInfo) {
16310 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16311
16312 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16313 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16314
16315 SourceLocation AnalysisLoc;
16316 if (Body)
16317 AnalysisLoc = Body->getEndLoc();
16318 else if (FD)
16319 AnalysisLoc = FD->getEndLoc();
16322 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16323
16324 // If we skip function body, we can't tell if a function is a coroutine.
16325 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16326 if (FSI->isCoroutine())
16328 else
16330 }
16331
16332 // Diagnose invalid SYCL kernel entry point function declarations
16333 // and build SYCLKernelCallStmts for valid ones.
16334 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16335 SYCLKernelEntryPointAttr *SKEPAttr =
16336 FD->getAttr<SYCLKernelEntryPointAttr>();
16337 if (FD->isDefaulted()) {
16338 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16339 << SKEPAttr << /*defaulted function*/ 3;
16340 SKEPAttr->setInvalidAttr();
16341 } else if (FD->isDeleted()) {
16342 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16343 << SKEPAttr << /*deleted function*/ 2;
16344 SKEPAttr->setInvalidAttr();
16345 } else if (FSI->isCoroutine()) {
16346 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16347 << SKEPAttr << /*coroutine*/ 7;
16348 SKEPAttr->setInvalidAttr();
16349 } else if (Body && isa<CXXTryStmt>(Body)) {
16350 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16351 << SKEPAttr << /*function defined with a function try block*/ 8;
16352 SKEPAttr->setInvalidAttr();
16353 }
16354
16355 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
16356 StmtResult SR =
16357 SYCL().BuildSYCLKernelCallStmt(FD, cast<CompoundStmt>(Body));
16358 if (SR.isInvalid())
16359 return nullptr;
16360 Body = SR.get();
16361 }
16362 }
16363
16364 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16365 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16366 if (FD->isDeletedAsWritten())
16367 Diag(SEAttr->getLocation(),
16368 diag::err_sycl_external_invalid_deleted_function)
16369 << SEAttr;
16370 }
16371
16372 {
16373 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16374 // one is already popped when finishing the lambda in BuildLambdaExpr().
16375 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16376 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16377 if (FD) {
16378 // The function body and the DefaultedOrDeletedInfo, if present, use
16379 // the same storage; don't overwrite the latter if the former is null
16380 // (the body is initialised to null anyway, so even if the latter isn't
16381 // present, this would still be a no-op).
16382 if (Body)
16383 FD->setBody(Body);
16384 FD->setWillHaveBody(false);
16385
16386 if (getLangOpts().CPlusPlus14) {
16387 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16388 FD->getReturnType()->isUndeducedType()) {
16389 // For a function with a deduced result type to return void,
16390 // the result type as written must be 'auto' or 'decltype(auto)',
16391 // possibly cv-qualified or constrained, but not ref-qualified.
16392 if (!FD->getReturnType()->getAs<AutoType>()) {
16393 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16394 << FD->getReturnType();
16395 FD->setInvalidDecl();
16396 } else {
16397 // Falling off the end of the function is the same as 'return;'.
16398 Expr *Dummy = nullptr;
16400 FD, dcl->getLocation(), Dummy,
16401 FD->getReturnType()->getAs<AutoType>()))
16402 FD->setInvalidDecl();
16403 }
16404 }
16405 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16406 // In C++11, we don't use 'auto' deduction rules for lambda call
16407 // operators because we don't support return type deduction.
16408 auto *LSI = getCurLambda();
16409 if (LSI->HasImplicitReturnType) {
16411
16412 // C++11 [expr.prim.lambda]p4:
16413 // [...] if there are no return statements in the compound-statement
16414 // [the deduced type is] the type void
16415 QualType RetType =
16416 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16417
16418 // Update the return type to the deduced type.
16419 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16420 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16421 Proto->getExtProtoInfo()));
16422 }
16423 }
16424
16425 // If the function implicitly returns zero (like 'main') or is naked,
16426 // don't complain about missing return statements.
16427 // Clang implicitly returns 0 in C89 mode, but that's considered an
16428 // extension. The check is necessary to ensure the expected extension
16429 // warning is emitted in C89 mode.
16430 if ((FD->hasImplicitReturnZero() &&
16431 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16432 FD->hasAttr<NakedAttr>())
16434
16435 // MSVC permits the use of pure specifier (=0) on function definition,
16436 // defined at class scope, warn about this non-standard construct.
16437 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16438 !FD->isOutOfLine())
16439 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16440
16441 if (!FD->isInvalidDecl()) {
16442 // Don't diagnose unused parameters of defaulted, deleted or naked
16443 // functions.
16444 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16445 !FD->hasAttr<NakedAttr>())
16448 FD->getReturnType(), FD);
16449
16450 // If this is a structor, we need a vtable.
16451 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16452 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16453 else if (CXXDestructorDecl *Destructor =
16454 dyn_cast<CXXDestructorDecl>(FD))
16455 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16456
16457 // Try to apply the named return value optimization. We have to check
16458 // if we can do this here because lambdas keep return statements around
16459 // to deduce an implicit return type.
16460 if (FD->getReturnType()->isRecordType() &&
16462 computeNRVO(Body, FSI);
16463 }
16464
16465 // GNU warning -Wmissing-prototypes:
16466 // Warn if a global function is defined without a previous
16467 // prototype declaration. This warning is issued even if the
16468 // definition itself provides a prototype. The aim is to detect
16469 // global functions that fail to be declared in header files.
16470 const FunctionDecl *PossiblePrototype = nullptr;
16471 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16472 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16473
16474 if (PossiblePrototype) {
16475 // We found a declaration that is not a prototype,
16476 // but that could be a zero-parameter prototype
16477 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16478 TypeLoc TL = TI->getTypeLoc();
16480 Diag(PossiblePrototype->getLocation(),
16481 diag::note_declaration_not_a_prototype)
16482 << (FD->getNumParams() != 0)
16484 FTL.getRParenLoc(), "void")
16485 : FixItHint{});
16486 }
16487 } else {
16488 // Returns true if the token beginning at this Loc is `const`.
16489 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16490 const LangOptions &LangOpts) {
16491 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16492 if (LocInfo.first.isInvalid())
16493 return false;
16494
16495 bool Invalid = false;
16496 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16497 if (Invalid)
16498 return false;
16499
16500 if (LocInfo.second > Buffer.size())
16501 return false;
16502
16503 const char *LexStart = Buffer.data() + LocInfo.second;
16504 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16505
16506 return StartTok.consume_front("const") &&
16507 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16508 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16509 };
16510
16511 auto findBeginLoc = [&]() {
16512 // If the return type has `const` qualifier, we want to insert
16513 // `static` before `const` (and not before the typename).
16514 if ((FD->getReturnType()->isAnyPointerType() &&
16517 // But only do this if we can determine where the `const` is.
16518
16519 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16520 getLangOpts()))
16521
16522 return FD->getBeginLoc();
16523 }
16524 return FD->getTypeSpecStartLoc();
16525 };
16527 diag::note_static_for_internal_linkage)
16528 << /* function */ 1
16529 << (FD->getStorageClass() == SC_None
16530 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16531 : FixItHint{});
16532 }
16533 }
16534
16535 // We might not have found a prototype because we didn't wish to warn on
16536 // the lack of a missing prototype. Try again without the checks for
16537 // whether we want to warn on the missing prototype.
16538 if (!PossiblePrototype)
16539 (void)FindPossiblePrototype(FD, PossiblePrototype);
16540
16541 // If the function being defined does not have a prototype, then we may
16542 // need to diagnose it as changing behavior in C23 because we now know
16543 // whether the function accepts arguments or not. This only handles the
16544 // case where the definition has no prototype but does have parameters
16545 // and either there is no previous potential prototype, or the previous
16546 // potential prototype also has no actual prototype. This handles cases
16547 // like:
16548 // void f(); void f(a) int a; {}
16549 // void g(a) int a; {}
16550 // See MergeFunctionDecl() for other cases of the behavior change
16551 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16552 // type without a prototype.
16553 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16554 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16555 !PossiblePrototype->isImplicit()))) {
16556 // The function definition has parameters, so this will change behavior
16557 // in C23. If there is a possible prototype, it comes before the
16558 // function definition.
16559 // FIXME: The declaration may have already been diagnosed as being
16560 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16561 // there's no way to test for the "changes behavior" condition in
16562 // SemaType.cpp when forming the declaration's function type. So, we do
16563 // this awkward dance instead.
16564 //
16565 // If we have a possible prototype and it declares a function with a
16566 // prototype, we don't want to diagnose it; if we have a possible
16567 // prototype and it has no prototype, it may have already been
16568 // diagnosed in SemaType.cpp as deprecated depending on whether
16569 // -Wstrict-prototypes is enabled. If we already warned about it being
16570 // deprecated, add a note that it also changes behavior. If we didn't
16571 // warn about it being deprecated (because the diagnostic is not
16572 // enabled), warn now that it is deprecated and changes behavior.
16573
16574 // This K&R C function definition definitely changes behavior in C23,
16575 // so diagnose it.
16576 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16577 << /*definition*/ 1 << /* not supported in C23 */ 0;
16578
16579 // If we have a possible prototype for the function which is a user-
16580 // visible declaration, we already tested that it has no prototype.
16581 // This will change behavior in C23. This gets a warning rather than a
16582 // note because it's the same behavior-changing problem as with the
16583 // definition.
16584 if (PossiblePrototype)
16585 Diag(PossiblePrototype->getLocation(),
16586 diag::warn_non_prototype_changes_behavior)
16587 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16588 << /*definition*/ 1;
16589 }
16590
16591 // Warn on CPUDispatch with an actual body.
16592 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16593 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16594 if (!CmpndBody->body_empty())
16595 Diag(CmpndBody->body_front()->getBeginLoc(),
16596 diag::warn_dispatch_body_ignored);
16597
16598 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16599 const CXXMethodDecl *KeyFunction;
16600 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16601 MD->isVirtual() &&
16602 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16603 MD == KeyFunction->getCanonicalDecl()) {
16604 // Update the key-function state if necessary for this ABI.
16605 if (FD->isInlined() &&
16608
16609 // If the newly-chosen key function is already defined, then we
16610 // need to mark the vtable as used retroactively.
16611 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16612 const FunctionDecl *Definition;
16613 if (KeyFunction && KeyFunction->isDefined(Definition))
16614 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16615 } else {
16616 // We just defined they key function; mark the vtable as used.
16617 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16618 }
16619 }
16620 }
16621
16622 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16623 "Function parsing confused");
16624 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16625 assert(MD == getCurMethodDecl() && "Method parsing confused");
16626 MD->setBody(Body);
16627 if (!MD->isInvalidDecl()) {
16629 MD->getReturnType(), MD);
16630
16631 if (Body)
16632 computeNRVO(Body, FSI);
16633 }
16634 if (FSI->ObjCShouldCallSuper) {
16635 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16636 << MD->getSelector().getAsString();
16637 FSI->ObjCShouldCallSuper = false;
16638 }
16640 const ObjCMethodDecl *InitMethod = nullptr;
16641 bool isDesignated =
16642 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16643 assert(isDesignated && InitMethod);
16644 (void)isDesignated;
16645
16646 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16647 auto IFace = MD->getClassInterface();
16648 if (!IFace)
16649 return false;
16650 auto SuperD = IFace->getSuperClass();
16651 if (!SuperD)
16652 return false;
16653 return SuperD->getIdentifier() ==
16654 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16655 };
16656 // Don't issue this warning for unavailable inits or direct subclasses
16657 // of NSObject.
16658 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16659 Diag(MD->getLocation(),
16660 diag::warn_objc_designated_init_missing_super_call);
16661 Diag(InitMethod->getLocation(),
16662 diag::note_objc_designated_init_marked_here);
16663 }
16665 }
16666 if (FSI->ObjCWarnForNoInitDelegation) {
16667 // Don't issue this warning for unavailable inits.
16668 if (!MD->isUnavailable())
16669 Diag(MD->getLocation(),
16670 diag::warn_objc_secondary_init_missing_init_call);
16671 FSI->ObjCWarnForNoInitDelegation = false;
16672 }
16673
16675 } else {
16676 // Parsing the function declaration failed in some way. Pop the fake scope
16677 // we pushed on.
16678 PopFunctionScopeInfo(ActivePolicy, dcl);
16679 return nullptr;
16680 }
16681
16682 if (Body && FSI->HasPotentialAvailabilityViolations)
16684
16685 assert(!FSI->ObjCShouldCallSuper &&
16686 "This should only be set for ObjC methods, which should have been "
16687 "handled in the block above.");
16688
16689 // Verify and clean out per-function state.
16690 if (Body && (!FD || !FD->isDefaulted())) {
16691 // C++ constructors that have function-try-blocks can't have return
16692 // statements in the handlers of that block. (C++ [except.handle]p14)
16693 // Verify this.
16694 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16695 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16696
16697 // Verify that gotos and switch cases don't jump into scopes illegally.
16700
16701 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16702 if (!Destructor->getParent()->isDependentType())
16704
16706 Destructor->getParent());
16707 }
16708
16709 // If any errors have occurred, clear out any temporaries that may have
16710 // been leftover. This ensures that these temporaries won't be picked up
16711 // for deletion in some later function.
16714 getDiagnostics().getSuppressAllDiagnostics()) {
16716 }
16717 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16718 // Since the body is valid, issue any analysis-based warnings that are
16719 // enabled.
16720 ActivePolicy = &WP;
16721 }
16722
16723 if (!IsInstantiation && FD &&
16724 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16725 !FD->isInvalidDecl() &&
16727 FD->setInvalidDecl();
16728
16729 if (FD && FD->hasAttr<NakedAttr>()) {
16730 for (const Stmt *S : Body->children()) {
16731 // Allow local register variables without initializer as they don't
16732 // require prologue.
16733 bool RegisterVariables = false;
16734 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16735 for (const auto *Decl : DS->decls()) {
16736 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16737 RegisterVariables =
16738 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16739 if (!RegisterVariables)
16740 break;
16741 }
16742 }
16743 }
16744 if (RegisterVariables)
16745 continue;
16746 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16747 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16748 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16749 FD->setInvalidDecl();
16750 break;
16751 }
16752 }
16753 }
16754
16755 assert(ExprCleanupObjects.size() ==
16756 ExprEvalContexts.back().NumCleanupObjects &&
16757 "Leftover temporaries in function");
16758 assert(!Cleanup.exprNeedsCleanups() &&
16759 "Unaccounted cleanups in function");
16760 assert(MaybeODRUseExprs.empty() &&
16761 "Leftover expressions for odr-use checking");
16762 }
16763 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16764 // the declaration context below. Otherwise, we're unable to transform
16765 // 'this' expressions when transforming immediate context functions.
16766
16767 if (FD)
16769
16770 if (!IsInstantiation)
16772
16773 if (!RetainFunctionScopeInfo)
16774 PopFunctionScopeInfo(ActivePolicy, dcl);
16775 // If any errors have occurred, clear out any temporaries that may have
16776 // been leftover. This ensures that these temporaries won't be picked up for
16777 // deletion in some later function.
16780 }
16781
16782 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
16783 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
16784 auto ES = getEmissionStatus(FD);
16788 }
16789
16790 if (FD && !FD->isDeleted())
16791 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16792
16793 return dcl;
16794}
16795
16796/// When we finish delayed parsing of an attribute, we must attach it to the
16797/// relevant Decl.
16799 ParsedAttributes &Attrs) {
16800 // Always attach attributes to the underlying decl.
16801 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16802 D = TD->getTemplatedDecl();
16803 ProcessDeclAttributeList(S, D, Attrs);
16805
16806 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16807 if (Method->isStatic())
16809}
16810
16812 IdentifierInfo &II, Scope *S) {
16813 // It is not valid to implicitly define a function in C23.
16815 "Implicit function declarations aren't allowed in this language mode");
16816
16817 // Find the scope in which the identifier is injected and the corresponding
16818 // DeclContext.
16819 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16820 // In that case, we inject the declaration into the translation unit scope
16821 // instead.
16822 Scope *BlockScope = S;
16823 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16824 BlockScope = BlockScope->getParent();
16825
16826 // Loop until we find a DeclContext that is either a function/method or the
16827 // translation unit, which are the only two valid places to implicitly define
16828 // a function. This avoids accidentally defining the function within a tag
16829 // declaration, for example.
16830 Scope *ContextScope = BlockScope;
16831 while (!ContextScope->getEntity() ||
16832 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16833 !ContextScope->getEntity()->isTranslationUnit()))
16834 ContextScope = ContextScope->getParent();
16835 ContextRAII SavedContext(*this, ContextScope->getEntity());
16836
16837 // Before we produce a declaration for an implicitly defined
16838 // function, see whether there was a locally-scoped declaration of
16839 // this name as a function or variable. If so, use that
16840 // (non-visible) declaration, and complain about it.
16841 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16842 if (ExternCPrev) {
16843 // We still need to inject the function into the enclosing block scope so
16844 // that later (non-call) uses can see it.
16845 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16846
16847 // C89 footnote 38:
16848 // If in fact it is not defined as having type "function returning int",
16849 // the behavior is undefined.
16850 if (!isa<FunctionDecl>(ExternCPrev) ||
16852 cast<FunctionDecl>(ExternCPrev)->getType(),
16854 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16855 << ExternCPrev << !getLangOpts().C99;
16856 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16857 return ExternCPrev;
16858 }
16859 }
16860
16861 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16862 unsigned diag_id;
16863 if (II.getName().starts_with("__builtin_"))
16864 diag_id = diag::warn_builtin_unknown;
16865 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16866 else if (getLangOpts().C99)
16867 diag_id = diag::ext_implicit_function_decl_c99;
16868 else
16869 diag_id = diag::warn_implicit_function_decl;
16870
16871 TypoCorrection Corrected;
16872 // Because typo correction is expensive, only do it if the implicit
16873 // function declaration is going to be treated as an error.
16874 //
16875 // Perform the correction before issuing the main diagnostic, as some
16876 // consumers use typo-correction callbacks to enhance the main diagnostic.
16877 if (S && !ExternCPrev &&
16881 S, nullptr, CCC, CorrectTypoKind::NonError);
16882 }
16883
16884 Diag(Loc, diag_id) << &II;
16885 if (Corrected) {
16886 // If the correction is going to suggest an implicitly defined function,
16887 // skip the correction as not being a particularly good idea.
16888 bool Diagnose = true;
16889 if (const auto *D = Corrected.getCorrectionDecl())
16890 Diagnose = !D->isImplicit();
16891 if (Diagnose)
16892 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16893 /*ErrorRecovery*/ false);
16894 }
16895
16896 // If we found a prior declaration of this function, don't bother building
16897 // another one. We've already pushed that one into scope, so there's nothing
16898 // more to do.
16899 if (ExternCPrev)
16900 return ExternCPrev;
16901
16902 // Set a Declarator for the implicit definition: int foo();
16903 const char *Dummy;
16904 AttributeFactory attrFactory;
16905 DeclSpec DS(attrFactory);
16906 unsigned DiagID;
16907 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16909 (void)Error; // Silence warning.
16910 assert(!Error && "Error setting up implicit decl!");
16911 SourceLocation NoLoc;
16913 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16914 /*IsAmbiguous=*/false,
16915 /*LParenLoc=*/NoLoc,
16916 /*Params=*/nullptr,
16917 /*NumParams=*/0,
16918 /*EllipsisLoc=*/NoLoc,
16919 /*RParenLoc=*/NoLoc,
16920 /*RefQualifierIsLvalueRef=*/true,
16921 /*RefQualifierLoc=*/NoLoc,
16922 /*MutableLoc=*/NoLoc, EST_None,
16923 /*ESpecRange=*/SourceRange(),
16924 /*Exceptions=*/nullptr,
16925 /*ExceptionRanges=*/nullptr,
16926 /*NumExceptions=*/0,
16927 /*NoexceptExpr=*/nullptr,
16928 /*ExceptionSpecTokens=*/nullptr,
16929 /*DeclsInPrototype=*/{}, Loc, Loc,
16930 D),
16931 std::move(DS.getAttributes()), SourceLocation());
16932 D.SetIdentifier(&II, Loc);
16933
16934 // Insert this function into the enclosing block scope.
16935 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16936 FD->setImplicit();
16937
16939
16940 return FD;
16941}
16942
16944 FunctionDecl *FD) {
16945 if (FD->isInvalidDecl())
16946 return;
16947
16948 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16949 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16950 return;
16951
16952 UnsignedOrNone AlignmentParam = std::nullopt;
16953 bool IsNothrow = false;
16954 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16955 return;
16956
16957 // C++2a [basic.stc.dynamic.allocation]p4:
16958 // An allocation function that has a non-throwing exception specification
16959 // indicates failure by returning a null pointer value. Any other allocation
16960 // function never returns a null pointer value and indicates failure only by
16961 // throwing an exception [...]
16962 //
16963 // However, -fcheck-new invalidates this possible assumption, so don't add
16964 // NonNull when that is enabled.
16965 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16966 !getLangOpts().CheckNew)
16967 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16968
16969 // C++2a [basic.stc.dynamic.allocation]p2:
16970 // An allocation function attempts to allocate the requested amount of
16971 // storage. [...] If the request succeeds, the value returned by a
16972 // replaceable allocation function is a [...] pointer value p0 different
16973 // from any previously returned value p1 [...]
16974 //
16975 // However, this particular information is being added in codegen,
16976 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16977
16978 // C++2a [basic.stc.dynamic.allocation]p2:
16979 // An allocation function attempts to allocate the requested amount of
16980 // storage. If it is successful, it returns the address of the start of a
16981 // block of storage whose length in bytes is at least as large as the
16982 // requested size.
16983 if (!FD->hasAttr<AllocSizeAttr>()) {
16984 FD->addAttr(AllocSizeAttr::CreateImplicit(
16985 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16986 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16987 }
16988
16989 // C++2a [basic.stc.dynamic.allocation]p3:
16990 // For an allocation function [...], the pointer returned on a successful
16991 // call shall represent the address of storage that is aligned as follows:
16992 // (3.1) If the allocation function takes an argument of type
16993 // std​::​align_­val_­t, the storage will have the alignment
16994 // specified by the value of this argument.
16995 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16996 FD->addAttr(AllocAlignAttr::CreateImplicit(
16997 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16998 }
16999
17000 // FIXME:
17001 // C++2a [basic.stc.dynamic.allocation]p3:
17002 // For an allocation function [...], the pointer returned on a successful
17003 // call shall represent the address of storage that is aligned as follows:
17004 // (3.2) Otherwise, if the allocation function is named operator new[],
17005 // the storage is aligned for any object that does not have
17006 // new-extended alignment ([basic.align]) and is no larger than the
17007 // requested size.
17008 // (3.3) Otherwise, the storage is aligned for any object that does not
17009 // have new-extended alignment and is of the requested size.
17010}
17011
17013 if (FD->isInvalidDecl())
17014 return;
17015
17016 // If this is a built-in function, map its builtin attributes to
17017 // actual attributes.
17018 if (unsigned BuiltinID = FD->getBuiltinID()) {
17019 // Handle printf-formatting attributes.
17020 unsigned FormatIdx;
17021 bool HasVAListArg;
17022 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17023 if (!FD->hasAttr<FormatAttr>()) {
17024 const char *fmt = "printf";
17025 unsigned int NumParams = FD->getNumParams();
17026 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17027 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17028 fmt = "NSString";
17029 FD->addAttr(FormatAttr::CreateImplicit(Context,
17030 &Context.Idents.get(fmt),
17031 FormatIdx+1,
17032 HasVAListArg ? 0 : FormatIdx+2,
17033 FD->getLocation()));
17034 }
17035 }
17036 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17037 HasVAListArg)) {
17038 if (!FD->hasAttr<FormatAttr>())
17039 FD->addAttr(FormatAttr::CreateImplicit(Context,
17040 &Context.Idents.get("scanf"),
17041 FormatIdx+1,
17042 HasVAListArg ? 0 : FormatIdx+2,
17043 FD->getLocation()));
17044 }
17045
17046 // Handle automatically recognized callbacks.
17047 SmallVector<int, 4> Encoding;
17048 if (!FD->hasAttr<CallbackAttr>() &&
17049 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17050 FD->addAttr(CallbackAttr::CreateImplicit(
17051 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17052
17053 // Mark const if we don't care about errno and/or floating point exceptions
17054 // that are the only thing preventing the function from being const. This
17055 // allows IRgen to use LLVM intrinsics for such functions.
17056 bool NoExceptions =
17058 bool ConstWithoutErrnoAndExceptions =
17060 bool ConstWithoutExceptions =
17062 if (!FD->hasAttr<ConstAttr>() &&
17063 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17064 (!ConstWithoutErrnoAndExceptions ||
17065 (!getLangOpts().MathErrno && NoExceptions)) &&
17066 (!ConstWithoutExceptions || NoExceptions))
17067 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17068
17069 // We make "fma" on GNU or Windows const because we know it does not set
17070 // errno in those environments even though it could set errno based on the
17071 // C standard.
17072 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17073 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17074 !FD->hasAttr<ConstAttr>()) {
17075 switch (BuiltinID) {
17076 case Builtin::BI__builtin_fma:
17077 case Builtin::BI__builtin_fmaf:
17078 case Builtin::BI__builtin_fmal:
17079 case Builtin::BIfma:
17080 case Builtin::BIfmaf:
17081 case Builtin::BIfmal:
17082 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17083 break;
17084 default:
17085 break;
17086 }
17087 }
17088
17089 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17090 !FD->hasAttr<ReturnsTwiceAttr>())
17091 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17092 FD->getLocation()));
17093 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17094 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17095 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17096 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17097 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17098 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17099 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17100 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17101 // Add the appropriate attribute, depending on the CUDA compilation mode
17102 // and which target the builtin belongs to. For example, during host
17103 // compilation, aux builtins are __device__, while the rest are __host__.
17104 if (getLangOpts().CUDAIsDevice !=
17106 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17107 else
17108 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17109 }
17110
17111 // Add known guaranteed alignment for allocation functions.
17112 switch (BuiltinID) {
17113 case Builtin::BImemalign:
17114 case Builtin::BIaligned_alloc:
17115 if (!FD->hasAttr<AllocAlignAttr>())
17116 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17117 FD->getLocation()));
17118 break;
17119 default:
17120 break;
17121 }
17122
17123 // Add allocsize attribute for allocation functions.
17124 switch (BuiltinID) {
17125 case Builtin::BIcalloc:
17126 FD->addAttr(AllocSizeAttr::CreateImplicit(
17127 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17128 break;
17129 case Builtin::BImemalign:
17130 case Builtin::BIaligned_alloc:
17131 case Builtin::BIrealloc:
17132 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17133 ParamIdx(), FD->getLocation()));
17134 break;
17135 case Builtin::BImalloc:
17136 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17137 ParamIdx(), FD->getLocation()));
17138 break;
17139 default:
17140 break;
17141 }
17142 }
17143
17148
17149 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17150 // throw, add an implicit nothrow attribute to any extern "C" function we come
17151 // across.
17152 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17153 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17154 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17155 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17156 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17157 }
17158
17159 IdentifierInfo *Name = FD->getIdentifier();
17160 if (!Name)
17161 return;
17163 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
17164 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17166 // Okay: this could be a libc/libm/Objective-C function we know
17167 // about.
17168 } else
17169 return;
17170
17171 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17172 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17173 // target-specific builtins, perhaps?
17174 if (!FD->hasAttr<FormatAttr>())
17175 FD->addAttr(FormatAttr::CreateImplicit(Context,
17176 &Context.Idents.get("printf"), 2,
17177 Name->isStr("vasprintf") ? 0 : 3,
17178 FD->getLocation()));
17179 }
17180
17181 if (Name->isStr("__CFStringMakeConstantString")) {
17182 // We already have a __builtin___CFStringMakeConstantString,
17183 // but builds that use -fno-constant-cfstrings don't go through that.
17184 if (!FD->hasAttr<FormatArgAttr>())
17185 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17186 FD->getLocation()));
17187 }
17188}
17189
17191 TypeSourceInfo *TInfo) {
17192 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17193 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17194
17195 if (!TInfo) {
17196 assert(D.isInvalidType() && "no declarator info for valid type");
17198 }
17199
17200 // Scope manipulation handled by caller.
17201 TypedefDecl *NewTD =
17203 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17204
17205 // Bail out immediately if we have an invalid declaration.
17206 if (D.isInvalidType()) {
17207 NewTD->setInvalidDecl();
17208 return NewTD;
17209 }
17210
17211 if (D.getDeclSpec().isModulePrivateSpecified()) {
17213 Diag(NewTD->getLocation(), diag::err_module_private_local)
17214 << 2 << NewTD
17215 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17217 D.getDeclSpec().getModulePrivateSpecLoc());
17218 else
17219 NewTD->setModulePrivate();
17220 }
17221
17222 // C++ [dcl.typedef]p8:
17223 // If the typedef declaration defines an unnamed class (or
17224 // enum), the first typedef-name declared by the declaration
17225 // to be that class type (or enum type) is used to denote the
17226 // class type (or enum type) for linkage purposes only.
17227 // We need to check whether the type was declared in the declaration.
17228 switch (D.getDeclSpec().getTypeSpecType()) {
17229 case TST_enum:
17230 case TST_struct:
17231 case TST_interface:
17232 case TST_union:
17233 case TST_class: {
17234 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17235 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17236 break;
17237 }
17238
17239 default:
17240 break;
17241 }
17242
17243 return NewTD;
17244}
17245
17247 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17248 QualType T = TI->getType();
17249
17250 if (T->isDependentType())
17251 return false;
17252
17253 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17254 // integral type; any cv-qualification is ignored.
17255 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17256 // non-atomic version of the type specified by the type specifiers in the
17257 // specifier qualifier list.
17258 // Because of how odd C's rule is, we'll let the user know that operations
17259 // involving the enumeration type will be non-atomic.
17260 if (T->isAtomicType())
17261 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17262
17263 Qualifiers Q = T.getQualifiers();
17264 std::optional<unsigned> QualSelect;
17265 if (Q.hasConst() && Q.hasVolatile())
17266 QualSelect = diag::CVQualList::Both;
17267 else if (Q.hasConst())
17268 QualSelect = diag::CVQualList::Const;
17269 else if (Q.hasVolatile())
17270 QualSelect = diag::CVQualList::Volatile;
17271
17272 if (QualSelect)
17273 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17274
17275 T = T.getAtomicUnqualifiedType();
17276
17277 // This doesn't use 'isIntegralType' despite the error message mentioning
17278 // integral type because isIntegralType would also allow enum types in C.
17279 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17280 if (BT->isInteger())
17281 return false;
17282
17283 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17284 << T << T->isBitIntType();
17285}
17286
17288 QualType EnumUnderlyingTy, bool IsFixed,
17289 const EnumDecl *Prev) {
17290 if (IsScoped != Prev->isScoped()) {
17291 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17292 << Prev->isScoped();
17293 Diag(Prev->getLocation(), diag::note_previous_declaration);
17294 return true;
17295 }
17296
17297 if (IsFixed && Prev->isFixed()) {
17298 if (!EnumUnderlyingTy->isDependentType() &&
17299 !Prev->getIntegerType()->isDependentType() &&
17300 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17301 Prev->getIntegerType())) {
17302 // TODO: Highlight the underlying type of the redeclaration.
17303 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17304 << EnumUnderlyingTy << Prev->getIntegerType();
17305 Diag(Prev->getLocation(), diag::note_previous_declaration)
17306 << Prev->getIntegerTypeRange();
17307 return true;
17308 }
17309 } else if (IsFixed != Prev->isFixed()) {
17310 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17311 << Prev->isFixed();
17312 Diag(Prev->getLocation(), diag::note_previous_declaration);
17313 return true;
17314 }
17315
17316 return false;
17317}
17318
17319/// Get diagnostic %select index for tag kind for
17320/// redeclaration diagnostic message.
17321/// WARNING: Indexes apply to particular diagnostics only!
17322///
17323/// \returns diagnostic %select index.
17325 switch (Tag) {
17327 return 0;
17329 return 1;
17330 case TagTypeKind::Class:
17331 return 2;
17332 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17333 }
17334}
17335
17336/// Determine if tag kind is a class-key compatible with
17337/// class for redeclaration (class, struct, or __interface).
17338///
17339/// \returns true iff the tag kind is compatible.
17341{
17342 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17344}
17345
17347 if (isa<TypedefDecl>(PrevDecl))
17348 return NonTagKind::Typedef;
17349 else if (isa<TypeAliasDecl>(PrevDecl))
17350 return NonTagKind::TypeAlias;
17351 else if (isa<ClassTemplateDecl>(PrevDecl))
17352 return NonTagKind::Template;
17353 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17355 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17357 switch (TTK) {
17360 case TagTypeKind::Class:
17361 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17363 case TagTypeKind::Union:
17364 return NonTagKind::NonUnion;
17365 case TagTypeKind::Enum:
17366 return NonTagKind::NonEnum;
17367 }
17368 llvm_unreachable("invalid TTK");
17369}
17370
17372 TagTypeKind NewTag, bool isDefinition,
17373 SourceLocation NewTagLoc,
17374 const IdentifierInfo *Name) {
17375 // C++ [dcl.type.elab]p3:
17376 // The class-key or enum keyword present in the
17377 // elaborated-type-specifier shall agree in kind with the
17378 // declaration to which the name in the elaborated-type-specifier
17379 // refers. This rule also applies to the form of
17380 // elaborated-type-specifier that declares a class-name or
17381 // friend class since it can be construed as referring to the
17382 // definition of the class. Thus, in any
17383 // elaborated-type-specifier, the enum keyword shall be used to
17384 // refer to an enumeration (7.2), the union class-key shall be
17385 // used to refer to a union (clause 9), and either the class or
17386 // struct class-key shall be used to refer to a class (clause 9)
17387 // declared using the class or struct class-key.
17388 TagTypeKind OldTag = Previous->getTagKind();
17389 if (OldTag != NewTag &&
17391 return false;
17392
17393 // Tags are compatible, but we might still want to warn on mismatched tags.
17394 // Non-class tags can't be mismatched at this point.
17396 return true;
17397
17398 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17399 // by our warning analysis. We don't want to warn about mismatches with (eg)
17400 // declarations in system headers that are designed to be specialized, but if
17401 // a user asks us to warn, we should warn if their code contains mismatched
17402 // declarations.
17403 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17404 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17405 Loc);
17406 };
17407 if (IsIgnoredLoc(NewTagLoc))
17408 return true;
17409
17410 auto IsIgnored = [&](const TagDecl *Tag) {
17411 return IsIgnoredLoc(Tag->getLocation());
17412 };
17413 while (IsIgnored(Previous)) {
17414 Previous = Previous->getPreviousDecl();
17415 if (!Previous)
17416 return true;
17417 OldTag = Previous->getTagKind();
17418 }
17419
17420 bool isTemplate = false;
17421 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17422 isTemplate = Record->getDescribedClassTemplate();
17423
17425 if (OldTag != NewTag) {
17426 // In a template instantiation, do not offer fix-its for tag mismatches
17427 // since they usually mess up the template instead of fixing the problem.
17428 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17430 << getRedeclDiagFromTagKind(OldTag);
17431 // FIXME: Note previous location?
17432 }
17433 return true;
17434 }
17435
17436 if (isDefinition) {
17437 // On definitions, check all previous tags and issue a fix-it for each
17438 // one that doesn't match the current tag.
17439 if (Previous->getDefinition()) {
17440 // Don't suggest fix-its for redefinitions.
17441 return true;
17442 }
17443
17444 bool previousMismatch = false;
17445 for (const TagDecl *I : Previous->redecls()) {
17446 if (I->getTagKind() != NewTag) {
17447 // Ignore previous declarations for which the warning was disabled.
17448 if (IsIgnored(I))
17449 continue;
17450
17451 if (!previousMismatch) {
17452 previousMismatch = true;
17453 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17455 << getRedeclDiagFromTagKind(I->getTagKind());
17456 }
17457 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17459 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17461 }
17462 }
17463 return true;
17464 }
17465
17466 // Identify the prevailing tag kind: this is the kind of the definition (if
17467 // there is a non-ignored definition), or otherwise the kind of the prior
17468 // (non-ignored) declaration.
17469 const TagDecl *PrevDef = Previous->getDefinition();
17470 if (PrevDef && IsIgnored(PrevDef))
17471 PrevDef = nullptr;
17472 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17473 if (Redecl->getTagKind() != NewTag) {
17474 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17476 << getRedeclDiagFromTagKind(OldTag);
17477 Diag(Redecl->getLocation(), diag::note_previous_use);
17478
17479 // If there is a previous definition, suggest a fix-it.
17480 if (PrevDef) {
17481 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17485 }
17486 }
17487
17488 return true;
17489}
17490
17491/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17492/// from an outer enclosing namespace or file scope inside a friend declaration.
17493/// This should provide the commented out code in the following snippet:
17494/// namespace N {
17495/// struct X;
17496/// namespace M {
17497/// struct Y { friend struct /*N::*/ X; };
17498/// }
17499/// }
17501 SourceLocation NameLoc) {
17502 // While the decl is in a namespace, do repeated lookup of that name and see
17503 // if we get the same namespace back. If we do not, continue until
17504 // translation unit scope, at which point we have a fully qualified NNS.
17507 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17508 // This tag should be declared in a namespace, which can only be enclosed by
17509 // other namespaces. Bail if there's an anonymous namespace in the chain.
17510 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17511 if (!Namespace || Namespace->isAnonymousNamespace())
17512 return FixItHint();
17513 IdentifierInfo *II = Namespace->getIdentifier();
17514 Namespaces.push_back(II);
17515 NamedDecl *Lookup = SemaRef.LookupSingleName(
17516 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17517 if (Lookup == Namespace)
17518 break;
17519 }
17520
17521 // Once we have all the namespaces, reverse them to go outermost first, and
17522 // build an NNS.
17523 SmallString<64> Insertion;
17524 llvm::raw_svector_ostream OS(Insertion);
17525 if (DC->isTranslationUnit())
17526 OS << "::";
17527 std::reverse(Namespaces.begin(), Namespaces.end());
17528 for (auto *II : Namespaces)
17529 OS << II->getName() << "::";
17530 return FixItHint::CreateInsertion(NameLoc, Insertion);
17531}
17532
17533/// Determine whether a tag originally declared in context \p OldDC can
17534/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17535/// found a declaration in \p OldDC as a previous decl, perhaps through a
17536/// using-declaration).
17538 DeclContext *NewDC) {
17539 OldDC = OldDC->getRedeclContext();
17540 NewDC = NewDC->getRedeclContext();
17541
17542 if (OldDC->Equals(NewDC))
17543 return true;
17544
17545 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17546 // encloses the other).
17547 if (S.getLangOpts().MSVCCompat &&
17548 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17549 return true;
17550
17551 return false;
17552}
17553
17555Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17556 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17557 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17558 SourceLocation ModulePrivateLoc,
17559 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17560 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17561 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17562 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17563 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17564 // If this is not a definition, it must have a name.
17565 IdentifierInfo *OrigName = Name;
17566 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17567 "Nameless record must be a definition!");
17568 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17569
17570 OwnedDecl = false;
17572 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17573
17574 // FIXME: Check member specializations more carefully.
17575 bool isMemberSpecialization = false;
17576 bool IsInjectedClassName = false;
17577 bool Invalid = false;
17578
17579 // We only need to do this matching if we have template parameters
17580 // or a scope specifier, which also conveniently avoids this work
17581 // for non-C++ cases.
17582 if (TemplateParameterLists.size() > 0 ||
17583 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17584 TemplateParameterList *TemplateParams =
17586 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17587 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17588
17589 // C++23 [dcl.type.elab] p2:
17590 // If an elaborated-type-specifier is the sole constituent of a
17591 // declaration, the declaration is ill-formed unless it is an explicit
17592 // specialization, an explicit instantiation or it has one of the
17593 // following forms: [...]
17594 // C++23 [dcl.enum] p1:
17595 // If the enum-head-name of an opaque-enum-declaration contains a
17596 // nested-name-specifier, the declaration shall be an explicit
17597 // specialization.
17598 //
17599 // FIXME: Class template partial specializations can be forward declared
17600 // per CWG2213, but the resolution failed to allow qualified forward
17601 // declarations. This is almost certainly unintentional, so we allow them.
17602 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17603 !isMemberSpecialization)
17604 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17606
17607 if (TemplateParams) {
17608 if (Kind == TagTypeKind::Enum) {
17609 Diag(KWLoc, diag::err_enum_template);
17610 return true;
17611 }
17612
17613 if (TemplateParams->size() > 0) {
17614 // This is a declaration or definition of a class template (which may
17615 // be a member of another template).
17616
17617 if (Invalid)
17618 return true;
17619
17620 OwnedDecl = false;
17622 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17623 AS, ModulePrivateLoc,
17624 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17625 TemplateParameterLists.data(), SkipBody);
17626 return Result.get();
17627 } else {
17628 // The "template<>" header is extraneous.
17629 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17630 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17631 isMemberSpecialization = true;
17632 }
17633 }
17634
17635 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17636 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17637 return true;
17638 }
17639
17640 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17641 // C++23 [dcl.type.elab]p4:
17642 // If an elaborated-type-specifier appears with the friend specifier as
17643 // an entire member-declaration, the member-declaration shall have one
17644 // of the following forms:
17645 // friend class-key nested-name-specifier(opt) identifier ;
17646 // friend class-key simple-template-id ;
17647 // friend class-key nested-name-specifier template(opt)
17648 // simple-template-id ;
17649 //
17650 // Since enum is not a class-key, so declarations like "friend enum E;"
17651 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17652 // invalid, most implementations accept so we issue a pedantic warning.
17653 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17654 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17655 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17656 Diag(KWLoc, diag::note_enum_friend)
17657 << (ScopedEnum + ScopedEnumUsesClassTag);
17658 }
17659
17660 // Figure out the underlying type if this a enum declaration. We need to do
17661 // this early, because it's needed to detect if this is an incompatible
17662 // redeclaration.
17663 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17664 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17665
17666 if (Kind == TagTypeKind::Enum) {
17667 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17668 // No underlying type explicitly specified, or we failed to parse the
17669 // type, default to int.
17670 EnumUnderlying = Context.IntTy.getTypePtr();
17671 } else if (UnderlyingType.get()) {
17672 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17673 // integral type; any cv-qualification is ignored.
17674 // C23 6.7.3.3p5: The underlying type of the enumeration is the
17675 // unqualified, non-atomic version of the type specified by the type
17676 // specifiers in the specifier qualifier list.
17677 TypeSourceInfo *TI = nullptr;
17678 GetTypeFromParser(UnderlyingType.get(), &TI);
17679 EnumUnderlying = TI;
17680
17682 // Recover by falling back to int.
17683 EnumUnderlying = Context.IntTy.getTypePtr();
17684
17687 EnumUnderlying = Context.IntTy.getTypePtr();
17688
17689 // If the underlying type is atomic, we need to adjust the type before
17690 // continuing. This only happens in the case we stored a TypeSourceInfo
17691 // into EnumUnderlying because the other cases are error recovery up to
17692 // this point. But because it's not possible to gin up a TypeSourceInfo
17693 // for a non-atomic type from an atomic one, we'll store into the Type
17694 // field instead. FIXME: it would be nice to have an easy way to get a
17695 // derived TypeSourceInfo which strips qualifiers including the weird
17696 // ones like _Atomic where it forms a different type.
17697 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
17698 TI && TI->getType()->isAtomicType())
17699 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
17700
17701 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17702 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17703 // of 'int'. However, if this is an unfixed forward declaration, don't set
17704 // the underlying type unless the user enables -fms-compatibility. This
17705 // makes unfixed forward declared enums incomplete and is more conforming.
17706 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17707 EnumUnderlying = Context.IntTy.getTypePtr();
17708 }
17709 }
17710
17711 DeclContext *SearchDC = CurContext;
17712 DeclContext *DC = CurContext;
17713 bool isStdBadAlloc = false;
17714 bool isStdAlignValT = false;
17715
17717 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17718 Redecl = RedeclarationKind::NotForRedeclaration;
17719
17720 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17721 /// implemented asks for structural equivalence checking, the returned decl
17722 /// here is passed back to the parser, allowing the tag body to be parsed.
17723 auto createTagFromNewDecl = [&]() -> TagDecl * {
17724 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17725 // If there is an identifier, use the location of the identifier as the
17726 // location of the decl, otherwise use the location of the struct/union
17727 // keyword.
17728 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17729 TagDecl *New = nullptr;
17730
17731 if (Kind == TagTypeKind::Enum) {
17732 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17733 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17734 // If this is an undefined enum, bail.
17735 if (TUK != TagUseKind::Definition && !Invalid)
17736 return nullptr;
17737 if (EnumUnderlying) {
17738 EnumDecl *ED = cast<EnumDecl>(New);
17739 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17741 else
17742 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17743 QualType EnumTy = ED->getIntegerType();
17746 : EnumTy);
17747 }
17748 } else { // struct/union
17749 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17750 nullptr);
17751 }
17752
17753 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17754 // Add alignment attributes if necessary; these attributes are checked
17755 // when the ASTContext lays out the structure.
17756 //
17757 // It is important for implementing the correct semantics that this
17758 // happen here (in ActOnTag). The #pragma pack stack is
17759 // maintained as a result of parser callbacks which can occur at
17760 // many points during the parsing of a struct declaration (because
17761 // the #pragma tokens are effectively skipped over during the
17762 // parsing of the struct).
17763 if (TUK == TagUseKind::Definition &&
17764 (!SkipBody || !SkipBody->ShouldSkip)) {
17765 if (LangOpts.HLSL)
17766 RD->addAttr(PackedAttr::CreateImplicit(Context));
17769 }
17770 }
17771 New->setLexicalDeclContext(CurContext);
17772 return New;
17773 };
17774
17775 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17776 if (Name && SS.isNotEmpty()) {
17777 // We have a nested-name tag ('struct foo::bar').
17778
17779 // Check for invalid 'foo::'.
17780 if (SS.isInvalid()) {
17781 Name = nullptr;
17782 goto CreateNewDecl;
17783 }
17784
17785 // If this is a friend or a reference to a class in a dependent
17786 // context, don't try to make a decl for it.
17787 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17788 DC = computeDeclContext(SS, false);
17789 if (!DC) {
17790 IsDependent = true;
17791 return true;
17792 }
17793 } else {
17794 DC = computeDeclContext(SS, true);
17795 if (!DC) {
17796 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17797 << SS.getRange();
17798 return true;
17799 }
17800 }
17801
17802 if (RequireCompleteDeclContext(SS, DC))
17803 return true;
17804
17805 SearchDC = DC;
17806 // Look-up name inside 'foo::'.
17808
17809 if (Previous.isAmbiguous())
17810 return true;
17811
17812 if (Previous.empty()) {
17813 // Name lookup did not find anything. However, if the
17814 // nested-name-specifier refers to the current instantiation,
17815 // and that current instantiation has any dependent base
17816 // classes, we might find something at instantiation time: treat
17817 // this as a dependent elaborated-type-specifier.
17818 // But this only makes any sense for reference-like lookups.
17819 if (Previous.wasNotFoundInCurrentInstantiation() &&
17820 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17821 IsDependent = true;
17822 return true;
17823 }
17824
17825 // A tag 'foo::bar' must already exist.
17826 Diag(NameLoc, diag::err_not_tag_in_scope)
17827 << Kind << Name << DC << SS.getRange();
17828 Name = nullptr;
17829 Invalid = true;
17830 goto CreateNewDecl;
17831 }
17832 } else if (Name) {
17833 // C++14 [class.mem]p14:
17834 // If T is the name of a class, then each of the following shall have a
17835 // name different from T:
17836 // -- every member of class T that is itself a type
17837 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17838 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17839 return true;
17840
17841 // If this is a named struct, check to see if there was a previous forward
17842 // declaration or definition.
17843 // FIXME: We're looking into outer scopes here, even when we
17844 // shouldn't be. Doing so can result in ambiguities that we
17845 // shouldn't be diagnosing.
17846 LookupName(Previous, S);
17847
17848 // When declaring or defining a tag, ignore ambiguities introduced
17849 // by types using'ed into this scope.
17850 if (Previous.isAmbiguous() &&
17852 LookupResult::Filter F = Previous.makeFilter();
17853 while (F.hasNext()) {
17854 NamedDecl *ND = F.next();
17855 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17856 SearchDC->getRedeclContext()))
17857 F.erase();
17858 }
17859 F.done();
17860 }
17861
17862 // C++11 [namespace.memdef]p3:
17863 // If the name in a friend declaration is neither qualified nor
17864 // a template-id and the declaration is a function or an
17865 // elaborated-type-specifier, the lookup to determine whether
17866 // the entity has been previously declared shall not consider
17867 // any scopes outside the innermost enclosing namespace.
17868 //
17869 // MSVC doesn't implement the above rule for types, so a friend tag
17870 // declaration may be a redeclaration of a type declared in an enclosing
17871 // scope. They do implement this rule for friend functions.
17872 //
17873 // Does it matter that this should be by scope instead of by
17874 // semantic context?
17875 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17876 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17877 LookupResult::Filter F = Previous.makeFilter();
17878 bool FriendSawTagOutsideEnclosingNamespace = false;
17879 while (F.hasNext()) {
17880 NamedDecl *ND = F.next();
17882 if (DC->isFileContext() &&
17883 !EnclosingNS->Encloses(ND->getDeclContext())) {
17884 if (getLangOpts().MSVCCompat)
17885 FriendSawTagOutsideEnclosingNamespace = true;
17886 else
17887 F.erase();
17888 }
17889 }
17890 F.done();
17891
17892 // Diagnose this MSVC extension in the easy case where lookup would have
17893 // unambiguously found something outside the enclosing namespace.
17894 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17895 NamedDecl *ND = Previous.getFoundDecl();
17896 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17897 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17898 }
17899 }
17900
17901 // Note: there used to be some attempt at recovery here.
17902 if (Previous.isAmbiguous())
17903 return true;
17904
17905 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17906 // FIXME: This makes sure that we ignore the contexts associated
17907 // with C structs, unions, and enums when looking for a matching
17908 // tag declaration or definition. See the similar lookup tweak
17909 // in Sema::LookupName; is there a better way to deal with this?
17910 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17911 SearchDC = SearchDC->getParent();
17912 } else if (getLangOpts().CPlusPlus) {
17913 // Inside ObjCContainer want to keep it as a lexical decl context but go
17914 // past it (most often to TranslationUnit) to find the semantic decl
17915 // context.
17916 while (isa<ObjCContainerDecl>(SearchDC))
17917 SearchDC = SearchDC->getParent();
17918 }
17919 } else if (getLangOpts().CPlusPlus) {
17920 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17921 // TagDecl the same way as we skip it for named TagDecl.
17922 while (isa<ObjCContainerDecl>(SearchDC))
17923 SearchDC = SearchDC->getParent();
17924 }
17925
17926 if (Previous.isSingleResult() &&
17927 Previous.getFoundDecl()->isTemplateParameter()) {
17928 // Maybe we will complain about the shadowed template parameter.
17929 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17930 // Just pretend that we didn't see the previous declaration.
17931 Previous.clear();
17932 }
17933
17934 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17935 DC->Equals(getStdNamespace())) {
17936 if (Name->isStr("bad_alloc")) {
17937 // This is a declaration of or a reference to "std::bad_alloc".
17938 isStdBadAlloc = true;
17939
17940 // If std::bad_alloc has been implicitly declared (but made invisible to
17941 // name lookup), fill in this implicit declaration as the previous
17942 // declaration, so that the declarations get chained appropriately.
17943 if (Previous.empty() && StdBadAlloc)
17944 Previous.addDecl(getStdBadAlloc());
17945 } else if (Name->isStr("align_val_t")) {
17946 isStdAlignValT = true;
17947 if (Previous.empty() && StdAlignValT)
17948 Previous.addDecl(getStdAlignValT());
17949 }
17950 }
17951
17952 // If we didn't find a previous declaration, and this is a reference
17953 // (or friend reference), move to the correct scope. In C++, we
17954 // also need to do a redeclaration lookup there, just in case
17955 // there's a shadow friend decl.
17956 if (Name && Previous.empty() &&
17957 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17958 IsTemplateParamOrArg)) {
17959 if (Invalid) goto CreateNewDecl;
17960 assert(SS.isEmpty());
17961
17962 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17963 // C++ [basic.scope.pdecl]p5:
17964 // -- for an elaborated-type-specifier of the form
17965 //
17966 // class-key identifier
17967 //
17968 // if the elaborated-type-specifier is used in the
17969 // decl-specifier-seq or parameter-declaration-clause of a
17970 // function defined in namespace scope, the identifier is
17971 // declared as a class-name in the namespace that contains
17972 // the declaration; otherwise, except as a friend
17973 // declaration, the identifier is declared in the smallest
17974 // non-class, non-function-prototype scope that contains the
17975 // declaration.
17976 //
17977 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17978 // C structs and unions.
17979 //
17980 // It is an error in C++ to declare (rather than define) an enum
17981 // type, including via an elaborated type specifier. We'll
17982 // diagnose that later; for now, declare the enum in the same
17983 // scope as we would have picked for any other tag type.
17984 //
17985 // GNU C also supports this behavior as part of its incomplete
17986 // enum types extension, while GNU C++ does not.
17987 //
17988 // Find the context where we'll be declaring the tag.
17989 // FIXME: We would like to maintain the current DeclContext as the
17990 // lexical context,
17991 SearchDC = getTagInjectionContext(SearchDC);
17992
17993 // Find the scope where we'll be declaring the tag.
17995 } else {
17996 assert(TUK == TagUseKind::Friend);
17997 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17998
17999 // C++ [namespace.memdef]p3:
18000 // If a friend declaration in a non-local class first declares a
18001 // class or function, the friend class or function is a member of
18002 // the innermost enclosing namespace.
18003 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18004 : SearchDC->getEnclosingNamespaceContext();
18005 }
18006
18007 // In C++, we need to do a redeclaration lookup to properly
18008 // diagnose some problems.
18009 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18010 // hidden declaration so that we don't get ambiguity errors when using a
18011 // type declared by an elaborated-type-specifier. In C that is not correct
18012 // and we should instead merge compatible types found by lookup.
18013 if (getLangOpts().CPlusPlus) {
18014 // FIXME: This can perform qualified lookups into function contexts,
18015 // which are meaningless.
18016 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18017 LookupQualifiedName(Previous, SearchDC);
18018 } else {
18019 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18020 LookupName(Previous, S);
18021 }
18022 }
18023
18024 // If we have a known previous declaration to use, then use it.
18025 if (Previous.empty() && SkipBody && SkipBody->Previous)
18026 Previous.addDecl(SkipBody->Previous);
18027
18028 if (!Previous.empty()) {
18029 NamedDecl *PrevDecl = Previous.getFoundDecl();
18030 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18031
18032 // It's okay to have a tag decl in the same scope as a typedef
18033 // which hides a tag decl in the same scope. Finding this
18034 // with a redeclaration lookup can only actually happen in C++.
18035 //
18036 // This is also okay for elaborated-type-specifiers, which is
18037 // technically forbidden by the current standard but which is
18038 // okay according to the likely resolution of an open issue;
18039 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18040 if (getLangOpts().CPlusPlus) {
18041 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18042 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18043 if (Tag->getDeclName() == Name &&
18044 Tag->getDeclContext()->getRedeclContext()
18045 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18046 PrevDecl = Tag;
18047 Previous.clear();
18048 Previous.addDecl(Tag);
18049 Previous.resolveKind();
18050 }
18051 }
18052 } else if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18053 TUK == TagUseKind::Reference && RD &&
18054 RD->isInjectedClassName()) {
18055 // If lookup found the injected class name, the previous declaration is
18056 // the class being injected into.
18057 PrevDecl = cast<TagDecl>(RD->getDeclContext());
18058 Previous.clear();
18059 Previous.addDecl(PrevDecl);
18060 Previous.resolveKind();
18061 IsInjectedClassName = true;
18062 }
18063 }
18064
18065 // If this is a redeclaration of a using shadow declaration, it must
18066 // declare a tag in the same context. In MSVC mode, we allow a
18067 // redefinition if either context is within the other.
18068 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18069 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18070 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18071 TUK != TagUseKind::Friend &&
18072 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18073 !(OldTag && isAcceptableTagRedeclContext(
18074 *this, OldTag->getDeclContext(), SearchDC))) {
18075 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18076 Diag(Shadow->getTargetDecl()->getLocation(),
18077 diag::note_using_decl_target);
18078 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18079 << 0;
18080 // Recover by ignoring the old declaration.
18081 Previous.clear();
18082 goto CreateNewDecl;
18083 }
18084 }
18085
18086 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18087 // If this is a use of a previous tag, or if the tag is already declared
18088 // in the same scope (so that the definition/declaration completes or
18089 // rementions the tag), reuse the decl.
18090 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18091 isDeclInScope(DirectPrevDecl, SearchDC, S,
18092 SS.isNotEmpty() || isMemberSpecialization)) {
18093 // Make sure that this wasn't declared as an enum and now used as a
18094 // struct or something similar.
18095 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18096 TUK == TagUseKind::Definition, KWLoc,
18097 Name)) {
18098 bool SafeToContinue =
18099 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18100 Kind != TagTypeKind::Enum);
18101 if (SafeToContinue)
18102 Diag(KWLoc, diag::err_use_with_wrong_tag)
18103 << Name
18105 PrevTagDecl->getKindName());
18106 else
18107 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18108 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18109
18110 if (SafeToContinue)
18111 Kind = PrevTagDecl->getTagKind();
18112 else {
18113 // Recover by making this an anonymous redefinition.
18114 Name = nullptr;
18115 Previous.clear();
18116 Invalid = true;
18117 }
18118 }
18119
18120 if (Kind == TagTypeKind::Enum &&
18121 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18122 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18123 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18124 return PrevTagDecl;
18125
18126 QualType EnumUnderlyingTy;
18127 if (TypeSourceInfo *TI =
18128 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18129 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18130 else if (const Type *T =
18131 dyn_cast_if_present<const Type *>(EnumUnderlying))
18132 EnumUnderlyingTy = QualType(T, 0);
18133
18134 // All conflicts with previous declarations are recovered by
18135 // returning the previous declaration, unless this is a definition,
18136 // in which case we want the caller to bail out.
18137 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18138 ScopedEnum, EnumUnderlyingTy,
18139 IsFixed, PrevEnum))
18140 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18141 }
18142
18143 // C++11 [class.mem]p1:
18144 // A member shall not be declared twice in the member-specification,
18145 // except that a nested class or member class template can be declared
18146 // and then later defined.
18147 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18148 S->isDeclScope(PrevDecl)) {
18149 Diag(NameLoc, diag::ext_member_redeclared);
18150 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18151 }
18152
18153 if (!Invalid) {
18154 // If this is a use, just return the declaration we found, unless
18155 // we have attributes.
18156 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18157 if (!Attrs.empty()) {
18158 // FIXME: Diagnose these attributes. For now, we create a new
18159 // declaration to hold them.
18160 } else if (TUK == TagUseKind::Reference &&
18161 (PrevTagDecl->getFriendObjectKind() ==
18163 PrevDecl->getOwningModule() != getCurrentModule()) &&
18164 SS.isEmpty()) {
18165 // This declaration is a reference to an existing entity, but
18166 // has different visibility from that entity: it either makes
18167 // a friend visible or it makes a type visible in a new module.
18168 // In either case, create a new declaration. We only do this if
18169 // the declaration would have meant the same thing if no prior
18170 // declaration were found, that is, if it was found in the same
18171 // scope where we would have injected a declaration.
18172 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18173 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18174 return PrevTagDecl;
18175 // This is in the injected scope, create a new declaration in
18176 // that scope.
18178 } else {
18179 return PrevTagDecl;
18180 }
18181 }
18182
18183 // Diagnose attempts to redefine a tag.
18184 if (TUK == TagUseKind::Definition) {
18185 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18186 // If the type is currently being defined, complain
18187 // about a nested redefinition.
18188 if (Def->isBeingDefined()) {
18189 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18190 Diag(PrevTagDecl->getLocation(),
18191 diag::note_previous_definition);
18192 Name = nullptr;
18193 Previous.clear();
18194 Invalid = true;
18195 } else {
18196 // If we're defining a specialization and the previous
18197 // definition is from an implicit instantiation, don't emit an
18198 // error here; we'll catch this in the general case below.
18199 bool IsExplicitSpecializationAfterInstantiation = false;
18200 if (isMemberSpecialization) {
18201 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18202 IsExplicitSpecializationAfterInstantiation =
18203 RD->getTemplateSpecializationKind() !=
18205 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18206 IsExplicitSpecializationAfterInstantiation =
18207 ED->getTemplateSpecializationKind() !=
18209 }
18210
18211 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18212 // do not keep more that one definition around (merge them).
18213 // However, ensure the decl passes the structural compatibility
18214 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18215 NamedDecl *Hidden = nullptr;
18216 bool HiddenDefVisible = false;
18217 if (SkipBody &&
18218 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||
18219 getLangOpts().C23)) {
18220 // There is a definition of this tag, but it is not visible.
18221 // We explicitly make use of C++'s one definition rule here,
18222 // and assume that this definition is identical to the hidden
18223 // one we already have. Make the existing definition visible
18224 // and use it in place of this one.
18225 if (!getLangOpts().CPlusPlus) {
18226 // Postpone making the old definition visible until after we
18227 // complete parsing the new one and do the structural
18228 // comparison.
18229 SkipBody->CheckSameAsPrevious = true;
18230 SkipBody->New = createTagFromNewDecl();
18231 SkipBody->Previous = Def;
18232
18233 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18234 return Def;
18235 }
18236
18237 SkipBody->ShouldSkip = true;
18238 SkipBody->Previous = Def;
18239 if (!HiddenDefVisible && Hidden)
18241 // Carry on and handle it like a normal definition. We'll
18242 // skip starting the definition later.
18243
18244 } else if (!IsExplicitSpecializationAfterInstantiation) {
18245 // A redeclaration in function prototype scope in C isn't
18246 // visible elsewhere, so merely issue a warning.
18247 if (!getLangOpts().CPlusPlus &&
18248 S->containedInPrototypeScope())
18249 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18250 << Name;
18251 else
18252 Diag(NameLoc, diag::err_redefinition) << Name;
18254 NameLoc.isValid() ? NameLoc : KWLoc);
18255 // If this is a redefinition, recover by making this
18256 // struct be anonymous, which will make any later
18257 // references get the previous definition.
18258 Name = nullptr;
18259 Previous.clear();
18260 Invalid = true;
18261 }
18262 }
18263 }
18264
18265 // Okay, this is definition of a previously declared or referenced
18266 // tag. We're going to create a new Decl for it.
18267 }
18268
18269 // Okay, we're going to make a redeclaration. If this is some kind
18270 // of reference, make sure we build the redeclaration in the same DC
18271 // as the original, and ignore the current access specifier.
18272 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18273 SearchDC = PrevTagDecl->getDeclContext();
18274 AS = AS_none;
18275 }
18276 }
18277 // If we get here we have (another) forward declaration or we
18278 // have a definition. Just create a new decl.
18279
18280 } else {
18281 // If we get here, this is a definition of a new tag type in a nested
18282 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18283 // new decl/type. We set PrevDecl to NULL so that the entities
18284 // have distinct types.
18285 Previous.clear();
18286 }
18287 // If we get here, we're going to create a new Decl. If PrevDecl
18288 // is non-NULL, it's a definition of the tag declared by
18289 // PrevDecl. If it's NULL, we have a new definition.
18290
18291 // Otherwise, PrevDecl is not a tag, but was found with tag
18292 // lookup. This is only actually possible in C++, where a few
18293 // things like templates still live in the tag namespace.
18294 } else {
18295 // Use a better diagnostic if an elaborated-type-specifier
18296 // found the wrong kind of type on the first
18297 // (non-redeclaration) lookup.
18298 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18299 !Previous.isForRedeclaration()) {
18300 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18301 Diag(NameLoc, diag::err_tag_reference_non_tag)
18302 << PrevDecl << NTK << Kind;
18303 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18304 Invalid = true;
18305
18306 // Otherwise, only diagnose if the declaration is in scope.
18307 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18308 SS.isNotEmpty() || isMemberSpecialization)) {
18309 // do nothing
18310
18311 // Diagnose implicit declarations introduced by elaborated types.
18312 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18313 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18314 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18315 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18316 Invalid = true;
18317
18318 // Otherwise it's a declaration. Call out a particularly common
18319 // case here.
18320 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18321 unsigned Kind = 0;
18322 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18323 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18324 << Name << Kind << TND->getUnderlyingType();
18325 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18326 Invalid = true;
18327
18328 // Otherwise, diagnose.
18329 } else {
18330 // The tag name clashes with something else in the target scope,
18331 // issue an error and recover by making this tag be anonymous.
18332 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18333 notePreviousDefinition(PrevDecl, NameLoc);
18334 Name = nullptr;
18335 Invalid = true;
18336 }
18337
18338 // The existing declaration isn't relevant to us; we're in a
18339 // new scope, so clear out the previous declaration.
18340 Previous.clear();
18341 }
18342 }
18343
18344CreateNewDecl:
18345
18346 TagDecl *PrevDecl = nullptr;
18347 if (Previous.isSingleResult())
18348 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18349
18350 // If there is an identifier, use the location of the identifier as the
18351 // location of the decl, otherwise use the location of the struct/union
18352 // keyword.
18353 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18354
18355 // Otherwise, create a new declaration. If there is a previous
18356 // declaration of the same entity, the two will be linked via
18357 // PrevDecl.
18358 TagDecl *New;
18359
18360 if (Kind == TagTypeKind::Enum) {
18361 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18362 // enum X { A, B, C } D; D should chain to X.
18363 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18364 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18365 ScopedEnumUsesClassTag, IsFixed);
18366
18367 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18368 StdAlignValT = cast<EnumDecl>(New);
18369
18370 // If this is an undefined enum, warn.
18371 if (TUK != TagUseKind::Definition && !Invalid) {
18372 TagDecl *Def;
18373 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
18374 // C++0x: 7.2p2: opaque-enum-declaration.
18375 // Conflicts are diagnosed above. Do nothing.
18376 }
18377 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18378 Diag(Loc, diag::ext_forward_ref_enum_def)
18379 << New;
18380 Diag(Def->getLocation(), diag::note_previous_definition);
18381 } else {
18382 unsigned DiagID = diag::ext_forward_ref_enum;
18383 if (getLangOpts().MSVCCompat)
18384 DiagID = diag::ext_ms_forward_ref_enum;
18385 else if (getLangOpts().CPlusPlus)
18386 DiagID = diag::err_forward_ref_enum;
18387 Diag(Loc, DiagID);
18388 }
18389 }
18390
18391 if (EnumUnderlying) {
18392 EnumDecl *ED = cast<EnumDecl>(New);
18393 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18395 else
18396 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18397 QualType EnumTy = ED->getIntegerType();
18400 : EnumTy);
18401 assert(ED->isComplete() && "enum with type should be complete");
18402 }
18403 } else {
18404 // struct/union/class
18405
18406 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18407 // struct X { int A; } D; D should chain to X.
18408 if (getLangOpts().CPlusPlus) {
18409 // FIXME: Look for a way to use RecordDecl for simple structs.
18410 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18411 cast_or_null<CXXRecordDecl>(PrevDecl));
18412
18413 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18414 StdBadAlloc = cast<CXXRecordDecl>(New);
18415 } else
18416 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18417 cast_or_null<RecordDecl>(PrevDecl));
18418 }
18419
18420 // Only C23 and later allow defining new types in 'offsetof()'.
18421 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18423 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18424 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18425
18426 // C++11 [dcl.type]p3:
18427 // A type-specifier-seq shall not define a class or enumeration [...].
18428 if (!Invalid && getLangOpts().CPlusPlus &&
18429 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18430 TUK == TagUseKind::Definition) {
18431 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18433 Invalid = true;
18434 }
18435
18437 DC->getDeclKind() == Decl::Enum) {
18438 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18440 Invalid = true;
18441 }
18442
18443 // Maybe add qualifier info.
18444 if (SS.isNotEmpty()) {
18445 if (SS.isSet()) {
18446 // If this is either a declaration or a definition, check the
18447 // nested-name-specifier against the current context.
18448 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18449 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18450 /*TemplateId=*/nullptr,
18451 isMemberSpecialization))
18452 Invalid = true;
18453
18454 New->setQualifierInfo(SS.getWithLocInContext(Context));
18455 if (TemplateParameterLists.size() > 0) {
18456 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18457 }
18458 }
18459 else
18460 Invalid = true;
18461 }
18462
18463 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18464 // Add alignment attributes if necessary; these attributes are checked when
18465 // the ASTContext lays out the structure.
18466 //
18467 // It is important for implementing the correct semantics that this
18468 // happen here (in ActOnTag). The #pragma pack stack is
18469 // maintained as a result of parser callbacks which can occur at
18470 // many points during the parsing of a struct declaration (because
18471 // the #pragma tokens are effectively skipped over during the
18472 // parsing of the struct).
18473 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18474 if (LangOpts.HLSL)
18475 RD->addAttr(PackedAttr::CreateImplicit(Context));
18478 }
18479 }
18480
18481 if (ModulePrivateLoc.isValid()) {
18482 if (isMemberSpecialization)
18483 Diag(New->getLocation(), diag::err_module_private_specialization)
18484 << 2
18485 << FixItHint::CreateRemoval(ModulePrivateLoc);
18486 // __module_private__ does not apply to local classes. However, we only
18487 // diagnose this as an error when the declaration specifiers are
18488 // freestanding. Here, we just ignore the __module_private__.
18489 else if (!SearchDC->isFunctionOrMethod())
18490 New->setModulePrivate();
18491 }
18492
18493 // If this is a specialization of a member class (of a class template),
18494 // check the specialization.
18495 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18496 Invalid = true;
18497
18498 // If we're declaring or defining a tag in function prototype scope in C,
18499 // note that this type can only be used within the function and add it to
18500 // the list of decls to inject into the function definition scope. However,
18501 // in C23 and later, while the type is only visible within the function, the
18502 // function can be called with a compatible type defined in the same TU, so
18503 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18504 if ((Name || Kind == TagTypeKind::Enum) &&
18505 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18506 if (getLangOpts().CPlusPlus) {
18507 // C++ [dcl.fct]p6:
18508 // Types shall not be defined in return or parameter types.
18509 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18510 Diag(Loc, diag::err_type_defined_in_param_type)
18511 << Name;
18512 Invalid = true;
18513 }
18514 if (TUK == TagUseKind::Declaration)
18515 Invalid = true;
18516 } else if (!PrevDecl) {
18517 // In C23 mode, if the declaration is complete, we do not want to
18518 // diagnose.
18519 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18520 Diag(Loc, diag::warn_decl_in_param_list)
18522 }
18523 }
18524
18525 if (Invalid)
18526 New->setInvalidDecl();
18527
18528 // Set the lexical context. If the tag has a C++ scope specifier, the
18529 // lexical context will be different from the semantic context.
18530 New->setLexicalDeclContext(CurContext);
18531
18532 // Mark this as a friend decl if applicable.
18533 // In Microsoft mode, a friend declaration also acts as a forward
18534 // declaration so we always pass true to setObjectOfFriendDecl to make
18535 // the tag name visible.
18536 if (TUK == TagUseKind::Friend)
18537 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18538
18539 // Set the access specifier.
18540 if (!Invalid && SearchDC->isRecord())
18541 SetMemberAccessSpecifier(New, PrevDecl, AS);
18542
18543 if (PrevDecl)
18545
18546 if (TUK == TagUseKind::Definition) {
18547 if (!SkipBody || !SkipBody->ShouldSkip) {
18548 New->startDefinition();
18549 } else {
18550 New->setCompleteDefinition();
18551 New->demoteThisDefinitionToDeclaration();
18552 }
18553 }
18554
18555 ProcessDeclAttributeList(S, New, Attrs);
18557
18558 // If this has an identifier, add it to the scope stack.
18559 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18560 // We might be replacing an existing declaration in the lookup tables;
18561 // if so, borrow its access specifier.
18562 if (PrevDecl)
18563 New->setAccess(PrevDecl->getAccess());
18564
18565 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18567 if (Name) // can be null along some error paths
18568 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18569 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18570 } else if (Name) {
18571 S = getNonFieldDeclScope(S);
18572 PushOnScopeChains(New, S, true);
18573 } else {
18575 }
18576
18577 // If this is the C FILE type, notify the AST context.
18578 if (IdentifierInfo *II = New->getIdentifier())
18579 if (!New->isInvalidDecl() &&
18580 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18581 II->isStr("FILE"))
18583
18584 if (PrevDecl)
18585 mergeDeclAttributes(New, PrevDecl);
18586
18587 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18590 }
18591
18592 // If there's a #pragma GCC visibility in scope, set the visibility of this
18593 // record.
18595
18596 // If this is not a definition, process API notes for it now.
18597 if (TUK != TagUseKind::Definition)
18599
18600 if (isMemberSpecialization && !New->isInvalidDecl())
18602
18603 OwnedDecl = true;
18604 // In C++, don't return an invalid declaration. We can't recover well from
18605 // the cases where we make the type anonymous.
18606 if (Invalid && getLangOpts().CPlusPlus) {
18607 if (New->isBeingDefined())
18608 if (auto RD = dyn_cast<RecordDecl>(New))
18609 RD->completeDefinition();
18610 return true;
18611 } else if (SkipBody && SkipBody->ShouldSkip) {
18612 return SkipBody->Previous;
18613 } else {
18614 return New;
18615 }
18616}
18617
18620 TagDecl *Tag = cast<TagDecl>(TagD);
18621
18622 // Enter the tag context.
18623 PushDeclContext(S, Tag);
18624
18626
18627 // If there's a #pragma GCC visibility in scope, set the visibility of this
18628 // record.
18630}
18631
18633 SkipBodyInfo &SkipBody) {
18634 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18635 return false;
18636
18637 // Make the previous decl visible.
18639 CleanupMergedEnum(S, SkipBody.New);
18640 return true;
18641}
18642
18644 Scope *S, Decl *TagD, SourceLocation FinalLoc, bool IsFinalSpelledSealed,
18645 bool IsAbstract, SourceLocation TriviallyRelocatable,
18646 SourceLocation Replaceable, SourceLocation LBraceLoc) {
18648 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18649
18650 FieldCollector->StartClass();
18651
18652 if (!Record->getIdentifier())
18653 return;
18654
18655 if (IsAbstract)
18656 Record->markAbstract();
18657
18658 if (FinalLoc.isValid()) {
18659 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18660 IsFinalSpelledSealed
18661 ? FinalAttr::Keyword_sealed
18662 : FinalAttr::Keyword_final));
18663 }
18664
18665 if (TriviallyRelocatable.isValid())
18666 Record->addAttr(
18667 TriviallyRelocatableAttr::Create(Context, TriviallyRelocatable));
18668
18669 if (Replaceable.isValid())
18670 Record->addAttr(ReplaceableAttr::Create(Context, Replaceable));
18671
18672 // C++ [class]p2:
18673 // [...] The class-name is also inserted into the scope of the
18674 // class itself; this is known as the injected-class-name. For
18675 // purposes of access checking, the injected-class-name is treated
18676 // as if it were a public member name.
18677 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18678 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18679 Record->getLocation(), Record->getIdentifier());
18680 InjectedClassName->setImplicit();
18681 InjectedClassName->setAccess(AS_public);
18682 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18683 InjectedClassName->setDescribedClassTemplate(Template);
18684
18685 PushOnScopeChains(InjectedClassName, S);
18686 assert(InjectedClassName->isInjectedClassName() &&
18687 "Broken injected-class-name");
18688}
18689
18691 SourceRange BraceRange) {
18693 TagDecl *Tag = cast<TagDecl>(TagD);
18694 Tag->setBraceRange(BraceRange);
18695
18696 // Make sure we "complete" the definition even it is invalid.
18697 if (Tag->isBeingDefined()) {
18698 assert(Tag->isInvalidDecl() && "We should already have completed it");
18699 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18700 RD->completeDefinition();
18701 }
18702
18703 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18704 FieldCollector->FinishClass();
18705 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18706 auto *Def = RD->getDefinition();
18707 assert(Def && "The record is expected to have a completed definition");
18708 unsigned NumInitMethods = 0;
18709 for (auto *Method : Def->methods()) {
18710 if (!Method->getIdentifier())
18711 continue;
18712 if (Method->getName() == "__init")
18713 NumInitMethods++;
18714 }
18715 if (NumInitMethods > 1 || !Def->hasInitMethod())
18716 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18717 }
18718
18719 // If we're defining a dynamic class in a module interface unit, we always
18720 // need to produce the vtable for it, even if the vtable is not used in the
18721 // current TU.
18722 //
18723 // The case where the current class is not dynamic is handled in
18724 // MarkVTableUsed.
18725 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18726 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18727 }
18728
18729 // Exit this scope of this tag's definition.
18731
18732 if (getCurLexicalContext()->isObjCContainer() &&
18733 Tag->getDeclContext()->isFileContext())
18734 Tag->setTopLevelDeclInObjCContainer();
18735
18736 // Notify the consumer that we've defined a tag.
18737 if (!Tag->isInvalidDecl())
18739
18740 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18741 // from XLs and instead matches the XL #pragma pack(1) behavior.
18742 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18743 AlignPackStack.hasValue()) {
18744 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18745 // Only diagnose #pragma align(packed).
18746 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18747 return;
18748 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18749 if (!RD)
18750 return;
18751 // Only warn if there is at least 1 bitfield member.
18752 if (llvm::any_of(RD->fields(),
18753 [](const FieldDecl *FD) { return FD->isBitField(); }))
18754 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18755 }
18756}
18757
18760 TagDecl *Tag = cast<TagDecl>(TagD);
18761 Tag->setInvalidDecl();
18762
18763 // Make sure we "complete" the definition even it is invalid.
18764 if (Tag->isBeingDefined()) {
18765 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18766 RD->completeDefinition();
18767 }
18768
18769 // We're undoing ActOnTagStartDefinition here, not
18770 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18771 // the FieldCollector.
18772
18774}
18775
18776// Note that FieldName may be null for anonymous bitfields.
18778 const IdentifierInfo *FieldName,
18779 QualType FieldTy, bool IsMsStruct,
18780 Expr *BitWidth) {
18781 assert(BitWidth);
18782 if (BitWidth->containsErrors())
18783 return ExprError();
18784
18785 // C99 6.7.2.1p4 - verify the field type.
18786 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18787 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18788 // Handle incomplete and sizeless types with a specific error.
18789 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18790 diag::err_field_incomplete_or_sizeless))
18791 return ExprError();
18792 if (FieldName)
18793 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18794 << FieldName << FieldTy << BitWidth->getSourceRange();
18795 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18796 << FieldTy << BitWidth->getSourceRange();
18798 return ExprError();
18799
18800 // If the bit-width is type- or value-dependent, don't try to check
18801 // it now.
18802 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18803 return BitWidth;
18804
18805 llvm::APSInt Value;
18806 ExprResult ICE =
18808 if (ICE.isInvalid())
18809 return ICE;
18810 BitWidth = ICE.get();
18811
18812 // Zero-width bitfield is ok for anonymous field.
18813 if (Value == 0 && FieldName)
18814 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18815 << FieldName << BitWidth->getSourceRange();
18816
18817 if (Value.isSigned() && Value.isNegative()) {
18818 if (FieldName)
18819 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18820 << FieldName << toString(Value, 10);
18821 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18822 << toString(Value, 10);
18823 }
18824
18825 // The size of the bit-field must not exceed our maximum permitted object
18826 // size.
18827 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18828 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18829 << !FieldName << FieldName << toString(Value, 10);
18830 }
18831
18832 if (!FieldTy->isDependentType()) {
18833 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18834 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18835 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18836
18837 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18838 // ABI.
18839 bool CStdConstraintViolation =
18840 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18841 bool MSBitfieldViolation =
18842 Value.ugt(TypeStorageSize) &&
18843 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18844 if (CStdConstraintViolation || MSBitfieldViolation) {
18845 unsigned DiagWidth =
18846 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18847 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18848 << (bool)FieldName << FieldName << toString(Value, 10)
18849 << !CStdConstraintViolation << DiagWidth;
18850 }
18851
18852 // Warn on types where the user might conceivably expect to get all
18853 // specified bits as value bits: that's all integral types other than
18854 // 'bool'.
18855 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18856 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18857 << FieldName << toString(Value, 10)
18858 << (unsigned)TypeWidth;
18859 }
18860 }
18861
18862 if (isa<ConstantExpr>(BitWidth))
18863 return BitWidth;
18864 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
18865}
18866
18868 Declarator &D, Expr *BitfieldWidth) {
18869 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18870 D, BitfieldWidth,
18871 /*InitStyle=*/ICIS_NoInit, AS_public);
18872 return Res;
18873}
18874
18876 SourceLocation DeclStart,
18877 Declarator &D, Expr *BitWidth,
18878 InClassInitStyle InitStyle,
18879 AccessSpecifier AS) {
18880 if (D.isDecompositionDeclarator()) {
18881 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18882 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18883 << Decomp.getSourceRange();
18884 return nullptr;
18885 }
18886
18887 const IdentifierInfo *II = D.getIdentifier();
18888 SourceLocation Loc = DeclStart;
18889 if (II) Loc = D.getIdentifierLoc();
18890
18892 QualType T = TInfo->getType();
18893 if (getLangOpts().CPlusPlus) {
18895
18896 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18898 D.setInvalidType();
18899 T = Context.IntTy;
18901 }
18902 }
18903
18904 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18905
18906 if (D.getDeclSpec().isInlineSpecified())
18907 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18908 << getLangOpts().CPlusPlus17;
18909 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18910 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18911 diag::err_invalid_thread)
18913
18914 // Check to see if this name was declared as a member previously
18915 NamedDecl *PrevDecl = nullptr;
18917 RedeclarationKind::ForVisibleRedeclaration);
18918 LookupName(Previous, S);
18919 switch (Previous.getResultKind()) {
18922 PrevDecl = Previous.getAsSingle<NamedDecl>();
18923 break;
18924
18926 PrevDecl = Previous.getRepresentativeDecl();
18927 break;
18928
18932 break;
18933 }
18934 Previous.suppressDiagnostics();
18935
18936 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18937 // Maybe we will complain about the shadowed template parameter.
18938 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18939 // Just pretend that we didn't see the previous declaration.
18940 PrevDecl = nullptr;
18941 }
18942
18943 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18944 PrevDecl = nullptr;
18945
18946 bool Mutable
18947 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18948 SourceLocation TSSL = D.getBeginLoc();
18949 FieldDecl *NewFD
18950 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18951 TSSL, AS, PrevDecl, &D);
18952
18953 if (NewFD->isInvalidDecl())
18954 Record->setInvalidDecl();
18955
18956 if (D.getDeclSpec().isModulePrivateSpecified())
18957 NewFD->setModulePrivate();
18958
18959 if (NewFD->isInvalidDecl() && PrevDecl) {
18960 // Don't introduce NewFD into scope; there's already something
18961 // with the same name in the same scope.
18962 } else if (II) {
18963 PushOnScopeChains(NewFD, S);
18964 } else
18965 Record->addDecl(NewFD);
18966
18967 return NewFD;
18968}
18969
18971 TypeSourceInfo *TInfo,
18973 bool Mutable, Expr *BitWidth,
18974 InClassInitStyle InitStyle,
18975 SourceLocation TSSL,
18976 AccessSpecifier AS, NamedDecl *PrevDecl,
18977 Declarator *D) {
18978 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18979 bool InvalidDecl = false;
18980 if (D) InvalidDecl = D->isInvalidType();
18981
18982 // If we receive a broken type, recover by assuming 'int' and
18983 // marking this declaration as invalid.
18984 if (T.isNull() || T->containsErrors()) {
18985 InvalidDecl = true;
18986 T = Context.IntTy;
18987 }
18988
18990 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18991 bool isIncomplete =
18992 LangOpts.HLSL // HLSL allows sizeless builtin types
18993 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
18995 diag::err_field_incomplete_or_sizeless);
18996 if (isIncomplete) {
18997 // Fields of incomplete type force their record to be invalid.
18998 Record->setInvalidDecl();
18999 InvalidDecl = true;
19000 } else {
19001 NamedDecl *Def;
19002 EltTy->isIncompleteType(&Def);
19003 if (Def && Def->isInvalidDecl()) {
19004 Record->setInvalidDecl();
19005 InvalidDecl = true;
19006 }
19007 }
19008 }
19009
19010 // TR 18037 does not allow fields to be declared with address space
19011 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19013 Diag(Loc, diag::err_field_with_address_space);
19014 Record->setInvalidDecl();
19015 InvalidDecl = true;
19016 }
19017
19018 if (LangOpts.OpenCL) {
19019 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19020 // used as structure or union field: image, sampler, event or block types.
19021 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19022 T->isBlockPointerType()) {
19023 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19024 Record->setInvalidDecl();
19025 InvalidDecl = true;
19026 }
19027 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19028 // is enabled.
19029 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19030 "__cl_clang_bitfields", LangOpts)) {
19031 Diag(Loc, diag::err_opencl_bitfields);
19032 InvalidDecl = true;
19033 }
19034 }
19035
19036 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19037 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19038 T.hasQualifiers()) {
19039 InvalidDecl = true;
19040 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19041 }
19042
19043 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19044 // than a variably modified type.
19045 if (!InvalidDecl && T->isVariablyModifiedType()) {
19047 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19048 InvalidDecl = true;
19049 }
19050
19051 // Fields can not have abstract class types
19052 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19053 diag::err_abstract_type_in_decl,
19055 InvalidDecl = true;
19056
19057 if (InvalidDecl)
19058 BitWidth = nullptr;
19059 // If this is declared as a bit-field, check the bit-field.
19060 if (BitWidth) {
19061 BitWidth =
19062 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19063 if (!BitWidth) {
19064 InvalidDecl = true;
19065 BitWidth = nullptr;
19066 }
19067 }
19068
19069 // Check that 'mutable' is consistent with the type of the declaration.
19070 if (!InvalidDecl && Mutable) {
19071 unsigned DiagID = 0;
19072 if (T->isReferenceType())
19073 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19074 : diag::err_mutable_reference;
19075 else if (T.isConstQualified())
19076 DiagID = diag::err_mutable_const;
19077
19078 if (DiagID) {
19079 SourceLocation ErrLoc = Loc;
19080 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19081 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19082 Diag(ErrLoc, DiagID);
19083 if (DiagID != diag::ext_mutable_reference) {
19084 Mutable = false;
19085 InvalidDecl = true;
19086 }
19087 }
19088 }
19089
19090 // C++11 [class.union]p8 (DR1460):
19091 // At most one variant member of a union may have a
19092 // brace-or-equal-initializer.
19093 if (InitStyle != ICIS_NoInit)
19094 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
19095
19096 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19097 BitWidth, Mutable, InitStyle);
19098 if (InvalidDecl)
19099 NewFD->setInvalidDecl();
19100
19101 if (!InvalidDecl)
19103
19104 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19105 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19106 Diag(Loc, diag::err_duplicate_member) << II;
19107 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19108 NewFD->setInvalidDecl();
19109 }
19110
19111 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19112 if (Record->isUnion()) {
19113 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19114 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19115
19116 // C++ [class.union]p1: An object of a class with a non-trivial
19117 // constructor, a non-trivial copy constructor, a non-trivial
19118 // destructor, or a non-trivial copy assignment operator
19119 // cannot be a member of a union, nor can an array of such
19120 // objects.
19121 if (CheckNontrivialField(NewFD))
19122 NewFD->setInvalidDecl();
19123 }
19124
19125 // C++ [class.union]p1: If a union contains a member of reference type,
19126 // the program is ill-formed, except when compiling with MSVC extensions
19127 // enabled.
19128 if (EltTy->isReferenceType()) {
19129 const bool HaveMSExt =
19130 getLangOpts().MicrosoftExt &&
19132
19133 Diag(NewFD->getLocation(),
19134 HaveMSExt ? diag::ext_union_member_of_reference_type
19135 : diag::err_union_member_of_reference_type)
19136 << NewFD->getDeclName() << EltTy;
19137 if (!HaveMSExt)
19138 NewFD->setInvalidDecl();
19139 }
19140 }
19141 }
19142
19143 // FIXME: We need to pass in the attributes given an AST
19144 // representation, not a parser representation.
19145 if (D) {
19146 // FIXME: The current scope is almost... but not entirely... correct here.
19148
19149 if (NewFD->hasAttrs())
19151 }
19152
19153 // In auto-retain/release, infer strong retension for fields of
19154 // retainable type.
19155 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19156 NewFD->setInvalidDecl();
19157
19158 if (T.isObjCGCWeak())
19159 Diag(Loc, diag::warn_attribute_weak_on_field);
19160
19161 // PPC MMA non-pointer types are not allowed as field types.
19162 if (Context.getTargetInfo().getTriple().isPPC64() &&
19163 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19164 NewFD->setInvalidDecl();
19165
19166 NewFD->setAccess(AS);
19167 return NewFD;
19168}
19169
19171 assert(FD);
19172 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19173
19174 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19175 return false;
19176
19178 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19179 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19180 // We check for copy constructors before constructors
19181 // because otherwise we'll never get complaints about
19182 // copy constructors.
19183
19185 // We're required to check for any non-trivial constructors. Since the
19186 // implicit default constructor is suppressed if there are any
19187 // user-declared constructors, we just need to check that there is a
19188 // trivial default constructor and a trivial copy constructor. (We don't
19189 // worry about move constructors here, since this is a C++98 check.)
19190 if (RDecl->hasNonTrivialCopyConstructor())
19192 else if (!RDecl->hasTrivialDefaultConstructor())
19194 else if (RDecl->hasNonTrivialCopyAssignment())
19196 else if (RDecl->hasNonTrivialDestructor())
19198
19199 if (member != CXXSpecialMemberKind::Invalid) {
19200 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19201 RDecl->hasObjectMember()) {
19202 // Objective-C++ ARC: it is an error to have a non-trivial field of
19203 // a union. However, system headers in Objective-C programs
19204 // occasionally have Objective-C lifetime objects within unions,
19205 // and rather than cause the program to fail, we make those
19206 // members unavailable.
19208 if (getSourceManager().isInSystemHeader(Loc)) {
19209 if (!FD->hasAttr<UnavailableAttr>())
19210 FD->addAttr(UnavailableAttr::CreateImplicit(
19211 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19212 return false;
19213 }
19214 }
19215
19216 Diag(FD->getLocation(),
19218 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19219 : diag::err_illegal_union_or_anon_struct_member)
19220 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19221 DiagnoseNontrivial(RDecl, member);
19222 return !getLangOpts().CPlusPlus11;
19223 }
19224 }
19225
19226 return false;
19227}
19228
19230 SmallVectorImpl<Decl *> &AllIvarDecls) {
19231 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19232 return;
19233
19234 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19235 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19236
19237 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19238 return;
19239 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19240 if (!ID) {
19241 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19242 if (!CD->IsClassExtension())
19243 return;
19244 }
19245 // No need to add this to end of @implementation.
19246 else
19247 return;
19248 }
19249 // All conditions are met. Add a new bitfield to the tail end of ivars.
19250 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19252 Expr *BitWidth =
19253 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19254
19255 Ivar = ObjCIvarDecl::Create(
19256 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19258 ObjCIvarDecl::Private, BitWidth, true);
19259 AllIvarDecls.push_back(Ivar);
19260}
19261
19262/// [class.dtor]p4:
19263/// At the end of the definition of a class, overload resolution is
19264/// performed among the prospective destructors declared in that class with
19265/// an empty argument list to select the destructor for the class, also
19266/// known as the selected destructor.
19267///
19268/// We do the overload resolution here, then mark the selected constructor in the AST.
19269/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19271 if (!Record->hasUserDeclaredDestructor()) {
19272 return;
19273 }
19274
19275 SourceLocation Loc = Record->getLocation();
19277
19278 for (auto *Decl : Record->decls()) {
19279 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19280 if (DD->isInvalidDecl())
19281 continue;
19282 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19283 OCS);
19284 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19285 }
19286 }
19287
19288 if (OCS.empty()) {
19289 return;
19290 }
19292 unsigned Msg = 0;
19293 OverloadCandidateDisplayKind DisplayKind;
19294
19295 switch (OCS.BestViableFunction(S, Loc, Best)) {
19296 case OR_Success:
19297 case OR_Deleted:
19298 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19299 break;
19300
19301 case OR_Ambiguous:
19302 Msg = diag::err_ambiguous_destructor;
19303 DisplayKind = OCD_AmbiguousCandidates;
19304 break;
19305
19307 Msg = diag::err_no_viable_destructor;
19308 DisplayKind = OCD_AllCandidates;
19309 break;
19310 }
19311
19312 if (Msg) {
19313 // OpenCL have got their own thing going with destructors. It's slightly broken,
19314 // but we allow it.
19315 if (!S.LangOpts.OpenCL) {
19316 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19317 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19318 Record->setInvalidDecl();
19319 }
19320 // It's a bit hacky: At this point we've raised an error but we want the
19321 // rest of the compiler to continue somehow working. However almost
19322 // everything we'll try to do with the class will depend on there being a
19323 // destructor. So let's pretend the first one is selected and hope for the
19324 // best.
19325 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19326 }
19327}
19328
19329/// [class.mem.special]p5
19330/// Two special member functions are of the same kind if:
19331/// - they are both default constructors,
19332/// - they are both copy or move constructors with the same first parameter
19333/// type, or
19334/// - they are both copy or move assignment operators with the same first
19335/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19337 CXXMethodDecl *M1,
19338 CXXMethodDecl *M2,
19340 // We don't want to compare templates to non-templates: See
19341 // https://github.com/llvm/llvm-project/issues/59206
19343 return bool(M1->getDescribedFunctionTemplate()) ==
19345 // FIXME: better resolve CWG
19346 // https://cplusplus.github.io/CWG/issues/2787.html
19347 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19348 M2->getNonObjectParameter(0)->getType()))
19349 return false;
19352 return false;
19353
19354 return true;
19355}
19356
19357/// [class.mem.special]p6:
19358/// An eligible special member function is a special member function for which:
19359/// - the function is not deleted,
19360/// - the associated constraints, if any, are satisfied, and
19361/// - no special member function of the same kind whose associated constraints
19362/// [CWG2595], if any, are satisfied is more constrained.
19366 SmallVector<bool, 4> SatisfactionStatus;
19367
19368 for (CXXMethodDecl *Method : Methods) {
19369 if (!Method->getTrailingRequiresClause())
19370 SatisfactionStatus.push_back(true);
19371 else {
19372 ConstraintSatisfaction Satisfaction;
19373 if (S.CheckFunctionConstraints(Method, Satisfaction))
19374 SatisfactionStatus.push_back(false);
19375 else
19376 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19377 }
19378 }
19379
19380 for (size_t i = 0; i < Methods.size(); i++) {
19381 if (!SatisfactionStatus[i])
19382 continue;
19383 CXXMethodDecl *Method = Methods[i];
19384 CXXMethodDecl *OrigMethod = Method;
19385 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19386 OrigMethod = cast<CXXMethodDecl>(MF);
19387
19389 bool AnotherMethodIsMoreConstrained = false;
19390 for (size_t j = 0; j < Methods.size(); j++) {
19391 if (i == j || !SatisfactionStatus[j])
19392 continue;
19393 CXXMethodDecl *OtherMethod = Methods[j];
19394 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19395 OtherMethod = cast<CXXMethodDecl>(MF);
19396
19397 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19398 CSM))
19399 continue;
19400
19402 if (!Other)
19403 continue;
19404 if (!Orig) {
19405 AnotherMethodIsMoreConstrained = true;
19406 break;
19407 }
19408 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
19409 AnotherMethodIsMoreConstrained)) {
19410 // There was an error with the constraints comparison. Exit the loop
19411 // and don't consider this function eligible.
19412 AnotherMethodIsMoreConstrained = true;
19413 }
19414 if (AnotherMethodIsMoreConstrained)
19415 break;
19416 }
19417 // FIXME: Do not consider deleted methods as eligible after implementing
19418 // DR1734 and DR1496.
19419 if (!AnotherMethodIsMoreConstrained) {
19420 Method->setIneligibleOrNotSelected(false);
19421 Record->addedEligibleSpecialMemberFunction(Method,
19422 1 << llvm::to_underlying(CSM));
19423 }
19424 }
19425}
19426
19429 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19430 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19431 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19432 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19433 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19434
19435 for (auto *Decl : Record->decls()) {
19436 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19437 if (!MD) {
19438 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19439 if (FTD)
19440 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19441 }
19442 if (!MD)
19443 continue;
19444 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19445 if (CD->isInvalidDecl())
19446 continue;
19447 if (CD->isDefaultConstructor())
19448 DefaultConstructors.push_back(MD);
19449 else if (CD->isCopyConstructor())
19450 CopyConstructors.push_back(MD);
19451 else if (CD->isMoveConstructor())
19452 MoveConstructors.push_back(MD);
19453 } else if (MD->isCopyAssignmentOperator()) {
19454 CopyAssignmentOperators.push_back(MD);
19455 } else if (MD->isMoveAssignmentOperator()) {
19456 MoveAssignmentOperators.push_back(MD);
19457 }
19458 }
19459
19460 SetEligibleMethods(S, Record, DefaultConstructors,
19462 SetEligibleMethods(S, Record, CopyConstructors,
19464 SetEligibleMethods(S, Record, MoveConstructors,
19466 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19468 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19470}
19471
19472bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19473 // Check to see if a FieldDecl is a pointer to a function.
19474 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19475 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19476 if (!FD) {
19477 // Check whether this is a forward declaration that was inserted by
19478 // Clang. This happens when a non-forward declared / defined type is
19479 // used, e.g.:
19480 //
19481 // struct foo {
19482 // struct bar *(*f)();
19483 // struct bar *(*g)();
19484 // };
19485 //
19486 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19487 // incomplete definition.
19488 if (const auto *TD = dyn_cast<TagDecl>(D))
19489 return !TD->isCompleteDefinition();
19490 return false;
19491 }
19492 QualType FieldType = FD->getType().getDesugaredType(Context);
19493 if (isa<PointerType>(FieldType)) {
19494 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19495 return PointeeType.getDesugaredType(Context)->isFunctionType();
19496 }
19497 // If a member is a struct entirely of function pointers, that counts too.
19498 if (const auto *Record = FieldType->getAsRecordDecl();
19499 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19500 return true;
19501 return false;
19502 };
19503
19504 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
19505}
19506
19507void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19508 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19509 SourceLocation RBrac,
19510 const ParsedAttributesView &Attrs) {
19511 assert(EnclosingDecl && "missing record or interface decl");
19512
19513 // If this is an Objective-C @implementation or category and we have
19514 // new fields here we should reset the layout of the interface since
19515 // it will now change.
19516 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19517 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19518 switch (DC->getKind()) {
19519 default: break;
19520 case Decl::ObjCCategory:
19521 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19522 break;
19523 case Decl::ObjCImplementation:
19524 Context.
19525 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19526 break;
19527 }
19528 }
19529
19530 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19531 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19532
19533 // Start counting up the number of named members; make sure to include
19534 // members of anonymous structs and unions in the total.
19535 unsigned NumNamedMembers = 0;
19536 if (Record) {
19537 for (const auto *I : Record->decls()) {
19538 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19539 if (IFD->getDeclName())
19540 ++NumNamedMembers;
19541 }
19542 }
19543
19544 // Verify that all the fields are okay.
19546 const FieldDecl *PreviousField = nullptr;
19547 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19548 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
19549 FieldDecl *FD = cast<FieldDecl>(*i);
19550
19551 // Get the type for the field.
19552 const Type *FDTy = FD->getType().getTypePtr();
19553
19554 if (!FD->isAnonymousStructOrUnion()) {
19555 // Remember all fields written by the user.
19556 RecFields.push_back(FD);
19557 }
19558
19559 // If the field is already invalid for some reason, don't emit more
19560 // diagnostics about it.
19561 if (FD->isInvalidDecl()) {
19562 EnclosingDecl->setInvalidDecl();
19563 continue;
19564 }
19565
19566 // C99 6.7.2.1p2:
19567 // A structure or union shall not contain a member with
19568 // incomplete or function type (hence, a structure shall not
19569 // contain an instance of itself, but may contain a pointer to
19570 // an instance of itself), except that the last member of a
19571 // structure with more than one named member may have incomplete
19572 // array type; such a structure (and any union containing,
19573 // possibly recursively, a member that is such a structure)
19574 // shall not be a member of a structure or an element of an
19575 // array.
19576 bool IsLastField = (i + 1 == Fields.end());
19577 if (FDTy->isFunctionType()) {
19578 // Field declared as a function.
19579 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19580 << FD->getDeclName();
19581 FD->setInvalidDecl();
19582 EnclosingDecl->setInvalidDecl();
19583 continue;
19584 } else if (FDTy->isIncompleteArrayType() &&
19585 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19586 if (Record) {
19587 // Flexible array member.
19588 // Microsoft and g++ is more permissive regarding flexible array.
19589 // It will accept flexible array in union and also
19590 // as the sole element of a struct/class.
19591 unsigned DiagID = 0;
19592 if (!Record->isUnion() && !IsLastField) {
19593 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19594 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19595 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19596 FD->setInvalidDecl();
19597 EnclosingDecl->setInvalidDecl();
19598 continue;
19599 } else if (Record->isUnion())
19600 DiagID = getLangOpts().MicrosoftExt
19601 ? diag::ext_flexible_array_union_ms
19602 : diag::ext_flexible_array_union_gnu;
19603 else if (NumNamedMembers < 1)
19604 DiagID = getLangOpts().MicrosoftExt
19605 ? diag::ext_flexible_array_empty_aggregate_ms
19606 : diag::ext_flexible_array_empty_aggregate_gnu;
19607
19608 if (DiagID)
19609 Diag(FD->getLocation(), DiagID)
19610 << FD->getDeclName() << Record->getTagKind();
19611 // While the layout of types that contain virtual bases is not specified
19612 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19613 // virtual bases after the derived members. This would make a flexible
19614 // array member declared at the end of an object not adjacent to the end
19615 // of the type.
19616 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19617 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19618 << FD->getDeclName() << Record->getTagKind();
19619 if (!getLangOpts().C99)
19620 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19621 << FD->getDeclName() << Record->getTagKind();
19622
19623 // If the element type has a non-trivial destructor, we would not
19624 // implicitly destroy the elements, so disallow it for now.
19625 //
19626 // FIXME: GCC allows this. We should probably either implicitly delete
19627 // the destructor of the containing class, or just allow this.
19628 QualType BaseElem = Context.getBaseElementType(FD->getType());
19629 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19630 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19631 << FD->getDeclName() << FD->getType();
19632 FD->setInvalidDecl();
19633 EnclosingDecl->setInvalidDecl();
19634 continue;
19635 }
19636 // Okay, we have a legal flexible array member at the end of the struct.
19637 Record->setHasFlexibleArrayMember(true);
19638 } else {
19639 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19640 // unless they are followed by another ivar. That check is done
19641 // elsewhere, after synthesized ivars are known.
19642 }
19643 } else if (!FDTy->isDependentType() &&
19644 (LangOpts.HLSL // HLSL allows sizeless builtin types
19646 diag::err_incomplete_type)
19648 FD->getLocation(), FD->getType(),
19649 diag::err_field_incomplete_or_sizeless))) {
19650 // Incomplete type
19651 FD->setInvalidDecl();
19652 EnclosingDecl->setInvalidDecl();
19653 continue;
19654 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
19655 if (Record && RD->hasFlexibleArrayMember()) {
19656 // A type which contains a flexible array member is considered to be a
19657 // flexible array member.
19658 Record->setHasFlexibleArrayMember(true);
19659 if (!Record->isUnion()) {
19660 // If this is a struct/class and this is not the last element, reject
19661 // it. Note that GCC supports variable sized arrays in the middle of
19662 // structures.
19663 if (!IsLastField)
19664 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19665 << FD->getDeclName() << FD->getType();
19666 else {
19667 // We support flexible arrays at the end of structs in
19668 // other structs as an extension.
19669 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19670 << FD->getDeclName();
19671 }
19672 }
19673 }
19674 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19676 diag::err_abstract_type_in_decl,
19678 // Ivars can not have abstract class types
19679 FD->setInvalidDecl();
19680 }
19681 if (Record && RD->hasObjectMember())
19682 Record->setHasObjectMember(true);
19683 if (Record && RD->hasVolatileMember())
19684 Record->setHasVolatileMember(true);
19685 } else if (FDTy->isObjCObjectType()) {
19686 /// A field cannot be an Objective-c object
19687 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19690 FD->setType(T);
19691 } else if (Record && Record->isUnion() &&
19693 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19694 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19697 // For backward compatibility, fields of C unions declared in system
19698 // headers that have non-trivial ObjC ownership qualifications are marked
19699 // as unavailable unless the qualifier is explicit and __strong. This can
19700 // break ABI compatibility between programs compiled with ARC and MRR, but
19701 // is a better option than rejecting programs using those unions under
19702 // ARC.
19703 FD->addAttr(UnavailableAttr::CreateImplicit(
19704 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19705 FD->getLocation()));
19706 } else if (getLangOpts().ObjC &&
19707 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19708 !Record->hasObjectMember()) {
19709 if (FD->getType()->isObjCObjectPointerType() ||
19710 FD->getType().isObjCGCStrong())
19711 Record->setHasObjectMember(true);
19712 else if (Context.getAsArrayType(FD->getType())) {
19713 QualType BaseType = Context.getBaseElementType(FD->getType());
19714 if (const auto *RD = BaseType->getAsRecordDecl();
19715 RD && RD->hasObjectMember())
19716 Record->setHasObjectMember(true);
19717 else if (BaseType->isObjCObjectPointerType() ||
19718 BaseType.isObjCGCStrong())
19719 Record->setHasObjectMember(true);
19720 }
19721 }
19722
19723 if (Record && !getLangOpts().CPlusPlus &&
19724 !shouldIgnoreForRecordTriviality(FD)) {
19725 QualType FT = FD->getType();
19727 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19729 Record->isUnion())
19730 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19731 }
19734 Record->setNonTrivialToPrimitiveCopy(true);
19735 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19736 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19737 }
19738 if (FD->hasAttr<ExplicitInitAttr>())
19739 Record->setHasUninitializedExplicitInitFields(true);
19740 if (FT.isDestructedType()) {
19741 Record->setNonTrivialToPrimitiveDestroy(true);
19742 Record->setParamDestroyedInCallee(true);
19743 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19744 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19745 }
19746
19747 if (const auto *RD = FT->getAsRecordDecl()) {
19748 if (RD->getArgPassingRestrictions() ==
19750 Record->setArgPassingRestrictions(
19752 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
19753 Record->setArgPassingRestrictions(
19755 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
19756 Q && Q.isAddressDiscriminated()) {
19757 Record->setArgPassingRestrictions(
19759 Record->setNonTrivialToPrimitiveCopy(true);
19760 }
19761 }
19762
19763 if (Record && FD->getType().isVolatileQualified())
19764 Record->setHasVolatileMember(true);
19765 bool ReportMSBitfieldStoragePacking =
19766 Record && PreviousField &&
19767 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
19768 Record->getLocation());
19769 auto IsNonDependentBitField = [](const FieldDecl *FD) {
19770 return FD->isBitField() && !FD->getType()->isDependentType();
19771 };
19772
19773 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
19774 IsNonDependentBitField(PreviousField)) {
19775 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
19776 CharUnits PreviousFieldStorageSize =
19777 Context.getTypeSizeInChars(PreviousField->getType());
19778 if (FDStorageSize != PreviousFieldStorageSize) {
19779 Diag(FD->getLocation(),
19780 diag::warn_ms_bitfield_mismatched_storage_packing)
19781 << FD << FD->getType() << FDStorageSize.getQuantity()
19782 << PreviousFieldStorageSize.getQuantity();
19783 Diag(PreviousField->getLocation(),
19784 diag::note_ms_bitfield_mismatched_storage_size_previous)
19785 << PreviousField << PreviousField->getType();
19786 }
19787 }
19788 // Keep track of the number of named members.
19789 if (FD->getIdentifier())
19790 ++NumNamedMembers;
19791 }
19792
19793 // Okay, we successfully defined 'Record'.
19794 if (Record) {
19795 bool Completed = false;
19796 if (S) {
19797 Scope *Parent = S->getParent();
19798 if (Parent && Parent->isTypeAliasScope() &&
19799 Parent->isTemplateParamScope())
19800 Record->setInvalidDecl();
19801 }
19802
19803 if (CXXRecord) {
19804 if (!CXXRecord->isInvalidDecl()) {
19805 // Set access bits correctly on the directly-declared conversions.
19807 I = CXXRecord->conversion_begin(),
19808 E = CXXRecord->conversion_end(); I != E; ++I)
19809 I.setAccess((*I)->getAccess());
19810 }
19811
19812 // Add any implicitly-declared members to this class.
19814
19815 if (!CXXRecord->isDependentType()) {
19816 if (!CXXRecord->isInvalidDecl()) {
19817 // If we have virtual base classes, we may end up finding multiple
19818 // final overriders for a given virtual function. Check for this
19819 // problem now.
19820 if (CXXRecord->getNumVBases()) {
19821 CXXFinalOverriderMap FinalOverriders;
19822 CXXRecord->getFinalOverriders(FinalOverriders);
19823
19824 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19825 MEnd = FinalOverriders.end();
19826 M != MEnd; ++M) {
19827 for (OverridingMethods::iterator SO = M->second.begin(),
19828 SOEnd = M->second.end();
19829 SO != SOEnd; ++SO) {
19830 assert(SO->second.size() > 0 &&
19831 "Virtual function without overriding functions?");
19832 if (SO->second.size() == 1)
19833 continue;
19834
19835 // C++ [class.virtual]p2:
19836 // In a derived class, if a virtual member function of a base
19837 // class subobject has more than one final overrider the
19838 // program is ill-formed.
19839 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19840 << (const NamedDecl *)M->first << Record;
19841 Diag(M->first->getLocation(),
19842 diag::note_overridden_virtual_function);
19844 OM = SO->second.begin(),
19845 OMEnd = SO->second.end();
19846 OM != OMEnd; ++OM)
19847 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19848 << (const NamedDecl *)M->first << OM->Method->getParent();
19849
19850 Record->setInvalidDecl();
19851 }
19852 }
19853 CXXRecord->completeDefinition(&FinalOverriders);
19854 Completed = true;
19855 }
19856 }
19857 ComputeSelectedDestructor(*this, CXXRecord);
19859 }
19860 }
19861
19862 if (!Completed)
19863 Record->completeDefinition();
19864
19865 // Handle attributes before checking the layout.
19867
19868 // Maybe randomize the record's decls. We automatically randomize a record
19869 // of function pointers, unless it has the "no_randomize_layout" attribute.
19870 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
19871 !Record->isRandomized() && !Record->isUnion() &&
19872 (Record->hasAttr<RandomizeLayoutAttr>() ||
19873 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19874 EntirelyFunctionPointers(Record)))) {
19875 SmallVector<Decl *, 32> NewDeclOrdering;
19877 NewDeclOrdering))
19878 Record->reorderDecls(NewDeclOrdering);
19879 }
19880
19881 // We may have deferred checking for a deleted destructor. Check now.
19882 if (CXXRecord) {
19883 auto *Dtor = CXXRecord->getDestructor();
19884 if (Dtor && Dtor->isImplicit() &&
19886 CXXRecord->setImplicitDestructorIsDeleted();
19887 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19888 }
19889 }
19890
19891 if (Record->hasAttrs()) {
19893
19894 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19895 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19896 IA->getRange(), IA->getBestCase(),
19897 IA->getInheritanceModel());
19898 }
19899
19900 // Check if the structure/union declaration is a type that can have zero
19901 // size in C. For C this is a language extension, for C++ it may cause
19902 // compatibility problems.
19903 bool CheckForZeroSize;
19904 if (!getLangOpts().CPlusPlus) {
19905 CheckForZeroSize = true;
19906 } else {
19907 // For C++ filter out types that cannot be referenced in C code.
19908 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19909 CheckForZeroSize =
19910 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19911 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19912 CXXRecord->isCLike();
19913 }
19914 if (CheckForZeroSize) {
19915 bool ZeroSize = true;
19916 bool IsEmpty = true;
19917 unsigned NonBitFields = 0;
19918 for (RecordDecl::field_iterator I = Record->field_begin(),
19919 E = Record->field_end();
19920 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19921 IsEmpty = false;
19922 if (I->isUnnamedBitField()) {
19923 if (!I->isZeroLengthBitField())
19924 ZeroSize = false;
19925 } else {
19926 ++NonBitFields;
19927 QualType FieldType = I->getType();
19928 if (FieldType->isIncompleteType() ||
19929 !Context.getTypeSizeInChars(FieldType).isZero())
19930 ZeroSize = false;
19931 }
19932 }
19933
19934 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19935 // allowed in C++, but warn if its declaration is inside
19936 // extern "C" block.
19937 if (ZeroSize) {
19938 Diag(RecLoc, getLangOpts().CPlusPlus ?
19939 diag::warn_zero_size_struct_union_in_extern_c :
19940 diag::warn_zero_size_struct_union_compat)
19941 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19942 }
19943
19944 // Structs without named members are extension in C (C99 6.7.2.1p7),
19945 // but are accepted by GCC. In C2y, this became implementation-defined
19946 // (C2y 6.7.3.2p10).
19947 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
19948 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
19949 : diag::ext_no_named_members_in_struct_union)
19950 << Record->isUnion();
19951 }
19952 }
19953 } else {
19954 ObjCIvarDecl **ClsFields =
19955 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19956 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19957 ID->setEndOfDefinitionLoc(RBrac);
19958 // Add ivar's to class's DeclContext.
19959 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19960 ClsFields[i]->setLexicalDeclContext(ID);
19961 ID->addDecl(ClsFields[i]);
19962 }
19963 // Must enforce the rule that ivars in the base classes may not be
19964 // duplicates.
19965 if (ID->getSuperClass())
19966 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19967 } else if (ObjCImplementationDecl *IMPDecl =
19968 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19969 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19970 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19971 // Ivar declared in @implementation never belongs to the implementation.
19972 // Only it is in implementation's lexical context.
19973 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19974 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
19975 RBrac);
19976 IMPDecl->setIvarLBraceLoc(LBrac);
19977 IMPDecl->setIvarRBraceLoc(RBrac);
19978 } else if (ObjCCategoryDecl *CDecl =
19979 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19980 // case of ivars in class extension; all other cases have been
19981 // reported as errors elsewhere.
19982 // FIXME. Class extension does not have a LocEnd field.
19983 // CDecl->setLocEnd(RBrac);
19984 // Add ivar's to class extension's DeclContext.
19985 // Diagnose redeclaration of private ivars.
19986 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19987 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19988 if (IDecl) {
19989 if (const ObjCIvarDecl *ClsIvar =
19990 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19991 Diag(ClsFields[i]->getLocation(),
19992 diag::err_duplicate_ivar_declaration);
19993 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19994 continue;
19995 }
19996 for (const auto *Ext : IDecl->known_extensions()) {
19997 if (const ObjCIvarDecl *ClsExtIvar
19998 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19999 Diag(ClsFields[i]->getLocation(),
20000 diag::err_duplicate_ivar_declaration);
20001 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20002 continue;
20003 }
20004 }
20005 }
20006 ClsFields[i]->setLexicalDeclContext(CDecl);
20007 CDecl->addDecl(ClsFields[i]);
20008 }
20009 CDecl->setIvarLBraceLoc(LBrac);
20010 CDecl->setIvarRBraceLoc(RBrac);
20011 }
20012 }
20014}
20015
20016// Given an integral type, return the next larger integral type
20017// (or a NULL type of no such type exists).
20019 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20020 // enum checking below.
20021 assert((T->isIntegralType(Context) ||
20022 T->isEnumeralType()) && "Integral type required!");
20023 const unsigned NumTypes = 4;
20024 QualType SignedIntegralTypes[NumTypes] = {
20025 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20026 };
20027 QualType UnsignedIntegralTypes[NumTypes] = {
20028 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20029 Context.UnsignedLongLongTy
20030 };
20031
20032 unsigned BitWidth = Context.getTypeSize(T);
20033 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20034 : UnsignedIntegralTypes;
20035 for (unsigned I = 0; I != NumTypes; ++I)
20036 if (Context.getTypeSize(Types[I]) > BitWidth)
20037 return Types[I];
20038
20039 return QualType();
20040}
20041
20043 EnumConstantDecl *LastEnumConst,
20044 SourceLocation IdLoc,
20046 Expr *Val) {
20047 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20048 llvm::APSInt EnumVal(IntWidth);
20049 QualType EltTy;
20050
20052 Val = nullptr;
20053
20054 if (Val)
20055 Val = DefaultLvalueConversion(Val).get();
20056
20057 if (Val) {
20058 if (Enum->isDependentType() || Val->isTypeDependent() ||
20059 Val->containsErrors())
20060 EltTy = Context.DependentTy;
20061 else {
20062 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20063 // underlying type, but do allow it in all other contexts.
20064 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20065 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20066 // constant-expression in the enumerator-definition shall be a converted
20067 // constant expression of the underlying type.
20068 EltTy = Enum->getIntegerType();
20070 Val, EltTy, EnumVal, CCEKind::Enumerator);
20071 if (Converted.isInvalid())
20072 Val = nullptr;
20073 else
20074 Val = Converted.get();
20075 } else if (!Val->isValueDependent() &&
20076 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20078 .get())) {
20079 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20080 } else {
20081 if (Enum->isComplete()) {
20082 EltTy = Enum->getIntegerType();
20083
20084 // In Obj-C and Microsoft mode, require the enumeration value to be
20085 // representable in the underlying type of the enumeration. In C++11,
20086 // we perform a non-narrowing conversion as part of converted constant
20087 // expression checking.
20088 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20090 .getTriple()
20091 .isWindowsMSVCEnvironment()) {
20092 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20093 } else {
20094 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20095 }
20096 }
20097
20098 // Cast to the underlying type.
20099 Val = ImpCastExprToType(Val, EltTy,
20100 EltTy->isBooleanType() ? CK_IntegralToBoolean
20101 : CK_IntegralCast)
20102 .get();
20103 } else if (getLangOpts().CPlusPlus) {
20104 // C++11 [dcl.enum]p5:
20105 // If the underlying type is not fixed, the type of each enumerator
20106 // is the type of its initializing value:
20107 // - If an initializer is specified for an enumerator, the
20108 // initializing value has the same type as the expression.
20109 EltTy = Val->getType();
20110 } else {
20111 // C99 6.7.2.2p2:
20112 // The expression that defines the value of an enumeration constant
20113 // shall be an integer constant expression that has a value
20114 // representable as an int.
20115
20116 // Complain if the value is not representable in an int.
20118 Diag(IdLoc, getLangOpts().C23
20119 ? diag::warn_c17_compat_enum_value_not_int
20120 : diag::ext_c23_enum_value_not_int)
20121 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20122 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20123 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20124 // Force the type of the expression to 'int'.
20125 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20126 }
20127 EltTy = Val->getType();
20128 }
20129 }
20130 }
20131 }
20132
20133 if (!Val) {
20134 if (Enum->isDependentType())
20135 EltTy = Context.DependentTy;
20136 else if (!LastEnumConst) {
20137 // C++0x [dcl.enum]p5:
20138 // If the underlying type is not fixed, the type of each enumerator
20139 // is the type of its initializing value:
20140 // - If no initializer is specified for the first enumerator, the
20141 // initializing value has an unspecified integral type.
20142 //
20143 // GCC uses 'int' for its unspecified integral type, as does
20144 // C99 6.7.2.2p3.
20145 if (Enum->isFixed()) {
20146 EltTy = Enum->getIntegerType();
20147 }
20148 else {
20149 EltTy = Context.IntTy;
20150 }
20151 } else {
20152 // Assign the last value + 1.
20153 EnumVal = LastEnumConst->getInitVal();
20154 ++EnumVal;
20155 EltTy = LastEnumConst->getType();
20156
20157 // Check for overflow on increment.
20158 if (EnumVal < LastEnumConst->getInitVal()) {
20159 // C++0x [dcl.enum]p5:
20160 // If the underlying type is not fixed, the type of each enumerator
20161 // is the type of its initializing value:
20162 //
20163 // - Otherwise the type of the initializing value is the same as
20164 // the type of the initializing value of the preceding enumerator
20165 // unless the incremented value is not representable in that type,
20166 // in which case the type is an unspecified integral type
20167 // sufficient to contain the incremented value. If no such type
20168 // exists, the program is ill-formed.
20170 if (T.isNull() || Enum->isFixed()) {
20171 // There is no integral type larger enough to represent this
20172 // value. Complain, then allow the value to wrap around.
20173 EnumVal = LastEnumConst->getInitVal();
20174 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20175 ++EnumVal;
20176 if (Enum->isFixed())
20177 // When the underlying type is fixed, this is ill-formed.
20178 Diag(IdLoc, diag::err_enumerator_wrapped)
20179 << toString(EnumVal, 10)
20180 << EltTy;
20181 else
20182 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20183 << toString(EnumVal, 10);
20184 } else {
20185 EltTy = T;
20186 }
20187
20188 // Retrieve the last enumerator's value, extent that type to the
20189 // type that is supposed to be large enough to represent the incremented
20190 // value, then increment.
20191 EnumVal = LastEnumConst->getInitVal();
20192 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20193 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20194 ++EnumVal;
20195
20196 // If we're not in C++, diagnose the overflow of enumerator values,
20197 // which in C99 means that the enumerator value is not representable in
20198 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20199 // are representable in some larger integral type and we allow it in
20200 // older language modes as an extension.
20201 // Exclude fixed enumerators since they are diagnosed with an error for
20202 // this case.
20203 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20204 Diag(IdLoc, getLangOpts().C23
20205 ? diag::warn_c17_compat_enum_value_not_int
20206 : diag::ext_c23_enum_value_not_int)
20207 << 1 << toString(EnumVal, 10) << 1;
20208 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20209 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20210 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20211 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20212 : diag::ext_c23_enum_value_not_int)
20213 << 1 << toString(EnumVal, 10) << 1;
20214 }
20215 }
20216 }
20217
20218 if (!EltTy->isDependentType()) {
20219 // Make the enumerator value match the signedness and size of the
20220 // enumerator's type.
20221 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20222 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20223 }
20224
20225 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20226 Val, EnumVal);
20227}
20228
20230 SourceLocation IILoc) {
20231 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20233 return SkipBodyInfo();
20234
20235 // We have an anonymous enum definition. Look up the first enumerator to
20236 // determine if we should merge the definition with an existing one and
20237 // skip the body.
20238 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20240 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20241 if (!PrevECD)
20242 return SkipBodyInfo();
20243
20244 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20245 NamedDecl *Hidden;
20246 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20248 Skip.Previous = Hidden;
20249 return Skip;
20250 }
20251
20252 return SkipBodyInfo();
20253}
20254
20255Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20257 const ParsedAttributesView &Attrs,
20258 SourceLocation EqualLoc, Expr *Val,
20259 SkipBodyInfo *SkipBody) {
20260 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20261 EnumConstantDecl *LastEnumConst =
20262 cast_or_null<EnumConstantDecl>(lastEnumConst);
20263
20264 // The scope passed in may not be a decl scope. Zip up the scope tree until
20265 // we find one that is.
20266 S = getNonFieldDeclScope(S);
20267
20268 // Verify that there isn't already something declared with this name in this
20269 // scope.
20270 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20271 RedeclarationKind::ForVisibleRedeclaration);
20272 LookupName(R, S);
20273 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20274
20275 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20276 // Maybe we will complain about the shadowed template parameter.
20277 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20278 // Just pretend that we didn't see the previous declaration.
20279 PrevDecl = nullptr;
20280 }
20281
20282 // C++ [class.mem]p15:
20283 // If T is the name of a class, then each of the following shall have a name
20284 // different from T:
20285 // - every enumerator of every member of class T that is an unscoped
20286 // enumerated type
20287 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20289 DeclarationNameInfo(Id, IdLoc)))
20290 return nullptr;
20291
20293 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20294 if (!New)
20295 return nullptr;
20296
20297 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20298 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20299 // Check for other kinds of shadowing not already handled.
20300 CheckShadow(New, PrevDecl, R);
20301 }
20302
20303 // When in C++, we may get a TagDecl with the same name; in this case the
20304 // enum constant will 'hide' the tag.
20305 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20306 "Received TagDecl when not in C++!");
20307 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20308 if (isa<EnumConstantDecl>(PrevDecl))
20309 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20310 else
20311 Diag(IdLoc, diag::err_redefinition) << Id;
20312 notePreviousDefinition(PrevDecl, IdLoc);
20313 return nullptr;
20314 }
20315 }
20316
20317 // Process attributes.
20318 ProcessDeclAttributeList(S, New, Attrs);
20321
20322 // Register this decl in the current scope stack.
20323 New->setAccess(TheEnumDecl->getAccess());
20325
20327
20328 return New;
20329}
20330
20331// Returns true when the enum initial expression does not trigger the
20332// duplicate enum warning. A few common cases are exempted as follows:
20333// Element2 = Element1
20334// Element2 = Element1 + 1
20335// Element2 = Element1 - 1
20336// Where Element2 and Element1 are from the same enum.
20338 Expr *InitExpr = ECD->getInitExpr();
20339 if (!InitExpr)
20340 return true;
20341 InitExpr = InitExpr->IgnoreImpCasts();
20342
20343 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20344 if (!BO->isAdditiveOp())
20345 return true;
20346 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20347 if (!IL)
20348 return true;
20349 if (IL->getValue() != 1)
20350 return true;
20351
20352 InitExpr = BO->getLHS();
20353 }
20354
20355 // This checks if the elements are from the same enum.
20356 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20357 if (!DRE)
20358 return true;
20359
20360 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20361 if (!EnumConstant)
20362 return true;
20363
20364 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
20365 Enum)
20366 return true;
20367
20368 return false;
20369}
20370
20371// Emits a warning when an element is implicitly set a value that
20372// a previous element has already been set to.
20375 // Avoid anonymous enums
20376 if (!Enum->getIdentifier())
20377 return;
20378
20379 // Only check for small enums.
20380 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20381 return;
20382
20383 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20384 return;
20385
20386 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20387 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20388
20389 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20390
20391 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20392 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20393
20394 // Use int64_t as a key to avoid needing special handling for map keys.
20395 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20396 llvm::APSInt Val = D->getInitVal();
20397 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20398 };
20399
20400 DuplicatesVector DupVector;
20401 ValueToVectorMap EnumMap;
20402
20403 // Populate the EnumMap with all values represented by enum constants without
20404 // an initializer.
20405 for (auto *Element : Elements) {
20406 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20407
20408 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20409 // this constant. Skip this enum since it may be ill-formed.
20410 if (!ECD) {
20411 return;
20412 }
20413
20414 // Constants with initializers are handled in the next loop.
20415 if (ECD->getInitExpr())
20416 continue;
20417
20418 // Duplicate values are handled in the next loop.
20419 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20420 }
20421
20422 if (EnumMap.size() == 0)
20423 return;
20424
20425 // Create vectors for any values that has duplicates.
20426 for (auto *Element : Elements) {
20427 // The last loop returned if any constant was null.
20428 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
20429 if (!ValidDuplicateEnum(ECD, Enum))
20430 continue;
20431
20432 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20433 if (Iter == EnumMap.end())
20434 continue;
20435
20436 DeclOrVector& Entry = Iter->second;
20437 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
20438 // Ensure constants are different.
20439 if (D == ECD)
20440 continue;
20441
20442 // Create new vector and push values onto it.
20443 auto Vec = std::make_unique<ECDVector>();
20444 Vec->push_back(D);
20445 Vec->push_back(ECD);
20446
20447 // Update entry to point to the duplicates vector.
20448 Entry = Vec.get();
20449
20450 // Store the vector somewhere we can consult later for quick emission of
20451 // diagnostics.
20452 DupVector.emplace_back(std::move(Vec));
20453 continue;
20454 }
20455
20456 ECDVector *Vec = cast<ECDVector *>(Entry);
20457 // Make sure constants are not added more than once.
20458 if (*Vec->begin() == ECD)
20459 continue;
20460
20461 Vec->push_back(ECD);
20462 }
20463
20464 // Emit diagnostics.
20465 for (const auto &Vec : DupVector) {
20466 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20467
20468 // Emit warning for one enum constant.
20469 auto *FirstECD = Vec->front();
20470 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20471 << FirstECD << toString(FirstECD->getInitVal(), 10)
20472 << FirstECD->getSourceRange();
20473
20474 // Emit one note for each of the remaining enum constants with
20475 // the same value.
20476 for (auto *ECD : llvm::drop_begin(*Vec))
20477 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20478 << ECD << toString(ECD->getInitVal(), 10)
20479 << ECD->getSourceRange();
20480 }
20481}
20482
20483bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20484 bool AllowMask) const {
20485 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20486 assert(ED->isCompleteDefinition() && "expected enum definition");
20487
20488 auto R = FlagBitsCache.try_emplace(ED);
20489 llvm::APInt &FlagBits = R.first->second;
20490
20491 if (R.second) {
20492 for (auto *E : ED->enumerators()) {
20493 const auto &EVal = E->getInitVal();
20494 // Only single-bit enumerators introduce new flag values.
20495 if (EVal.isPowerOf2())
20496 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20497 }
20498 }
20499
20500 // A value is in a flag enum if either its bits are a subset of the enum's
20501 // flag bits (the first condition) or we are allowing masks and the same is
20502 // true of its complement (the second condition). When masks are allowed, we
20503 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20504 //
20505 // While it's true that any value could be used as a mask, the assumption is
20506 // that a mask will have all of the insignificant bits set. Anything else is
20507 // likely a logic error.
20508 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20509 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20510}
20511
20513 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20514 const ParsedAttributesView &Attrs) {
20515 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20517
20518 ProcessDeclAttributeList(S, Enum, Attrs);
20520
20521 if (Enum->isDependentType()) {
20522 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20523 EnumConstantDecl *ECD =
20524 cast_or_null<EnumConstantDecl>(Elements[i]);
20525 if (!ECD) continue;
20526
20527 ECD->setType(EnumType);
20528 }
20529
20530 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20531 return;
20532 }
20533
20534 // Verify that all the values are okay, compute the size of the values, and
20535 // reverse the list.
20536 unsigned NumNegativeBits = 0;
20537 unsigned NumPositiveBits = 0;
20538 bool MembersRepresentableByInt =
20539 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
20540
20541 // Figure out the type that should be used for this enum.
20542 QualType BestType;
20543 unsigned BestWidth;
20544
20545 // C++0x N3000 [conv.prom]p3:
20546 // An rvalue of an unscoped enumeration type whose underlying
20547 // type is not fixed can be converted to an rvalue of the first
20548 // of the following types that can represent all the values of
20549 // the enumeration: int, unsigned int, long int, unsigned long
20550 // int, long long int, or unsigned long long int.
20551 // C99 6.4.4.3p2:
20552 // An identifier declared as an enumeration constant has type int.
20553 // The C99 rule is modified by C23.
20554 QualType BestPromotionType;
20555
20556 bool Packed = Enum->hasAttr<PackedAttr>();
20557 // -fshort-enums is the equivalent to specifying the packed attribute on all
20558 // enum definitions.
20559 if (LangOpts.ShortEnums)
20560 Packed = true;
20561
20562 // If the enum already has a type because it is fixed or dictated by the
20563 // target, promote that type instead of analyzing the enumerators.
20564 if (Enum->isComplete()) {
20565 BestType = Enum->getIntegerType();
20566 if (Context.isPromotableIntegerType(BestType))
20567 BestPromotionType = Context.getPromotedIntegerType(BestType);
20568 else
20569 BestPromotionType = BestType;
20570
20571 BestWidth = Context.getIntWidth(BestType);
20572 } else {
20573 bool EnumTooLarge = Context.computeBestEnumTypes(
20574 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20575 BestWidth = Context.getIntWidth(BestType);
20576 if (EnumTooLarge)
20577 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20578 }
20579
20580 // Loop over all of the enumerator constants, changing their types to match
20581 // the type of the enum if needed.
20582 for (auto *D : Elements) {
20583 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20584 if (!ECD) continue; // Already issued a diagnostic.
20585
20586 // C99 says the enumerators have int type, but we allow, as an
20587 // extension, the enumerators to be larger than int size. If each
20588 // enumerator value fits in an int, type it as an int, otherwise type it the
20589 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20590 // that X has type 'int', not 'unsigned'.
20591
20592 // Determine whether the value fits into an int.
20593 llvm::APSInt InitVal = ECD->getInitVal();
20594
20595 // If it fits into an integer type, force it. Otherwise force it to match
20596 // the enum decl type.
20597 QualType NewTy;
20598 unsigned NewWidth;
20599 bool NewSign;
20600 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20601 MembersRepresentableByInt) {
20602 // C23 6.7.3.3.3p15:
20603 // The enumeration member type for an enumerated type without fixed
20604 // underlying type upon completion is:
20605 // - int if all the values of the enumeration are representable as an
20606 // int; or,
20607 // - the enumerated type
20608 NewTy = Context.IntTy;
20609 NewWidth = Context.getTargetInfo().getIntWidth();
20610 NewSign = true;
20611 } else if (ECD->getType() == BestType) {
20612 // Already the right type!
20613 if (getLangOpts().CPlusPlus)
20614 // C++ [dcl.enum]p4: Following the closing brace of an
20615 // enum-specifier, each enumerator has the type of its
20616 // enumeration.
20617 ECD->setType(EnumType);
20618 continue;
20619 } else {
20620 NewTy = BestType;
20621 NewWidth = BestWidth;
20622 NewSign = BestType->isSignedIntegerOrEnumerationType();
20623 }
20624
20625 // Adjust the APSInt value.
20626 InitVal = InitVal.extOrTrunc(NewWidth);
20627 InitVal.setIsSigned(NewSign);
20628 ECD->setInitVal(Context, InitVal);
20629
20630 // Adjust the Expr initializer and type.
20631 if (ECD->getInitExpr() &&
20632 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20633 ECD->setInitExpr(ImplicitCastExpr::Create(
20634 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20635 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20636 if (getLangOpts().CPlusPlus)
20637 // C++ [dcl.enum]p4: Following the closing brace of an
20638 // enum-specifier, each enumerator has the type of its
20639 // enumeration.
20640 ECD->setType(EnumType);
20641 else
20642 ECD->setType(NewTy);
20643 }
20644
20645 Enum->completeDefinition(BestType, BestPromotionType,
20646 NumPositiveBits, NumNegativeBits);
20647
20648 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20649
20650 if (Enum->isClosedFlag()) {
20651 for (Decl *D : Elements) {
20652 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20653 if (!ECD) continue; // Already issued a diagnostic.
20654
20655 llvm::APSInt InitVal = ECD->getInitVal();
20656 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20657 !IsValueInFlagEnum(Enum, InitVal, true))
20658 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20659 << ECD << Enum;
20660 }
20661 }
20662
20663 // Now that the enum type is defined, ensure it's not been underaligned.
20664 if (Enum->hasAttrs())
20666}
20667
20669 SourceLocation EndLoc) {
20670
20672 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
20674 return New;
20675}
20676
20678 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20680 PushDeclContext(S, New);
20682 PushCompoundScope(false);
20683 return New;
20684}
20685
20687 if (Statement)
20688 D->setStmt(Statement);
20692}
20693
20695 IdentifierInfo* AliasName,
20696 SourceLocation PragmaLoc,
20697 SourceLocation NameLoc,
20698 SourceLocation AliasNameLoc) {
20699 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20701 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20703 AsmLabelAttr *Attr =
20704 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
20705
20706 // If a declaration that:
20707 // 1) declares a function or a variable
20708 // 2) has external linkage
20709 // already exists, add a label attribute to it.
20710 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20711 if (isDeclExternC(PrevDecl))
20712 PrevDecl->addAttr(Attr);
20713 else
20714 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20715 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20716 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20717 } else
20718 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20719}
20720
20722 SourceLocation PragmaLoc,
20723 SourceLocation NameLoc) {
20724 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20725
20726 if (PrevDecl) {
20727 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20728 } else {
20729 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20730 }
20731}
20732
20734 IdentifierInfo* AliasName,
20735 SourceLocation PragmaLoc,
20736 SourceLocation NameLoc,
20737 SourceLocation AliasNameLoc) {
20738 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20740 WeakInfo W = WeakInfo(Name, NameLoc);
20741
20742 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20743 if (!PrevDecl->hasAttr<AliasAttr>())
20744 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20746 } else {
20747 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20748 }
20749}
20750
20752 bool Final) {
20753 assert(FD && "Expected non-null FunctionDecl");
20754
20755 // SYCL functions can be template, so we check if they have appropriate
20756 // attribute prior to checking if it is a template.
20757 if (LangOpts.SYCLIsDevice && FD->hasAttr<DeviceKernelAttr>())
20759
20760 // Templates are emitted when they're instantiated.
20761 if (FD->isDependentContext())
20763
20764 // Check whether this function is an externally visible definition.
20765 auto IsEmittedForExternalSymbol = [this, FD]() {
20766 // We have to check the GVA linkage of the function's *definition* -- if we
20767 // only have a declaration, we don't know whether or not the function will
20768 // be emitted, because (say) the definition could include "inline".
20769 const FunctionDecl *Def = FD->getDefinition();
20770
20771 // We can't compute linkage when we skip function bodies.
20772 return Def && !Def->hasSkippedBody() &&
20774 getASTContext().GetGVALinkageForFunction(Def));
20775 };
20776
20777 if (LangOpts.OpenMPIsTargetDevice) {
20778 // In OpenMP device mode we will not emit host only functions, or functions
20779 // we don't need due to their linkage.
20780 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20781 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20782 // DevTy may be changed later by
20783 // #pragma omp declare target to(*) device_type(*).
20784 // Therefore DevTy having no value does not imply host. The emission status
20785 // will be checked again at the end of compilation unit with Final = true.
20786 if (DevTy)
20787 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20789 // If we have an explicit value for the device type, or we are in a target
20790 // declare context, we need to emit all extern and used symbols.
20791 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20792 if (IsEmittedForExternalSymbol())
20794 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20795 // we'll omit it.
20796 if (Final)
20798 } else if (LangOpts.OpenMP > 45) {
20799 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20800 // function. In 5.0, no_host was introduced which might cause a function to
20801 // be omitted.
20802 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20803 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20804 if (DevTy)
20805 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20807 }
20808
20809 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20811
20812 if (LangOpts.CUDA) {
20813 // When compiling for device, host functions are never emitted. Similarly,
20814 // when compiling for host, device and global functions are never emitted.
20815 // (Technically, we do emit a host-side stub for global functions, but this
20816 // doesn't count for our purposes here.)
20818 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20820 if (!LangOpts.CUDAIsDevice &&
20823
20824 if (IsEmittedForExternalSymbol())
20826
20827 // If FD is a virtual destructor of an explicit instantiation
20828 // of a template class, return Emitted.
20829 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(FD)) {
20830 if (Destructor->isVirtual()) {
20831 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
20832 Destructor->getParent())) {
20834 Spec->getTemplateSpecializationKind();
20838 }
20839 }
20840 }
20841 }
20842
20843 // Otherwise, the function is known-emitted if it's in our set of
20844 // known-emitted functions.
20846}
20847
20849 // Host-side references to a __global__ function refer to the stub, so the
20850 // function itself is never emitted and therefore should not be marked.
20851 // If we have host fn calls kernel fn calls host+device, the HD function
20852 // does not get instantiated on the host. We model this by omitting at the
20853 // call to the kernel from the callgraph. This ensures that, when compiling
20854 // for host, only HD functions actually called from the host get marked as
20855 // known-emitted.
20856 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20858}
20859
20861 bool &Visible) {
20862 Visible = hasVisibleDefinition(D, Suggested);
20863 // The redefinition of D in the **current** TU is allowed if D is invisible or
20864 // D is defined in the global module of other module units. We didn't check if
20865 // it is in global module as, we'll check the redefinition in named module
20866 // later with better diagnostic message.
20867 return D->isInAnotherModuleUnit() || !Visible;
20868}
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
Defines enum values for all the target-independent builtin functions.
const Decl * D
IndirectLocalPath & Path
enum clang::sema::@1840::IndirectLocalPathEntry::EntryKind Kind
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
static bool isDeclExternC(const T &D)
Definition: Decl.cpp:2229
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::Target Target
Definition: MachO.h:51
llvm::MachO::Record Record
Definition: MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition: Mangle.cpp:74
#define SM(sm)
Definition: OffloadArch.cpp:16
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:1179
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis for CUDA constructs.
@ None
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:16252
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:7002
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:175
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15765
static bool isMainVar(DeclarationName Name, VarDecl *VD)
Definition: SemaDecl.cpp:7603
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:11576
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:230
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:3449
static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7093
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:3614
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:830
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:6697
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:1529
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:6735
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:2327
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:9388
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:3561
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
Definition: SemaDecl.cpp:8368
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:9734
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
Definition: SemaDecl.cpp:3376
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
Definition: SemaDecl.cpp:8744
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
Definition: SemaDecl.cpp:11978
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:2734
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:4588
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
Definition: SemaDecl.cpp:12072
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15749
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
Definition: SemaDecl.cpp:11696
static NestedNameSpecifier synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:594
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:2095
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
Definition: SemaDecl.cpp:15375
static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7128
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
Definition: SemaDecl.cpp:11585
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:7344
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:20373
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
Definition: SemaDecl.cpp:5148
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:2987
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
Definition: SemaDecl.cpp:17340
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:3596
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7181
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:6083
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:5015
static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From, Sema &S)
Definition: SemaDecl.cpp:3340
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:9424
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:9913
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
Definition: SemaDecl.cpp:16282
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:3503
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:8713
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2703
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
Definition: SemaDecl.cpp:9606
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
Definition: SemaDecl.cpp:3132
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:8393
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:17500
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:5428
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:8630
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
Definition: SemaDecl.cpp:1971
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
Definition: SemaDecl.cpp:9924
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:5504
OpenCLParamType
Definition: SemaDecl.cpp:9597
@ InvalidAddrSpacePtrKernelParam
Definition: SemaDecl.cpp:9601
@ ValidKernelParam
Definition: SemaDecl.cpp:9598
@ InvalidKernelParam
Definition: SemaDecl.cpp:9602
@ RecordKernelParam
Definition: SemaDecl.cpp:9603
@ PtrKernelParam
Definition: SemaDecl.cpp:9600
@ PtrPtrKernelParam
Definition: SemaDecl.cpp:9599
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:6192
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:19336
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:613
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:19270
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:7389
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:5594
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11502
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:9904
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
Definition: SemaDecl.cpp:3410
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:3540
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:17324
static void checkInheritableAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7101
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
Definition: SemaDecl.cpp:2221
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:4485
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:9230
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
Definition: SemaDecl.cpp:6118
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:19363
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:845
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
Definition: SemaDecl.cpp:7416
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:8357
@ SDK_StructuredBinding
Definition: SemaDecl.cpp:8364
@ SDK_Field
Definition: SemaDecl.cpp:8361
@ SDK_Global
Definition: SemaDecl.cpp:8359
@ SDK_Local
Definition: SemaDecl.cpp:8358
@ SDK_Typedef
Definition: SemaDecl.cpp:8362
@ SDK_StaticMember
Definition: SemaDecl.cpp:8360
@ SDK_Using
Definition: SemaDecl.cpp:8363
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4961
static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
Definition: SemaDecl.cpp:7575
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:3524
static void checkWeakAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7049
static void checkSelectAnyAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7081
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:9628
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:5608
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
Definition: SemaDecl.cpp:12665
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
Definition: SemaDecl.cpp:7467
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
Definition: SemaDecl.cpp:1840
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
Definition: SemaDecl.cpp:19427
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11315
static bool looksMutable(QualType T, const ASTContext &Ctx)
Definition: SemaDecl.cpp:13653
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
Definition: SemaDecl.cpp:1829
static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From, F &&propagator)
Definition: SemaDecl.cpp:3355
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2958
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:6619
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:15157
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
Definition: SemaDecl.cpp:7563
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:6065
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1882
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2845
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
Definition: SemaDecl.cpp:11255
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
Definition: SemaDecl.cpp:6963
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:5573
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:11727
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:8384
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:11551
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:7195
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11333
static void checkAliasAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7068
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:2454
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:20337
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:20018
static void checkWeakRefAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7059
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:7375
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2722
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
Definition: SemaDecl.cpp:11162
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Definition: SemaDecl.cpp:11600
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1856
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:17537
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
SourceRange Range
Definition: SemaObjC.cpp:753
SourceLocation Loc
Definition: SemaObjC.cpp:754
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
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.
StateNode * Previous
std::string Label
__device__ int
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
Definition: SemaDecl.cpp:16239
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:16241
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
SourceManager & getSourceManager()
Definition: ASTContext.h:801
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1201
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:3056
QualType getParenType(QualType NamedType) const
CanQualType LongTy
Definition: ASTContext.h:1231
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.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:744
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2359
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) 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:2140
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2851
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2867
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:2243
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:2166
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:2219
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:3062
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:1250
QualType getUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType=QualType()) const
IdentifierTable & Idents
Definition: ASTContext.h:740
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:742
bool computeEnumBits(RangeT EnumConstants, unsigned &NumNegativeBits, unsigned &NumPositiveBits)
Compute NumNegativeBits and NumPositiveBits for an enum based on the constant values of its enumerato...
Definition: ASTContext.h:1831
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:894
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
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:532
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:2344
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:2256
CanQualType UnsignedLongTy
Definition: ASTContext.h:1232
bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, unsigned NumPositiveBits, QualType &BestType, QualType &BestPromotionType)
Compute BestType and BestPromotionType for an enum based on the highest number of negative and positi...
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:3155
CanQualType CharTy
Definition: ASTContext.h:1224
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
CanQualType IntTy
Definition: ASTContext.h:1231
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:2442
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:793
void ResetObjCLayout(const ObjCInterfaceDecl *D)
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:2333
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2898
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2625
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:1222
CanQualType UnsignedIntTy
Definition: ASTContext.h:1232
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
CanQualType UnknownAnyTy
Definition: ASTContext.h:1251
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1233
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1232
bool isRepresentableIntegerValue(llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
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:1750
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1604
QualType getTagType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *TD, bool OwnsTag) const
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:3059
CanQualType ShortTy
Definition: ASTContext.h:1231
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:2153
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.
QualType getUnresolvedUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D) const
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:859
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:2465
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.
QualType getDeducedTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:2230
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:1231
CanQualType getCanonicalTagType(const TagDecl *TD) const
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:2536
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2542
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2539
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2548
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2545
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:2656
The result of parsing/analyzing an expression, statement etc.
Definition: Ownership.h:154
bool isUnset() const
Definition: Ownership.h:168
PtrTy get() const
Definition: Ownership.h:171
bool isInvalid() const
Definition: Ownership.h:167
bool isUsable() const
Definition: Ownership.h:169
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: TypeBase.h:3507
Wrapper for source info for arrays.
Definition: TypeLoc.h:1757
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1759
Expr * getSizeExpr() const
Definition: TypeLoc.h:1779
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1787
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1767
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: TypeBase.h:3738
QualType getElementType() const
Definition: TypeBase.h:3750
Attr - This represents one attribute.
Definition: Attr.h:44
attr::Kind getKind() const
Definition: Attr.h:90
bool isInherited() const
Definition: Attr.h:99
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition: Attr.h:104
SourceLocation getLocation() const
Definition: Attr.h:97
bool isStandardAttributeSyntax() const
The attribute is spelled [[]] in either C or C++ mode, including standard attributes spelled with a k...
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:622
AttributeFactory & getFactory() const
Definition: ParsedAttr.h:718
Type source information for an attributed type.
Definition: TypeLoc.h:1017
const T * getAttrAs()
Definition: TypeLoc.h:1047
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:1031
An attributed type is a type to which a type attribute has been applied.
Definition: TypeBase.h:6585
QualType getModifiedType() const
Definition: TypeBase.h:6615
bool isCallingConv() const
Definition: Type.cpp:4438
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: TypeBase.h:7180
AutoTypeKeyword getKeyword() const
Definition: TypeBase.h:7211
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4389
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3974
A binding in a decomposition declaration.
Definition: DeclCXX.h:4179
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4634
bool doesNotEscape() const
Definition: Decl.h:4785
This class is used for builtin types like 'int'.
Definition: TypeBase.h:3182
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:228
bool performsCallback(unsigned ID, llvm::SmallVectorImpl< int > &Encoding) const
Determine whether this builtin has callback behavior (see llvm::AbstractCallSites for details).
Definition: Builtins.cpp:296
bool isAuxBuiltinID(unsigned ID) const
Return true if the builtin ID belongs exclusively to the AuxTarget, and false if it belongs to both p...
Definition: Builtins.h:414
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:375
bool isReturnsTwice(unsigned ID) const
Return true if we know this builtin can return twice.
Definition: Builtins.h:290
bool isImmediate(unsigned ID) const
Returns true if this is an immediate (consteval) function.
Definition: Builtins.h:436
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:400
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:355
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:264
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.cpp:80
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition: Builtins.h:320
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:291
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:335
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:313
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:286
bool isConstWithoutExceptions(unsigned ID) const
Definition: Builtins.h:404
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache",...
Definition: Builtins.h:327
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition: Builtins.h:269
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:280
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition: Builtins.h:275
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:1549
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2604
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(), const AssociatedConstraint &TrailingRequiresClause={})
Definition: DeclCXX.cpp:2968
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2937
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition: DeclCXX.cpp:3154
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, const AssociatedConstraint &TrailingRequiresClause={}, const CXXDeductionGuideDecl *SourceDG=nullptr, SourceDeductionGuideKind SK=SourceDeductionGuideKind::None)
Definition: DeclCXX.cpp:2367
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2869
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause={})
Definition: DeclCXX.cpp:3098
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:2129
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:2703
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2755
bool isVirtual() const
Definition: DeclCXX.h:2184
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition: DeclCXX.cpp:2488
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2255
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2735
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2290
bool isConst() const
Definition: DeclCXX.h:2181
bool isStatic() const
Definition: DeclCXX.cpp:2401
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2714
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2225
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:84
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition: DeclCXX.cpp:132
base_class_iterator bases_end()
Definition: DeclCXX.h:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1366
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1554
base_class_range bases()
Definition: DeclCXX.h:608
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:602
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:2075
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:615
capture_const_range captures() const
Definition: DeclCXX.h:1097
bool hasDefinition() const
Definition: DeclCXX.h:561
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:2042
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: DeclCXX.cpp:2146
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1059
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:2046
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:522
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:180
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:206
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:185
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:97
SourceRange getRange() const
Definition: DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:83
bool isSet() const
Deprecated.
Definition: DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:183
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:103
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2879
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:4327
Represents the canonical version of C arrays with a specified constant size.
Definition: TypeBase.h:3776
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:214
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:254
bool isZeroSize() const
Return true if the size is zero.
Definition: TypeBase.h:3846
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: TypeBase.h:3832
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:346
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:37
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:1382
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2393
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2238
bool isFileContext() const
Definition: DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2077
bool isObjCContainer() const
Definition: DeclBase.h:2148
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1358
bool isClosure() const
Definition: DeclBase.h:2142
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2125
bool isNamespace() const
Definition: DeclBase.h:2198
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1879
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1325
bool isTranslationUnit() const
Definition: DeclBase.h:2185
bool isRecord() const
Definition: DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2022
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1712
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1793
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1662
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2040
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1459
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2373
bool isFunctionOrMethod() const
Definition: DeclBase.h:2161
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1309
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1409
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Definition: DeclBase.cpp:1428
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2102
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1450
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:64
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1272
ValueDecl * getDecl()
Definition: Expr.h:1340
SourceLocation getBeginLoc() const
Definition: Expr.h:1351
Captures information about "declaration specifiers".
Definition: DeclSpec.h:217
bool isVirtualSpecified() const
Definition: DeclSpec.h:618
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:799
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:279
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:565
static const TST TST_typename
Definition: DeclSpec.h:276
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:619
bool isNoreturnSpecified() const
Definition: DeclSpec.h:631
TST getTypeSpecType() const
Definition: DeclSpec.h:507
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:480
SCS getStorageClassSpec() const
Definition: DeclSpec.h:471
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:834
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:545
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:544
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:679
static const TST TST_interface
Definition: DeclSpec.h:274
static const TST TST_typeofExpr
Definition: DeclSpec.h:278
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:586
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:678
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:632
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:475
static const TST TST_union
Definition: DeclSpec.h:272
SCS
storage-class-specifier
Definition: DeclSpec.h:221
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:624
static const TST TST_int
Definition: DeclSpec.h:255
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:800
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1480
ParsedType getRepAsType() const
Definition: DeclSpec.h:517
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:758
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:472
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:843
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:596
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:587
Expr * getRepAsExpr() const
Definition: DeclSpec.h:525
static const TST TST_enum
Definition: DeclSpec.h:271
static const TST TST_decltype
Definition: DeclSpec.h:281
static bool isDeclRep(TST T)
Definition: DeclSpec.h:439
bool isInlineSpecified() const
Definition: DeclSpec.h:607
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:588
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:280
static const TST TST_class
Definition: DeclSpec.h:275
static const TST TST_void
Definition: DeclSpec.h:249
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:532
static const TST TST_atomic
Definition: DeclSpec.h:291
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:481
Decl * getRepAsDecl() const
Definition: DeclSpec.h:521
static const TST TST_unspecified
Definition: DeclSpec.h:248
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:590
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:619
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:806
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:552
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:762
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:237
static const TST TST_error
Definition: DeclSpec.h:298
bool isTypeSpecOwned() const
Definition: DeclSpec.h:511
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:610
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:591
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:589
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:791
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:621
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:807
static const TST TST_typeofType
Definition: DeclSpec.h:277
static const TST TST_auto
Definition: DeclSpec.h:288
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:802
static const TST TST_struct
Definition: DeclSpec.h:273
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:1061
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1076
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:319
bool isInStdNamespace() const
Definition: DeclBase.cpp:427
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:435
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1226
bool isFromGlobalModule() const
Whether this declaration comes from global module.
Definition: DeclBase.cpp:1180
T * getAttr() const
Definition: DeclBase.h:573
bool hasAttrs() const
Definition: DeclBase.h:518
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:524
void addAttr(Attr *A)
Definition: DeclBase.cpp:1022
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:593
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:520
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:771
bool isInNamedModule() const
Whether this declaration comes from a named module.
Definition: DeclBase.cpp:1184
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1151
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:156
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:638
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:893
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1219
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1217
@ FOK_Declared
A friend of a previously-declared entity.
Definition: DeclBase.h:1218
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:286
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1121
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:578
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Definition: DeclBase.cpp:1138
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:251
void dropAttrs()
Definition: DeclBase.cpp:1015
@ 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:1180
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2793
bool isInvalidDecl() const
Definition: DeclBase.h:588
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1169
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:559
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:502
SourceLocation getLocation() const
Definition: DeclBase.h:439
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
void setImplicit(bool I=true)
Definition: DeclBase.h:594
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:553
DeclContext * getDeclContext()
Definition: DeclBase.h:448
attr_range attrs() const
Definition: DeclBase.h:535
AccessSpecifier getAccess() const
Definition: DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:431
void dropAttr()
Definition: DeclBase.h:556
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:360
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1636
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:918
bool hasAttr() const
Definition: DeclBase.h:577
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1235
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:364
Kind getKind() const
Definition: DeclBase.h:442
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:427
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.
bool isAnyOperatorNewOrDelete() const
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:779
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:821
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2050
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2090
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1988
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:830
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:854
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:813
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:2000
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:836
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:808
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2034
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1874
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2372
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2021
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2657
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2313
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2368
const ParsedAttributesView & getDeclarationAttributes() const
Definition: DeclSpec.h:2660
A decomposition declaration.
Definition: DeclCXX.h:4243
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3613
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1762
SourceRange getSourceRange() const
Definition: DeclSpec.h:1810
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1808
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2493
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: TypeBase.h:7146
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: TypeBase.h:7167
bool isDeduced() const
Definition: TypeBase.h:7168
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2581
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2561
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2570
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:950
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:965
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3420
llvm::APSInt getInitVal() const
Definition: Decl.h:3440
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5579
const Expr * getInitExpr() const
Definition: Decl.h:3438
Represents an enum.
Definition: Decl.h:4004
enumerator_range enumerators() const
Definition: Decl.h:4141
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4213
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:4177
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:4180
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4227
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4953
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4992
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4222
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4967
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:4163
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4168
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: TypeBase.h:6522
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1924
This represents one expression.
Definition: Expr.h:112
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:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3073
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition: Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3069
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3053
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:273
QualType getType() const
Definition: Expr.h:144
Represents difference between two FPOptions values.
Definition: LangOptions.h:919
void applyChanges(FPOptionsOverride FPO)
Definition: LangOptions.h:1032
bool isFPConstrained() const
Definition: LangOptions.h:844
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
Definition: LangOptions.h:1026
Represents a member of a struct/union/class.
Definition: Decl.h:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3260
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4656
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3393
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:4641
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:4702
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5712
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:78
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:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:128
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:102
Represents a function declaration or definition.
Definition: Decl.h:1999
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2686
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition: Decl.h:2188
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2794
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2475
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4146
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3674
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4139
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4134
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3290
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2313
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2698
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2677
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3965
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3703
param_iterator param_end()
Definition: Decl.h:2784
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2918
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2692
QualType getReturnType() const
Definition: Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2771
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3647
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2388
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2376
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3555
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4254
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2447
void setWillHaveBody(bool V=true)
Definition: Decl.h:2683
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.h:2593
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2442
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4264
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3688
param_iterator param_begin()
Definition: Decl.h:2783
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2820
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3125
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2539
FunctionEffectsRef getFunctionEffects() const
Definition: Decl.h:3131
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3363
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4198
@ TK_MemberSpecialization
Definition: Decl.h:2011
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2885
bool isStatic() const
Definition: Decl.h:2926
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4467
void setTrivial(bool IT)
Definition: Decl.h:2377
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4085
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2469
bool isDeletedAsWritten() const
Definition: Decl.h:2543
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2352
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3559
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2356
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2427
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2348
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2676
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2281
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3356
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2913
bool param_empty() const
Definition: Decl.h:2782
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3215
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2217
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3643
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2384
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2420
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4490
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2930
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:4079
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2472
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4358
void setDefaulted(bool D=true)
Definition: Decl.h:2385
bool isConsteval() const
Definition: Decl.h:2481
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:2859
void setBody(Stmt *B)
Definition: Decl.cpp:3283
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3573
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3161
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition: Decl.h:2458
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4106
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3767
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2210
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3191
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2434
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:3238
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2896
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3629
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2682
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition: TypeBase.h:5218
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5724
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: TypeBase.h:5082
Represents a prototype with parameter type info, e.g.
Definition: TypeBase.h:5282
unsigned getNumParams() const
Definition: TypeBase.h:5560
QualType getParamType(unsigned i) const
Definition: TypeBase.h:5562
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: TypeBase.h:5779
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: TypeBase.h:5595
bool isVariadic() const
Whether this function prototype is variadic.
Definition: TypeBase.h:5686
ExtProtoInfo getExtProtoInfo() const
Definition: TypeBase.h:5571
ArrayRef< QualType > getParamTypes() const
Definition: TypeBase.h:5567
ArrayRef< QualType > param_types() const
Definition: TypeBase.h:5722
Declaration of a template function.
Definition: DeclTemplate.h:952
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:537
Wrapper for source info for functions.
Definition: TypeLoc.h:1624
A class which abstracts out some details necessary for making a call.
Definition: TypeBase.h:4589
ExtInfo withCallingConv(CallingConv cc) const
Definition: TypeBase.h:4701
CallingConv getCC() const
Definition: TypeBase.h:4648
ExtInfo withProducesResult(bool producesResult) const
Definition: TypeBase.h:4667
unsigned getRegParm() const
Definition: TypeBase.h:4641
bool getNoCallerSavedRegs() const
Definition: TypeBase.h:4637
ExtInfo withNoReturn(bool noReturn) const
Definition: TypeBase.h:4660
bool getProducesResult() const
Definition: TypeBase.h:4635
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: TypeBase.h:4681
ExtInfo withRegParm(unsigned RegParm) const
Definition: TypeBase.h:4695
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: TypeBase.h:4478
ExtInfo getExtInfo() const
Definition: TypeBase.h:4834
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3613
unsigned getRegParmType() const
Definition: TypeBase.h:4821
CallingConv getCallConv() const
Definition: TypeBase.h:4833
QualType getReturnType() const
Definition: TypeBase.h:4818
bool getCmseNSCallAttr() const
Definition: TypeBase.h:4832
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:3789
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2068
Represents a C array with an unspecified size.
Definition: TypeBase.h:3925
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3464
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5606
void setInherited(bool I)
Definition: Attr.h:156
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2575
Describes an C or C++ initializer list.
Definition: Expr.h:5235
child_range children()
Definition: Expr.h:5434
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:7739
@ 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:971
Represents the declaration of a label.
Definition: Decl.h:523
bool isResolvedMSAsmLabel() const
Definition: Decl.h:558
LabelStmt * getStmt() const
Definition: Decl.h:547
bool isMSAsmLabel() const
Definition: Decl.h:557
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1970
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:229
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:619
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:749
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:668
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:469
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
Definition: LangOptions.cpp:81
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
Definition: LangOptions.h:526
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
Definition: LangOptions.h:674
bool isTargetDevice() const
True when compiling for an offloading target device.
Definition: LangOptions.h:757
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:65
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:508
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:1377
Visibility getVisibility() const
Definition: Visibility.h:89
Linkage getLinkage() const
Definition: Visibility.h:88
Represents a linkage specification.
Definition: DeclCXX.h:3009
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:3184
void InstantiatedLocal(const Decl *D, Decl *Inst)
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:723
bool hasNext() const
Definition: Lookup.h:708
NamedDecl * next()
Definition: Lookup.h:712
Represents the results of name lookup.
Definition: Lookup.h:147
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:666
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:569
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:672
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:576
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
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:3300
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: TypeBase.h:3669
Describes a module or submodule.
Definition: Module.h:144
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:150
Module * Parent
The parent of this module.
Definition: Module.h:193
bool isPrivateModule() const
Definition: Module.h:249
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition: Module.h:648
bool isModuleImplementation() const
Is this a module implementation.
Definition: Module.h:664
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:653
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:239
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:224
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:722
@ ClassId_NSObject
Definition: NSAPI.h:30
This represents a decl that may have a name.
Definition: Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:294
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Decl.cpp:1085
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:300
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1095
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition: Decl.h:478
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:428
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:339
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1206
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:706
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1930
bool isExternallyVisible() const
Definition: Decl.h:432
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:396
Represent a C++ namespace.
Definition: Decl.h:591
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:642
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.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
static constexpr NestedNameSpecifier getGlobal()
bool containsErrors() const
Whether this nested name specifier contains an error.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Type
A type, stored as a Type*.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2329
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2775
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:948
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition: DeclObjC.cpp:78
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2597
Represents an ObjC class declaration.
Definition: DeclObjC.h:1154
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1762
Wrapper for source info for ObjC interfaces.
Definition: TypeLoc.h:1283
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1293
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1952
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:1830
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:940
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
ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for protocol qualifiers are stored aft...
Definition: TypeLoc.h:904
Wrapper for void* pointer.
Definition: Ownership.h:51
PtrTy get() const
Definition: Ownership.h:81
static OpaquePtr make(PtrTy P)
Definition: Ownership.h:61
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1180
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:1153
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1157
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1369
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:256
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1395
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1408
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1391
Sugar for parentheses used when specifying types.
Definition: TypeBase.h:3320
Represents a parameter to a function.
Definition: Decl.h:1789
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1849
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1853
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1822
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:2946
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:119
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:817
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:897
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:937
AttributePool & getPool() const
Definition: ParsedAttr.h:944
PipeType - OpenCL20.
Definition: TypeBase.h:8161
Pointer-authentication qualifiers.
Definition: TypeBase.h:152
bool isAddressDiscriminated() const
Definition: TypeBase.h:265
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1474
Wrapper for source info for pointers.
Definition: TypeLoc.h:1493
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1499
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: TypeBase.h:3346
QualType getPointeeType() const
Definition: TypeBase.h:3356
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: TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: TypeBase.h:8427
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: TypeBase.h:8421
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:87
PointerAuthQualifier getPointerAuth() const
Definition: TypeBase.h:1453
@ DK_nontrivial_c_struct
Definition: TypeBase.h:1538
PrimitiveDefaultInitializeKind
Definition: TypeBase.h:1463
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2925
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:109
QualType withoutLocalFastQualifiers() const
Definition: TypeBase.h:1214
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: TypeBase.h:1296
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: TypeBase.h:1004
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:2974
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: TypeBase.h:8343
LangAS getAddressSpace() const
Return the address space of this type.
Definition: TypeBase.h:8469
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:81
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: TypeBase.h:8383
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: TypeBase.h:1438
QualType getCanonicalType() const
Definition: TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: TypeBase.h:8437
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition: Type.cpp:2958
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: TypeBase.h:1433
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: TypeBase.h:8416
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition: Type.cpp:1670
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: TypeBase.h:1545
bool isCanonical() const
Definition: TypeBase.h:8400
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: TypeBase.h:1309
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: TypeBase.h:1332
bool hasNonTrivialObjCLifetime() const
Definition: TypeBase.h:1442
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2699
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: TypeBase.h:1493
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: TypeBase.h:1498
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition: Type.h:75
A qualifier set is used to build a set of qualifiers.
Definition: TypeBase.h:8283
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: TypeBase.h:8290
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4710
The collection of all-type qualifiers we support.
Definition: TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition: TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: TypeBase.h:367
bool hasConst() const
Definition: TypeBase.h:457
void removeConst()
Definition: TypeBase.h:459
bool hasVolatile() const
Definition: TypeBase.h:467
ObjCLifetime getObjCLifetime() const
Definition: TypeBase.h:545
bool empty() const
Definition: TypeBase.h:647
Represents a struct/union/class.
Definition: Decl.h:4309
bool hasObjectMember() const
Definition: Decl.h:4369
field_range fields() const
Definition: Decl.h:4512
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5111
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4493
field_iterator field_begin() const
Definition: Decl.cpp:5154
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:7364
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:857
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:213
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:201
redecl_iterator redecls_end() const
Definition: Redeclarable.h:300
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:223
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:5292
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:220
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:293
Base for LValueReferenceType and RValueReferenceType.
Definition: TypeBase.h:3589
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3160
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:3203
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:398
void RemoveDecl(Decl *D)
Definition: Scope.h:370
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:401
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:619
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:287
@ 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:1403
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:111
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId, bool DeferHint=false)
Emit a compatibility diagnostic.
Definition: SemaBase.cpp:91
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:33
void checkAllowedInitializer(VarDecl *VD)
Definition: SemaCUDA.cpp:669
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
Definition: SemaCUDA.cpp:1086
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:757
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
Definition: SemaCUDA.cpp:1022
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition: SemaCUDA.cpp:822
void CheckEntryPoint(FunctionDecl *FD)
Definition: SemaHLSL.cpp:774
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition: SemaHLSL.cpp:655
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition: SemaHLSL.cpp:621
void deduceAddressSpace(VarDecl *Decl)
Definition: SemaHLSL.cpp:3597
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition: SemaHLSL.cpp:724
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition: SemaHLSL.cpp:691
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition: SemaHLSL.cpp:635
void ActOnVariableDeclarator(VarDecl *VD)
Definition: SemaHLSL.cpp:3631
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:1156
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:1444
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 ActOnVariableDeclarator(VarDecl *VD)
Function called when a variable declarator is created, which lets us implement the 'routine' 'functio...
OpenACCRoutineDeclAttr * mergeRoutineDeclAttr(const OpenACCRoutineDeclAttr &Old)
void ActOnFunctionDeclarator(FunctionDecl *FD)
Called when a function decl is created, which lets us implement the 'routine' 'doesn't match next thi...
void ActOnVariableInit(VarDecl *VD, QualType InitType)
Called when a variable is initialized, so we can implement the 'routine 'doesn't match the next thing...
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:1439
void CheckSYCLExternalFunctionDecl(FunctionDecl *FD)
Definition: SemaSYCL.cpp:253
StmtResult BuildSYCLKernelCallStmt(FunctionDecl *FD, CompoundStmt *Body)
Definition: SemaSYCL.cpp:437
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition: SemaSYCL.cpp:270
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition: SemaSwift.cpp:26
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition: SemaWasm.cpp:334
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition: SemaWasm.cpp:313
bool IsAlignAttr() const
Definition: Sema.h:1884
Mode getAlignMode() const
Definition: Sema.h:1886
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3468
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:1352
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:1364
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition: Sema.h:3682
static NameClassification VarTemplate(TemplateName Name)
Definition: Sema.h:3692
static NameClassification Unknown()
Definition: Sema.h:3662
static NameClassification OverloadSet(ExprResult E)
Definition: Sema.h:3666
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition: Sema.h:3710
static NameClassification FunctionTemplate(TemplateName Name)
Definition: Sema.h:3698
static NameClassification NonType(NamedDecl *D)
Definition: Sema.h:3672
static NameClassification Concept(TemplateName Name)
Definition: Sema.h:3704
static NameClassification UndeclaredNonType()
Definition: Sema.h:3678
static NameClassification TypeTemplate(TemplateName Name)
Definition: Sema.h:3686
static NameClassification Error()
Definition: Sema.h:3658
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12359
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12392
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:850
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:14587
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:11188
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6383
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition: Sema.h:3560
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6857
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12936
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition: Sema.cpp:2539
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:1113
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:2526
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
Definition: SemaType.cpp:9253
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:6774
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:9951
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:1617
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:15533
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:8189
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:6264
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:9277
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9281
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:9300
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:9316
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:9313
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9289
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:9284
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6790
void ActOnPopScope(SourceLocation Loc, Scope *S)
Definition: SemaDecl.cpp:2237
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5461
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:16227
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:13099
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:35
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:3654
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.
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:17346
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:6251
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:20255
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:18758
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:7611
SemaOpenMP & OpenMP()
Definition: Sema.h:1498
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:6236
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:1234
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:18690
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition: Sema.h:4721
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:3542
PragmaClangSection PragmaClangRodataSection
Definition: Sema.h:1810
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:16811
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:6456
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:15397
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:1193
SemaCUDA & CUDA()
Definition: Sema.h:1438
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:17664
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:1513
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
Definition: SemaAttr.cpp:277
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:2442
Preprocessor & getPreprocessor() const
Definition: Sema.h:917
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:7008
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:2041
PragmaStack< StringLiteral * > CodeSegStack
Definition: Sema.h:2035
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:1277
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:6393
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:4967
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:54
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:12484
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:17012
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:2157
@ 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:18777
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:18875
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation=false, bool RetainFunctionScopeInfo=false)
Performs semantic analysis at the end of a function body.
Definition: SemaDecl.cpp:16307
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:14984
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:1489
SemaSYCL & SYCL()
Definition: Sema.h:1523
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15876
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:1647
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3532
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:671
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:1715
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:20668
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15520
ASTContext & Context
Definition: Sema.h:1276
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:15004
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5943
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:915
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20686
void * SkippedDefinitionContext
Definition: Sema.h:4350
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:921
SemaObjC & ObjC()
Definition: Sema.h:1483
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
Definition: SemaDecl.cpp:5466
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:5077
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
Definition: SemaDecl.cpp:20860
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:75
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1555
PragmaStack< bool > StrictGuardStackCheckStack
Definition: Sema.h:2038
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:3550
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:2388
ASTContext & getASTContext() const
Definition: Sema.h:918
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:16296
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:1771
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:18155
PragmaStack< StringLiteral * > ConstSegStack
Definition: Sema.h:2034
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:756
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:695
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3142
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition: SemaAttr.cpp:112
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:4923
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 RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9606
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20848
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:1184
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:5625
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1652
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:17371
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:9217
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:12073
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:8307
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:795
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:4501
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2330
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:1305
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:168
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition: Sema.h:4559
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:17246
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition: Sema.h:913
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2348
void PopCompoundScope()
Definition: Sema.cpp:2481
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:20229
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition: Sema.h:14238
@ UPPC_EnumeratorValue
The enumerator value.
Definition: Sema.h:14241
@ UPPC_Initializer
An initializer.
Definition: Sema.h:14253
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:14247
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:14226
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:14265
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition: Sema.h:14250
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:14229
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition: Sema.h:14232
const LangOptions & getLangOpts() const
Definition: Sema.h:911
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:2074
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:::lifetimebound]] attr for std:: functions and methods.
Definition: SemaAttr.cpp:220
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition: Sema.h:3567
SemaOpenACC & OpenACC()
Definition: Sema.h:1488
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1446
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:6750
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:6784
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1656
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:1275
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:8417
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:2113
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition: Sema.h:1274
bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:18632
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
Definition: SemaExpr.cpp:17700
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2557
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition: Sema.h:15330
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15715
SemaHLSL & HLSL()
Definition: Sema.h:1448
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1888
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:12098
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:18970
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:1811
SemaRISCV & RISCV()
Definition: Sema.h:1513
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:15504
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:3782
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:207
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:20409
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:1528
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:1321
PragmaStack< AlignPackInfo > AlignPackStack
Definition: Sema.h:2023
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:16185
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6915
PragmaStack< StringLiteral * > BSSSegStack
Definition: Sema.h:2033
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition: Sema.h:1117
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
Definition: SemaType.cpp:8217
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:894
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1433
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8564
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.
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition: Sema.h:4736
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
Definition: SemaDecl.cpp:12684
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1307
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2476
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:15237
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Definition: SemaDecl.cpp:2344
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:2319
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:20721
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:19170
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6912
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1333
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
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:9944
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:9093
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:633
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:3230
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:15324
StringLiteral * CurInitSeg
Last section used with #pragma init_seg.
Definition: Sema.h:2073
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20751
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:9807
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:9113
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:15821
void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl)
Definition: SemaDecl.cpp:13664
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15745
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1411
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:15277
SemaOpenCL & OpenCL()
Definition: Sema.h:1493
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5948
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:15575
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:8605
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1347
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4868
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
Definition: SemaDecl.cpp:16157
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
void CleanupMergedEnum(Scope *S, Decl *New)
CleanupMergedEnum - We have just merged the decl 'New' by making another definition visible.
Definition: SemaDecl.cpp:2688
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition: Sema.h:3564
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9361
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:16209
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:11200
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13791
SourceManager & getSourceManager() const
Definition: Sema.h:916
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:3517
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:4424
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:20512
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:1398
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:11376
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:18618
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:1812
@ NTCUK_Destruct
Definition: Sema.h:4065
@ NTCUK_Init
Definition: Sema.h:4064
@ NTCUK_Copy
Definition: Sema.h:4066
PragmaClangSection PragmaClangDataSection
Definition: Sema.h:1809
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20595
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:14172
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:1286
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:20694
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:90
MaybeODRUseExprSet MaybeODRUseExprs
Definition: Sema.h:6717
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:218
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:20677
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8440
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...
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14616
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:15162
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2497
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:4617
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:6478
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:623
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
Definition: SemaDecl.cpp:19229
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
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:1951
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition: Sema.h:3538
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17422
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:270
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:20042
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12719
ASTConsumer & Consumer
Definition: Sema.h:1277
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4622
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:6919
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2108
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:1312
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1772
@ 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:16943
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:15281
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5693
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14947
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:17555
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:4947
SemaPPC & PPC()
Definition: Sema.h:1503
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:75
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9241
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:15667
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:1239
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1394
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:21246
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19507
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:1300
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:11224
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:3557
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:18228
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:8262
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1366
void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D)
Definition: SemaDecl.cpp:15349
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.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3184
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:1279
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:5901
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
Definition: SemaDecl.cpp:16291
DiagnosticsEngine & Diags
Definition: Sema.h:1278
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:912
FPOptions CurFPFeatures
Definition: Sema.h:1272
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:16287
NamespaceDecl * getStdNamespace() const
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:6807
PragmaStack< StringLiteral * > DataSegStack
Definition: Sema.h:2032
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:710
DiagCtorKind
Definition: Sema.h:3579
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7434
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:15312
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11532
@ TPC_ClassTemplateMember
Definition: Sema.h:11530
@ TPC_FunctionTemplate
Definition: Sema.h:11529
@ TPC_Other
Definition: Sema.h:11527
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11533
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:6894
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:16798
bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl)
Certain globally-unique variables might be accidentally duplicated if built into multiple shared libr...
Definition: SemaDecl.cpp:13565
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2126
void PopDeclContext()
Definition: SemaDecl.cpp:1373
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:6494
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:1637
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:8995
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:14214
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:13284
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:1622
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:17190
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13696
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:18867
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
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:4460
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:14533
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:279
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:3532
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:2096
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:21528
PragmaClangSection PragmaClangBSSSection
Definition: Sema.h:1808
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6210
@ AbstractVariableType
Definition: Sema.h:6188
@ AbstractReturnType
Definition: Sema.h:6186
@ AbstractFieldType
Definition: Sema.h:6189
@ AbstractIvarType
Definition: Sema.h:6190
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:1761
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:8311
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:1295
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:8231
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:20733
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:8777
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:1380
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:13247
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:2492
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2773
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:3513
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
Definition: SemaAttr.cpp:1284
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:16171
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:13544
SemaWasm & Wasm()
Definition: Sema.h:1538
IdentifierResolver IdResolver
Definition: Sema.h:3461
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:20483
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2488
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:714
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:15549
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition: SemaDecl.cpp:143
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:8270
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:3805
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6197
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:17287
SemaARM & ARM()
Definition: Sema.h:1418
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:322
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation TriviallyRelocatable, SourceLocation Replaceable, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
Definition: SemaDecl.cpp:18643
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8599
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Definition: SemaDecl.cpp:1322
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.
FileIDAndOffset getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
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.
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:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
child_range children()
Definition: Stmt.cpp:295
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1801
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition: Expr.h:1947
StringRef getString() const
Definition: Expr.h:1869
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3714
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3996
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition: Decl.cpp:4870
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3804
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3790
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3809
bool isStruct() const
Definition: Decl.h:3916
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4842
bool isUnion() const
Definition: Decl.h:3919
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3941
TagKind getTagKind() const
Definition: Decl.h:3908
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:810
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:226
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1573
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1288
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:527
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
Definition: TargetInfo.h:1867
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1616
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
Definition: TargetInfo.h:1567
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1624
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1563
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1360
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1431
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:577
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
Definition: TargetInfo.h:1537
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1326
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1526
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:668
A convenient class for passing around template argument information.
Definition: TemplateBase.h:634
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:652
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:653
ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:661
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:528
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:396
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:415
Represents a C++ template name within the type system.
Definition: TemplateName.h:222
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:74
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:207
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4609
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:102
bool isOneOf(Ts... Ks) const
Definition: Token.h:104
bool isNot(tok::TokenKind K) const
Definition: Token.h:103
A declaration that models statements at global scope.
Definition: Decl.h:4597
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5730
Represents a declaration of a type.
Definition: Decl.h:3510
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
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:354
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:1417
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:222
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:154
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:942
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:227
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2843
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:193
A container of type source information.
Definition: TypeBase.h:8314
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition: TypeBase.h:8325
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:556
The base class of the type hierarchy.
Definition: TypeBase.h:1833
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:2572
bool isStructureType() const
Definition: Type.cpp:678
bool isDecltypeType() const
Definition: TypeBase.h:8804
bool isDependentSizedArrayType() const
Definition: TypeBase.h:8699
bool isBlockPointerType() const
Definition: TypeBase.h:8600
bool isVoidType() const
Definition: TypeBase.h:8936
bool isBooleanType() const
Definition: TypeBase.h:9066
bool isFunctionReferenceType() const
Definition: TypeBase.h:8654
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2229
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: TypeBase.h:9116
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2998
bool isIncompleteArrayType() const
Definition: TypeBase.h:8687
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: TypeBase.h:9235
bool isDependentAddressSpaceType() const
Definition: TypeBase.h:8745
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.h:26
bool isConstantArrayType() const
Definition: TypeBase.h:8683
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: TypeBase.h:9096
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.h:41
bool isVoidPointerType() const
Definition: Type.cpp:712
bool isArrayType() const
Definition: TypeBase.h:8679
bool isFunctionPointerType() const
Definition: TypeBase.h:8647
bool isPointerType() const
Definition: TypeBase.h:8580
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2578
const T * castAs() const
Member-template castAs<specific type>.
Definition: TypeBase.h:9226
bool isReferenceType() const
Definition: TypeBase.h:8604
bool isEnumeralType() const
Definition: TypeBase.h:8711
bool isScalarType() const
Definition: TypeBase.h:9038
bool isVariableArrayType() const
Definition: TypeBase.h:8691
bool isClkEventT() const
Definition: TypeBase.h:8822
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2107
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: TypeBase.h:9054
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.h:65
bool isImageType() const
Definition: TypeBase.h:8834
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: TypeBase.h:2917
bool isPipeType() const
Definition: TypeBase.h:8841
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: TypeBase.h:2808
bool isBitIntType() const
Definition: TypeBase.h:8845
bool isOpenCLSpecificType() const
Definition: TypeBase.h:8870
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2415
RecordDecl * castAsRecordDecl() const
Definition: Type.h:48
bool isHalfType() const
Definition: TypeBase.h:8940
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2060
bool isHLSLSpecificType() const
Definition: TypeBase.h:8888
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2562
bool containsErrors() const
Whether this type is an error type.
Definition: TypeBase.h:2794
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: TypeBase.h:9109
bool isAtomicType() const
Definition: TypeBase.h:8762
bool isFunctionProtoType() const
Definition: TypeBase.h:2619
bool isObjCIdType() const
Definition: TypeBase.h:8782
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: TypeBase.h:2818
bool isObjCObjectType() const
Definition: TypeBase.h:8753
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5355
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: TypeBase.h:9072
bool isEventT() const
Definition: TypeBase.h:8818
bool isPointerOrReferenceType() const
Definition: TypeBase.h:8584
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:5299
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2440
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: TypeBase.h:9176
bool isFunctionType() const
Definition: TypeBase.h:8576
bool isObjCObjectPointerType() const
Definition: TypeBase.h:8749
bool isMemberFunctionPointerType() const
Definition: TypeBase.h:8665
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2599
bool isFloatingType() const
Definition: Type.cpp:2308
bool isAnyPointerType() const
Definition: TypeBase.h:8588
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:2065
bool isSamplerT() const
Definition: TypeBase.h:8814
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:653
bool isNullPtrType() const
Definition: TypeBase.h:8973
bool isRecordType() const
Definition: TypeBase.h:8707
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:5066
bool isUnionType() const
Definition: Type.cpp:718
bool isFunctionNoProtoType() const
Definition: TypeBase.h:2618
bool isReserveIDT() const
Definition: TypeBase.h:8830
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3664
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5629
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3559
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3609
QualType getUnderlyingType() const
Definition: Decl.h:3614
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3620
Wrapper for source info for typedefs.
Definition: TypeLoc.h:782
TypedefNameDecl * getDecl() const
Definition: TypeBase.h:6127
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.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2246
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:998
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:432
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Wrapper for source info for unresolved typename using decls.
Definition: TypeLoc.h:787
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3393
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3457
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3358
Wrapper for source info for types used via transparent aliases.
Definition: TypeLoc.h:790
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:711
void setType(QualType newType)
Definition: Decl.h:723
QualType getType() const
Definition: Decl.h:722
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5455
Represents a variable declaration or definition.
Definition: Decl.h:925
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2810
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2151
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1524
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1568
TLSKind getTLSKind() const
Definition: Decl.cpp:2168
bool hasInit() const
Definition: Decl.cpp:2398
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1451
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2260
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2190
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:2461
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2257
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1577
bool isCXXCondDecl() const
Definition: Decl.h:1610
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:936
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition: Decl.h:939
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:933
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2163
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1592
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1282
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1225
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2366
void setInlineSpecified()
Definition: Decl.h:1557
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1207
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2772
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1341
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1172
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1550
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1176
const Expr * getInit() const
Definition: Decl.h:1367
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1216
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1183
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2429
void setConstexpr(bool IC)
Definition: Decl.h:1571
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:948
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:951
void setInit(Expr *I)
Definition: Decl.cpp:2477
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2345
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1297
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1294
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1300
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2815
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2245
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1252
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1167
void setImplicitlyInline()
Definition: Decl.h:1562
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1475
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1587
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2706
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1261
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:2779
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1357
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: TypeBase.h:3982
Expr * getSizeExpr() const
Definition: TypeBase.h:3996
Captures information about a #pragma weak directive.
Definition: Weak.h:25
Policy getPolicyInEffectAt(SourceLocation Loc)
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:1096
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...
#define bool
Definition: gpuintrin.h:32
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 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:33
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:1857
@ NonFunction
This is not an overload because the lookup results contain a non-function.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
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
std::pair< FileID, unsigned > FileIDAndOffset
@ 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:31
CUDAFunctionTarget
Definition: Cuda.h:60
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:102
int hasAttribute(AttributeCommonInfo::Syntax Syntax, llvm::StringRef ScopeName, llvm::StringRef AttrName, const TargetInfo &Target, const LangOptions &LangOpts, bool CheckPlugins)
Return the version number associated with the attribute if we recognize and implement the attribute s...
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:35
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
@ NotFound
No entity found met the criteria.
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
@ Found
Name lookup found a single declaration that met the criteria.
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
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
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:602
NonTrivialCUnionContext
Definition: Sema.h:530
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition: Sema.h:626
@ None
Don't merge availability attributes at all.
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
@ 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.
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 DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:41
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
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)
@ SD_Thread
Thread storage duration.
Definition: Specifiers.h:342
@ SD_Static
Static storage duration.
Definition: Specifiers.h:343
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
@ Parameter
The parameter type of a method or function.
@ Result
The result type of a method or function.
OffsetOfKind
Definition: Sema.h:614
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:51
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:319
@ Template
We are parsing a template declaration.
TagUseKind
Definition: Sema.h:448
TagTypeKind
The kind of a tag type.
Definition: TypeBase.h:5906
@ 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:263
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
ExprResult ExprError()
Definition: Ownership.h:265
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1524
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
@ TU_Complete
The translation unit is a complete translation unit.
Definition: LangOptions.h:1099
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:424
@ 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:230
const FunctionProtoType * T
MultiVersionKind
Definition: Decl.h:1978
bool isExternalFormalLinkage(Linkage L)
Definition: Linkage.h:117
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1288
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:366
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ 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
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
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
@ Enumerator
Enumerator value with fixed underlying type.
@ 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:5967
ReservedIdentifierStatus
@ Other
Other implicit parameter.
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:37
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:60
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:259
const Expr * ConstraintExpr
Definition: Decl.h:87
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:1398
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition: DeclSpec.h:1549
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1373
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1332
const IdentifierInfo * Ident
Definition: DeclSpec.h:1304
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1221
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1633
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:132
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1614
enum clang::DeclaratorChunk::@211 Kind
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1657
RetTy visit(QualType FT, Ts &&... Args)
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:645
Extra information about a function prototype.
Definition: TypeBase.h:5367
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: TypeBase.h:5394
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: TypeBase.h:5945
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3246
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:60
std::vector< std::string > Features
Definition: TargetInfo.h:61
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
SourceLocation PragmaLocation
Definition: Sema.h:1805
ValueType CurrentValue
Definition: Sema.h:2008
bool CheckSameAsPrevious
Definition: Sema.h:352
NamedDecl * Previous
Definition: Sema.h:353
NamedDecl * New
Definition: Sema.h:354
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.