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" |
14 | #include "clang/AST/ASTConsumer.h" |
15 | #include "clang/AST/ASTContext.h" |
16 | #include "clang/AST/ASTLambda.h" |
17 | #include "clang/AST/CXXInheritance.h" |
18 | #include "clang/AST/CharUnits.h" |
19 | #include "clang/AST/CommentDiagnostic.h" |
20 | #include "clang/AST/Decl.h" |
21 | #include "clang/AST/DeclCXX.h" |
22 | #include "clang/AST/DeclObjC.h" |
23 | #include "clang/AST/DeclTemplate.h" |
24 | #include "clang/AST/EvaluatedExprVisitor.h" |
25 | #include "clang/AST/Expr.h" |
26 | #include "clang/AST/ExprCXX.h" |
27 | #include "clang/AST/NonTrivialTypeVisitor.h" |
28 | #include "clang/AST/Randstruct.h" |
29 | #include "clang/AST/StmtCXX.h" |
30 | #include "clang/AST/Type.h" |
31 | #include "clang/Basic/Builtins.h" |
32 | #include "clang/Basic/HLSLRuntime.h" |
33 | #include "clang/Basic/PartialDiagnostic.h" |
34 | #include "clang/Basic/SourceManager.h" |
35 | #include "clang/Basic/TargetInfo.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() |
40 | #include "clang/Sema/CXXFieldCollector.h" |
41 | #include "clang/Sema/DeclSpec.h" |
42 | #include "clang/Sema/DelayedDiagnostic.h" |
43 | #include "clang/Sema/Initialization.h" |
44 | #include "clang/Sema/Lookup.h" |
45 | #include "clang/Sema/ParsedTemplate.h" |
46 | #include "clang/Sema/Scope.h" |
47 | #include "clang/Sema/ScopeInfo.h" |
48 | #include "clang/Sema/SemaCUDA.h" |
49 | #include "clang/Sema/SemaHLSL.h" |
50 | #include "clang/Sema/SemaInternal.h" |
51 | #include "clang/Sema/SemaObjC.h" |
52 | #include "clang/Sema/SemaOpenMP.h" |
53 | #include "clang/Sema/SemaPPC.h" |
54 | #include "clang/Sema/SemaRISCV.h" |
55 | #include "clang/Sema/SemaSwift.h" |
56 | #include "clang/Sema/SemaWasm.h" |
57 | #include "clang/Sema/Template.h" |
58 | #include "llvm/ADT/STLForwardCompat.h" |
59 | #include "llvm/ADT/SmallString.h" |
60 | #include "llvm/ADT/StringExtras.h" |
61 | #include "llvm/TargetParser/Triple.h" |
62 | #include <algorithm> |
63 | #include <cstring> |
64 | #include <functional> |
65 | #include <optional> |
66 | #include <unordered_map> |
67 | |
68 | using namespace clang; |
69 | using namespace sema; |
70 | |
71 | Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { |
72 | if (OwnedType) { |
73 | Decl *Group[2] = { OwnedType, Ptr }; |
74 | return DeclGroupPtrTy::make(P: DeclGroupRef::Create(C&: Context, Decls: Group, NumDecls: 2)); |
75 | } |
76 | |
77 | return DeclGroupPtrTy::make(P: DeclGroupRef(Ptr)); |
78 | } |
79 | |
80 | namespace { |
81 | |
82 | class TypeNameValidatorCCC final : public CorrectionCandidateCallback { |
83 | public: |
84 | TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, |
85 | bool AllowTemplates = false, |
86 | bool AllowNonTemplates = true) |
87 | : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), |
88 | AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { |
89 | WantExpressionKeywords = false; |
90 | WantCXXNamedCasts = false; |
91 | WantRemainingKeywords = false; |
92 | } |
93 | |
94 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
95 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { |
96 | if (!AllowInvalidDecl && ND->isInvalidDecl()) |
97 | return false; |
98 | |
99 | if (getAsTypeTemplateDecl(D: ND)) |
100 | return AllowTemplates; |
101 | |
102 | bool IsType = isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND); |
103 | if (!IsType) |
104 | return false; |
105 | |
106 | if (AllowNonTemplates) |
107 | return true; |
108 | |
109 | // An injected-class-name of a class template (specialization) is valid |
110 | // as a template or as a non-template. |
111 | if (AllowTemplates) { |
112 | auto *RD = dyn_cast<CXXRecordDecl>(Val: ND); |
113 | if (!RD || !RD->isInjectedClassName()) |
114 | return false; |
115 | RD = cast<CXXRecordDecl>(Val: RD->getDeclContext()); |
116 | return RD->getDescribedClassTemplate() || |
117 | isa<ClassTemplateSpecializationDecl>(Val: RD); |
118 | } |
119 | |
120 | return false; |
121 | } |
122 | |
123 | return !WantClassName && candidate.isKeyword(); |
124 | } |
125 | |
126 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
127 | return std::make_unique<TypeNameValidatorCCC>(args&: *this); |
128 | } |
129 | |
130 | private: |
131 | bool AllowInvalidDecl; |
132 | bool WantClassName; |
133 | bool AllowTemplates; |
134 | bool AllowNonTemplates; |
135 | }; |
136 | |
137 | } // end anonymous namespace |
138 | |
139 | namespace { |
140 | enum class UnqualifiedTypeNameLookupResult { |
141 | NotFound, |
142 | FoundNonType, |
143 | FoundType |
144 | }; |
145 | } // end anonymous namespace |
146 | |
147 | /// Tries to perform unqualified lookup of the type decls in bases for |
148 | /// dependent class. |
149 | /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a |
150 | /// type decl, \a FoundType if only type decls are found. |
151 | static UnqualifiedTypeNameLookupResult |
152 | lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, |
153 | SourceLocation NameLoc, |
154 | const CXXRecordDecl *RD) { |
155 | if (!RD->hasDefinition()) |
156 | return UnqualifiedTypeNameLookupResult::NotFound; |
157 | // Look for type decls in base classes. |
158 | UnqualifiedTypeNameLookupResult FoundTypeDecl = |
159 | UnqualifiedTypeNameLookupResult::NotFound; |
160 | for (const auto &Base : RD->bases()) { |
161 | const CXXRecordDecl *BaseRD = nullptr; |
162 | if (auto *BaseTT = Base.getType()->getAs<TagType>()) |
163 | BaseRD = BaseTT->getAsCXXRecordDecl(); |
164 | else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { |
165 | // Look for type decls in dependent base classes that have known primary |
166 | // templates. |
167 | if (!TST || !TST->isDependentType()) |
168 | continue; |
169 | auto *TD = TST->getTemplateName().getAsTemplateDecl(); |
170 | if (!TD) |
171 | continue; |
172 | if (auto *BasePrimaryTemplate = |
173 | dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl())) { |
174 | if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) |
175 | BaseRD = BasePrimaryTemplate; |
176 | else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) { |
177 | if (const ClassTemplatePartialSpecializationDecl *PS = |
178 | CTD->findPartialSpecialization(T: Base.getType())) |
179 | if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) |
180 | BaseRD = PS; |
181 | } |
182 | } |
183 | } |
184 | if (BaseRD) { |
185 | for (NamedDecl *ND : BaseRD->lookup(Name: &II)) { |
186 | if (!isa<TypeDecl>(Val: ND)) |
187 | return UnqualifiedTypeNameLookupResult::FoundNonType; |
188 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; |
189 | } |
190 | if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { |
191 | switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD: BaseRD)) { |
192 | case UnqualifiedTypeNameLookupResult::FoundNonType: |
193 | return UnqualifiedTypeNameLookupResult::FoundNonType; |
194 | case UnqualifiedTypeNameLookupResult::FoundType: |
195 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; |
196 | break; |
197 | case UnqualifiedTypeNameLookupResult::NotFound: |
198 | break; |
199 | } |
200 | } |
201 | } |
202 | } |
203 | |
204 | return FoundTypeDecl; |
205 | } |
206 | |
207 | static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, |
208 | const IdentifierInfo &II, |
209 | SourceLocation NameLoc) { |
210 | // Lookup in the parent class template context, if any. |
211 | const CXXRecordDecl *RD = nullptr; |
212 | UnqualifiedTypeNameLookupResult FoundTypeDecl = |
213 | UnqualifiedTypeNameLookupResult::NotFound; |
214 | for (DeclContext *DC = S.CurContext; |
215 | DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; |
216 | DC = DC->getParent()) { |
217 | // Look for type decls in dependent base classes that have known primary |
218 | // templates. |
219 | RD = dyn_cast<CXXRecordDecl>(Val: DC); |
220 | if (RD && RD->getDescribedClassTemplate()) |
221 | FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); |
222 | } |
223 | if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) |
224 | return nullptr; |
225 | |
226 | // We found some types in dependent base classes. Recover as if the user |
227 | // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the |
228 | // lookup during template instantiation. |
229 | S.Diag(Loc: NameLoc, DiagID: diag::ext_found_in_dependent_base) << &II; |
230 | |
231 | ASTContext &Context = S.Context; |
232 | auto *NNS = NestedNameSpecifier::Create(Context, Prefix: nullptr, Template: false, |
233 | T: cast<Type>(Val: Context.getRecordType(Decl: RD))); |
234 | QualType T = |
235 | Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::Typename, NNS, Name: &II); |
236 | |
237 | CXXScopeSpec SS; |
238 | SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc)); |
239 | |
240 | TypeLocBuilder Builder; |
241 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); |
242 | DepTL.setNameLoc(NameLoc); |
243 | DepTL.setElaboratedKeywordLoc(SourceLocation()); |
244 | DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
245 | return S.CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T)); |
246 | } |
247 | |
248 | /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. |
249 | static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T, |
250 | SourceLocation NameLoc, |
251 | bool WantNontrivialTypeSourceInfo = true) { |
252 | switch (T->getTypeClass()) { |
253 | case Type::DeducedTemplateSpecialization: |
254 | case Type::Enum: |
255 | case Type::InjectedClassName: |
256 | case Type::Record: |
257 | case Type::Typedef: |
258 | case Type::UnresolvedUsing: |
259 | case Type::Using: |
260 | break; |
261 | // These can never be qualified so an ElaboratedType node |
262 | // would carry no additional meaning. |
263 | case Type::ObjCInterface: |
264 | case Type::ObjCTypeParam: |
265 | case Type::TemplateTypeParm: |
266 | return ParsedType::make(P: T); |
267 | default: |
268 | llvm_unreachable("Unexpected Type Class" ); |
269 | } |
270 | |
271 | if (!SS || SS->isEmpty()) |
272 | return ParsedType::make(P: S.Context.getElaboratedType( |
273 | Keyword: ElaboratedTypeKeyword::None, NNS: nullptr, NamedType: T, OwnedTagDecl: nullptr)); |
274 | |
275 | QualType ElTy = S.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS: *SS, T); |
276 | if (!WantNontrivialTypeSourceInfo) |
277 | return ParsedType::make(P: ElTy); |
278 | |
279 | TypeLocBuilder Builder; |
280 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); |
281 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T: ElTy); |
282 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); |
283 | ElabTL.setQualifierLoc(SS->getWithLocInContext(Context&: S.Context)); |
284 | return S.CreateParsedType(T: ElTy, TInfo: Builder.getTypeSourceInfo(Context&: S.Context, T: ElTy)); |
285 | } |
286 | |
287 | ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, |
288 | Scope *S, CXXScopeSpec *SS, bool isClassName, |
289 | bool HasTrailingDot, ParsedType ObjectTypePtr, |
290 | bool IsCtorOrDtorName, |
291 | bool WantNontrivialTypeSourceInfo, |
292 | bool IsClassTemplateDeductionContext, |
293 | ImplicitTypenameContext AllowImplicitTypename, |
294 | IdentifierInfo **CorrectedII) { |
295 | // FIXME: Consider allowing this outside C++1z mode as an extension. |
296 | bool AllowDeducedTemplate = IsClassTemplateDeductionContext && |
297 | getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && |
298 | !isClassName && !HasTrailingDot; |
299 | |
300 | // Determine where we will perform name lookup. |
301 | DeclContext *LookupCtx = nullptr; |
302 | if (ObjectTypePtr) { |
303 | QualType ObjectType = ObjectTypePtr.get(); |
304 | if (ObjectType->isRecordType()) |
305 | LookupCtx = computeDeclContext(T: ObjectType); |
306 | } else if (SS && SS->isNotEmpty()) { |
307 | LookupCtx = computeDeclContext(SS: *SS, EnteringContext: false); |
308 | |
309 | if (!LookupCtx) { |
310 | if (isDependentScopeSpecifier(SS: *SS)) { |
311 | // C++ [temp.res]p3: |
312 | // A qualified-id that refers to a type and in which the |
313 | // nested-name-specifier depends on a template-parameter (14.6.2) |
314 | // shall be prefixed by the keyword typename to indicate that the |
315 | // qualified-id denotes a type, forming an |
316 | // elaborated-type-specifier (7.1.5.3). |
317 | // |
318 | // We therefore do not perform any name lookup if the result would |
319 | // refer to a member of an unknown specialization. |
320 | // In C++2a, in several contexts a 'typename' is not required. Also |
321 | // allow this as an extension. |
322 | if (AllowImplicitTypename == ImplicitTypenameContext::No && |
323 | !isClassName && !IsCtorOrDtorName) |
324 | return nullptr; |
325 | bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName; |
326 | if (IsImplicitTypename) { |
327 | SourceLocation QualifiedLoc = SS->getRange().getBegin(); |
328 | if (getLangOpts().CPlusPlus20) |
329 | Diag(Loc: QualifiedLoc, DiagID: diag::warn_cxx17_compat_implicit_typename); |
330 | else |
331 | Diag(Loc: QualifiedLoc, DiagID: diag::ext_implicit_typename) |
332 | << SS->getScopeRep() << II.getName() |
333 | << FixItHint::CreateInsertion(InsertionLoc: QualifiedLoc, Code: "typename " ); |
334 | } |
335 | |
336 | // We know from the grammar that this name refers to a type, |
337 | // so build a dependent node to describe the type. |
338 | if (WantNontrivialTypeSourceInfo) |
339 | return ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II, IdLoc: NameLoc, |
340 | IsImplicitTypename: (ImplicitTypenameContext)IsImplicitTypename) |
341 | .get(); |
342 | |
343 | NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); |
344 | QualType T = CheckTypenameType( |
345 | Keyword: IsImplicitTypename ? ElaboratedTypeKeyword::Typename |
346 | : ElaboratedTypeKeyword::None, |
347 | KeywordLoc: SourceLocation(), QualifierLoc, II, IILoc: NameLoc); |
348 | return ParsedType::make(P: T); |
349 | } |
350 | |
351 | return nullptr; |
352 | } |
353 | |
354 | if (!LookupCtx->isDependentContext() && |
355 | RequireCompleteDeclContext(SS&: *SS, DC: LookupCtx)) |
356 | return nullptr; |
357 | } |
358 | |
359 | // FIXME: LookupNestedNameSpecifierName isn't the right kind of |
360 | // lookup for class-names. |
361 | LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : |
362 | LookupOrdinaryName; |
363 | LookupResult Result(*this, &II, NameLoc, Kind); |
364 | if (LookupCtx) { |
365 | // Perform "qualified" name lookup into the declaration context we |
366 | // computed, which is either the type of the base of a member access |
367 | // expression or the declaration context associated with a prior |
368 | // nested-name-specifier. |
369 | LookupQualifiedName(R&: Result, LookupCtx); |
370 | |
371 | if (ObjectTypePtr && Result.empty()) { |
372 | // C++ [basic.lookup.classref]p3: |
373 | // If the unqualified-id is ~type-name, the type-name is looked up |
374 | // in the context of the entire postfix-expression. If the type T of |
375 | // the object expression is of a class type C, the type-name is also |
376 | // looked up in the scope of class C. At least one of the lookups shall |
377 | // find a name that refers to (possibly cv-qualified) T. |
378 | LookupName(R&: Result, S); |
379 | } |
380 | } else { |
381 | // Perform unqualified name lookup. |
382 | LookupName(R&: Result, S); |
383 | |
384 | // For unqualified lookup in a class template in MSVC mode, look into |
385 | // dependent base classes where the primary class template is known. |
386 | if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { |
387 | if (ParsedType TypeInBase = |
388 | recoverFromTypeInKnownDependentBase(S&: *this, II, NameLoc)) |
389 | return TypeInBase; |
390 | } |
391 | } |
392 | |
393 | NamedDecl *IIDecl = nullptr; |
394 | UsingShadowDecl *FoundUsingShadow = nullptr; |
395 | switch (Result.getResultKind()) { |
396 | case LookupResult::NotFound: |
397 | if (CorrectedII) { |
398 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, |
399 | AllowDeducedTemplate); |
400 | TypoCorrection Correction = CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Kind, |
401 | S, SS, CCC, Mode: CTK_ErrorRecovery); |
402 | IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); |
403 | TemplateTy Template; |
404 | bool MemberOfUnknownSpecialization; |
405 | UnqualifiedId TemplateName; |
406 | TemplateName.setIdentifier(Id: NewII, IdLoc: NameLoc); |
407 | NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); |
408 | CXXScopeSpec NewSS, *NewSSPtr = SS; |
409 | if (SS && NNS) { |
410 | NewSS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc)); |
411 | NewSSPtr = &NewSS; |
412 | } |
413 | if (Correction && (NNS || NewII != &II) && |
414 | // Ignore a correction to a template type as the to-be-corrected |
415 | // identifier is not a template (typo correction for template names |
416 | // is handled elsewhere). |
417 | !(getLangOpts().CPlusPlus && NewSSPtr && |
418 | isTemplateName(S, SS&: *NewSSPtr, hasTemplateKeyword: false, Name: TemplateName, ObjectType: nullptr, EnteringContext: false, |
419 | Template, MemberOfUnknownSpecialization))) { |
420 | ParsedType Ty = getTypeName(II: *NewII, NameLoc, S, SS: NewSSPtr, |
421 | isClassName, HasTrailingDot, ObjectTypePtr, |
422 | IsCtorOrDtorName, |
423 | WantNontrivialTypeSourceInfo, |
424 | IsClassTemplateDeductionContext); |
425 | if (Ty) { |
426 | diagnoseTypo(Correction, |
427 | TypoDiag: PDiag(DiagID: diag::err_unknown_type_or_class_name_suggest) |
428 | << Result.getLookupName() << isClassName); |
429 | if (SS && NNS) |
430 | SS->MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc)); |
431 | *CorrectedII = NewII; |
432 | return Ty; |
433 | } |
434 | } |
435 | } |
436 | Result.suppressDiagnostics(); |
437 | return nullptr; |
438 | case LookupResult::NotFoundInCurrentInstantiation: |
439 | if (AllowImplicitTypename == ImplicitTypenameContext::Yes) { |
440 | QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, |
441 | NNS: SS->getScopeRep(), Name: &II); |
442 | TypeLocBuilder TLB; |
443 | DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T); |
444 | TL.setElaboratedKeywordLoc(SourceLocation()); |
445 | TL.setQualifierLoc(SS->getWithLocInContext(Context)); |
446 | TL.setNameLoc(NameLoc); |
447 | return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T)); |
448 | } |
449 | [[fallthrough]]; |
450 | case LookupResult::FoundOverloaded: |
451 | case LookupResult::FoundUnresolvedValue: |
452 | Result.suppressDiagnostics(); |
453 | return nullptr; |
454 | |
455 | case LookupResult::Ambiguous: |
456 | // Recover from type-hiding ambiguities by hiding the type. We'll |
457 | // do the lookup again when looking for an object, and we can |
458 | // diagnose the error then. If we don't do this, then the error |
459 | // about hiding the type will be immediately followed by an error |
460 | // that only makes sense if the identifier was treated like a type. |
461 | if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { |
462 | Result.suppressDiagnostics(); |
463 | return nullptr; |
464 | } |
465 | |
466 | // Look to see if we have a type anywhere in the list of results. |
467 | for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); |
468 | Res != ResEnd; ++Res) { |
469 | NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); |
470 | if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( |
471 | Val: RealRes) || |
472 | (AllowDeducedTemplate && getAsTypeTemplateDecl(D: RealRes))) { |
473 | if (!IIDecl || |
474 | // Make the selection of the recovery decl deterministic. |
475 | RealRes->getLocation() < IIDecl->getLocation()) { |
476 | IIDecl = RealRes; |
477 | FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Res); |
478 | } |
479 | } |
480 | } |
481 | |
482 | if (!IIDecl) { |
483 | // None of the entities we found is a type, so there is no way |
484 | // to even assume that the result is a type. In this case, don't |
485 | // complain about the ambiguity. The parser will either try to |
486 | // perform this lookup again (e.g., as an object name), which |
487 | // will produce the ambiguity, or will complain that it expected |
488 | // a type name. |
489 | Result.suppressDiagnostics(); |
490 | return nullptr; |
491 | } |
492 | |
493 | // We found a type within the ambiguous lookup; diagnose the |
494 | // ambiguity and then return that type. This might be the right |
495 | // answer, or it might not be, but it suppresses any attempt to |
496 | // perform the name lookup again. |
497 | break; |
498 | |
499 | case LookupResult::Found: |
500 | IIDecl = Result.getFoundDecl(); |
501 | FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Result.begin()); |
502 | break; |
503 | } |
504 | |
505 | assert(IIDecl && "Didn't find decl" ); |
506 | |
507 | QualType T; |
508 | if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: IIDecl)) { |
509 | // C++ [class.qual]p2: A lookup that would find the injected-class-name |
510 | // instead names the constructors of the class, except when naming a class. |
511 | // This is ill-formed when we're not actually forming a ctor or dtor name. |
512 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx); |
513 | auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: TD); |
514 | if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && |
515 | FoundRD->isInjectedClassName() && |
516 | declaresSameEntity(D1: LookupRD, D2: cast<Decl>(Val: FoundRD->getParent()))) |
517 | Diag(Loc: NameLoc, DiagID: diag::err_out_of_line_qualified_id_type_names_constructor) |
518 | << &II << /*Type*/1; |
519 | |
520 | DiagnoseUseOfDecl(D: IIDecl, Locs: NameLoc); |
521 | |
522 | T = Context.getTypeDeclType(Decl: TD); |
523 | MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false); |
524 | } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) { |
525 | (void)DiagnoseUseOfDecl(D: IDecl, Locs: NameLoc); |
526 | if (!HasTrailingDot) |
527 | T = Context.getObjCInterfaceType(Decl: IDecl); |
528 | FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl. |
529 | } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) { |
530 | (void)DiagnoseUseOfDecl(D: UD, Locs: NameLoc); |
531 | // Recover with 'int' |
532 | return ParsedType::make(P: Context.IntTy); |
533 | } else if (AllowDeducedTemplate) { |
534 | if (auto *TD = getAsTypeTemplateDecl(D: IIDecl)) { |
535 | assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD); |
536 | TemplateName Template = Context.getQualifiedTemplateName( |
537 | NNS: SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false, |
538 | Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD)); |
539 | T = Context.getDeducedTemplateSpecializationType(Template, DeducedType: QualType(), |
540 | IsDependent: false); |
541 | // Don't wrap in a further UsingType. |
542 | FoundUsingShadow = nullptr; |
543 | } |
544 | } |
545 | |
546 | if (T.isNull()) { |
547 | // If it's not plausibly a type, suppress diagnostics. |
548 | Result.suppressDiagnostics(); |
549 | return nullptr; |
550 | } |
551 | |
552 | if (FoundUsingShadow) |
553 | T = Context.getUsingType(Found: FoundUsingShadow, Underlying: T); |
554 | |
555 | return buildNamedType(S&: *this, SS, T, NameLoc, WantNontrivialTypeSourceInfo); |
556 | } |
557 | |
558 | // Builds a fake NNS for the given decl context. |
559 | static NestedNameSpecifier * |
560 | synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { |
561 | for (;; DC = DC->getLookupParent()) { |
562 | DC = DC->getPrimaryContext(); |
563 | auto *ND = dyn_cast<NamespaceDecl>(Val: DC); |
564 | if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) |
565 | return NestedNameSpecifier::Create(Context, Prefix: nullptr, NS: ND); |
566 | else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) |
567 | return NestedNameSpecifier::Create(Context, Prefix: nullptr, Template: RD->isTemplateDecl(), |
568 | T: RD->getTypeForDecl()); |
569 | else if (isa<TranslationUnitDecl>(Val: DC)) |
570 | return NestedNameSpecifier::GlobalSpecifier(Context); |
571 | } |
572 | llvm_unreachable("something isn't in TU scope?" ); |
573 | } |
574 | |
575 | /// Find the parent class with dependent bases of the innermost enclosing method |
576 | /// context. Do not look for enclosing CXXRecordDecls directly, or we will end |
577 | /// up allowing unqualified dependent type names at class-level, which MSVC |
578 | /// correctly rejects. |
579 | static const CXXRecordDecl * |
580 | findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { |
581 | for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { |
582 | DC = DC->getPrimaryContext(); |
583 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC)) |
584 | if (MD->getParent()->hasAnyDependentBases()) |
585 | return MD->getParent(); |
586 | } |
587 | return nullptr; |
588 | } |
589 | |
590 | ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, |
591 | SourceLocation NameLoc, |
592 | bool IsTemplateTypeArg) { |
593 | assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode" ); |
594 | |
595 | NestedNameSpecifier *NNS = nullptr; |
596 | if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { |
597 | // If we weren't able to parse a default template argument, delay lookup |
598 | // until instantiation time by making a non-dependent DependentTypeName. We |
599 | // pretend we saw a NestedNameSpecifier referring to the current scope, and |
600 | // lookup is retried. |
601 | // FIXME: This hurts our diagnostic quality, since we get errors like "no |
602 | // type named 'Foo' in 'current_namespace'" when the user didn't write any |
603 | // name specifiers. |
604 | NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext); |
605 | Diag(Loc: NameLoc, DiagID: diag::ext_ms_delayed_template_argument) << &II; |
606 | } else if (const CXXRecordDecl *RD = |
607 | findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) { |
608 | // Build a DependentNameType that will perform lookup into RD at |
609 | // instantiation time. |
610 | NNS = NestedNameSpecifier::Create(Context, Prefix: nullptr, Template: RD->isTemplateDecl(), |
611 | T: RD->getTypeForDecl()); |
612 | |
613 | // Diagnose that this identifier was undeclared, and retry the lookup during |
614 | // template instantiation. |
615 | Diag(Loc: NameLoc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base) << &II |
616 | << RD; |
617 | } else { |
618 | // This is not a situation that we should recover from. |
619 | return ParsedType(); |
620 | } |
621 | |
622 | QualType T = |
623 | Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II); |
624 | |
625 | // Build type location information. We synthesized the qualifier, so we have |
626 | // to build a fake NestedNameSpecifierLoc. |
627 | NestedNameSpecifierLocBuilder NNSLocBuilder; |
628 | NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc)); |
629 | NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); |
630 | |
631 | TypeLocBuilder Builder; |
632 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); |
633 | DepTL.setNameLoc(NameLoc); |
634 | DepTL.setElaboratedKeywordLoc(SourceLocation()); |
635 | DepTL.setQualifierLoc(QualifierLoc); |
636 | return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T)); |
637 | } |
638 | |
639 | DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { |
640 | // Do a tag name lookup in this scope. |
641 | LookupResult R(*this, &II, SourceLocation(), LookupTagName); |
642 | LookupName(R, S, AllowBuiltinCreation: false); |
643 | R.suppressDiagnostics(); |
644 | if (R.getResultKind() == LookupResult::Found) |
645 | if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { |
646 | switch (TD->getTagKind()) { |
647 | case TagTypeKind::Struct: |
648 | return DeclSpec::TST_struct; |
649 | case TagTypeKind::Interface: |
650 | return DeclSpec::TST_interface; |
651 | case TagTypeKind::Union: |
652 | return DeclSpec::TST_union; |
653 | case TagTypeKind::Class: |
654 | return DeclSpec::TST_class; |
655 | case TagTypeKind::Enum: |
656 | return DeclSpec::TST_enum; |
657 | } |
658 | } |
659 | |
660 | return DeclSpec::TST_unspecified; |
661 | } |
662 | |
663 | bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { |
664 | if (CurContext->isRecord()) { |
665 | if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) |
666 | return true; |
667 | |
668 | const Type *Ty = SS->getScopeRep()->getAsType(); |
669 | |
670 | CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: CurContext); |
671 | for (const auto &Base : RD->bases()) |
672 | if (Ty && Context.hasSameUnqualifiedType(T1: QualType(Ty, 1), T2: Base.getType())) |
673 | return true; |
674 | return S->isFunctionPrototypeScope(); |
675 | } |
676 | return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); |
677 | } |
678 | |
679 | void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, |
680 | SourceLocation IILoc, |
681 | Scope *S, |
682 | CXXScopeSpec *SS, |
683 | ParsedType &SuggestedType, |
684 | bool IsTemplateName) { |
685 | // Don't report typename errors for editor placeholders. |
686 | if (II->isEditorPlaceholder()) |
687 | return; |
688 | // We don't have anything to suggest (yet). |
689 | SuggestedType = nullptr; |
690 | |
691 | // There may have been a typo in the name of the type. Look up typo |
692 | // results, in case we have something that we can suggest. |
693 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, |
694 | /*AllowTemplates=*/IsTemplateName, |
695 | /*AllowNonTemplates=*/!IsTemplateName); |
696 | if (TypoCorrection Corrected = |
697 | CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS, |
698 | CCC, Mode: CTK_ErrorRecovery)) { |
699 | // FIXME: Support error recovery for the template-name case. |
700 | bool CanRecover = !IsTemplateName; |
701 | if (Corrected.isKeyword()) { |
702 | // We corrected to a keyword. |
703 | diagnoseTypo(Correction: Corrected, |
704 | TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest |
705 | : diag::err_unknown_typename_suggest) |
706 | << II); |
707 | II = Corrected.getCorrectionAsIdentifierInfo(); |
708 | } else { |
709 | // We found a similarly-named type or interface; suggest that. |
710 | if (!SS || !SS->isSet()) { |
711 | diagnoseTypo(Correction: Corrected, |
712 | TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest |
713 | : diag::err_unknown_typename_suggest) |
714 | << II, ErrorRecovery: CanRecover); |
715 | } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) { |
716 | std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts())); |
717 | bool DroppedSpecifier = |
718 | Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr; |
719 | diagnoseTypo(Correction: Corrected, |
720 | TypoDiag: PDiag(DiagID: IsTemplateName |
721 | ? diag::err_no_member_template_suggest |
722 | : diag::err_unknown_nested_typename_suggest) |
723 | << II << DC << DroppedSpecifier << SS->getRange(), |
724 | ErrorRecovery: CanRecover); |
725 | } else { |
726 | llvm_unreachable("could not have corrected a typo here" ); |
727 | } |
728 | |
729 | if (!CanRecover) |
730 | return; |
731 | |
732 | CXXScopeSpec tmpSS; |
733 | if (Corrected.getCorrectionSpecifier()) |
734 | tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(), |
735 | R: SourceRange(IILoc)); |
736 | // FIXME: Support class template argument deduction here. |
737 | SuggestedType = |
738 | getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S, |
739 | SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr, |
740 | /*IsCtorOrDtorName=*/false, |
741 | /*WantNontrivialTypeSourceInfo=*/true); |
742 | } |
743 | return; |
744 | } |
745 | |
746 | if (getLangOpts().CPlusPlus && !IsTemplateName) { |
747 | // See if II is a class template that the user forgot to pass arguments to. |
748 | UnqualifiedId Name; |
749 | Name.setIdentifier(Id: II, IdLoc: IILoc); |
750 | CXXScopeSpec EmptySS; |
751 | TemplateTy TemplateResult; |
752 | bool MemberOfUnknownSpecialization; |
753 | if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, |
754 | Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult, |
755 | MemberOfUnknownSpecialization) == TNK_Type_template) { |
756 | diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc); |
757 | return; |
758 | } |
759 | } |
760 | |
761 | // FIXME: Should we move the logic that tries to recover from a missing tag |
762 | // (struct, union, enum) from Parser::ParseImplicitInt here, instead? |
763 | |
764 | if (!SS || (!SS->isSet() && !SS->isInvalid())) |
765 | Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_template |
766 | : diag::err_unknown_typename) |
767 | << II; |
768 | else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) |
769 | Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_member_template |
770 | : diag::err_typename_nested_not_found) |
771 | << II << DC << SS->getRange(); |
772 | else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { |
773 | SuggestedType = |
774 | ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get(); |
775 | } else if (isDependentScopeSpecifier(SS: *SS)) { |
776 | unsigned DiagID = diag::err_typename_missing; |
777 | if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) |
778 | DiagID = diag::ext_typename_missing; |
779 | |
780 | Diag(Loc: SS->getRange().getBegin(), DiagID) |
781 | << SS->getScopeRep() << II->getName() |
782 | << SourceRange(SS->getRange().getBegin(), IILoc) |
783 | << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename " ); |
784 | SuggestedType = ActOnTypenameType(S, TypenameLoc: SourceLocation(), |
785 | SS: *SS, II: *II, IdLoc: IILoc).get(); |
786 | } else { |
787 | assert(SS && SS->isInvalid() && |
788 | "Invalid scope specifier has already been diagnosed" ); |
789 | } |
790 | } |
791 | |
792 | /// Determine whether the given result set contains either a type name |
793 | /// or |
794 | static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { |
795 | bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && |
796 | NextToken.is(K: tok::less); |
797 | |
798 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { |
799 | if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I)) |
800 | return true; |
801 | |
802 | if (CheckTemplate && isa<TemplateDecl>(Val: *I)) |
803 | return true; |
804 | } |
805 | |
806 | return false; |
807 | } |
808 | |
809 | static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, |
810 | Scope *S, CXXScopeSpec &SS, |
811 | IdentifierInfo *&Name, |
812 | SourceLocation NameLoc) { |
813 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); |
814 | SemaRef.LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType()); |
815 | if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { |
816 | StringRef FixItTagName; |
817 | switch (Tag->getTagKind()) { |
818 | case TagTypeKind::Class: |
819 | FixItTagName = "class " ; |
820 | break; |
821 | |
822 | case TagTypeKind::Enum: |
823 | FixItTagName = "enum " ; |
824 | break; |
825 | |
826 | case TagTypeKind::Struct: |
827 | FixItTagName = "struct " ; |
828 | break; |
829 | |
830 | case TagTypeKind::Interface: |
831 | FixItTagName = "__interface " ; |
832 | break; |
833 | |
834 | case TagTypeKind::Union: |
835 | FixItTagName = "union " ; |
836 | break; |
837 | } |
838 | |
839 | StringRef TagName = FixItTagName.drop_back(); |
840 | SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_use_of_tag_name_without_tag) |
841 | << Name << TagName << SemaRef.getLangOpts().CPlusPlus |
842 | << FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: FixItTagName); |
843 | |
844 | for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); |
845 | I != IEnd; ++I) |
846 | SemaRef.Diag(Loc: (*I)->getLocation(), DiagID: diag::note_decl_hiding_tag_type) |
847 | << Name << TagName; |
848 | |
849 | // Replace lookup results with just the tag decl. |
850 | Result.clear(Kind: Sema::LookupTagName); |
851 | SemaRef.LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType()); |
852 | return true; |
853 | } |
854 | |
855 | return false; |
856 | } |
857 | |
858 | Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, |
859 | IdentifierInfo *&Name, |
860 | SourceLocation NameLoc, |
861 | const Token &NextToken, |
862 | CorrectionCandidateCallback *CCC) { |
863 | DeclarationNameInfo NameInfo(Name, NameLoc); |
864 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); |
865 | |
866 | assert(NextToken.isNot(tok::coloncolon) && |
867 | "parse nested name specifiers before calling ClassifyName" ); |
868 | if (getLangOpts().CPlusPlus && SS.isSet() && |
869 | isCurrentClassName(II: *Name, S, SS: &SS)) { |
870 | // Per [class.qual]p2, this names the constructors of SS, not the |
871 | // injected-class-name. We don't have a classification for that. |
872 | // There's not much point caching this result, since the parser |
873 | // will reject it later. |
874 | return NameClassification::Unknown(); |
875 | } |
876 | |
877 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); |
878 | LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType(), |
879 | /*AllowBuiltinCreation=*/!CurMethod); |
880 | |
881 | if (SS.isInvalid()) |
882 | return NameClassification::Error(); |
883 | |
884 | // For unqualified lookup in a class template in MSVC mode, look into |
885 | // dependent base classes where the primary class template is known. |
886 | if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { |
887 | if (ParsedType TypeInBase = |
888 | recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc)) |
889 | return TypeInBase; |
890 | } |
891 | |
892 | // Perform lookup for Objective-C instance variables (including automatically |
893 | // synthesized instance variables), if we're in an Objective-C method. |
894 | // FIXME: This lookup really, really needs to be folded in to the normal |
895 | // unqualified lookup mechanism. |
896 | if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) { |
897 | DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Name); |
898 | if (Ivar.isInvalid()) |
899 | return NameClassification::Error(); |
900 | if (Ivar.isUsable()) |
901 | return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get())); |
902 | |
903 | // We defer builtin creation until after ivar lookup inside ObjC methods. |
904 | if (Result.empty()) |
905 | LookupBuiltin(R&: Result); |
906 | } |
907 | |
908 | bool SecondTry = false; |
909 | bool IsFilteredTemplateName = false; |
910 | |
911 | Corrected: |
912 | switch (Result.getResultKind()) { |
913 | case LookupResult::NotFound: |
914 | // If an unqualified-id is followed by a '(', then we have a function |
915 | // call. |
916 | if (SS.isEmpty() && NextToken.is(K: tok::l_paren)) { |
917 | // In C++, this is an ADL-only call. |
918 | // FIXME: Reference? |
919 | if (getLangOpts().CPlusPlus) |
920 | return NameClassification::UndeclaredNonType(); |
921 | |
922 | // C90 6.3.2.2: |
923 | // If the expression that precedes the parenthesized argument list in a |
924 | // function call consists solely of an identifier, and if no |
925 | // declaration is visible for this identifier, the identifier is |
926 | // implicitly declared exactly as if, in the innermost block containing |
927 | // the function call, the declaration |
928 | // |
929 | // extern int identifier (); |
930 | // |
931 | // appeared. |
932 | // |
933 | // We also allow this in C99 as an extension. However, this is not |
934 | // allowed in all language modes as functions without prototypes may not |
935 | // be supported. |
936 | if (getLangOpts().implicitFunctionsAllowed()) { |
937 | if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S)) |
938 | return NameClassification::NonType(D); |
939 | } |
940 | } |
941 | |
942 | if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) { |
943 | // In C++20 onwards, this could be an ADL-only call to a function |
944 | // template, and we're required to assume that this is a template name. |
945 | // |
946 | // FIXME: Find a way to still do typo correction in this case. |
947 | TemplateName Template = |
948 | Context.getAssumedTemplateName(Name: NameInfo.getName()); |
949 | return NameClassification::UndeclaredTemplate(Name: Template); |
950 | } |
951 | |
952 | // In C, we first see whether there is a tag type by the same name, in |
953 | // which case it's likely that the user just forgot to write "enum", |
954 | // "struct", or "union". |
955 | if (!getLangOpts().CPlusPlus && !SecondTry && |
956 | isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) { |
957 | break; |
958 | } |
959 | |
960 | // Perform typo correction to determine if there is another name that is |
961 | // close to this name. |
962 | if (!SecondTry && CCC) { |
963 | SecondTry = true; |
964 | if (TypoCorrection Corrected = |
965 | CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S, |
966 | SS: &SS, CCC&: *CCC, Mode: CTK_ErrorRecovery)) { |
967 | unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; |
968 | unsigned QualifiedDiag = diag::err_no_member_suggest; |
969 | |
970 | NamedDecl *FirstDecl = Corrected.getFoundDecl(); |
971 | NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); |
972 | if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) && |
973 | UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) { |
974 | UnqualifiedDiag = diag::err_no_template_suggest; |
975 | QualifiedDiag = diag::err_no_member_template_suggest; |
976 | } else if (UnderlyingFirstDecl && |
977 | (isa<TypeDecl>(Val: UnderlyingFirstDecl) || |
978 | isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) || |
979 | isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) { |
980 | UnqualifiedDiag = diag::err_unknown_typename_suggest; |
981 | QualifiedDiag = diag::err_unknown_nested_typename_suggest; |
982 | } |
983 | |
984 | if (SS.isEmpty()) { |
985 | diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name); |
986 | } else {// FIXME: is this even reachable? Test it. |
987 | std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts())); |
988 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && |
989 | Name->getName() == CorrectedStr; |
990 | diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag) |
991 | << Name << computeDeclContext(SS, EnteringContext: false) |
992 | << DroppedSpecifier << SS.getRange()); |
993 | } |
994 | |
995 | // Update the name, so that the caller has the new name. |
996 | Name = Corrected.getCorrectionAsIdentifierInfo(); |
997 | |
998 | // Typo correction corrected to a keyword. |
999 | if (Corrected.isKeyword()) |
1000 | return Name; |
1001 | |
1002 | // Also update the LookupResult... |
1003 | // FIXME: This should probably go away at some point |
1004 | Result.clear(); |
1005 | Result.setLookupName(Corrected.getCorrection()); |
1006 | if (FirstDecl) |
1007 | Result.addDecl(D: FirstDecl); |
1008 | |
1009 | // If we found an Objective-C instance variable, let |
1010 | // LookupInObjCMethod build the appropriate expression to |
1011 | // reference the ivar. |
1012 | // FIXME: This is a gross hack. |
1013 | if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { |
1014 | DeclResult R = |
1015 | ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier()); |
1016 | if (R.isInvalid()) |
1017 | return NameClassification::Error(); |
1018 | if (R.isUsable()) |
1019 | return NameClassification::NonType(D: Ivar); |
1020 | } |
1021 | |
1022 | goto Corrected; |
1023 | } |
1024 | } |
1025 | |
1026 | // We failed to correct; just fall through and let the parser deal with it. |
1027 | Result.suppressDiagnostics(); |
1028 | return NameClassification::Unknown(); |
1029 | |
1030 | case LookupResult::NotFoundInCurrentInstantiation: { |
1031 | // We performed name lookup into the current instantiation, and there were |
1032 | // dependent bases, so we treat this result the same way as any other |
1033 | // dependent nested-name-specifier. |
1034 | |
1035 | // C++ [temp.res]p2: |
1036 | // A name used in a template declaration or definition and that is |
1037 | // dependent on a template-parameter is assumed not to name a type |
1038 | // unless the applicable name lookup finds a type name or the name is |
1039 | // qualified by the keyword typename. |
1040 | // |
1041 | // FIXME: If the next token is '<', we might want to ask the parser to |
1042 | // perform some heroics to see if we actually have a |
1043 | // template-argument-list, which would indicate a missing 'template' |
1044 | // keyword here. |
1045 | return NameClassification::DependentNonType(); |
1046 | } |
1047 | |
1048 | case LookupResult::Found: |
1049 | case LookupResult::FoundOverloaded: |
1050 | case LookupResult::FoundUnresolvedValue: |
1051 | break; |
1052 | |
1053 | case LookupResult::Ambiguous: |
1054 | if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) && |
1055 | hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true, |
1056 | /*AllowDependent=*/false)) { |
1057 | // C++ [temp.local]p3: |
1058 | // A lookup that finds an injected-class-name (10.2) can result in an |
1059 | // ambiguity in certain cases (for example, if it is found in more than |
1060 | // one base class). If all of the injected-class-names that are found |
1061 | // refer to specializations of the same class template, and if the name |
1062 | // is followed by a template-argument-list, the reference refers to the |
1063 | // class template itself and not a specialization thereof, and is not |
1064 | // ambiguous. |
1065 | // |
1066 | // This filtering can make an ambiguous result into an unambiguous one, |
1067 | // so try again after filtering out template names. |
1068 | FilterAcceptableTemplateNames(R&: Result); |
1069 | if (!Result.isAmbiguous()) { |
1070 | IsFilteredTemplateName = true; |
1071 | break; |
1072 | } |
1073 | } |
1074 | |
1075 | // Diagnose the ambiguity and return an error. |
1076 | return NameClassification::Error(); |
1077 | } |
1078 | |
1079 | if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) && |
1080 | (IsFilteredTemplateName || |
1081 | hasAnyAcceptableTemplateNames( |
1082 | R&: Result, /*AllowFunctionTemplates=*/true, |
1083 | /*AllowDependent=*/false, |
1084 | /*AllowNonTemplateFunctions*/ SS.isEmpty() && |
1085 | getLangOpts().CPlusPlus20))) { |
1086 | // C++ [temp.names]p3: |
1087 | // After name lookup (3.4) finds that a name is a template-name or that |
1088 | // an operator-function-id or a literal- operator-id refers to a set of |
1089 | // overloaded functions any member of which is a function template if |
1090 | // this is followed by a <, the < is always taken as the delimiter of a |
1091 | // template-argument-list and never as the less-than operator. |
1092 | // C++2a [temp.names]p2: |
1093 | // A name is also considered to refer to a template if it is an |
1094 | // unqualified-id followed by a < and name lookup finds either one |
1095 | // or more functions or finds nothing. |
1096 | if (!IsFilteredTemplateName) |
1097 | FilterAcceptableTemplateNames(R&: Result); |
1098 | |
1099 | bool IsFunctionTemplate; |
1100 | bool IsVarTemplate; |
1101 | TemplateName Template; |
1102 | if (Result.end() - Result.begin() > 1) { |
1103 | IsFunctionTemplate = true; |
1104 | Template = Context.getOverloadedTemplateName(Begin: Result.begin(), |
1105 | End: Result.end()); |
1106 | } else if (!Result.empty()) { |
1107 | auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl( |
1108 | D: *Result.begin(), /*AllowFunctionTemplates=*/true, |
1109 | /*AllowDependent=*/false)); |
1110 | IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD); |
1111 | IsVarTemplate = isa<VarTemplateDecl>(Val: TD); |
1112 | |
1113 | UsingShadowDecl *FoundUsingShadow = |
1114 | dyn_cast<UsingShadowDecl>(Val: *Result.begin()); |
1115 | assert(!FoundUsingShadow || |
1116 | TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl())); |
1117 | Template = Context.getQualifiedTemplateName( |
1118 | NNS: SS.getScopeRep(), |
1119 | /*TemplateKeyword=*/false, |
1120 | Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD)); |
1121 | } else { |
1122 | // All results were non-template functions. This is a function template |
1123 | // name. |
1124 | IsFunctionTemplate = true; |
1125 | Template = Context.getAssumedTemplateName(Name: NameInfo.getName()); |
1126 | } |
1127 | |
1128 | if (IsFunctionTemplate) { |
1129 | // Function templates always go through overload resolution, at which |
1130 | // point we'll perform the various checks (e.g., accessibility) we need |
1131 | // to based on which function we selected. |
1132 | Result.suppressDiagnostics(); |
1133 | |
1134 | return NameClassification::FunctionTemplate(Name: Template); |
1135 | } |
1136 | |
1137 | return IsVarTemplate ? NameClassification::VarTemplate(Name: Template) |
1138 | : NameClassification::TypeTemplate(Name: Template); |
1139 | } |
1140 | |
1141 | auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) { |
1142 | QualType T = Context.getTypeDeclType(Decl: Type); |
1143 | if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found)) |
1144 | T = Context.getUsingType(Found: USD, Underlying: T); |
1145 | return buildNamedType(S&: *this, SS: &SS, T, NameLoc); |
1146 | }; |
1147 | |
1148 | NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); |
1149 | if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) { |
1150 | DiagnoseUseOfDecl(D: Type, Locs: NameLoc); |
1151 | MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false); |
1152 | return BuildTypeFor(Type, *Result.begin()); |
1153 | } |
1154 | |
1155 | ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl); |
1156 | if (!Class) { |
1157 | // FIXME: It's unfortunate that we don't have a Type node for handling this. |
1158 | if (ObjCCompatibleAliasDecl *Alias = |
1159 | dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl)) |
1160 | Class = Alias->getClassInterface(); |
1161 | } |
1162 | |
1163 | if (Class) { |
1164 | DiagnoseUseOfDecl(D: Class, Locs: NameLoc); |
1165 | |
1166 | if (NextToken.is(K: tok::period)) { |
1167 | // Interface. <something> is parsed as a property reference expression. |
1168 | // Just return "unknown" as a fall-through for now. |
1169 | Result.suppressDiagnostics(); |
1170 | return NameClassification::Unknown(); |
1171 | } |
1172 | |
1173 | QualType T = Context.getObjCInterfaceType(Decl: Class); |
1174 | return ParsedType::make(P: T); |
1175 | } |
1176 | |
1177 | if (isa<ConceptDecl>(Val: FirstDecl)) { |
1178 | // We want to preserve the UsingShadowDecl for concepts. |
1179 | if (auto *USD = dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl())) |
1180 | return NameClassification::Concept(Name: TemplateName(USD)); |
1181 | return NameClassification::Concept( |
1182 | Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl))); |
1183 | } |
1184 | |
1185 | if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) { |
1186 | (void)DiagnoseUseOfDecl(D: EmptyD, Locs: NameLoc); |
1187 | return NameClassification::Error(); |
1188 | } |
1189 | |
1190 | // We can have a type template here if we're classifying a template argument. |
1191 | if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) && |
1192 | !isa<VarTemplateDecl>(Val: FirstDecl)) |
1193 | return NameClassification::TypeTemplate( |
1194 | Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl))); |
1195 | |
1196 | // Check for a tag type hidden by a non-type decl in a few cases where it |
1197 | // seems likely a type is wanted instead of the non-type that was found. |
1198 | bool NextIsOp = NextToken.isOneOf(K1: tok::amp, K2: tok::star); |
1199 | if ((NextToken.is(K: tok::identifier) || |
1200 | (NextIsOp && |
1201 | FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && |
1202 | isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) { |
1203 | TypeDecl *Type = Result.getAsSingle<TypeDecl>(); |
1204 | DiagnoseUseOfDecl(D: Type, Locs: NameLoc); |
1205 | return BuildTypeFor(Type, *Result.begin()); |
1206 | } |
1207 | |
1208 | // If we already know which single declaration is referenced, just annotate |
1209 | // that declaration directly. Defer resolving even non-overloaded class |
1210 | // member accesses, as we need to defer certain access checks until we know |
1211 | // the context. |
1212 | bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren)); |
1213 | if (Result.isSingleResult() && !ADL && |
1214 | (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl))) |
1215 | return NameClassification::NonType(D: Result.getRepresentativeDecl()); |
1216 | |
1217 | // Otherwise, this is an overload set that we will need to resolve later. |
1218 | Result.suppressDiagnostics(); |
1219 | return NameClassification::OverloadSet(E: UnresolvedLookupExpr::Create( |
1220 | Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context), |
1221 | NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Begin: Result.begin(), End: Result.end(), |
1222 | /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false)); |
1223 | } |
1224 | |
1225 | ExprResult |
1226 | Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, |
1227 | SourceLocation NameLoc) { |
1228 | assert(getLangOpts().CPlusPlus && "ADL-only call in C?" ); |
1229 | CXXScopeSpec SS; |
1230 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); |
1231 | return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true); |
1232 | } |
1233 | |
1234 | ExprResult |
1235 | Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, |
1236 | IdentifierInfo *Name, |
1237 | SourceLocation NameLoc, |
1238 | bool IsAddressOfOperand) { |
1239 | DeclarationNameInfo NameInfo(Name, NameLoc); |
1240 | return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), |
1241 | NameInfo, isAddressOfOperand: IsAddressOfOperand, |
1242 | /*TemplateArgs=*/nullptr); |
1243 | } |
1244 | |
1245 | ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, |
1246 | NamedDecl *Found, |
1247 | SourceLocation NameLoc, |
1248 | const Token &NextToken) { |
1249 | if (getCurMethodDecl() && SS.isEmpty()) |
1250 | if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl())) |
1251 | return ObjC().BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar); |
1252 | |
1253 | // Reconstruct the lookup result. |
1254 | LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); |
1255 | Result.addDecl(D: Found); |
1256 | Result.resolveKind(); |
1257 | |
1258 | bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren)); |
1259 | return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true); |
1260 | } |
1261 | |
1262 | ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { |
1263 | // For an implicit class member access, transform the result into a member |
1264 | // access expression if necessary. |
1265 | auto *ULE = cast<UnresolvedLookupExpr>(Val: E); |
1266 | if ((*ULE->decls_begin())->isCXXClassMember()) { |
1267 | CXXScopeSpec SS; |
1268 | SS.Adopt(Other: ULE->getQualifierLoc()); |
1269 | |
1270 | // Reconstruct the lookup result. |
1271 | LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), |
1272 | LookupOrdinaryName); |
1273 | Result.setNamingClass(ULE->getNamingClass()); |
1274 | for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) |
1275 | Result.addDecl(D: *I, AS: I.getAccess()); |
1276 | Result.resolveKind(); |
1277 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result, |
1278 | TemplateArgs: nullptr, S); |
1279 | } |
1280 | |
1281 | // Otherwise, this is already in the form we needed, and no further checks |
1282 | // are necessary. |
1283 | return ULE; |
1284 | } |
1285 | |
1286 | Sema::TemplateNameKindForDiagnostics |
1287 | Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { |
1288 | auto *TD = Name.getAsTemplateDecl(); |
1289 | if (!TD) |
1290 | return TemplateNameKindForDiagnostics::DependentTemplate; |
1291 | if (isa<ClassTemplateDecl>(Val: TD)) |
1292 | return TemplateNameKindForDiagnostics::ClassTemplate; |
1293 | if (isa<FunctionTemplateDecl>(Val: TD)) |
1294 | return TemplateNameKindForDiagnostics::FunctionTemplate; |
1295 | if (isa<VarTemplateDecl>(Val: TD)) |
1296 | return TemplateNameKindForDiagnostics::VarTemplate; |
1297 | if (isa<TypeAliasTemplateDecl>(Val: TD)) |
1298 | return TemplateNameKindForDiagnostics::AliasTemplate; |
1299 | if (isa<TemplateTemplateParmDecl>(Val: TD)) |
1300 | return TemplateNameKindForDiagnostics::TemplateTemplateParam; |
1301 | if (isa<ConceptDecl>(Val: TD)) |
1302 | return TemplateNameKindForDiagnostics::Concept; |
1303 | return TemplateNameKindForDiagnostics::DependentTemplate; |
1304 | } |
1305 | |
1306 | void Sema::PushDeclContext(Scope *S, DeclContext *DC) { |
1307 | assert(DC->getLexicalParent() == CurContext && |
1308 | "The next DeclContext should be lexically contained in the current one." ); |
1309 | CurContext = DC; |
1310 | S->setEntity(DC); |
1311 | } |
1312 | |
1313 | void Sema::PopDeclContext() { |
1314 | assert(CurContext && "DeclContext imbalance!" ); |
1315 | |
1316 | CurContext = CurContext->getLexicalParent(); |
1317 | assert(CurContext && "Popped translation unit!" ); |
1318 | } |
1319 | |
1320 | Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, |
1321 | Decl *D) { |
1322 | // Unlike PushDeclContext, the context to which we return is not necessarily |
1323 | // the containing DC of TD, because the new context will be some pre-existing |
1324 | // TagDecl definition instead of a fresh one. |
1325 | auto Result = static_cast<SkippedDefinitionContext>(CurContext); |
1326 | CurContext = cast<TagDecl>(Val: D)->getDefinition(); |
1327 | assert(CurContext && "skipping definition of undefined tag" ); |
1328 | // Start lookups from the parent of the current context; we don't want to look |
1329 | // into the pre-existing complete definition. |
1330 | S->setEntity(CurContext->getLookupParent()); |
1331 | return Result; |
1332 | } |
1333 | |
1334 | void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { |
1335 | CurContext = static_cast<decltype(CurContext)>(Context); |
1336 | } |
1337 | |
1338 | void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { |
1339 | // C++0x [basic.lookup.unqual]p13: |
1340 | // A name used in the definition of a static data member of class |
1341 | // X (after the qualified-id of the static member) is looked up as |
1342 | // if the name was used in a member function of X. |
1343 | // C++0x [basic.lookup.unqual]p14: |
1344 | // If a variable member of a namespace is defined outside of the |
1345 | // scope of its namespace then any name used in the definition of |
1346 | // the variable member (after the declarator-id) is looked up as |
1347 | // if the definition of the variable member occurred in its |
1348 | // namespace. |
1349 | // Both of these imply that we should push a scope whose context |
1350 | // is the semantic context of the declaration. We can't use |
1351 | // PushDeclContext here because that context is not necessarily |
1352 | // lexically contained in the current context. Fortunately, |
1353 | // the containing scope should have the appropriate information. |
1354 | |
1355 | assert(!S->getEntity() && "scope already has entity" ); |
1356 | |
1357 | #ifndef NDEBUG |
1358 | Scope *Ancestor = S->getParent(); |
1359 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); |
1360 | assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch" ); |
1361 | #endif |
1362 | |
1363 | CurContext = DC; |
1364 | S->setEntity(DC); |
1365 | |
1366 | if (S->getParent()->isTemplateParamScope()) { |
1367 | // Also set the corresponding entities for all immediately-enclosing |
1368 | // template parameter scopes. |
1369 | EnterTemplatedContext(S: S->getParent(), DC); |
1370 | } |
1371 | } |
1372 | |
1373 | void Sema::ExitDeclaratorContext(Scope *S) { |
1374 | assert(S->getEntity() == CurContext && "Context imbalance!" ); |
1375 | |
1376 | // Switch back to the lexical context. The safety of this is |
1377 | // enforced by an assert in EnterDeclaratorContext. |
1378 | Scope *Ancestor = S->getParent(); |
1379 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); |
1380 | CurContext = Ancestor->getEntity(); |
1381 | |
1382 | // We don't need to do anything with the scope, which is going to |
1383 | // disappear. |
1384 | } |
1385 | |
1386 | void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { |
1387 | assert(S->isTemplateParamScope() && |
1388 | "expected to be initializing a template parameter scope" ); |
1389 | |
1390 | // C++20 [temp.local]p7: |
1391 | // In the definition of a member of a class template that appears outside |
1392 | // of the class template definition, the name of a member of the class |
1393 | // template hides the name of a template-parameter of any enclosing class |
1394 | // templates (but not a template-parameter of the member if the member is a |
1395 | // class or function template). |
1396 | // C++20 [temp.local]p9: |
1397 | // In the definition of a class template or in the definition of a member |
1398 | // of such a template that appears outside of the template definition, for |
1399 | // each non-dependent base class (13.8.2.1), if the name of the base class |
1400 | // or the name of a member of the base class is the same as the name of a |
1401 | // template-parameter, the base class name or member name hides the |
1402 | // template-parameter name (6.4.10). |
1403 | // |
1404 | // This means that a template parameter scope should be searched immediately |
1405 | // after searching the DeclContext for which it is a template parameter |
1406 | // scope. For example, for |
1407 | // template<typename T> template<typename U> template<typename V> |
1408 | // void N::A<T>::B<U>::f(...) |
1409 | // we search V then B<U> (and base classes) then U then A<T> (and base |
1410 | // classes) then T then N then ::. |
1411 | unsigned ScopeDepth = getTemplateDepth(S); |
1412 | for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { |
1413 | DeclContext *SearchDCAfterScope = DC; |
1414 | for (; DC; DC = DC->getLookupParent()) { |
1415 | if (const TemplateParameterList *TPL = |
1416 | cast<Decl>(Val: DC)->getDescribedTemplateParams()) { |
1417 | unsigned DCDepth = TPL->getDepth() + 1; |
1418 | if (DCDepth > ScopeDepth) |
1419 | continue; |
1420 | if (ScopeDepth == DCDepth) |
1421 | SearchDCAfterScope = DC = DC->getLookupParent(); |
1422 | break; |
1423 | } |
1424 | } |
1425 | S->setLookupEntity(SearchDCAfterScope); |
1426 | } |
1427 | } |
1428 | |
1429 | void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { |
1430 | // We assume that the caller has already called |
1431 | // ActOnReenterTemplateScope so getTemplatedDecl() works. |
1432 | FunctionDecl *FD = D->getAsFunction(); |
1433 | if (!FD) |
1434 | return; |
1435 | |
1436 | // Same implementation as PushDeclContext, but enters the context |
1437 | // from the lexical parent, rather than the top-level class. |
1438 | assert(CurContext == FD->getLexicalParent() && |
1439 | "The next DeclContext should be lexically contained in the current one." ); |
1440 | CurContext = FD; |
1441 | S->setEntity(CurContext); |
1442 | |
1443 | for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { |
1444 | ParmVarDecl *Param = FD->getParamDecl(i: P); |
1445 | // If the parameter has an identifier, then add it to the scope |
1446 | if (Param->getIdentifier()) { |
1447 | S->AddDecl(D: Param); |
1448 | IdResolver.AddDecl(D: Param); |
1449 | } |
1450 | } |
1451 | } |
1452 | |
1453 | void Sema::ActOnExitFunctionContext() { |
1454 | // Same implementation as PopDeclContext, but returns to the lexical parent, |
1455 | // rather than the top-level class. |
1456 | assert(CurContext && "DeclContext imbalance!" ); |
1457 | CurContext = CurContext->getLexicalParent(); |
1458 | assert(CurContext && "Popped translation unit!" ); |
1459 | } |
1460 | |
1461 | /// Determine whether overloading is allowed for a new function |
1462 | /// declaration considering prior declarations of the same name. |
1463 | /// |
1464 | /// This routine determines whether overloading is possible, not |
1465 | /// whether a new declaration actually overloads a previous one. |
1466 | /// It will return true in C++ (where overloads are always permitted) |
1467 | /// or, as a C extension, when either the new declaration or a |
1468 | /// previous one is declared with the 'overloadable' attribute. |
1469 | static bool AllowOverloadingOfFunction(const LookupResult &Previous, |
1470 | ASTContext &Context, |
1471 | const FunctionDecl *New) { |
1472 | if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>()) |
1473 | return true; |
1474 | |
1475 | // Multiversion function declarations are not overloads in the |
1476 | // usual sense of that term, but lookup will report that an |
1477 | // overload set was found if more than one multiversion function |
1478 | // declaration is present for the same name. It is therefore |
1479 | // inadequate to assume that some prior declaration(s) had |
1480 | // the overloadable attribute; checking is required. Since one |
1481 | // declaration is permitted to omit the attribute, it is necessary |
1482 | // to check at least two; hence the 'any_of' check below. Note that |
1483 | // the overloadable attribute is implicitly added to declarations |
1484 | // that were required to have it but did not. |
1485 | if (Previous.getResultKind() == LookupResult::FoundOverloaded) { |
1486 | return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) { |
1487 | return ND->hasAttr<OverloadableAttr>(); |
1488 | }); |
1489 | } else if (Previous.getResultKind() == LookupResult::Found) |
1490 | return Previous.getFoundDecl()->hasAttr<OverloadableAttr>(); |
1491 | |
1492 | return false; |
1493 | } |
1494 | |
1495 | void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { |
1496 | // Move up the scope chain until we find the nearest enclosing |
1497 | // non-transparent context. The declaration will be introduced into this |
1498 | // scope. |
1499 | while (S->getEntity() && S->getEntity()->isTransparentContext()) |
1500 | S = S->getParent(); |
1501 | |
1502 | // Add scoped declarations into their context, so that they can be |
1503 | // found later. Declarations without a context won't be inserted |
1504 | // into any context. |
1505 | if (AddToContext) |
1506 | CurContext->addDecl(D); |
1507 | |
1508 | // Out-of-line definitions shouldn't be pushed into scope in C++, unless they |
1509 | // are function-local declarations. |
1510 | if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) |
1511 | return; |
1512 | |
1513 | // Template instantiations should also not be pushed into scope. |
1514 | if (isa<FunctionDecl>(Val: D) && |
1515 | cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization()) |
1516 | return; |
1517 | |
1518 | if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) { |
1519 | S->AddDecl(D); |
1520 | return; |
1521 | } |
1522 | // If this replaces anything in the current scope, |
1523 | IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()), |
1524 | IEnd = IdResolver.end(); |
1525 | for (; I != IEnd; ++I) { |
1526 | if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) { |
1527 | S->RemoveDecl(D: *I); |
1528 | IdResolver.RemoveDecl(D: *I); |
1529 | |
1530 | // Should only need to replace one decl. |
1531 | break; |
1532 | } |
1533 | } |
1534 | |
1535 | S->AddDecl(D); |
1536 | |
1537 | if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) { |
1538 | // Implicitly-generated labels may end up getting generated in an order that |
1539 | // isn't strictly lexical, which breaks name lookup. Be careful to insert |
1540 | // the label at the appropriate place in the identifier chain. |
1541 | for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) { |
1542 | DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); |
1543 | if (IDC == CurContext) { |
1544 | if (!S->isDeclScope(D: *I)) |
1545 | continue; |
1546 | } else if (IDC->Encloses(DC: CurContext)) |
1547 | break; |
1548 | } |
1549 | |
1550 | IdResolver.InsertDeclAfter(Pos: I, D); |
1551 | } else { |
1552 | IdResolver.AddDecl(D); |
1553 | } |
1554 | warnOnReservedIdentifier(D); |
1555 | } |
1556 | |
1557 | bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, |
1558 | bool AllowInlineNamespace) const { |
1559 | return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); |
1560 | } |
1561 | |
1562 | Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { |
1563 | DeclContext *TargetDC = DC->getPrimaryContext(); |
1564 | do { |
1565 | if (DeclContext *ScopeDC = S->getEntity()) |
1566 | if (ScopeDC->getPrimaryContext() == TargetDC) |
1567 | return S; |
1568 | } while ((S = S->getParent())); |
1569 | |
1570 | return nullptr; |
1571 | } |
1572 | |
1573 | static bool isOutOfScopePreviousDeclaration(NamedDecl *, |
1574 | DeclContext*, |
1575 | ASTContext&); |
1576 | |
1577 | void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, |
1578 | bool ConsiderLinkage, |
1579 | bool AllowInlineNamespace) { |
1580 | LookupResult::Filter F = R.makeFilter(); |
1581 | while (F.hasNext()) { |
1582 | NamedDecl *D = F.next(); |
1583 | |
1584 | if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) |
1585 | continue; |
1586 | |
1587 | if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) |
1588 | continue; |
1589 | |
1590 | F.erase(); |
1591 | } |
1592 | |
1593 | F.done(); |
1594 | } |
1595 | |
1596 | bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { |
1597 | // [module.interface]p7: |
1598 | // A declaration is attached to a module as follows: |
1599 | // - If the declaration is a non-dependent friend declaration that nominates a |
1600 | // function with a declarator-id that is a qualified-id or template-id or that |
1601 | // nominates a class other than with an elaborated-type-specifier with neither |
1602 | // a nested-name-specifier nor a simple-template-id, it is attached to the |
1603 | // module to which the friend is attached ([basic.link]). |
1604 | if (New->getFriendObjectKind() && |
1605 | Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { |
1606 | New->setLocalOwningModule(Old->getOwningModule()); |
1607 | makeMergedDefinitionVisible(ND: New); |
1608 | return false; |
1609 | } |
1610 | |
1611 | Module *NewM = New->getOwningModule(); |
1612 | Module *OldM = Old->getOwningModule(); |
1613 | |
1614 | if (NewM && NewM->isPrivateModule()) |
1615 | NewM = NewM->Parent; |
1616 | if (OldM && OldM->isPrivateModule()) |
1617 | OldM = OldM->Parent; |
1618 | |
1619 | if (NewM == OldM) |
1620 | return false; |
1621 | |
1622 | if (NewM && OldM) { |
1623 | // A module implementation unit has visibility of the decls in its |
1624 | // implicitly imported interface. |
1625 | if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface) |
1626 | return false; |
1627 | |
1628 | // Partitions are part of the module, but a partition could import another |
1629 | // module, so verify that the PMIs agree. |
1630 | if ((NewM->isModulePartition() || OldM->isModulePartition()) && |
1631 | getASTContext().isInSameModule(M1: NewM, M2: OldM)) |
1632 | return false; |
1633 | } |
1634 | |
1635 | bool NewIsModuleInterface = NewM && NewM->isNamedModule(); |
1636 | bool OldIsModuleInterface = OldM && OldM->isNamedModule(); |
1637 | if (NewIsModuleInterface || OldIsModuleInterface) { |
1638 | // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: |
1639 | // if a declaration of D [...] appears in the purview of a module, all |
1640 | // other such declarations shall appear in the purview of the same module |
1641 | Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module) |
1642 | << New |
1643 | << NewIsModuleInterface |
1644 | << (NewIsModuleInterface ? NewM->getFullModuleName() : "" ) |
1645 | << OldIsModuleInterface |
1646 | << (OldIsModuleInterface ? OldM->getFullModuleName() : "" ); |
1647 | Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration); |
1648 | New->setInvalidDecl(); |
1649 | return true; |
1650 | } |
1651 | |
1652 | return false; |
1653 | } |
1654 | |
1655 | bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) { |
1656 | // [module.interface]p1: |
1657 | // An export-declaration shall inhabit a namespace scope. |
1658 | // |
1659 | // So it is meaningless to talk about redeclaration which is not at namespace |
1660 | // scope. |
1661 | if (!New->getLexicalDeclContext() |
1662 | ->getNonTransparentContext() |
1663 | ->isFileContext() || |
1664 | !Old->getLexicalDeclContext() |
1665 | ->getNonTransparentContext() |
1666 | ->isFileContext()) |
1667 | return false; |
1668 | |
1669 | bool IsNewExported = New->isInExportDeclContext(); |
1670 | bool IsOldExported = Old->isInExportDeclContext(); |
1671 | |
1672 | // It should be irrevelant if both of them are not exported. |
1673 | if (!IsNewExported && !IsOldExported) |
1674 | return false; |
1675 | |
1676 | if (IsOldExported) |
1677 | return false; |
1678 | |
1679 | // If the Old declaration are not attached to named modules |
1680 | // and the New declaration are attached to global module. |
1681 | // It should be fine to allow the export since it doesn't change |
1682 | // the linkage of declarations. See |
1683 | // https://github.com/llvm/llvm-project/issues/98583 for details. |
1684 | if (!Old->isInNamedModule() && New->getOwningModule() && |
1685 | New->getOwningModule()->isImplicitGlobalModule()) |
1686 | return false; |
1687 | |
1688 | assert(IsNewExported); |
1689 | |
1690 | auto Lk = Old->getFormalLinkage(); |
1691 | int S = 0; |
1692 | if (Lk == Linkage::Internal) |
1693 | S = 1; |
1694 | else if (Lk == Linkage::Module) |
1695 | S = 2; |
1696 | Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S; |
1697 | Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration); |
1698 | return true; |
1699 | } |
1700 | |
1701 | bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) { |
1702 | if (CheckRedeclarationModuleOwnership(New, Old)) |
1703 | return true; |
1704 | |
1705 | if (CheckRedeclarationExported(New, Old)) |
1706 | return true; |
1707 | |
1708 | return false; |
1709 | } |
1710 | |
1711 | bool Sema::IsRedefinitionInModule(const NamedDecl *New, |
1712 | const NamedDecl *Old) const { |
1713 | assert(getASTContext().isSameEntity(New, Old) && |
1714 | "New and Old are not the same definition, we should diagnostic it " |
1715 | "immediately instead of checking it." ); |
1716 | assert(const_cast<Sema *>(this)->isReachable(New) && |
1717 | const_cast<Sema *>(this)->isReachable(Old) && |
1718 | "We shouldn't see unreachable definitions here." ); |
1719 | |
1720 | Module *NewM = New->getOwningModule(); |
1721 | Module *OldM = Old->getOwningModule(); |
1722 | |
1723 | // We only checks for named modules here. The header like modules is skipped. |
1724 | // FIXME: This is not right if we import the header like modules in the module |
1725 | // purview. |
1726 | // |
1727 | // For example, assuming "header.h" provides definition for `D`. |
1728 | // ```C++ |
1729 | // //--- M.cppm |
1730 | // export module M; |
1731 | // import "header.h"; // or #include "header.h" but import it by clang modules |
1732 | // actually. |
1733 | // |
1734 | // //--- Use.cpp |
1735 | // import M; |
1736 | // import "header.h"; // or uses clang modules. |
1737 | // ``` |
1738 | // |
1739 | // In this case, `D` has multiple definitions in multiple TU (M.cppm and |
1740 | // Use.cpp) and `D` is attached to a named module `M`. The compiler should |
1741 | // reject it. But the current implementation couldn't detect the case since we |
1742 | // don't record the information about the importee modules. |
1743 | // |
1744 | // But this might not be painful in practice. Since the design of C++20 Named |
1745 | // Modules suggests us to use headers in global module fragment instead of |
1746 | // module purview. |
1747 | if (NewM && NewM->isHeaderLikeModule()) |
1748 | NewM = nullptr; |
1749 | if (OldM && OldM->isHeaderLikeModule()) |
1750 | OldM = nullptr; |
1751 | |
1752 | if (!NewM && !OldM) |
1753 | return true; |
1754 | |
1755 | // [basic.def.odr]p14.3 |
1756 | // Each such definition shall not be attached to a named module |
1757 | // ([module.unit]). |
1758 | if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule())) |
1759 | return true; |
1760 | |
1761 | // Then New and Old lives in the same TU if their share one same module unit. |
1762 | if (NewM) |
1763 | NewM = NewM->getTopLevelModule(); |
1764 | if (OldM) |
1765 | OldM = OldM->getTopLevelModule(); |
1766 | return OldM == NewM; |
1767 | } |
1768 | |
1769 | static bool isUsingDeclNotAtClassScope(NamedDecl *D) { |
1770 | if (D->getDeclContext()->isFileContext()) |
1771 | return false; |
1772 | |
1773 | return isa<UsingShadowDecl>(Val: D) || |
1774 | isa<UnresolvedUsingTypenameDecl>(Val: D) || |
1775 | isa<UnresolvedUsingValueDecl>(Val: D); |
1776 | } |
1777 | |
1778 | /// Removes using shadow declarations not at class scope from the lookup |
1779 | /// results. |
1780 | static void RemoveUsingDecls(LookupResult &R) { |
1781 | LookupResult::Filter F = R.makeFilter(); |
1782 | while (F.hasNext()) |
1783 | if (isUsingDeclNotAtClassScope(D: F.next())) |
1784 | F.erase(); |
1785 | |
1786 | F.done(); |
1787 | } |
1788 | |
1789 | /// Check for this common pattern: |
1790 | /// @code |
1791 | /// class S { |
1792 | /// S(const S&); // DO NOT IMPLEMENT |
1793 | /// void operator=(const S&); // DO NOT IMPLEMENT |
1794 | /// }; |
1795 | /// @endcode |
1796 | static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { |
1797 | // FIXME: Should check for private access too but access is set after we get |
1798 | // the decl here. |
1799 | if (D->doesThisDeclarationHaveABody()) |
1800 | return false; |
1801 | |
1802 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D)) |
1803 | return CD->isCopyConstructor(); |
1804 | return D->isCopyAssignmentOperator(); |
1805 | } |
1806 | |
1807 | bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { |
1808 | const DeclContext *DC = D->getDeclContext(); |
1809 | while (!DC->isTranslationUnit()) { |
1810 | if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){ |
1811 | if (!RD->hasNameForLinkage()) |
1812 | return true; |
1813 | } |
1814 | DC = DC->getParent(); |
1815 | } |
1816 | |
1817 | return !D->isExternallyVisible(); |
1818 | } |
1819 | |
1820 | // FIXME: This needs to be refactored; some other isInMainFile users want |
1821 | // these semantics. |
1822 | static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { |
1823 | if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile) |
1824 | return false; |
1825 | return S.SourceMgr.isInMainFile(Loc); |
1826 | } |
1827 | |
1828 | bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { |
1829 | assert(D); |
1830 | |
1831 | if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) |
1832 | return false; |
1833 | |
1834 | // Ignore all entities declared within templates, and out-of-line definitions |
1835 | // of members of class templates. |
1836 | if (D->getDeclContext()->isDependentContext() || |
1837 | D->getLexicalDeclContext()->isDependentContext()) |
1838 | return false; |
1839 | |
1840 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) { |
1841 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) |
1842 | return false; |
1843 | // A non-out-of-line declaration of a member specialization was implicitly |
1844 | // instantiated; it's the out-of-line declaration that we're interested in. |
1845 | if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && |
1846 | FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) |
1847 | return false; |
1848 | |
1849 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) { |
1850 | if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD)) |
1851 | return false; |
1852 | } else { |
1853 | // 'static inline' functions are defined in headers; don't warn. |
1854 | if (FD->isInlined() && !isMainFileLoc(S: *this, Loc: FD->getLocation())) |
1855 | return false; |
1856 | } |
1857 | |
1858 | if (FD->doesThisDeclarationHaveABody() && |
1859 | Context.DeclMustBeEmitted(D: FD)) |
1860 | return false; |
1861 | } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
1862 | // Constants and utility variables are defined in headers with internal |
1863 | // linkage; don't warn. (Unlike functions, there isn't a convenient marker |
1864 | // like "inline".) |
1865 | if (!isMainFileLoc(S: *this, Loc: VD->getLocation())) |
1866 | return false; |
1867 | |
1868 | if (Context.DeclMustBeEmitted(D: VD)) |
1869 | return false; |
1870 | |
1871 | if (VD->isStaticDataMember() && |
1872 | VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) |
1873 | return false; |
1874 | if (VD->isStaticDataMember() && |
1875 | VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && |
1876 | VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) |
1877 | return false; |
1878 | |
1879 | if (VD->isInline() && !isMainFileLoc(S: *this, Loc: VD->getLocation())) |
1880 | return false; |
1881 | } else { |
1882 | return false; |
1883 | } |
1884 | |
1885 | // Only warn for unused decls internal to the translation unit. |
1886 | // FIXME: This seems like a bogus check; it suppresses -Wunused-function |
1887 | // for inline functions defined in the main source file, for instance. |
1888 | return mightHaveNonExternalLinkage(D); |
1889 | } |
1890 | |
1891 | void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { |
1892 | if (!D) |
1893 | return; |
1894 | |
1895 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) { |
1896 | const FunctionDecl *First = FD->getFirstDecl(); |
1897 | if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First)) |
1898 | return; // First should already be in the vector. |
1899 | } |
1900 | |
1901 | if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
1902 | const VarDecl *First = VD->getFirstDecl(); |
1903 | if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First)) |
1904 | return; // First should already be in the vector. |
1905 | } |
1906 | |
1907 | if (ShouldWarnIfUnusedFileScopedDecl(D)) |
1908 | UnusedFileScopedDecls.push_back(LocalValue: D); |
1909 | } |
1910 | |
1911 | static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, |
1912 | const NamedDecl *D) { |
1913 | if (D->isInvalidDecl()) |
1914 | return false; |
1915 | |
1916 | if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) { |
1917 | // For a decomposition declaration, warn if none of the bindings are |
1918 | // referenced, instead of if the variable itself is referenced (which |
1919 | // it is, by the bindings' expressions). |
1920 | bool IsAllPlaceholders = true; |
1921 | for (const auto *BD : DD->bindings()) { |
1922 | if (BD->isReferenced() || BD->hasAttr<UnusedAttr>()) |
1923 | return false; |
1924 | IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts); |
1925 | } |
1926 | if (IsAllPlaceholders) |
1927 | return false; |
1928 | } else if (!D->getDeclName()) { |
1929 | return false; |
1930 | } else if (D->isReferenced() || D->isUsed()) { |
1931 | return false; |
1932 | } |
1933 | |
1934 | if (D->isPlaceholderVar(LangOpts)) |
1935 | return false; |
1936 | |
1937 | if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() || |
1938 | D->hasAttr<CleanupAttr>()) |
1939 | return false; |
1940 | |
1941 | if (isa<LabelDecl>(Val: D)) |
1942 | return true; |
1943 | |
1944 | // Except for labels, we only care about unused decls that are local to |
1945 | // functions. |
1946 | bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); |
1947 | if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext())) |
1948 | // For dependent types, the diagnostic is deferred. |
1949 | WithinFunction = |
1950 | WithinFunction || (R->isLocalClass() && !R->isDependentType()); |
1951 | if (!WithinFunction) |
1952 | return false; |
1953 | |
1954 | if (isa<TypedefNameDecl>(Val: D)) |
1955 | return true; |
1956 | |
1957 | // White-list anything that isn't a local variable. |
1958 | if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D)) |
1959 | return false; |
1960 | |
1961 | // Types of valid local variables should be complete, so this should succeed. |
1962 | if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
1963 | |
1964 | const Expr *Init = VD->getInit(); |
1965 | if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init)) |
1966 | Init = Cleanups->getSubExpr(); |
1967 | |
1968 | const auto *Ty = VD->getType().getTypePtr(); |
1969 | |
1970 | // Only look at the outermost level of typedef. |
1971 | if (const TypedefType *TT = Ty->getAs<TypedefType>()) { |
1972 | // Allow anything marked with __attribute__((unused)). |
1973 | if (TT->getDecl()->hasAttr<UnusedAttr>()) |
1974 | return false; |
1975 | } |
1976 | |
1977 | // Warn for reference variables whose initializtion performs lifetime |
1978 | // extension. |
1979 | if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init); |
1980 | MTE && MTE->getExtendingDecl()) { |
1981 | Ty = VD->getType().getNonReferenceType().getTypePtr(); |
1982 | Init = MTE->getSubExpr()->IgnoreImplicitAsWritten(); |
1983 | } |
1984 | |
1985 | // If we failed to complete the type for some reason, or if the type is |
1986 | // dependent, don't diagnose the variable. |
1987 | if (Ty->isIncompleteType() || Ty->isDependentType()) |
1988 | return false; |
1989 | |
1990 | // Look at the element type to ensure that the warning behaviour is |
1991 | // consistent for both scalars and arrays. |
1992 | Ty = Ty->getBaseElementTypeUnsafe(); |
1993 | |
1994 | if (const TagType *TT = Ty->getAs<TagType>()) { |
1995 | const TagDecl *Tag = TT->getDecl(); |
1996 | if (Tag->hasAttr<UnusedAttr>()) |
1997 | return false; |
1998 | |
1999 | if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) { |
2000 | if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) |
2001 | return false; |
2002 | |
2003 | if (Init) { |
2004 | const auto *Construct = |
2005 | dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts()); |
2006 | if (Construct && !Construct->isElidable()) { |
2007 | const CXXConstructorDecl *CD = Construct->getConstructor(); |
2008 | if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && |
2009 | (VD->getInit()->isValueDependent() || !VD->evaluateValue())) |
2010 | return false; |
2011 | } |
2012 | |
2013 | // Suppress the warning if we don't know how this is constructed, and |
2014 | // it could possibly be non-trivial constructor. |
2015 | if (Init->isTypeDependent()) { |
2016 | for (const CXXConstructorDecl *Ctor : RD->ctors()) |
2017 | if (!Ctor->isTrivial()) |
2018 | return false; |
2019 | } |
2020 | |
2021 | // Suppress the warning if the constructor is unresolved because |
2022 | // its arguments are dependent. |
2023 | if (isa<CXXUnresolvedConstructExpr>(Val: Init)) |
2024 | return false; |
2025 | } |
2026 | } |
2027 | } |
2028 | |
2029 | // TODO: __attribute__((unused)) templates? |
2030 | } |
2031 | |
2032 | return true; |
2033 | } |
2034 | |
2035 | static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, |
2036 | FixItHint &Hint) { |
2037 | if (isa<LabelDecl>(Val: D)) { |
2038 | SourceLocation AfterColon = Lexer::findLocationAfterToken( |
2039 | loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(), |
2040 | /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false); |
2041 | if (AfterColon.isInvalid()) |
2042 | return; |
2043 | Hint = FixItHint::CreateRemoval( |
2044 | RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon)); |
2045 | } |
2046 | } |
2047 | |
2048 | void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { |
2049 | DiagnoseUnusedNestedTypedefs( |
2050 | D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); }); |
2051 | } |
2052 | |
2053 | void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D, |
2054 | DiagReceiverTy DiagReceiver) { |
2055 | if (D->getTypeForDecl()->isDependentType()) |
2056 | return; |
2057 | |
2058 | for (auto *TmpD : D->decls()) { |
2059 | if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD)) |
2060 | DiagnoseUnusedDecl(ND: T, DiagReceiver); |
2061 | else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD)) |
2062 | DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver); |
2063 | } |
2064 | } |
2065 | |
2066 | void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { |
2067 | DiagnoseUnusedDecl( |
2068 | ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); }); |
2069 | } |
2070 | |
2071 | void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) { |
2072 | if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D)) |
2073 | return; |
2074 | |
2075 | if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) { |
2076 | // typedefs can be referenced later on, so the diagnostics are emitted |
2077 | // at end-of-translation-unit. |
2078 | UnusedLocalTypedefNameCandidates.insert(X: TD); |
2079 | return; |
2080 | } |
2081 | |
2082 | FixItHint Hint; |
2083 | GenerateFixForUnusedDecl(D, Ctx&: Context, Hint); |
2084 | |
2085 | unsigned DiagID; |
2086 | if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable()) |
2087 | DiagID = diag::warn_unused_exception_param; |
2088 | else if (isa<LabelDecl>(Val: D)) |
2089 | DiagID = diag::warn_unused_label; |
2090 | else |
2091 | DiagID = diag::warn_unused_variable; |
2092 | |
2093 | SourceLocation DiagLoc = D->getLocation(); |
2094 | DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc)); |
2095 | } |
2096 | |
2097 | void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD, |
2098 | DiagReceiverTy DiagReceiver) { |
2099 | // If it's not referenced, it can't be set. If it has the Cleanup attribute, |
2100 | // it's not really unused. |
2101 | if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>()) |
2102 | return; |
2103 | |
2104 | // In C++, `_` variables behave as if they were maybe_unused |
2105 | if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts())) |
2106 | return; |
2107 | |
2108 | const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); |
2109 | |
2110 | if (Ty->isReferenceType() || Ty->isDependentType()) |
2111 | return; |
2112 | |
2113 | if (const TagType *TT = Ty->getAs<TagType>()) { |
2114 | const TagDecl *Tag = TT->getDecl(); |
2115 | if (Tag->hasAttr<UnusedAttr>()) |
2116 | return; |
2117 | // In C++, don't warn for record types that don't have WarnUnusedAttr, to |
2118 | // mimic gcc's behavior. |
2119 | if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag); |
2120 | RD && !RD->hasAttr<WarnUnusedAttr>()) |
2121 | return; |
2122 | } |
2123 | |
2124 | // Don't warn about __block Objective-C pointer variables, as they might |
2125 | // be assigned in the block but not used elsewhere for the purpose of lifetime |
2126 | // extension. |
2127 | if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) |
2128 | return; |
2129 | |
2130 | // Don't warn about Objective-C pointer variables with precise lifetime |
2131 | // semantics; they can be used to ensure ARC releases the object at a known |
2132 | // time, which may mean assignment but no other references. |
2133 | if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType()) |
2134 | return; |
2135 | |
2136 | auto iter = RefsMinusAssignments.find(Val: VD); |
2137 | if (iter == RefsMinusAssignments.end()) |
2138 | return; |
2139 | |
2140 | assert(iter->getSecond() >= 0 && |
2141 | "Found a negative number of references to a VarDecl" ); |
2142 | if (int RefCnt = iter->getSecond(); RefCnt > 0) { |
2143 | // Assume the given VarDecl is "used" if its ref count stored in |
2144 | // `RefMinusAssignments` is positive, with one exception. |
2145 | // |
2146 | // For a C++ variable whose decl (with initializer) entirely consist the |
2147 | // condition expression of a if/while/for construct, |
2148 | // Clang creates a DeclRefExpr for the condition expression rather than a |
2149 | // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref |
2150 | // count stored in `RefMinusAssignment` equals 1 when the variable is never |
2151 | // used in the body of the if/while/for construct. |
2152 | bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1); |
2153 | if (!UnusedCXXCondDecl) |
2154 | return; |
2155 | } |
2156 | |
2157 | unsigned DiagID = isa<ParmVarDecl>(Val: VD) ? diag::warn_unused_but_set_parameter |
2158 | : diag::warn_unused_but_set_variable; |
2159 | DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD); |
2160 | } |
2161 | |
2162 | static void CheckPoppedLabel(LabelDecl *L, Sema &S, |
2163 | Sema::DiagReceiverTy DiagReceiver) { |
2164 | // Verify that we have no forward references left. If so, there was a goto |
2165 | // or address of a label taken, but no definition of it. Label fwd |
2166 | // definitions are indicated with a null substmt which is also not a resolved |
2167 | // MS inline assembly label name. |
2168 | bool Diagnose = false; |
2169 | if (L->isMSAsmLabel()) |
2170 | Diagnose = !L->isResolvedMSAsmLabel(); |
2171 | else |
2172 | Diagnose = L->getStmt() == nullptr; |
2173 | if (Diagnose) |
2174 | DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use) |
2175 | << L); |
2176 | } |
2177 | |
2178 | void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { |
2179 | S->applyNRVO(); |
2180 | |
2181 | if (S->decl_empty()) return; |
2182 | assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && |
2183 | "Scope shouldn't contain decls!" ); |
2184 | |
2185 | /// We visit the decls in non-deterministic order, but we want diagnostics |
2186 | /// emitted in deterministic order. Collect any diagnostic that may be emitted |
2187 | /// and sort the diagnostics before emitting them, after we visited all decls. |
2188 | struct LocAndDiag { |
2189 | SourceLocation Loc; |
2190 | std::optional<SourceLocation> PreviousDeclLoc; |
2191 | PartialDiagnostic PD; |
2192 | }; |
2193 | SmallVector<LocAndDiag, 16> DeclDiags; |
2194 | auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) { |
2195 | DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)}); |
2196 | }; |
2197 | auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc, |
2198 | SourceLocation PreviousDeclLoc, |
2199 | PartialDiagnostic PD) { |
2200 | DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)}); |
2201 | }; |
2202 | |
2203 | for (auto *TmpD : S->decls()) { |
2204 | assert(TmpD && "This decl didn't get pushed??" ); |
2205 | |
2206 | assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?" ); |
2207 | NamedDecl *D = cast<NamedDecl>(Val: TmpD); |
2208 | |
2209 | // Diagnose unused variables in this scope. |
2210 | if (!S->hasUnrecoverableErrorOccurred()) { |
2211 | DiagnoseUnusedDecl(D, DiagReceiver: addDiag); |
2212 | if (const auto *RD = dyn_cast<RecordDecl>(Val: D)) |
2213 | DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag); |
2214 | if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
2215 | DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag); |
2216 | RefsMinusAssignments.erase(Val: VD); |
2217 | } |
2218 | } |
2219 | |
2220 | if (!D->getDeclName()) continue; |
2221 | |
2222 | // If this was a forward reference to a label, verify it was defined. |
2223 | if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D)) |
2224 | CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag); |
2225 | |
2226 | // Partial translation units that are created in incremental processing must |
2227 | // not clean up the IdResolver because PTUs should take into account the |
2228 | // declarations that came from previous PTUs. |
2229 | if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC || |
2230 | getLangOpts().CPlusPlus) |
2231 | IdResolver.RemoveDecl(D); |
2232 | |
2233 | // Warn on it if we are shadowing a declaration. |
2234 | auto ShadowI = ShadowingDecls.find(Val: D); |
2235 | if (ShadowI != ShadowingDecls.end()) { |
2236 | if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) { |
2237 | addDiagWithPrev(D->getLocation(), FD->getLocation(), |
2238 | PDiag(DiagID: diag::warn_ctor_parm_shadows_field) |
2239 | << D << FD << FD->getParent()); |
2240 | } |
2241 | ShadowingDecls.erase(I: ShadowI); |
2242 | } |
2243 | } |
2244 | |
2245 | llvm::sort(C&: DeclDiags, |
2246 | Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool { |
2247 | // The particular order for diagnostics is not important, as long |
2248 | // as the order is deterministic. Using the raw location is going |
2249 | // to generally be in source order unless there are macro |
2250 | // expansions involved. |
2251 | return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding(); |
2252 | }); |
2253 | for (const LocAndDiag &D : DeclDiags) { |
2254 | Diag(Loc: D.Loc, PD: D.PD); |
2255 | if (D.PreviousDeclLoc) |
2256 | Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration); |
2257 | } |
2258 | } |
2259 | |
2260 | Scope *Sema::getNonFieldDeclScope(Scope *S) { |
2261 | while (((S->getFlags() & Scope::DeclScope) == 0) || |
2262 | (S->getEntity() && S->getEntity()->isTransparentContext()) || |
2263 | (S->isClassScope() && !getLangOpts().CPlusPlus)) |
2264 | S = S->getParent(); |
2265 | return S; |
2266 | } |
2267 | |
2268 | static StringRef (Builtin::Context &BuiltinInfo, unsigned ID, |
2269 | ASTContext::GetBuiltinTypeError Error) { |
2270 | switch (Error) { |
2271 | case ASTContext::GE_None: |
2272 | return "" ; |
2273 | case ASTContext::GE_Missing_type: |
2274 | return BuiltinInfo.getHeaderName(ID); |
2275 | case ASTContext::GE_Missing_stdio: |
2276 | return "stdio.h" ; |
2277 | case ASTContext::GE_Missing_setjmp: |
2278 | return "setjmp.h" ; |
2279 | case ASTContext::GE_Missing_ucontext: |
2280 | return "ucontext.h" ; |
2281 | } |
2282 | llvm_unreachable("unhandled error kind" ); |
2283 | } |
2284 | |
2285 | FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, |
2286 | unsigned ID, SourceLocation Loc) { |
2287 | DeclContext *Parent = Context.getTranslationUnitDecl(); |
2288 | |
2289 | if (getLangOpts().CPlusPlus) { |
2290 | LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( |
2291 | C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false); |
2292 | CLinkageDecl->setImplicit(); |
2293 | Parent->addDecl(D: CLinkageDecl); |
2294 | Parent = CLinkageDecl; |
2295 | } |
2296 | |
2297 | ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified; |
2298 | if (Context.BuiltinInfo.isImmediate(ID)) { |
2299 | assert(getLangOpts().CPlusPlus20 && |
2300 | "consteval builtins should only be available in C++20 mode" ); |
2301 | ConstexprKind = ConstexprSpecKind::Consteval; |
2302 | } |
2303 | |
2304 | FunctionDecl *New = FunctionDecl::Create( |
2305 | C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern, |
2306 | UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false, |
2307 | hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind); |
2308 | New->setImplicit(); |
2309 | New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID)); |
2310 | |
2311 | // Create Decl objects for each parameter, adding them to the |
2312 | // FunctionDecl. |
2313 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) { |
2314 | SmallVector<ParmVarDecl *, 16> Params; |
2315 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { |
2316 | ParmVarDecl *parm = ParmVarDecl::Create( |
2317 | C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr, |
2318 | T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr); |
2319 | parm->setScopeInfo(scopeDepth: 0, parameterIndex: i); |
2320 | Params.push_back(Elt: parm); |
2321 | } |
2322 | New->setParams(Params); |
2323 | } |
2324 | |
2325 | AddKnownFunctionAttributes(FD: New); |
2326 | return New; |
2327 | } |
2328 | |
2329 | NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, |
2330 | Scope *S, bool ForRedeclaration, |
2331 | SourceLocation Loc) { |
2332 | LookupNecessaryTypesForBuiltin(S, ID); |
2333 | |
2334 | ASTContext::GetBuiltinTypeError Error; |
2335 | QualType R = Context.GetBuiltinType(ID, Error); |
2336 | if (Error) { |
2337 | if (!ForRedeclaration) |
2338 | return nullptr; |
2339 | |
2340 | // If we have a builtin without an associated type we should not emit a |
2341 | // warning when we were not able to find a type for it. |
2342 | if (Error == ASTContext::GE_Missing_type || |
2343 | Context.BuiltinInfo.allowTypeMismatch(ID)) |
2344 | return nullptr; |
2345 | |
2346 | // If we could not find a type for setjmp it is because the jmp_buf type was |
2347 | // not defined prior to the setjmp declaration. |
2348 | if (Error == ASTContext::GE_Missing_setjmp) { |
2349 | Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf) |
2350 | << Context.BuiltinInfo.getName(ID); |
2351 | return nullptr; |
2352 | } |
2353 | |
2354 | // Generally, we emit a warning that the declaration requires the |
2355 | // appropriate header. |
2356 | Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader) |
2357 | << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error) |
2358 | << Context.BuiltinInfo.getName(ID); |
2359 | return nullptr; |
2360 | } |
2361 | |
2362 | if (!ForRedeclaration && |
2363 | (Context.BuiltinInfo.isPredefinedLibFunction(ID) || |
2364 | Context.BuiltinInfo.isHeaderDependentFunction(ID))) { |
2365 | Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99 |
2366 | : diag::ext_implicit_lib_function_decl) |
2367 | << Context.BuiltinInfo.getName(ID) << R; |
2368 | if (const char * = Context.BuiltinInfo.getHeaderName(ID)) |
2369 | Diag(Loc, DiagID: diag::note_include_header_or_declare) |
2370 | << Header << Context.BuiltinInfo.getName(ID); |
2371 | } |
2372 | |
2373 | if (R.isNull()) |
2374 | return nullptr; |
2375 | |
2376 | FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc); |
2377 | RegisterLocallyScopedExternCDecl(ND: New, S); |
2378 | |
2379 | // TUScope is the translation-unit scope to insert this function into. |
2380 | // FIXME: This is hideous. We need to teach PushOnScopeChains to |
2381 | // relate Scopes to DeclContexts, and probably eliminate CurContext |
2382 | // entirely, but we're not there yet. |
2383 | DeclContext *SavedContext = CurContext; |
2384 | CurContext = New->getDeclContext(); |
2385 | PushOnScopeChains(D: New, S: TUScope); |
2386 | CurContext = SavedContext; |
2387 | return New; |
2388 | } |
2389 | |
2390 | /// Typedef declarations don't have linkage, but they still denote the same |
2391 | /// entity if their types are the same. |
2392 | /// FIXME: This is notionally doing the same thing as ASTReaderDecl's |
2393 | /// isSameEntity. |
2394 | static void |
2395 | filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl, |
2396 | LookupResult &Previous) { |
2397 | // This is only interesting when modules are enabled. |
2398 | if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) |
2399 | return; |
2400 | |
2401 | // Empty sets are uninteresting. |
2402 | if (Previous.empty()) |
2403 | return; |
2404 | |
2405 | LookupResult::Filter Filter = Previous.makeFilter(); |
2406 | while (Filter.hasNext()) { |
2407 | NamedDecl *Old = Filter.next(); |
2408 | |
2409 | // Non-hidden declarations are never ignored. |
2410 | if (S.isVisible(D: Old)) |
2411 | continue; |
2412 | |
2413 | // Declarations of the same entity are not ignored, even if they have |
2414 | // different linkages. |
2415 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) { |
2416 | if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(), |
2417 | T2: Decl->getUnderlyingType())) |
2418 | continue; |
2419 | |
2420 | // If both declarations give a tag declaration a typedef name for linkage |
2421 | // purposes, then they declare the same entity. |
2422 | if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && |
2423 | Decl->getAnonDeclWithTypedefName()) |
2424 | continue; |
2425 | } |
2426 | |
2427 | Filter.erase(); |
2428 | } |
2429 | |
2430 | Filter.done(); |
2431 | } |
2432 | |
2433 | bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) { |
2434 | QualType OldType; |
2435 | if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old)) |
2436 | OldType = OldTypedef->getUnderlyingType(); |
2437 | else |
2438 | OldType = Context.getTypeDeclType(Decl: Old); |
2439 | QualType NewType = New->getUnderlyingType(); |
2440 | |
2441 | if (NewType->isVariablyModifiedType()) { |
2442 | // Must not redefine a typedef with a variably-modified type. |
2443 | int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0; |
2444 | Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef) |
2445 | << Kind << NewType; |
2446 | if (Old->getLocation().isValid()) |
2447 | notePreviousDefinition(Old, New: New->getLocation()); |
2448 | New->setInvalidDecl(); |
2449 | return true; |
2450 | } |
2451 | |
2452 | if (OldType != NewType && |
2453 | !OldType->isDependentType() && |
2454 | !NewType->isDependentType() && |
2455 | !Context.hasSameType(T1: OldType, T2: NewType)) { |
2456 | int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0; |
2457 | Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef) |
2458 | << Kind << NewType << OldType; |
2459 | if (Old->getLocation().isValid()) |
2460 | notePreviousDefinition(Old, New: New->getLocation()); |
2461 | New->setInvalidDecl(); |
2462 | return true; |
2463 | } |
2464 | return false; |
2465 | } |
2466 | |
2467 | void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, |
2468 | LookupResult &OldDecls) { |
2469 | // If the new decl is known invalid already, don't bother doing any |
2470 | // merging checks. |
2471 | if (New->isInvalidDecl()) return; |
2472 | |
2473 | // Allow multiple definitions for ObjC built-in typedefs. |
2474 | // FIXME: Verify the underlying types are equivalent! |
2475 | if (getLangOpts().ObjC) { |
2476 | const IdentifierInfo *TypeID = New->getIdentifier(); |
2477 | switch (TypeID->getLength()) { |
2478 | default: break; |
2479 | case 2: |
2480 | { |
2481 | if (!TypeID->isStr(Str: "id" )) |
2482 | break; |
2483 | QualType T = New->getUnderlyingType(); |
2484 | if (!T->isPointerType()) |
2485 | break; |
2486 | if (!T->isVoidPointerType()) { |
2487 | QualType PT = T->castAs<PointerType>()->getPointeeType(); |
2488 | if (!PT->isStructureType()) |
2489 | break; |
2490 | } |
2491 | Context.setObjCIdRedefinitionType(T); |
2492 | // Install the built-in type for 'id', ignoring the current definition. |
2493 | New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); |
2494 | return; |
2495 | } |
2496 | case 5: |
2497 | if (!TypeID->isStr(Str: "Class" )) |
2498 | break; |
2499 | Context.setObjCClassRedefinitionType(New->getUnderlyingType()); |
2500 | // Install the built-in type for 'Class', ignoring the current definition. |
2501 | New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); |
2502 | return; |
2503 | case 3: |
2504 | if (!TypeID->isStr(Str: "SEL" )) |
2505 | break; |
2506 | Context.setObjCSelRedefinitionType(New->getUnderlyingType()); |
2507 | // Install the built-in type for 'SEL', ignoring the current definition. |
2508 | New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); |
2509 | return; |
2510 | } |
2511 | // Fall through - the typedef name was not a builtin type. |
2512 | } |
2513 | |
2514 | // Verify the old decl was also a type. |
2515 | TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); |
2516 | if (!Old) { |
2517 | Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind) |
2518 | << New->getDeclName(); |
2519 | |
2520 | NamedDecl *OldD = OldDecls.getRepresentativeDecl(); |
2521 | if (OldD->getLocation().isValid()) |
2522 | notePreviousDefinition(Old: OldD, New: New->getLocation()); |
2523 | |
2524 | return New->setInvalidDecl(); |
2525 | } |
2526 | |
2527 | // If the old declaration is invalid, just give up here. |
2528 | if (Old->isInvalidDecl()) |
2529 | return New->setInvalidDecl(); |
2530 | |
2531 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) { |
2532 | auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); |
2533 | auto *NewTag = New->getAnonDeclWithTypedefName(); |
2534 | NamedDecl *Hidden = nullptr; |
2535 | if (OldTag && NewTag && |
2536 | OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && |
2537 | !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) { |
2538 | // There is a definition of this tag, but it is not visible. Use it |
2539 | // instead of our tag. |
2540 | New->setTypeForDecl(OldTD->getTypeForDecl()); |
2541 | if (OldTD->isModed()) |
2542 | New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(), |
2543 | modedTy: OldTD->getUnderlyingType()); |
2544 | else |
2545 | New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); |
2546 | |
2547 | // Make the old tag definition visible. |
2548 | makeMergedDefinitionVisible(ND: Hidden); |
2549 | |
2550 | // If this was an unscoped enumeration, yank all of its enumerators |
2551 | // out of the scope. |
2552 | if (isa<EnumDecl>(Val: NewTag)) { |
2553 | Scope *EnumScope = getNonFieldDeclScope(S); |
2554 | for (auto *D : NewTag->decls()) { |
2555 | auto *ED = cast<EnumConstantDecl>(Val: D); |
2556 | assert(EnumScope->isDeclScope(ED)); |
2557 | EnumScope->RemoveDecl(D: ED); |
2558 | IdResolver.RemoveDecl(D: ED); |
2559 | ED->getLexicalDeclContext()->removeDecl(D: ED); |
2560 | } |
2561 | } |
2562 | } |
2563 | } |
2564 | |
2565 | // If the typedef types are not identical, reject them in all languages and |
2566 | // with any extensions enabled. |
2567 | if (isIncompatibleTypedef(Old, New)) |
2568 | return; |
2569 | |
2570 | // The types match. Link up the redeclaration chain and merge attributes if |
2571 | // the old declaration was a typedef. |
2572 | if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) { |
2573 | New->setPreviousDecl(Typedef); |
2574 | mergeDeclAttributes(New, Old); |
2575 | } |
2576 | |
2577 | if (getLangOpts().MicrosoftExt) |
2578 | return; |
2579 | |
2580 | if (getLangOpts().CPlusPlus) { |
2581 | // C++ [dcl.typedef]p2: |
2582 | // In a given non-class scope, a typedef specifier can be used to |
2583 | // redefine the name of any type declared in that scope to refer |
2584 | // to the type to which it already refers. |
2585 | if (!isa<CXXRecordDecl>(Val: CurContext)) |
2586 | return; |
2587 | |
2588 | // C++0x [dcl.typedef]p4: |
2589 | // In a given class scope, a typedef specifier can be used to redefine |
2590 | // any class-name declared in that scope that is not also a typedef-name |
2591 | // to refer to the type to which it already refers. |
2592 | // |
2593 | // This wording came in via DR424, which was a correction to the |
2594 | // wording in DR56, which accidentally banned code like: |
2595 | // |
2596 | // struct S { |
2597 | // typedef struct A { } A; |
2598 | // }; |
2599 | // |
2600 | // in the C++03 standard. We implement the C++0x semantics, which |
2601 | // allow the above but disallow |
2602 | // |
2603 | // struct S { |
2604 | // typedef int I; |
2605 | // typedef int I; |
2606 | // }; |
2607 | // |
2608 | // since that was the intent of DR56. |
2609 | if (!isa<TypedefNameDecl>(Val: Old)) |
2610 | return; |
2611 | |
2612 | Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) |
2613 | << New->getDeclName(); |
2614 | notePreviousDefinition(Old, New: New->getLocation()); |
2615 | return New->setInvalidDecl(); |
2616 | } |
2617 | |
2618 | // Modules always permit redefinition of typedefs, as does C11. |
2619 | if (getLangOpts().Modules || getLangOpts().C11) |
2620 | return; |
2621 | |
2622 | // If we have a redefinition of a typedef in C, emit a warning. This warning |
2623 | // is normally mapped to an error, but can be controlled with |
2624 | // -Wtypedef-redefinition. If either the original or the redefinition is |
2625 | // in a system header, don't emit this for compatibility with GCC. |
2626 | if (getDiagnostics().getSuppressSystemWarnings() && |
2627 | // Some standard types are defined implicitly in Clang (e.g. OpenCL). |
2628 | (Old->isImplicit() || |
2629 | Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) || |
2630 | Context.getSourceManager().isInSystemHeader(Loc: New->getLocation()))) |
2631 | return; |
2632 | |
2633 | Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef) |
2634 | << New->getDeclName(); |
2635 | notePreviousDefinition(Old, New: New->getLocation()); |
2636 | } |
2637 | |
2638 | /// DeclhasAttr - returns true if decl Declaration already has the target |
2639 | /// attribute. |
2640 | static bool DeclHasAttr(const Decl *D, const Attr *A) { |
2641 | const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A); |
2642 | const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A); |
2643 | for (const auto *i : D->attrs()) |
2644 | if (i->getKind() == A->getKind()) { |
2645 | if (Ann) { |
2646 | if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation()) |
2647 | return true; |
2648 | continue; |
2649 | } |
2650 | // FIXME: Don't hardcode this check |
2651 | if (OA && isa<OwnershipAttr>(Val: i)) |
2652 | return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind(); |
2653 | return true; |
2654 | } |
2655 | |
2656 | return false; |
2657 | } |
2658 | |
2659 | static bool isAttributeTargetADefinition(Decl *D) { |
2660 | if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) |
2661 | return VD->isThisDeclarationADefinition(); |
2662 | if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) |
2663 | return TD->isCompleteDefinition() || TD->isBeingDefined(); |
2664 | return true; |
2665 | } |
2666 | |
2667 | /// Merge alignment attributes from \p Old to \p New, taking into account the |
2668 | /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. |
2669 | /// |
2670 | /// \return \c true if any attributes were added to \p New. |
2671 | static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { |
2672 | // Look for alignas attributes on Old, and pick out whichever attribute |
2673 | // specifies the strictest alignment requirement. |
2674 | AlignedAttr *OldAlignasAttr = nullptr; |
2675 | AlignedAttr *OldStrictestAlignAttr = nullptr; |
2676 | unsigned OldAlign = 0; |
2677 | for (auto *I : Old->specific_attrs<AlignedAttr>()) { |
2678 | // FIXME: We have no way of representing inherited dependent alignments |
2679 | // in a case like: |
2680 | // template<int A, int B> struct alignas(A) X; |
2681 | // template<int A, int B> struct alignas(B) X {}; |
2682 | // For now, we just ignore any alignas attributes which are not on the |
2683 | // definition in such a case. |
2684 | if (I->isAlignmentDependent()) |
2685 | return false; |
2686 | |
2687 | if (I->isAlignas()) |
2688 | OldAlignasAttr = I; |
2689 | |
2690 | unsigned Align = I->getAlignment(Ctx&: S.Context); |
2691 | if (Align > OldAlign) { |
2692 | OldAlign = Align; |
2693 | OldStrictestAlignAttr = I; |
2694 | } |
2695 | } |
2696 | |
2697 | // Look for alignas attributes on New. |
2698 | AlignedAttr *NewAlignasAttr = nullptr; |
2699 | unsigned NewAlign = 0; |
2700 | for (auto *I : New->specific_attrs<AlignedAttr>()) { |
2701 | if (I->isAlignmentDependent()) |
2702 | return false; |
2703 | |
2704 | if (I->isAlignas()) |
2705 | NewAlignasAttr = I; |
2706 | |
2707 | unsigned Align = I->getAlignment(Ctx&: S.Context); |
2708 | if (Align > NewAlign) |
2709 | NewAlign = Align; |
2710 | } |
2711 | |
2712 | if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { |
2713 | // Both declarations have 'alignas' attributes. We require them to match. |
2714 | // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but |
2715 | // fall short. (If two declarations both have alignas, they must both match |
2716 | // every definition, and so must match each other if there is a definition.) |
2717 | |
2718 | // If either declaration only contains 'alignas(0)' specifiers, then it |
2719 | // specifies the natural alignment for the type. |
2720 | if (OldAlign == 0 || NewAlign == 0) { |
2721 | QualType Ty; |
2722 | if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New)) |
2723 | Ty = VD->getType(); |
2724 | else |
2725 | Ty = S.Context.getTagDeclType(Decl: cast<TagDecl>(Val: New)); |
2726 | |
2727 | if (OldAlign == 0) |
2728 | OldAlign = S.Context.getTypeAlign(T: Ty); |
2729 | if (NewAlign == 0) |
2730 | NewAlign = S.Context.getTypeAlign(T: Ty); |
2731 | } |
2732 | |
2733 | if (OldAlign != NewAlign) { |
2734 | S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch) |
2735 | << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity() |
2736 | << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity(); |
2737 | S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration); |
2738 | } |
2739 | } |
2740 | |
2741 | if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) { |
2742 | // C++11 [dcl.align]p6: |
2743 | // if any declaration of an entity has an alignment-specifier, |
2744 | // every defining declaration of that entity shall specify an |
2745 | // equivalent alignment. |
2746 | // C11 6.7.5/7: |
2747 | // If the definition of an object does not have an alignment |
2748 | // specifier, any other declaration of that object shall also |
2749 | // have no alignment specifier. |
2750 | S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition) |
2751 | << OldAlignasAttr; |
2752 | S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration) |
2753 | << OldAlignasAttr; |
2754 | } |
2755 | |
2756 | bool AnyAdded = false; |
2757 | |
2758 | // Ensure we have an attribute representing the strictest alignment. |
2759 | if (OldAlign > NewAlign) { |
2760 | AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context); |
2761 | Clone->setInherited(true); |
2762 | New->addAttr(A: Clone); |
2763 | AnyAdded = true; |
2764 | } |
2765 | |
2766 | // Ensure we have an alignas attribute if the old declaration had one. |
2767 | if (OldAlignasAttr && !NewAlignasAttr && |
2768 | !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { |
2769 | AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context); |
2770 | Clone->setInherited(true); |
2771 | New->addAttr(A: Clone); |
2772 | AnyAdded = true; |
2773 | } |
2774 | |
2775 | return AnyAdded; |
2776 | } |
2777 | |
2778 | #define WANT_DECL_MERGE_LOGIC |
2779 | #include "clang/Sema/AttrParsedAttrImpl.inc" |
2780 | #undef WANT_DECL_MERGE_LOGIC |
2781 | |
2782 | static bool mergeDeclAttribute(Sema &S, NamedDecl *D, |
2783 | const InheritableAttr *Attr, |
2784 | Sema::AvailabilityMergeKind AMK) { |
2785 | // Diagnose any mutual exclusions between the attribute that we want to add |
2786 | // and attributes that already exist on the declaration. |
2787 | if (!DiagnoseMutualExclusions(S, D, A: Attr)) |
2788 | return false; |
2789 | |
2790 | // This function copies an attribute Attr from a previous declaration to the |
2791 | // new declaration D if the new declaration doesn't itself have that attribute |
2792 | // yet or if that attribute allows duplicates. |
2793 | // If you're adding a new attribute that requires logic different from |
2794 | // "use explicit attribute on decl if present, else use attribute from |
2795 | // previous decl", for example if the attribute needs to be consistent |
2796 | // between redeclarations, you need to call a custom merge function here. |
2797 | InheritableAttr *NewAttr = nullptr; |
2798 | if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr)) |
2799 | NewAttr = S.mergeAvailabilityAttr( |
2800 | D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(), |
2801 | Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(), |
2802 | Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK, |
2803 | Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment()); |
2804 | else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr)) |
2805 | NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility()); |
2806 | else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr)) |
2807 | NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility()); |
2808 | else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr)) |
2809 | NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA); |
2810 | else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr)) |
2811 | NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA); |
2812 | else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr)) |
2813 | NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic()); |
2814 | else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr)) |
2815 | NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(), |
2816 | FirstArg: FA->getFirstArg()); |
2817 | else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr)) |
2818 | NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName()); |
2819 | else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr)) |
2820 | NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName()); |
2821 | else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr)) |
2822 | NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(), |
2823 | Model: IA->getInheritanceModel()); |
2824 | else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr)) |
2825 | NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA, |
2826 | Ident: &S.Context.Idents.get(Name: AA->getSpelling())); |
2827 | else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) && |
2828 | (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) || |
2829 | isa<CUDAGlobalAttr>(Val: Attr))) { |
2830 | // CUDA target attributes are part of function signature for |
2831 | // overloading purposes and must not be merged. |
2832 | return false; |
2833 | } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr)) |
2834 | NewAttr = S.mergeMinSizeAttr(D, CI: *MA); |
2835 | else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr)) |
2836 | NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName()); |
2837 | else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr)) |
2838 | NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA); |
2839 | else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr)) |
2840 | NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA); |
2841 | else if (isa<AlignedAttr>(Val: Attr)) |
2842 | // AlignedAttrs are handled separately, because we need to handle all |
2843 | // such attributes on a declaration at the same time. |
2844 | NewAttr = nullptr; |
2845 | else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) && |
2846 | (AMK == Sema::AMK_Override || |
2847 | AMK == Sema::AMK_ProtocolImplementation || |
2848 | AMK == Sema::AMK_OptionalProtocolImplementation)) |
2849 | NewAttr = nullptr; |
2850 | else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr)) |
2851 | NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl()); |
2852 | else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr)) |
2853 | NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA); |
2854 | else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr)) |
2855 | NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA); |
2856 | else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr)) |
2857 | NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA); |
2858 | else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr)) |
2859 | NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA); |
2860 | else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr)) |
2861 | NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA); |
2862 | else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr)) |
2863 | NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(), |
2864 | Z: NT->getZ()); |
2865 | else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr)) |
2866 | NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType()); |
2867 | else if (isa<SuppressAttr>(Val: Attr)) |
2868 | // Do nothing. Each redeclaration should be suppressed separately. |
2869 | NewAttr = nullptr; |
2870 | else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr)) |
2871 | NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context)); |
2872 | |
2873 | if (NewAttr) { |
2874 | NewAttr->setInherited(true); |
2875 | D->addAttr(A: NewAttr); |
2876 | if (isa<MSInheritanceAttr>(Val: NewAttr)) |
2877 | S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D)); |
2878 | return true; |
2879 | } |
2880 | |
2881 | return false; |
2882 | } |
2883 | |
2884 | static const NamedDecl *getDefinition(const Decl *D) { |
2885 | if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D)) |
2886 | return TD->getDefinition(); |
2887 | if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
2888 | const VarDecl *Def = VD->getDefinition(); |
2889 | if (Def) |
2890 | return Def; |
2891 | return VD->getActingDefinition(); |
2892 | } |
2893 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) { |
2894 | const FunctionDecl *Def = nullptr; |
2895 | if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true)) |
2896 | return Def; |
2897 | } |
2898 | return nullptr; |
2899 | } |
2900 | |
2901 | static bool hasAttribute(const Decl *D, attr::Kind Kind) { |
2902 | for (const auto *Attribute : D->attrs()) |
2903 | if (Attribute->getKind() == Kind) |
2904 | return true; |
2905 | return false; |
2906 | } |
2907 | |
2908 | /// checkNewAttributesAfterDef - If we already have a definition, check that |
2909 | /// there are no new attributes in this declaration. |
2910 | static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { |
2911 | if (!New->hasAttrs()) |
2912 | return; |
2913 | |
2914 | const NamedDecl *Def = getDefinition(D: Old); |
2915 | if (!Def || Def == New) |
2916 | return; |
2917 | |
2918 | AttrVec &NewAttributes = New->getAttrs(); |
2919 | for (unsigned I = 0, E = NewAttributes.size(); I != E;) { |
2920 | const Attr *NewAttribute = NewAttributes[I]; |
2921 | |
2922 | if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) { |
2923 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) { |
2924 | SkipBodyInfo SkipBody; |
2925 | S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody); |
2926 | |
2927 | // If we're skipping this definition, drop the "alias" attribute. |
2928 | if (SkipBody.ShouldSkip) { |
2929 | NewAttributes.erase(CI: NewAttributes.begin() + I); |
2930 | --E; |
2931 | continue; |
2932 | } |
2933 | } else { |
2934 | VarDecl *VD = cast<VarDecl>(Val: New); |
2935 | unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() == |
2936 | VarDecl::TentativeDefinition |
2937 | ? diag::err_alias_after_tentative |
2938 | : diag::err_redefinition; |
2939 | S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName(); |
2940 | if (Diag == diag::err_redefinition) |
2941 | S.notePreviousDefinition(Old: Def, New: VD->getLocation()); |
2942 | else |
2943 | S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition); |
2944 | VD->setInvalidDecl(); |
2945 | } |
2946 | ++I; |
2947 | continue; |
2948 | } |
2949 | |
2950 | if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) { |
2951 | // Tentative definitions are only interesting for the alias check above. |
2952 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { |
2953 | ++I; |
2954 | continue; |
2955 | } |
2956 | } |
2957 | |
2958 | if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) { |
2959 | ++I; |
2960 | continue; // regular attr merging will take care of validating this. |
2961 | } |
2962 | |
2963 | if (isa<C11NoReturnAttr>(Val: NewAttribute)) { |
2964 | // C's _Noreturn is allowed to be added to a function after it is defined. |
2965 | ++I; |
2966 | continue; |
2967 | } else if (isa<UuidAttr>(Val: NewAttribute)) { |
2968 | // msvc will allow a subsequent definition to add an uuid to a class |
2969 | ++I; |
2970 | continue; |
2971 | } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) { |
2972 | if (AA->isAlignas()) { |
2973 | // C++11 [dcl.align]p6: |
2974 | // if any declaration of an entity has an alignment-specifier, |
2975 | // every defining declaration of that entity shall specify an |
2976 | // equivalent alignment. |
2977 | // C11 6.7.5/7: |
2978 | // If the definition of an object does not have an alignment |
2979 | // specifier, any other declaration of that object shall also |
2980 | // have no alignment specifier. |
2981 | S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition) |
2982 | << AA; |
2983 | S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration) |
2984 | << AA; |
2985 | NewAttributes.erase(CI: NewAttributes.begin() + I); |
2986 | --E; |
2987 | continue; |
2988 | } |
2989 | } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) { |
2990 | // If there is a C definition followed by a redeclaration with this |
2991 | // attribute then there are two different definitions. In C++, prefer the |
2992 | // standard diagnostics. |
2993 | if (!S.getLangOpts().CPlusPlus) { |
2994 | S.Diag(Loc: NewAttribute->getLocation(), |
2995 | DiagID: diag::err_loader_uninitialized_redeclaration); |
2996 | S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition); |
2997 | NewAttributes.erase(CI: NewAttributes.begin() + I); |
2998 | --E; |
2999 | continue; |
3000 | } |
3001 | } else if (isa<SelectAnyAttr>(Val: NewAttribute) && |
3002 | cast<VarDecl>(Val: New)->isInline() && |
3003 | !cast<VarDecl>(Val: New)->isInlineSpecified()) { |
3004 | // Don't warn about applying selectany to implicitly inline variables. |
3005 | // Older compilers and language modes would require the use of selectany |
3006 | // to make such variables inline, and it would have no effect if we |
3007 | // honored it. |
3008 | ++I; |
3009 | continue; |
3010 | } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) { |
3011 | // We allow to add OMP[Begin]DeclareVariantAttr to be added to |
3012 | // declarations after definitions. |
3013 | ++I; |
3014 | continue; |
3015 | } |
3016 | |
3017 | S.Diag(Loc: NewAttribute->getLocation(), |
3018 | DiagID: diag::warn_attribute_precede_definition); |
3019 | S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition); |
3020 | NewAttributes.erase(CI: NewAttributes.begin() + I); |
3021 | --E; |
3022 | } |
3023 | } |
3024 | |
3025 | static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, |
3026 | const ConstInitAttr *CIAttr, |
3027 | bool AttrBeforeInit) { |
3028 | SourceLocation InsertLoc = InitDecl->getInnerLocStart(); |
3029 | |
3030 | // Figure out a good way to write this specifier on the old declaration. |
3031 | // FIXME: We should just use the spelling of CIAttr, but we don't preserve |
3032 | // enough of the attribute list spelling information to extract that without |
3033 | // heroics. |
3034 | std::string SuitableSpelling; |
3035 | if (S.getLangOpts().CPlusPlus20) |
3036 | SuitableSpelling = std::string( |
3037 | S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit})); |
3038 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) |
3039 | SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( |
3040 | Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square, |
3041 | S.PP.getIdentifierInfo(Name: "clang" ), tok::coloncolon, |
3042 | S.PP.getIdentifierInfo(Name: "require_constant_initialization" ), |
3043 | tok::r_square, tok::r_square})); |
3044 | if (SuitableSpelling.empty()) |
3045 | SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( |
3046 | Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren, |
3047 | S.PP.getIdentifierInfo(Name: "require_constant_initialization" ), |
3048 | tok::r_paren, tok::r_paren})); |
3049 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) |
3050 | SuitableSpelling = "constinit" ; |
3051 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) |
3052 | SuitableSpelling = "[[clang::require_constant_initialization]]" ; |
3053 | if (SuitableSpelling.empty()) |
3054 | SuitableSpelling = "__attribute__((require_constant_initialization))" ; |
3055 | SuitableSpelling += " " ; |
3056 | |
3057 | if (AttrBeforeInit) { |
3058 | // extern constinit int a; |
3059 | // int a = 0; // error (missing 'constinit'), accepted as extension |
3060 | assert(CIAttr->isConstinit() && "should not diagnose this for attribute" ); |
3061 | S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing) |
3062 | << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling); |
3063 | S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here); |
3064 | } else { |
3065 | // int a = 0; |
3066 | // constinit extern int a; // error (missing 'constinit') |
3067 | S.Diag(Loc: CIAttr->getLocation(), |
3068 | DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late |
3069 | : diag::warn_require_const_init_added_too_late) |
3070 | << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation())); |
3071 | S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here) |
3072 | << CIAttr->isConstinit() |
3073 | << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling); |
3074 | } |
3075 | } |
3076 | |
3077 | void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, |
3078 | AvailabilityMergeKind AMK) { |
3079 | if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { |
3080 | UsedAttr *NewAttr = OldAttr->clone(C&: Context); |
3081 | NewAttr->setInherited(true); |
3082 | New->addAttr(A: NewAttr); |
3083 | } |
3084 | if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { |
3085 | RetainAttr *NewAttr = OldAttr->clone(C&: Context); |
3086 | NewAttr->setInherited(true); |
3087 | New->addAttr(A: NewAttr); |
3088 | } |
3089 | |
3090 | if (!Old->hasAttrs() && !New->hasAttrs()) |
3091 | return; |
3092 | |
3093 | // [dcl.constinit]p1: |
3094 | // If the [constinit] specifier is applied to any declaration of a |
3095 | // variable, it shall be applied to the initializing declaration. |
3096 | const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); |
3097 | const auto *NewConstInit = New->getAttr<ConstInitAttr>(); |
3098 | if (bool(OldConstInit) != bool(NewConstInit)) { |
3099 | const auto *OldVD = cast<VarDecl>(Val: Old); |
3100 | auto *NewVD = cast<VarDecl>(Val: New); |
3101 | |
3102 | // Find the initializing declaration. Note that we might not have linked |
3103 | // the new declaration into the redeclaration chain yet. |
3104 | const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); |
3105 | if (!InitDecl && |
3106 | (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) |
3107 | InitDecl = NewVD; |
3108 | |
3109 | if (InitDecl == NewVD) { |
3110 | // This is the initializing declaration. If it would inherit 'constinit', |
3111 | // that's ill-formed. (Note that we do not apply this to the attribute |
3112 | // form). |
3113 | if (OldConstInit && OldConstInit->isConstinit()) |
3114 | diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit, |
3115 | /*AttrBeforeInit=*/true); |
3116 | } else if (NewConstInit) { |
3117 | // This is the first time we've been told that this declaration should |
3118 | // have a constant initializer. If we already saw the initializing |
3119 | // declaration, this is too late. |
3120 | if (InitDecl && InitDecl != NewVD) { |
3121 | diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit, |
3122 | /*AttrBeforeInit=*/false); |
3123 | NewVD->dropAttr<ConstInitAttr>(); |
3124 | } |
3125 | } |
3126 | } |
3127 | |
3128 | // Attributes declared post-definition are currently ignored. |
3129 | checkNewAttributesAfterDef(S&: *this, New, Old); |
3130 | |
3131 | if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { |
3132 | if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { |
3133 | if (!OldA->isEquivalent(Other: NewA)) { |
3134 | // This redeclaration changes __asm__ label. |
3135 | Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label); |
3136 | Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration); |
3137 | } |
3138 | } else if (Old->isUsed()) { |
3139 | // This redeclaration adds an __asm__ label to a declaration that has |
3140 | // already been ODR-used. |
3141 | Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name) |
3142 | << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange(); |
3143 | } |
3144 | } |
3145 | |
3146 | // Re-declaration cannot add abi_tag's. |
3147 | if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { |
3148 | if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { |
3149 | for (const auto &NewTag : NewAbiTagAttr->tags()) { |
3150 | if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) { |
3151 | Diag(Loc: NewAbiTagAttr->getLocation(), |
3152 | DiagID: diag::err_new_abi_tag_on_redeclaration) |
3153 | << NewTag; |
3154 | Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration); |
3155 | } |
3156 | } |
3157 | } else { |
3158 | Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration); |
3159 | Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration); |
3160 | } |
3161 | } |
3162 | |
3163 | // This redeclaration adds a section attribute. |
3164 | if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { |
3165 | if (auto *VD = dyn_cast<VarDecl>(Val: New)) { |
3166 | if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { |
3167 | Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration); |
3168 | Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration); |
3169 | } |
3170 | } |
3171 | } |
3172 | |
3173 | // Redeclaration adds code-seg attribute. |
3174 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); |
3175 | if (NewCSA && !Old->hasAttr<CodeSegAttr>() && |
3176 | !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) { |
3177 | Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section) |
3178 | << 0 /*codeseg*/; |
3179 | Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration); |
3180 | } |
3181 | |
3182 | if (!Old->hasAttrs()) |
3183 | return; |
3184 | |
3185 | bool foundAny = New->hasAttrs(); |
3186 | |
3187 | // Ensure that any moving of objects within the allocated map is done before |
3188 | // we process them. |
3189 | if (!foundAny) New->setAttrs(AttrVec()); |
3190 | |
3191 | for (auto *I : Old->specific_attrs<InheritableAttr>()) { |
3192 | // Ignore deprecated/unavailable/availability attributes if requested. |
3193 | AvailabilityMergeKind LocalAMK = AMK_None; |
3194 | if (isa<DeprecatedAttr>(Val: I) || |
3195 | isa<UnavailableAttr>(Val: I) || |
3196 | isa<AvailabilityAttr>(Val: I)) { |
3197 | switch (AMK) { |
3198 | case AMK_None: |
3199 | continue; |
3200 | |
3201 | case AMK_Redeclaration: |
3202 | case AMK_Override: |
3203 | case AMK_ProtocolImplementation: |
3204 | case AMK_OptionalProtocolImplementation: |
3205 | LocalAMK = AMK; |
3206 | break; |
3207 | } |
3208 | } |
3209 | |
3210 | // Already handled. |
3211 | if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I)) |
3212 | continue; |
3213 | |
3214 | if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK)) |
3215 | foundAny = true; |
3216 | } |
3217 | |
3218 | if (mergeAlignedAttrs(S&: *this, New, Old)) |
3219 | foundAny = true; |
3220 | |
3221 | if (!foundAny) New->dropAttrs(); |
3222 | } |
3223 | |
3224 | /// mergeParamDeclAttributes - Copy attributes from the old parameter |
3225 | /// to the new one. |
3226 | static void mergeParamDeclAttributes(ParmVarDecl *newDecl, |
3227 | const ParmVarDecl *oldDecl, |
3228 | Sema &S) { |
3229 | // C++11 [dcl.attr.depend]p2: |
3230 | // The first declaration of a function shall specify the |
3231 | // carries_dependency attribute for its declarator-id if any declaration |
3232 | // of the function specifies the carries_dependency attribute. |
3233 | const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); |
3234 | if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { |
3235 | S.Diag(Loc: CDA->getLocation(), |
3236 | DiagID: diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; |
3237 | // Find the first declaration of the parameter. |
3238 | // FIXME: Should we build redeclaration chains for function parameters? |
3239 | const FunctionDecl *FirstFD = |
3240 | cast<FunctionDecl>(Val: oldDecl->getDeclContext())->getFirstDecl(); |
3241 | const ParmVarDecl *FirstVD = |
3242 | FirstFD->getParamDecl(i: oldDecl->getFunctionScopeIndex()); |
3243 | S.Diag(Loc: FirstVD->getLocation(), |
3244 | DiagID: diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; |
3245 | } |
3246 | |
3247 | // HLSL parameter declarations for inout and out must match between |
3248 | // declarations. In HLSL inout and out are ambiguous at the call site, but |
3249 | // have different calling behavior, so you cannot overload a method based on a |
3250 | // difference between inout and out annotations. |
3251 | if (S.getLangOpts().HLSL) { |
3252 | const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>(); |
3253 | const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>(); |
3254 | // We don't need to cover the case where one declaration doesn't have an |
3255 | // attribute. The only possible case there is if one declaration has an `in` |
3256 | // attribute and the other declaration has no attribute. This case is |
3257 | // allowed since parameters are `in` by default. |
3258 | if (NDAttr && ODAttr && |
3259 | NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) { |
3260 | S.Diag(Loc: newDecl->getLocation(), DiagID: diag::err_hlsl_param_qualifier_mismatch) |
3261 | << NDAttr << newDecl; |
3262 | S.Diag(Loc: oldDecl->getLocation(), DiagID: diag::note_previous_declaration_as) |
3263 | << ODAttr; |
3264 | } |
3265 | } |
3266 | |
3267 | if (!oldDecl->hasAttrs()) |
3268 | return; |
3269 | |
3270 | bool foundAny = newDecl->hasAttrs(); |
3271 | |
3272 | // Ensure that any moving of objects within the allocated map is |
3273 | // done before we process them. |
3274 | if (!foundAny) newDecl->setAttrs(AttrVec()); |
3275 | |
3276 | for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { |
3277 | if (!DeclHasAttr(D: newDecl, A: I)) { |
3278 | InheritableAttr *newAttr = |
3279 | cast<InheritableParamAttr>(Val: I->clone(C&: S.Context)); |
3280 | newAttr->setInherited(true); |
3281 | newDecl->addAttr(A: newAttr); |
3282 | foundAny = true; |
3283 | } |
3284 | } |
3285 | |
3286 | if (!foundAny) newDecl->dropAttrs(); |
3287 | } |
3288 | |
3289 | static bool EquivalentArrayTypes(QualType Old, QualType New, |
3290 | const ASTContext &Ctx) { |
3291 | |
3292 | auto NoSizeInfo = [&Ctx](QualType Ty) { |
3293 | if (Ty->isIncompleteArrayType() || Ty->isPointerType()) |
3294 | return true; |
3295 | if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty)) |
3296 | return VAT->getSizeModifier() == ArraySizeModifier::Star; |
3297 | return false; |
3298 | }; |
3299 | |
3300 | // `type[]` is equivalent to `type *` and `type[*]`. |
3301 | if (NoSizeInfo(Old) && NoSizeInfo(New)) |
3302 | return true; |
3303 | |
3304 | // Don't try to compare VLA sizes, unless one of them has the star modifier. |
3305 | if (Old->isVariableArrayType() && New->isVariableArrayType()) { |
3306 | const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old); |
3307 | const auto *NewVAT = Ctx.getAsVariableArrayType(T: New); |
3308 | if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^ |
3309 | (NewVAT->getSizeModifier() == ArraySizeModifier::Star)) |
3310 | return false; |
3311 | return true; |
3312 | } |
3313 | |
3314 | // Only compare size, ignore Size modifiers and CVR. |
3315 | if (Old->isConstantArrayType() && New->isConstantArrayType()) { |
3316 | return Ctx.getAsConstantArrayType(T: Old)->getSize() == |
3317 | Ctx.getAsConstantArrayType(T: New)->getSize(); |
3318 | } |
3319 | |
3320 | // Don't try to compare dependent sized array |
3321 | if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) { |
3322 | return true; |
3323 | } |
3324 | |
3325 | return Old == New; |
3326 | } |
3327 | |
3328 | static void mergeParamDeclTypes(ParmVarDecl *NewParam, |
3329 | const ParmVarDecl *OldParam, |
3330 | Sema &S) { |
3331 | if (auto Oldnullability = OldParam->getType()->getNullability()) { |
3332 | if (auto Newnullability = NewParam->getType()->getNullability()) { |
3333 | if (*Oldnullability != *Newnullability) { |
3334 | S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr) |
3335 | << DiagNullabilityKind( |
3336 | *Newnullability, |
3337 | ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) |
3338 | != 0)) |
3339 | << DiagNullabilityKind( |
3340 | *Oldnullability, |
3341 | ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) |
3342 | != 0)); |
3343 | S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration); |
3344 | } |
3345 | } else { |
3346 | QualType NewT = NewParam->getType(); |
3347 | NewT = S.Context.getAttributedType( |
3348 | attrKind: AttributedType::getNullabilityAttrKind(kind: *Oldnullability), |
3349 | modifiedType: NewT, equivalentType: NewT); |
3350 | NewParam->setType(NewT); |
3351 | } |
3352 | } |
3353 | const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType()); |
3354 | const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType()); |
3355 | if (OldParamDT && NewParamDT && |
3356 | OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) { |
3357 | QualType OldParamOT = OldParamDT->getOriginalType(); |
3358 | QualType NewParamOT = NewParamDT->getOriginalType(); |
3359 | if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) { |
3360 | S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form) |
3361 | << NewParam << NewParamOT; |
3362 | S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as) |
3363 | << OldParamOT; |
3364 | } |
3365 | } |
3366 | } |
3367 | |
3368 | namespace { |
3369 | |
3370 | /// Used in MergeFunctionDecl to keep track of function parameters in |
3371 | /// C. |
3372 | struct GNUCompatibleParamWarning { |
3373 | ParmVarDecl *OldParm; |
3374 | ParmVarDecl *NewParm; |
3375 | QualType PromotedType; |
3376 | }; |
3377 | |
3378 | } // end anonymous namespace |
3379 | |
3380 | // Determine whether the previous declaration was a definition, implicit |
3381 | // declaration, or a declaration. |
3382 | template <typename T> |
3383 | static std::pair<diag::kind, SourceLocation> |
3384 | getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { |
3385 | diag::kind PrevDiag; |
3386 | SourceLocation OldLocation = Old->getLocation(); |
3387 | if (Old->isThisDeclarationADefinition()) |
3388 | PrevDiag = diag::note_previous_definition; |
3389 | else if (Old->isImplicit()) { |
3390 | PrevDiag = diag::note_previous_implicit_declaration; |
3391 | if (const auto *FD = dyn_cast<FunctionDecl>(Old)) { |
3392 | if (FD->getBuiltinID()) |
3393 | PrevDiag = diag::note_previous_builtin_declaration; |
3394 | } |
3395 | if (OldLocation.isInvalid()) |
3396 | OldLocation = New->getLocation(); |
3397 | } else |
3398 | PrevDiag = diag::note_previous_declaration; |
3399 | return std::make_pair(x&: PrevDiag, y&: OldLocation); |
3400 | } |
3401 | |
3402 | /// canRedefineFunction - checks if a function can be redefined. Currently, |
3403 | /// only extern inline functions can be redefined, and even then only in |
3404 | /// GNU89 mode. |
3405 | static bool canRedefineFunction(const FunctionDecl *FD, |
3406 | const LangOptions& LangOpts) { |
3407 | return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && |
3408 | !LangOpts.CPlusPlus && |
3409 | FD->isInlineSpecified() && |
3410 | FD->getStorageClass() == SC_Extern); |
3411 | } |
3412 | |
3413 | const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { |
3414 | const AttributedType *AT = T->getAs<AttributedType>(); |
3415 | while (AT && !AT->isCallingConv()) |
3416 | AT = AT->getModifiedType()->getAs<AttributedType>(); |
3417 | return AT; |
3418 | } |
3419 | |
3420 | template <typename T> |
3421 | static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { |
3422 | const DeclContext *DC = Old->getDeclContext(); |
3423 | if (DC->isRecord()) |
3424 | return false; |
3425 | |
3426 | LanguageLinkage OldLinkage = Old->getLanguageLinkage(); |
3427 | if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) |
3428 | return true; |
3429 | if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) |
3430 | return true; |
3431 | return false; |
3432 | } |
3433 | |
3434 | template<typename T> static bool isExternC(T *D) { return D->isExternC(); } |
3435 | static bool isExternC(VarTemplateDecl *) { return false; } |
3436 | static bool isExternC(FunctionTemplateDecl *) { return false; } |
3437 | |
3438 | /// Check whether a redeclaration of an entity introduced by a |
3439 | /// using-declaration is valid, given that we know it's not an overload |
3440 | /// (nor a hidden tag declaration). |
3441 | template<typename ExpectedDecl> |
3442 | static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, |
3443 | ExpectedDecl *New) { |
3444 | // C++11 [basic.scope.declarative]p4: |
3445 | // Given a set of declarations in a single declarative region, each of |
3446 | // which specifies the same unqualified name, |
3447 | // -- they shall all refer to the same entity, or all refer to functions |
3448 | // and function templates; or |
3449 | // -- exactly one declaration shall declare a class name or enumeration |
3450 | // name that is not a typedef name and the other declarations shall all |
3451 | // refer to the same variable or enumerator, or all refer to functions |
3452 | // and function templates; in this case the class name or enumeration |
3453 | // name is hidden (3.3.10). |
3454 | |
3455 | // C++11 [namespace.udecl]p14: |
3456 | // If a function declaration in namespace scope or block scope has the |
3457 | // same name and the same parameter-type-list as a function introduced |
3458 | // by a using-declaration, and the declarations do not declare the same |
3459 | // function, the program is ill-formed. |
3460 | |
3461 | auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); |
3462 | if (Old && |
3463 | !Old->getDeclContext()->getRedeclContext()->Equals( |
3464 | New->getDeclContext()->getRedeclContext()) && |
3465 | !(isExternC(Old) && isExternC(New))) |
3466 | Old = nullptr; |
3467 | |
3468 | if (!Old) { |
3469 | S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); |
3470 | S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target); |
3471 | S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0; |
3472 | return true; |
3473 | } |
3474 | return false; |
3475 | } |
3476 | |
3477 | static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, |
3478 | const FunctionDecl *B) { |
3479 | assert(A->getNumParams() == B->getNumParams()); |
3480 | |
3481 | auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { |
3482 | const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); |
3483 | const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); |
3484 | if (AttrA == AttrB) |
3485 | return true; |
3486 | return AttrA && AttrB && AttrA->getType() == AttrB->getType() && |
3487 | AttrA->isDynamic() == AttrB->isDynamic(); |
3488 | }; |
3489 | |
3490 | return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); |
3491 | } |
3492 | |
3493 | /// If necessary, adjust the semantic declaration context for a qualified |
3494 | /// declaration to name the correct inline namespace within the qualifier. |
3495 | static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, |
3496 | DeclaratorDecl *OldD) { |
3497 | // The only case where we need to update the DeclContext is when |
3498 | // redeclaration lookup for a qualified name finds a declaration |
3499 | // in an inline namespace within the context named by the qualifier: |
3500 | // |
3501 | // inline namespace N { int f(); } |
3502 | // int ::f(); // Sema DC needs adjusting from :: to N::. |
3503 | // |
3504 | // For unqualified declarations, the semantic context *can* change |
3505 | // along the redeclaration chain (for local extern declarations, |
3506 | // extern "C" declarations, and friend declarations in particular). |
3507 | if (!NewD->getQualifier()) |
3508 | return; |
3509 | |
3510 | // NewD is probably already in the right context. |
3511 | auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); |
3512 | auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); |
3513 | if (NamedDC->Equals(DC: SemaDC)) |
3514 | return; |
3515 | |
3516 | assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || |
3517 | NewD->isInvalidDecl() || OldD->isInvalidDecl()) && |
3518 | "unexpected context for redeclaration" ); |
3519 | |
3520 | auto *LexDC = NewD->getLexicalDeclContext(); |
3521 | auto FixSemaDC = [=](NamedDecl *D) { |
3522 | if (!D) |
3523 | return; |
3524 | D->setDeclContext(SemaDC); |
3525 | D->setLexicalDeclContext(LexDC); |
3526 | }; |
3527 | |
3528 | FixSemaDC(NewD); |
3529 | if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD)) |
3530 | FixSemaDC(FD->getDescribedFunctionTemplate()); |
3531 | else if (auto *VD = dyn_cast<VarDecl>(Val: NewD)) |
3532 | FixSemaDC(VD->getDescribedVarTemplate()); |
3533 | } |
3534 | |
3535 | bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S, |
3536 | bool MergeTypeWithOld, bool NewDeclIsDefn) { |
3537 | // Verify the old decl was also a function. |
3538 | FunctionDecl *Old = OldD->getAsFunction(); |
3539 | if (!Old) { |
3540 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) { |
3541 | if (New->getFriendObjectKind()) { |
3542 | Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend); |
3543 | Diag(Loc: Shadow->getTargetDecl()->getLocation(), |
3544 | DiagID: diag::note_using_decl_target); |
3545 | Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) |
3546 | << 0; |
3547 | return true; |
3548 | } |
3549 | |
3550 | // Check whether the two declarations might declare the same function or |
3551 | // function template. |
3552 | if (FunctionTemplateDecl *NewTemplate = |
3553 | New->getDescribedFunctionTemplate()) { |
3554 | if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow, |
3555 | New: NewTemplate)) |
3556 | return true; |
3557 | OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl()) |
3558 | ->getAsFunction(); |
3559 | } else { |
3560 | if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New)) |
3561 | return true; |
3562 | OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl()); |
3563 | } |
3564 | } else { |
3565 | Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind) |
3566 | << New->getDeclName(); |
3567 | notePreviousDefinition(Old: OldD, New: New->getLocation()); |
3568 | return true; |
3569 | } |
3570 | } |
3571 | |
3572 | // If the old declaration was found in an inline namespace and the new |
3573 | // declaration was qualified, update the DeclContext to match. |
3574 | adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old); |
3575 | |
3576 | // If the old declaration is invalid, just give up here. |
3577 | if (Old->isInvalidDecl()) |
3578 | return true; |
3579 | |
3580 | // Disallow redeclaration of some builtins. |
3581 | if (!getASTContext().canBuiltinBeRedeclared(Old)) { |
3582 | Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName(); |
3583 | Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration) |
3584 | << Old << Old->getType(); |
3585 | return true; |
3586 | } |
3587 | |
3588 | diag::kind PrevDiag; |
3589 | SourceLocation OldLocation; |
3590 | std::tie(args&: PrevDiag, args&: OldLocation) = |
3591 | getNoteDiagForInvalidRedeclaration(Old, New); |
3592 | |
3593 | // Don't complain about this if we're in GNU89 mode and the old function |
3594 | // is an extern inline function. |
3595 | // Don't complain about specializations. They are not supposed to have |
3596 | // storage classes. |
3597 | if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) && |
3598 | New->getStorageClass() == SC_Static && |
3599 | Old->hasExternalFormalLinkage() && |
3600 | !New->getTemplateSpecializationInfo() && |
3601 | !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) { |
3602 | if (getLangOpts().MicrosoftExt) { |
3603 | Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New; |
3604 | Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType(); |
3605 | } else { |
3606 | Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static) << New; |
3607 | Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType(); |
3608 | return true; |
3609 | } |
3610 | } |
3611 | |
3612 | if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) |
3613 | if (!Old->hasAttr<InternalLinkageAttr>()) { |
3614 | Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) |
3615 | << ILA; |
3616 | Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration); |
3617 | New->dropAttr<InternalLinkageAttr>(); |
3618 | } |
3619 | |
3620 | if (auto *EA = New->getAttr<ErrorAttr>()) { |
3621 | if (!Old->hasAttr<ErrorAttr>()) { |
3622 | Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA; |
3623 | Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration); |
3624 | New->dropAttr<ErrorAttr>(); |
3625 | } |
3626 | } |
3627 | |
3628 | if (CheckRedeclarationInModule(New, Old)) |
3629 | return true; |
3630 | |
3631 | if (!getLangOpts().CPlusPlus) { |
3632 | bool OldOvl = Old->hasAttr<OverloadableAttr>(); |
3633 | if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { |
3634 | Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch) |
3635 | << New << OldOvl; |
3636 | |
3637 | // Try our best to find a decl that actually has the overloadable |
3638 | // attribute for the note. In most cases (e.g. programs with only one |
3639 | // broken declaration/definition), this won't matter. |
3640 | // |
3641 | // FIXME: We could do this if we juggled some extra state in |
3642 | // OverloadableAttr, rather than just removing it. |
3643 | const Decl *DiagOld = Old; |
3644 | if (OldOvl) { |
3645 | auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) { |
3646 | const auto *A = D->getAttr<OverloadableAttr>(); |
3647 | return A && !A->isImplicit(); |
3648 | }); |
3649 | // If we've implicitly added *all* of the overloadable attrs to this |
3650 | // chain, emitting a "previous redecl" note is pointless. |
3651 | DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; |
3652 | } |
3653 | |
3654 | if (DiagOld) |
3655 | Diag(Loc: DiagOld->getLocation(), |
3656 | DiagID: diag::note_attribute_overloadable_prev_overload) |
3657 | << OldOvl; |
3658 | |
3659 | if (OldOvl) |
3660 | New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context)); |
3661 | else |
3662 | New->dropAttr<OverloadableAttr>(); |
3663 | } |
3664 | } |
3665 | |
3666 | // It is not permitted to redeclare an SME function with different SME |
3667 | // attributes. |
3668 | if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) { |
3669 | Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch) |
3670 | << New->getType() << Old->getType(); |
3671 | Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration); |
3672 | return true; |
3673 | } |
3674 | |
3675 | // If a function is first declared with a calling convention, but is later |
3676 | // declared or defined without one, all following decls assume the calling |
3677 | // convention of the first. |
3678 | // |
3679 | // It's OK if a function is first declared without a calling convention, |
3680 | // but is later declared or defined with the default calling convention. |
3681 | // |
3682 | // To test if either decl has an explicit calling convention, we look for |
3683 | // AttributedType sugar nodes on the type as written. If they are missing or |
3684 | // were canonicalized away, we assume the calling convention was implicit. |
3685 | // |
3686 | // Note also that we DO NOT return at this point, because we still have |
3687 | // other tests to run. |
3688 | QualType OldQType = Context.getCanonicalType(T: Old->getType()); |
3689 | QualType NewQType = Context.getCanonicalType(T: New->getType()); |
3690 | const FunctionType *OldType = cast<FunctionType>(Val&: OldQType); |
3691 | const FunctionType *NewType = cast<FunctionType>(Val&: NewQType); |
3692 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); |
3693 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); |
3694 | bool RequiresAdjustment = false; |
3695 | |
3696 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { |
3697 | FunctionDecl *First = Old->getFirstDecl(); |
3698 | const FunctionType *FT = |
3699 | First->getType().getCanonicalType()->castAs<FunctionType>(); |
3700 | FunctionType::ExtInfo FI = FT->getExtInfo(); |
3701 | bool NewCCExplicit = getCallingConvAttributedType(T: New->getType()); |
3702 | if (!NewCCExplicit) { |
3703 | // Inherit the CC from the previous declaration if it was specified |
3704 | // there but not here. |
3705 | NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC()); |
3706 | RequiresAdjustment = true; |
3707 | } else if (Old->getBuiltinID()) { |
3708 | // Builtin attribute isn't propagated to the new one yet at this point, |
3709 | // so we check if the old one is a builtin. |
3710 | |
3711 | // Calling Conventions on a Builtin aren't really useful and setting a |
3712 | // default calling convention and cdecl'ing some builtin redeclarations is |
3713 | // common, so warn and ignore the calling convention on the redeclaration. |
3714 | Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported) |
3715 | << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC()) |
3716 | << (int)CallingConventionIgnoredReason::BuiltinFunction; |
3717 | NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC()); |
3718 | RequiresAdjustment = true; |
3719 | } else { |
3720 | // Calling conventions aren't compatible, so complain. |
3721 | bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType()); |
3722 | Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change) |
3723 | << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC()) |
3724 | << !FirstCCExplicit |
3725 | << (!FirstCCExplicit ? "" : |
3726 | FunctionType::getNameForCallConv(CC: FI.getCC())); |
3727 | |
3728 | // Put the note on the first decl, since it is the one that matters. |
3729 | Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration); |
3730 | return true; |
3731 | } |
3732 | } |
3733 | |
3734 | // FIXME: diagnose the other way around? |
3735 | if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { |
3736 | NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true); |
3737 | RequiresAdjustment = true; |
3738 | } |
3739 | |
3740 | // Merge regparm attribute. |
3741 | if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || |
3742 | OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { |
3743 | if (NewTypeInfo.getHasRegParm()) { |
3744 | Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch) |
3745 | << NewType->getRegParmType() |
3746 | << OldType->getRegParmType(); |
3747 | Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration); |
3748 | return true; |
3749 | } |
3750 | |
3751 | NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm()); |
3752 | RequiresAdjustment = true; |
3753 | } |
3754 | |
3755 | // Merge ns_returns_retained attribute. |
3756 | if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { |
3757 | if (NewTypeInfo.getProducesResult()) { |
3758 | Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) |
3759 | << "'ns_returns_retained'" ; |
3760 | Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration); |
3761 | return true; |
3762 | } |
3763 | |
3764 | NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true); |
3765 | RequiresAdjustment = true; |
3766 | } |
3767 | |
3768 | if (OldTypeInfo.getNoCallerSavedRegs() != |
3769 | NewTypeInfo.getNoCallerSavedRegs()) { |
3770 | if (NewTypeInfo.getNoCallerSavedRegs()) { |
3771 | AnyX86NoCallerSavedRegistersAttr *Attr = |
3772 | New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); |
3773 | Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr; |
3774 | Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration); |
3775 | return true; |
3776 | } |
3777 | |
3778 | NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true); |
3779 | RequiresAdjustment = true; |
3780 | } |
3781 | |
3782 | if (RequiresAdjustment) { |
3783 | const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); |
3784 | AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo); |
3785 | New->setType(QualType(AdjustedType, 0)); |
3786 | NewQType = Context.getCanonicalType(T: New->getType()); |
3787 | } |
3788 | |
3789 | // If this redeclaration makes the function inline, we may need to add it to |
3790 | // UndefinedButUsed. |
3791 | if (!Old->isInlined() && New->isInlined() && |
3792 | !New->hasAttr<GNUInlineAttr>() && |
3793 | !getLangOpts().GNUInline && |
3794 | Old->isUsed(CheckUsedAttr: false) && |
3795 | !Old->isDefined() && !New->isThisDeclarationADefinition()) |
3796 | UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(), |
3797 | y: SourceLocation())); |
3798 | |
3799 | // If this redeclaration makes it newly gnu_inline, we don't want to warn |
3800 | // about it. |
3801 | if (New->hasAttr<GNUInlineAttr>() && |
3802 | Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { |
3803 | UndefinedButUsed.erase(Key: Old->getCanonicalDecl()); |
3804 | } |
3805 | |
3806 | // If pass_object_size params don't match up perfectly, this isn't a valid |
3807 | // redeclaration. |
3808 | if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && |
3809 | !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) { |
3810 | Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params) |
3811 | << New->getDeclName(); |
3812 | Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType(); |
3813 | return true; |
3814 | } |
3815 | |
3816 | QualType OldQTypeForComparison = OldQType; |
3817 | if (Context.hasAnyFunctionEffects()) { |
3818 | const auto OldFX = Old->getFunctionEffects(); |
3819 | const auto NewFX = New->getFunctionEffects(); |
3820 | if (OldFX != NewFX) { |
3821 | const auto Diffs = FunctionEffectDifferences(OldFX, NewFX); |
3822 | for (const auto &Diff : Diffs) { |
3823 | if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) { |
3824 | Diag(Loc: New->getLocation(), |
3825 | DiagID: diag::warn_mismatched_func_effect_redeclaration) |
3826 | << Diff.effectName(); |
3827 | Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration); |
3828 | } |
3829 | } |
3830 | // Following a warning, we could skip merging effects from the previous |
3831 | // declaration, but that would trigger an additional "conflicting types" |
3832 | // error. |
3833 | if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) { |
3834 | FunctionEffectSet::Conflicts MergeErrs; |
3835 | FunctionEffectSet MergedFX = |
3836 | FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs); |
3837 | if (!MergeErrs.empty()) |
3838 | diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(), |
3839 | OldLoc: Old->getLocation()); |
3840 | |
3841 | FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo(); |
3842 | EPI.FunctionEffects = FunctionEffectsRef(MergedFX); |
3843 | QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(), |
3844 | Args: NewFPT->getParamTypes(), EPI); |
3845 | |
3846 | New->setType(ModQT); |
3847 | NewQType = New->getType(); |
3848 | |
3849 | // Revise OldQTForComparison to include the merged effects, |
3850 | // so as not to fail due to differences later. |
3851 | if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) { |
3852 | EPI = OldFPT->getExtProtoInfo(); |
3853 | EPI.FunctionEffects = FunctionEffectsRef(MergedFX); |
3854 | OldQTypeForComparison = Context.getFunctionType( |
3855 | ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI); |
3856 | } |
3857 | } |
3858 | } |
3859 | } |
3860 | |
3861 | if (getLangOpts().CPlusPlus) { |
3862 | OldQType = Context.getCanonicalType(T: Old->getType()); |
3863 | NewQType = Context.getCanonicalType(T: New->getType()); |
3864 | |
3865 | // Go back to the type source info to compare the declared return types, |
3866 | // per C++1y [dcl.type.auto]p13: |
3867 | // Redeclarations or specializations of a function or function template |
3868 | // with a declared return type that uses a placeholder type shall also |
3869 | // use that placeholder, not a deduced type. |
3870 | QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); |
3871 | QualType NewDeclaredReturnType = New->getDeclaredReturnType(); |
3872 | if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) && |
3873 | canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType, |
3874 | OldT: OldDeclaredReturnType)) { |
3875 | QualType ResQT; |
3876 | if (NewDeclaredReturnType->isObjCObjectPointerType() && |
3877 | OldDeclaredReturnType->isObjCObjectPointerType()) |
3878 | // FIXME: This does the wrong thing for a deduced return type. |
3879 | ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); |
3880 | if (ResQT.isNull()) { |
3881 | if (New->isCXXClassMember() && New->isOutOfLine()) |
3882 | Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type) |
3883 | << New << New->getReturnTypeSourceRange(); |
3884 | else |
3885 | Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type) |
3886 | << New->getReturnTypeSourceRange(); |
3887 | Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType() |
3888 | << Old->getReturnTypeSourceRange(); |
3889 | return true; |
3890 | } |
3891 | else |
3892 | NewQType = ResQT; |
3893 | } |
3894 | |
3895 | QualType OldReturnType = OldType->getReturnType(); |
3896 | QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType(); |
3897 | if (OldReturnType != NewReturnType) { |
3898 | // If this function has a deduced return type and has already been |
3899 | // defined, copy the deduced value from the old declaration. |
3900 | AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); |
3901 | if (OldAT && OldAT->isDeduced()) { |
3902 | QualType DT = OldAT->getDeducedType(); |
3903 | if (DT.isNull()) { |
3904 | New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType())); |
3905 | NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType)); |
3906 | } else { |
3907 | New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT)); |
3908 | NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT)); |
3909 | } |
3910 | } |
3911 | } |
3912 | |
3913 | const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old); |
3914 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New); |
3915 | if (OldMethod && NewMethod) { |
3916 | // Preserve triviality. |
3917 | NewMethod->setTrivial(OldMethod->isTrivial()); |
3918 | |
3919 | // MSVC allows explicit template specialization at class scope: |
3920 | // 2 CXXMethodDecls referring to the same function will be injected. |
3921 | // We don't want a redeclaration error. |
3922 | bool IsClassScopeExplicitSpecialization = |
3923 | OldMethod->isFunctionTemplateSpecialization() && |
3924 | NewMethod->isFunctionTemplateSpecialization(); |
3925 | bool isFriend = NewMethod->getFriendObjectKind(); |
3926 | |
3927 | if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && |
3928 | !IsClassScopeExplicitSpecialization) { |
3929 | // -- Member function declarations with the same name and the |
3930 | // same parameter types cannot be overloaded if any of them |
3931 | // is a static member function declaration. |
3932 | if (OldMethod->isStatic() != NewMethod->isStatic()) { |
3933 | Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member); |
3934 | Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType(); |
3935 | return true; |
3936 | } |
3937 | |
3938 | // C++ [class.mem]p1: |
3939 | // [...] A member shall not be declared twice in the |
3940 | // member-specification, except that a nested class or member |
3941 | // class template can be declared and then later defined. |
3942 | if (!inTemplateInstantiation()) { |
3943 | unsigned NewDiag; |
3944 | if (isa<CXXConstructorDecl>(Val: OldMethod)) |
3945 | NewDiag = diag::err_constructor_redeclared; |
3946 | else if (isa<CXXDestructorDecl>(Val: NewMethod)) |
3947 | NewDiag = diag::err_destructor_redeclared; |
3948 | else if (isa<CXXConversionDecl>(Val: NewMethod)) |
3949 | NewDiag = diag::err_conv_function_redeclared; |
3950 | else |
3951 | NewDiag = diag::err_member_redeclared; |
3952 | |
3953 | Diag(Loc: New->getLocation(), DiagID: NewDiag); |
3954 | } else { |
3955 | Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation) |
3956 | << New << New->getType(); |
3957 | } |
3958 | Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType(); |
3959 | return true; |
3960 | |
3961 | // Complain if this is an explicit declaration of a special |
3962 | // member that was initially declared implicitly. |
3963 | // |
3964 | // As an exception, it's okay to befriend such methods in order |
3965 | // to permit the implicit constructor/destructor/operator calls. |
3966 | } else if (OldMethod->isImplicit()) { |
3967 | if (isFriend) { |
3968 | NewMethod->setImplicit(); |
3969 | } else { |
3970 | Diag(Loc: NewMethod->getLocation(), |
3971 | DiagID: diag::err_definition_of_implicitly_declared_member) |
3972 | << New << llvm::to_underlying(E: getSpecialMember(MD: OldMethod)); |
3973 | return true; |
3974 | } |
3975 | } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { |
3976 | Diag(Loc: NewMethod->getLocation(), |
3977 | DiagID: diag::err_definition_of_explicitly_defaulted_member) |
3978 | << llvm::to_underlying(E: getSpecialMember(MD: OldMethod)); |
3979 | return true; |
3980 | } |
3981 | } |
3982 | |
3983 | // C++1z [over.load]p2 |
3984 | // Certain function declarations cannot be overloaded: |
3985 | // -- Function declarations that differ only in the return type, |
3986 | // the exception specification, or both cannot be overloaded. |
3987 | |
3988 | // Check the exception specifications match. This may recompute the type of |
3989 | // both Old and New if it resolved exception specifications, so grab the |
3990 | // types again after this. Because this updates the type, we do this before |
3991 | // any of the other checks below, which may update the "de facto" NewQType |
3992 | // but do not necessarily update the type of New. |
3993 | if (CheckEquivalentExceptionSpec(Old, New)) |
3994 | return true; |
3995 | |
3996 | // C++11 [dcl.attr.noreturn]p1: |
3997 | // The first declaration of a function shall specify the noreturn |
3998 | // attribute if any declaration of that function specifies the noreturn |
3999 | // attribute. |
4000 | if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) |
4001 | if (!Old->hasAttr<CXX11NoReturnAttr>()) { |
4002 | Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) |
4003 | << NRA; |
4004 | Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration); |
4005 | } |
4006 | |
4007 | // C++11 [dcl.attr.depend]p2: |
4008 | // The first declaration of a function shall specify the |
4009 | // carries_dependency attribute for its declarator-id if any declaration |
4010 | // of the function specifies the carries_dependency attribute. |
4011 | const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); |
4012 | if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { |
4013 | Diag(Loc: CDA->getLocation(), |
4014 | DiagID: diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; |
4015 | Diag(Loc: Old->getFirstDecl()->getLocation(), |
4016 | DiagID: diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; |
4017 | } |
4018 | |
4019 | // (C++98 8.3.5p3): |
4020 | // All declarations for a function shall agree exactly in both the |
4021 | // return type and the parameter-type-list. |
4022 | // We also want to respect all the extended bits except noreturn. |
4023 | |
4024 | // noreturn should now match unless the old type info didn't have it. |
4025 | if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { |
4026 | auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>(); |
4027 | const FunctionType *OldTypeForComparison |
4028 | = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true)); |
4029 | OldQTypeForComparison = QualType(OldTypeForComparison, 0); |
4030 | assert(OldQTypeForComparison.isCanonical()); |
4031 | } |
4032 | |
4033 | if (haveIncompatibleLanguageLinkages(Old, New)) { |
4034 | // As a special case, retain the language linkage from previous |
4035 | // declarations of a friend function as an extension. |
4036 | // |
4037 | // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC |
4038 | // and is useful because there's otherwise no way to specify language |
4039 | // linkage within class scope. |
4040 | // |
4041 | // Check cautiously as the friend object kind isn't yet complete. |
4042 | if (New->getFriendObjectKind() != Decl::FOK_None) { |
4043 | Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New; |
4044 | Diag(Loc: OldLocation, DiagID: PrevDiag); |
4045 | } else { |
4046 | Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New; |
4047 | Diag(Loc: OldLocation, DiagID: PrevDiag); |
4048 | return true; |
4049 | } |
4050 | } |
4051 | |
4052 | // If the function types are compatible, merge the declarations. Ignore the |
4053 | // exception specifier because it was already checked above in |
4054 | // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics |
4055 | // about incompatible types under -fms-compatibility. |
4056 | if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison, |
4057 | U: NewQType)) |
4058 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); |
4059 | |
4060 | // If the types are imprecise (due to dependent constructs in friends or |
4061 | // local extern declarations), it's OK if they differ. We'll check again |
4062 | // during instantiation. |
4063 | if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType)) |
4064 | return false; |
4065 | |
4066 | // Fall through for conflicting redeclarations and redefinitions. |
4067 | } |
4068 | |
4069 | // C: Function types need to be compatible, not identical. This handles |
4070 | // duplicate function decls like "void f(int); void f(enum X);" properly. |
4071 | if (!getLangOpts().CPlusPlus) { |
4072 | // C99 6.7.5.3p15: ...If one type has a parameter type list and the other |
4073 | // type is specified by a function definition that contains a (possibly |
4074 | // empty) identifier list, both shall agree in the number of parameters |
4075 | // and the type of each parameter shall be compatible with the type that |
4076 | // results from the application of default argument promotions to the |
4077 | // type of the corresponding identifier. ... |
4078 | // This cannot be handled by ASTContext::typesAreCompatible() because that |
4079 | // doesn't know whether the function type is for a definition or not when |
4080 | // eventually calling ASTContext::mergeFunctionTypes(). The only situation |
4081 | // we need to cover here is that the number of arguments agree as the |
4082 | // default argument promotion rules were already checked by |
4083 | // ASTContext::typesAreCompatible(). |
4084 | if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn && |
4085 | Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) { |
4086 | if (Old->hasInheritedPrototype()) |
4087 | Old = Old->getCanonicalDecl(); |
4088 | Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New; |
4089 | Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType(); |
4090 | return true; |
4091 | } |
4092 | |
4093 | // If we are merging two functions where only one of them has a prototype, |
4094 | // we may have enough information to decide to issue a diagnostic that the |
4095 | // function without a prototype will change behavior in C23. This handles |
4096 | // cases like: |
4097 | // void i(); void i(int j); |
4098 | // void i(int j); void i(); |
4099 | // void i(); void i(int j) {} |
4100 | // See ActOnFinishFunctionBody() for other cases of the behavior change |
4101 | // diagnostic. See GetFullTypeForDeclarator() for handling of a function |
4102 | // type without a prototype. |
4103 | if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() && |
4104 | !New->isImplicit() && !Old->isImplicit()) { |
4105 | const FunctionDecl *WithProto, *WithoutProto; |
4106 | if (New->hasWrittenPrototype()) { |
4107 | WithProto = New; |
4108 | WithoutProto = Old; |
4109 | } else { |
4110 | WithProto = Old; |
4111 | WithoutProto = New; |
4112 | } |
4113 | |
4114 | if (WithProto->getNumParams() != 0) { |
4115 | if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) { |
4116 | // The one without the prototype will be changing behavior in C23, so |
4117 | // warn about that one so long as it's a user-visible declaration. |
4118 | bool IsWithoutProtoADef = false, IsWithProtoADef = false; |
4119 | if (WithoutProto == New) |
4120 | IsWithoutProtoADef = NewDeclIsDefn; |
4121 | else |
4122 | IsWithProtoADef = NewDeclIsDefn; |
4123 | Diag(Loc: WithoutProto->getLocation(), |
4124 | DiagID: diag::warn_non_prototype_changes_behavior) |
4125 | << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1) |
4126 | << (WithoutProto == Old) << IsWithProtoADef; |
4127 | |
4128 | // The reason the one without the prototype will be changing behavior |
4129 | // is because of the one with the prototype, so note that so long as |
4130 | // it's a user-visible declaration. There is one exception to this: |
4131 | // when the new declaration is a definition without a prototype, the |
4132 | // old declaration with a prototype is not the cause of the issue, |
4133 | // and that does not need to be noted because the one with a |
4134 | // prototype will not change behavior in C23. |
4135 | if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() && |
4136 | !IsWithoutProtoADef) |
4137 | Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype); |
4138 | } |
4139 | } |
4140 | } |
4141 | |
4142 | if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) { |
4143 | const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); |
4144 | const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); |
4145 | const FunctionProtoType *OldProto = nullptr; |
4146 | if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) && |
4147 | (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) { |
4148 | // The old declaration provided a function prototype, but the |
4149 | // new declaration does not. Merge in the prototype. |
4150 | assert(!OldProto->hasExceptionSpec() && "Exception spec in C" ); |
4151 | NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(), |
4152 | Args: OldProto->getParamTypes(), |
4153 | EPI: OldProto->getExtProtoInfo()); |
4154 | New->setType(NewQType); |
4155 | New->setHasInheritedPrototype(); |
4156 | |
4157 | // Synthesize parameters with the same types. |
4158 | SmallVector<ParmVarDecl *, 16> Params; |
4159 | for (const auto &ParamType : OldProto->param_types()) { |
4160 | ParmVarDecl *Param = ParmVarDecl::Create( |
4161 | C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr, |
4162 | T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr); |
4163 | Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size()); |
4164 | Param->setImplicit(); |
4165 | Params.push_back(Elt: Param); |
4166 | } |
4167 | |
4168 | New->setParams(Params); |
4169 | } |
4170 | |
4171 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); |
4172 | } |
4173 | } |
4174 | |
4175 | // Check if the function types are compatible when pointer size address |
4176 | // spaces are ignored. |
4177 | if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType)) |
4178 | return false; |
4179 | |
4180 | // GNU C permits a K&R definition to follow a prototype declaration |
4181 | // if the declared types of the parameters in the K&R definition |
4182 | // match the types in the prototype declaration, even when the |
4183 | // promoted types of the parameters from the K&R definition differ |
4184 | // from the types in the prototype. GCC then keeps the types from |
4185 | // the prototype. |
4186 | // |
4187 | // If a variadic prototype is followed by a non-variadic K&R definition, |
4188 | // the K&R definition becomes variadic. This is sort of an edge case, but |
4189 | // it's legal per the standard depending on how you read C99 6.7.5.3p15 and |
4190 | // C99 6.9.1p8. |
4191 | if (!getLangOpts().CPlusPlus && |
4192 | Old->hasPrototype() && !New->hasPrototype() && |
4193 | New->getType()->getAs<FunctionProtoType>() && |
4194 | Old->getNumParams() == New->getNumParams()) { |
4195 | SmallVector<QualType, 16> ArgTypes; |
4196 | SmallVector<GNUCompatibleParamWarning, 16> Warnings; |
4197 | const FunctionProtoType *OldProto |
4198 | = Old->getType()->getAs<FunctionProtoType>(); |
4199 | const FunctionProtoType *NewProto |
4200 | = New->getType()->getAs<FunctionProtoType>(); |
4201 | |
4202 | // Determine whether this is the GNU C extension. |
4203 | QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), |
4204 | NewProto->getReturnType()); |
4205 | bool LooseCompatible = !MergedReturn.isNull(); |
4206 | for (unsigned Idx = 0, End = Old->getNumParams(); |
4207 | LooseCompatible && Idx != End; ++Idx) { |
4208 | ParmVarDecl *OldParm = Old->getParamDecl(i: Idx); |
4209 | ParmVarDecl *NewParm = New->getParamDecl(i: Idx); |
4210 | if (Context.typesAreCompatible(T1: OldParm->getType(), |
4211 | T2: NewProto->getParamType(i: Idx))) { |
4212 | ArgTypes.push_back(Elt: NewParm->getType()); |
4213 | } else if (Context.typesAreCompatible(T1: OldParm->getType(), |
4214 | T2: NewParm->getType(), |
4215 | /*CompareUnqualified=*/true)) { |
4216 | GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm, |
4217 | .PromotedType: NewProto->getParamType(i: Idx) }; |
4218 | Warnings.push_back(Elt: Warn); |
4219 | ArgTypes.push_back(Elt: NewParm->getType()); |
4220 | } else |
4221 | LooseCompatible = false; |
4222 | } |
4223 | |
4224 | if (LooseCompatible) { |
4225 | for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { |
4226 | Diag(Loc: Warnings[Warn].NewParm->getLocation(), |
4227 | DiagID: diag::ext_param_promoted_not_compatible_with_prototype) |
4228 | << Warnings[Warn].PromotedType |
4229 | << Warnings[Warn].OldParm->getType(); |
4230 | if (Warnings[Warn].OldParm->getLocation().isValid()) |
4231 | Diag(Loc: Warnings[Warn].OldParm->getLocation(), |
4232 | DiagID: diag::note_previous_declaration); |
4233 | } |
4234 | |
4235 | if (MergeTypeWithOld) |
4236 | New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes, |
4237 | EPI: OldProto->getExtProtoInfo())); |
4238 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); |
4239 | } |
4240 | |
4241 | // Fall through to diagnose conflicting types. |
4242 | } |
4243 | |
4244 | // A function that has already been declared has been redeclared or |
4245 | // defined with a different type; show an appropriate diagnostic. |
4246 | |
4247 | // If the previous declaration was an implicitly-generated builtin |
4248 | // declaration, then at the very least we should use a specialized note. |
4249 | unsigned BuiltinID; |
4250 | if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { |
4251 | // If it's actually a library-defined builtin function like 'malloc' |
4252 | // or 'printf', just warn about the incompatible redeclaration. |
4253 | if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) { |
4254 | Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New; |
4255 | Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration) |
4256 | << Old << Old->getType(); |
4257 | return false; |
4258 | } |
4259 | |
4260 | PrevDiag = diag::note_previous_builtin_declaration; |
4261 | } |
4262 | |
4263 | Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName(); |
4264 | Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType(); |
4265 | return true; |
4266 | } |
4267 | |
4268 | bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, |
4269 | Scope *S, bool MergeTypeWithOld) { |
4270 | // Merge the attributes |
4271 | mergeDeclAttributes(New, Old); |
4272 | |
4273 | // Merge "pure" flag. |
4274 | if (Old->isPureVirtual()) |
4275 | New->setIsPureVirtual(); |
4276 | |
4277 | // Merge "used" flag. |
4278 | if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false)) |
4279 | New->setIsUsed(); |
4280 | |
4281 | // Merge attributes from the parameters. These can mismatch with K&R |
4282 | // declarations. |
4283 | if (New->getNumParams() == Old->getNumParams()) |
4284 | for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { |
4285 | ParmVarDecl *NewParam = New->getParamDecl(i); |
4286 | ParmVarDecl *OldParam = Old->getParamDecl(i); |
4287 | mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this); |
4288 | mergeParamDeclTypes(NewParam, OldParam, S&: *this); |
4289 | } |
4290 | |
4291 | if (getLangOpts().CPlusPlus) |
4292 | return MergeCXXFunctionDecl(New, Old, S); |
4293 | |
4294 | // Merge the function types so the we get the composite types for the return |
4295 | // and argument types. Per C11 6.2.7/4, only update the type if the old decl |
4296 | // was visible. |
4297 | QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); |
4298 | if (!Merged.isNull() && MergeTypeWithOld) |
4299 | New->setType(Merged); |
4300 | |
4301 | return false; |
4302 | } |
4303 | |
4304 | void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, |
4305 | ObjCMethodDecl *oldMethod) { |
4306 | // Merge the attributes, including deprecated/unavailable |
4307 | AvailabilityMergeKind MergeKind = |
4308 | isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext()) |
4309 | ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation |
4310 | : AMK_ProtocolImplementation) |
4311 | : isa<ObjCImplDecl>(Val: newMethod->getDeclContext()) ? AMK_Redeclaration |
4312 | : AMK_Override; |
4313 | |
4314 | mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind); |
4315 | |
4316 | // Merge attributes from the parameters. |
4317 | ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), |
4318 | oe = oldMethod->param_end(); |
4319 | for (ObjCMethodDecl::param_iterator |
4320 | ni = newMethod->param_begin(), ne = newMethod->param_end(); |
4321 | ni != ne && oi != oe; ++ni, ++oi) |
4322 | mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this); |
4323 | |
4324 | ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod); |
4325 | } |
4326 | |
4327 | static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { |
4328 | assert(!S.Context.hasSameType(New->getType(), Old->getType())); |
4329 | |
4330 | S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition() |
4331 | ? diag::err_redefinition_different_type |
4332 | : diag::err_redeclaration_different_type) |
4333 | << New->getDeclName() << New->getType() << Old->getType(); |
4334 | |
4335 | diag::kind PrevDiag; |
4336 | SourceLocation OldLocation; |
4337 | std::tie(args&: PrevDiag, args&: OldLocation) |
4338 | = getNoteDiagForInvalidRedeclaration(Old, New); |
4339 | S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType(); |
4340 | New->setInvalidDecl(); |
4341 | } |
4342 | |
4343 | void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, |
4344 | bool MergeTypeWithOld) { |
4345 | if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors()) |
4346 | return; |
4347 | |
4348 | QualType MergedT; |
4349 | if (getLangOpts().CPlusPlus) { |
4350 | if (New->getType()->isUndeducedType()) { |
4351 | // We don't know what the new type is until the initializer is attached. |
4352 | return; |
4353 | } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) { |
4354 | // These could still be something that needs exception specs checked. |
4355 | return MergeVarDeclExceptionSpecs(New, Old); |
4356 | } |
4357 | // C++ [basic.link]p10: |
4358 | // [...] the types specified by all declarations referring to a given |
4359 | // object or function shall be identical, except that declarations for an |
4360 | // array object can specify array types that differ by the presence or |
4361 | // absence of a major array bound (8.3.4). |
4362 | else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { |
4363 | const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType()); |
4364 | const ArrayType *NewArray = Context.getAsArrayType(T: New->getType()); |
4365 | |
4366 | // We are merging a variable declaration New into Old. If it has an array |
4367 | // bound, and that bound differs from Old's bound, we should diagnose the |
4368 | // mismatch. |
4369 | if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { |
4370 | for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; |
4371 | PrevVD = PrevVD->getPreviousDecl()) { |
4372 | QualType PrevVDTy = PrevVD->getType(); |
4373 | if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) |
4374 | continue; |
4375 | |
4376 | if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy)) |
4377 | return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD); |
4378 | } |
4379 | } |
4380 | |
4381 | if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { |
4382 | if (Context.hasSameType(T1: OldArray->getElementType(), |
4383 | T2: NewArray->getElementType())) |
4384 | MergedT = New->getType(); |
4385 | } |
4386 | // FIXME: Check visibility. New is hidden but has a complete type. If New |
4387 | // has no array bound, it should not inherit one from Old, if Old is not |
4388 | // visible. |
4389 | else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { |
4390 | if (Context.hasSameType(T1: OldArray->getElementType(), |
4391 | T2: NewArray->getElementType())) |
4392 | MergedT = Old->getType(); |
4393 | } |
4394 | } |
4395 | else if (New->getType()->isObjCObjectPointerType() && |
4396 | Old->getType()->isObjCObjectPointerType()) { |
4397 | MergedT = Context.mergeObjCGCQualifiers(New->getType(), |
4398 | Old->getType()); |
4399 | } |
4400 | } else { |
4401 | // C 6.2.7p2: |
4402 | // All declarations that refer to the same object or function shall have |
4403 | // compatible type. |
4404 | MergedT = Context.mergeTypes(New->getType(), Old->getType()); |
4405 | } |
4406 | if (MergedT.isNull()) { |
4407 | // It's OK if we couldn't merge types if either type is dependent, for a |
4408 | // block-scope variable. In other cases (static data members of class |
4409 | // templates, variable templates, ...), we require the types to be |
4410 | // equivalent. |
4411 | // FIXME: The C++ standard doesn't say anything about this. |
4412 | if ((New->getType()->isDependentType() || |
4413 | Old->getType()->isDependentType()) && New->isLocalVarDecl()) { |
4414 | // If the old type was dependent, we can't merge with it, so the new type |
4415 | // becomes dependent for now. We'll reproduce the original type when we |
4416 | // instantiate the TypeSourceInfo for the variable. |
4417 | if (!New->getType()->isDependentType() && MergeTypeWithOld) |
4418 | New->setType(Context.DependentTy); |
4419 | return; |
4420 | } |
4421 | return diagnoseVarDeclTypeMismatch(S&: *this, New, Old); |
4422 | } |
4423 | |
4424 | // Don't actually update the type on the new declaration if the old |
4425 | // declaration was an extern declaration in a different scope. |
4426 | if (MergeTypeWithOld) |
4427 | New->setType(MergedT); |
4428 | } |
4429 | |
4430 | static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, |
4431 | LookupResult &Previous) { |
4432 | // C11 6.2.7p4: |
4433 | // For an identifier with internal or external linkage declared |
4434 | // in a scope in which a prior declaration of that identifier is |
4435 | // visible, if the prior declaration specifies internal or |
4436 | // external linkage, the type of the identifier at the later |
4437 | // declaration becomes the composite type. |
4438 | // |
4439 | // If the variable isn't visible, we do not merge with its type. |
4440 | if (Previous.isShadowed()) |
4441 | return false; |
4442 | |
4443 | if (S.getLangOpts().CPlusPlus) { |
4444 | // C++11 [dcl.array]p3: |
4445 | // If there is a preceding declaration of the entity in the same |
4446 | // scope in which the bound was specified, an omitted array bound |
4447 | // is taken to be the same as in that earlier declaration. |
4448 | return NewVD->isPreviousDeclInSameBlockScope() || |
4449 | (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && |
4450 | !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); |
4451 | } else { |
4452 | // If the old declaration was function-local, don't merge with its |
4453 | // type unless we're in the same function. |
4454 | return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || |
4455 | OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); |
4456 | } |
4457 | } |
4458 | |
4459 | void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { |
4460 | // If the new decl is already invalid, don't do any other checking. |
4461 | if (New->isInvalidDecl()) |
4462 | return; |
4463 | |
4464 | if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New)) |
4465 | return; |
4466 | |
4467 | VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); |
4468 | |
4469 | // Verify the old decl was also a variable or variable template. |
4470 | VarDecl *Old = nullptr; |
4471 | VarTemplateDecl *OldTemplate = nullptr; |
4472 | if (Previous.isSingleResult()) { |
4473 | if (NewTemplate) { |
4474 | OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl()); |
4475 | Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; |
4476 | |
4477 | if (auto *Shadow = |
4478 | dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl())) |
4479 | if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate)) |
4480 | return New->setInvalidDecl(); |
4481 | } else { |
4482 | Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl()); |
4483 | |
4484 | if (auto *Shadow = |
4485 | dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl())) |
4486 | if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New)) |
4487 | return New->setInvalidDecl(); |
4488 | } |
4489 | } |
4490 | if (!Old) { |
4491 | Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind) |
4492 | << New->getDeclName(); |
4493 | notePreviousDefinition(Old: Previous.getRepresentativeDecl(), |
4494 | New: New->getLocation()); |
4495 | return New->setInvalidDecl(); |
4496 | } |
4497 | |
4498 | // If the old declaration was found in an inline namespace and the new |
4499 | // declaration was qualified, update the DeclContext to match. |
4500 | adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old); |
4501 | |
4502 | // Ensure the template parameters are compatible. |
4503 | if (NewTemplate && |
4504 | !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(), |
4505 | Old: OldTemplate->getTemplateParameters(), |
4506 | /*Complain=*/true, Kind: TPL_TemplateMatch)) |
4507 | return New->setInvalidDecl(); |
4508 | |
4509 | // C++ [class.mem]p1: |
4510 | // A member shall not be declared twice in the member-specification [...] |
4511 | // |
4512 | // Here, we need only consider static data members. |
4513 | if (Old->isStaticDataMember() && !New->isOutOfLine()) { |
4514 | Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member) |
4515 | << New->getIdentifier(); |
4516 | Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration); |
4517 | New->setInvalidDecl(); |
4518 | } |
4519 | |
4520 | mergeDeclAttributes(New, Old); |
4521 | // Warn if an already-defined variable is made a weak_import in a subsequent |
4522 | // declaration |
4523 | if (New->hasAttr<WeakImportAttr>()) |
4524 | for (auto *D = Old; D; D = D->getPreviousDecl()) { |
4525 | if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) { |
4526 | Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName(); |
4527 | Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition); |
4528 | // Remove weak_import attribute on new declaration. |
4529 | New->dropAttr<WeakImportAttr>(); |
4530 | break; |
4531 | } |
4532 | } |
4533 | |
4534 | if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) |
4535 | if (!Old->hasAttr<InternalLinkageAttr>()) { |
4536 | Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) |
4537 | << ILA; |
4538 | Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration); |
4539 | New->dropAttr<InternalLinkageAttr>(); |
4540 | } |
4541 | |
4542 | // Merge the types. |
4543 | VarDecl *MostRecent = Old->getMostRecentDecl(); |
4544 | if (MostRecent != Old) { |
4545 | MergeVarDeclTypes(New, Old: MostRecent, |
4546 | MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous)); |
4547 | if (New->isInvalidDecl()) |
4548 | return; |
4549 | } |
4550 | |
4551 | MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous)); |
4552 | if (New->isInvalidDecl()) |
4553 | return; |
4554 | |
4555 | diag::kind PrevDiag; |
4556 | SourceLocation OldLocation; |
4557 | std::tie(args&: PrevDiag, args&: OldLocation) = |
4558 | getNoteDiagForInvalidRedeclaration(Old, New); |
4559 | |
4560 | // [dcl.stc]p8: Check if we have a non-static decl followed by a static. |
4561 | if (New->getStorageClass() == SC_Static && |
4562 | !New->isStaticDataMember() && |
4563 | Old->hasExternalFormalLinkage()) { |
4564 | if (getLangOpts().MicrosoftExt) { |
4565 | Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) |
4566 | << New->getDeclName(); |
4567 | Diag(Loc: OldLocation, DiagID: PrevDiag); |
4568 | } else { |
4569 | Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static) |
4570 | << New->getDeclName(); |
4571 | Diag(Loc: OldLocation, DiagID: PrevDiag); |
4572 | return New->setInvalidDecl(); |
4573 | } |
4574 | } |
4575 | // C99 6.2.2p4: |
4576 | // For an identifier declared with the storage-class specifier |
4577 | // extern in a scope in which a prior declaration of that |
4578 | // identifier is visible,23) if the prior declaration specifies |
4579 | // internal or external linkage, the linkage of the identifier at |
4580 | // the later declaration is the same as the linkage specified at |
4581 | // the prior declaration. If no prior declaration is visible, or |
4582 | // if the prior declaration specifies no linkage, then the |
4583 | // identifier has external linkage. |
4584 | if (New->hasExternalStorage() && Old->hasLinkage()) |
4585 | /* Okay */; |
4586 | else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && |
4587 | !New->isStaticDataMember() && |
4588 | Old->getCanonicalDecl()->getStorageClass() == SC_Static) { |
4589 | Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName(); |
4590 | Diag(Loc: OldLocation, DiagID: PrevDiag); |
4591 | return New->setInvalidDecl(); |
4592 | } |
4593 | |
4594 | // Check if extern is followed by non-extern and vice-versa. |
4595 | if (New->hasExternalStorage() && |
4596 | !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { |
4597 | Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName(); |
4598 | Diag(Loc: OldLocation, DiagID: PrevDiag); |
4599 | return New->setInvalidDecl(); |
4600 | } |
4601 | if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && |
4602 | !New->hasExternalStorage()) { |
4603 | Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName(); |
4604 | Diag(Loc: OldLocation, DiagID: PrevDiag); |
4605 | return New->setInvalidDecl(); |
4606 | } |
4607 | |
4608 | if (CheckRedeclarationInModule(New, Old)) |
4609 | return; |
4610 | |
4611 | // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. |
4612 | |
4613 | // FIXME: The test for external storage here seems wrong? We still |
4614 | // need to check for mismatches. |
4615 | if (!New->hasExternalStorage() && !New->isFileVarDecl() && |
4616 | // Don't complain about out-of-line definitions of static members. |
4617 | !(Old->getLexicalDeclContext()->isRecord() && |
4618 | !New->getLexicalDeclContext()->isRecord())) { |
4619 | Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName(); |
4620 | Diag(Loc: OldLocation, DiagID: PrevDiag); |
4621 | return New->setInvalidDecl(); |
4622 | } |
4623 | |
4624 | if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { |
4625 | if (VarDecl *Def = Old->getDefinition()) { |
4626 | // C++1z [dcl.fcn.spec]p4: |
4627 | // If the definition of a variable appears in a translation unit before |
4628 | // its first declaration as inline, the program is ill-formed. |
4629 | Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New; |
4630 | Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition); |
4631 | } |
4632 | } |
4633 | |
4634 | // If this redeclaration makes the variable inline, we may need to add it to |
4635 | // UndefinedButUsed. |
4636 | if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) && |
4637 | !Old->getDefinition() && !New->isThisDeclarationADefinition()) |
4638 | UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(), |
4639 | y: SourceLocation())); |
4640 | |
4641 | if (New->getTLSKind() != Old->getTLSKind()) { |
4642 | if (!Old->getTLSKind()) { |
4643 | Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName(); |
4644 | Diag(Loc: OldLocation, DiagID: PrevDiag); |
4645 | } else if (!New->getTLSKind()) { |
4646 | Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName(); |
4647 | Diag(Loc: OldLocation, DiagID: PrevDiag); |
4648 | } else { |
4649 | // Do not allow redeclaration to change the variable between requiring |
4650 | // static and dynamic initialization. |
4651 | // FIXME: GCC allows this, but uses the TLS keyword on the first |
4652 | // declaration to determine the kind. Do we need to be compatible here? |
4653 | Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind) |
4654 | << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); |
4655 | Diag(Loc: OldLocation, DiagID: PrevDiag); |
4656 | } |
4657 | } |
4658 | |
4659 | // C++ doesn't have tentative definitions, so go right ahead and check here. |
4660 | if (getLangOpts().CPlusPlus) { |
4661 | if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && |
4662 | Old->getCanonicalDecl()->isConstexpr()) { |
4663 | // This definition won't be a definition any more once it's been merged. |
4664 | Diag(Loc: New->getLocation(), |
4665 | DiagID: diag::warn_deprecated_redundant_constexpr_static_def); |
4666 | } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) { |
4667 | VarDecl *Def = Old->getDefinition(); |
4668 | if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New)) |
4669 | return; |
4670 | } |
4671 | } |
4672 | |
4673 | if (haveIncompatibleLanguageLinkages(Old, New)) { |
4674 | Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New; |
4675 | Diag(Loc: OldLocation, DiagID: PrevDiag); |
4676 | New->setInvalidDecl(); |
4677 | return; |
4678 | } |
4679 | |
4680 | // Merge "used" flag. |
4681 | if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false)) |
4682 | New->setIsUsed(); |
4683 | |
4684 | // Keep a chain of previous declarations. |
4685 | New->setPreviousDecl(Old); |
4686 | if (NewTemplate) |
4687 | NewTemplate->setPreviousDecl(OldTemplate); |
4688 | |
4689 | // Inherit access appropriately. |
4690 | New->setAccess(Old->getAccess()); |
4691 | if (NewTemplate) |
4692 | NewTemplate->setAccess(New->getAccess()); |
4693 | |
4694 | if (Old->isInline()) |
4695 | New->setImplicitlyInline(); |
4696 | } |
4697 | |
4698 | void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { |
4699 | SourceManager &SrcMgr = getSourceManager(); |
4700 | auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New); |
4701 | auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation()); |
4702 | auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first); |
4703 | auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first); |
4704 | auto &HSI = PP.getHeaderSearchInfo(); |
4705 | StringRef HdrFilename = |
4706 | SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation())); |
4707 | |
4708 | auto noteFromModuleOrInclude = [&](Module *Mod, |
4709 | SourceLocation IncLoc) -> bool { |
4710 | // Redefinition errors with modules are common with non modular mapped |
4711 | // headers, example: a non-modular header H in module A that also gets |
4712 | // included directly in a TU. Pointing twice to the same header/definition |
4713 | // is confusing, try to get better diagnostics when modules is on. |
4714 | if (IncLoc.isValid()) { |
4715 | if (Mod) { |
4716 | Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file) |
4717 | << HdrFilename.str() << Mod->getFullModuleName(); |
4718 | if (!Mod->DefinitionLoc.isInvalid()) |
4719 | Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here) |
4720 | << Mod->getFullModuleName(); |
4721 | } else { |
4722 | Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file) |
4723 | << HdrFilename.str(); |
4724 | } |
4725 | return true; |
4726 | } |
4727 | |
4728 | return false; |
4729 | }; |
4730 | |
4731 | // Is it the same file and same offset? Provide more information on why |
4732 | // this leads to a redefinition error. |
4733 | if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { |
4734 | SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first); |
4735 | SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first); |
4736 | bool EmittedDiag = |
4737 | noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); |
4738 | EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); |
4739 | |
4740 | // If the header has no guards, emit a note suggesting one. |
4741 | if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld)) |
4742 | Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards); |
4743 | |
4744 | if (EmittedDiag) |
4745 | return; |
4746 | } |
4747 | |
4748 | // Redefinition coming from different files or couldn't do better above. |
4749 | if (Old->getLocation().isValid()) |
4750 | Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition); |
4751 | } |
4752 | |
4753 | bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { |
4754 | if (!hasVisibleDefinition(D: Old) && |
4755 | (New->getFormalLinkage() == Linkage::Internal || New->isInline() || |
4756 | isa<VarTemplateSpecializationDecl>(Val: New) || |
4757 | New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() || |
4758 | New->getDeclContext()->isDependentContext())) { |
4759 | // The previous definition is hidden, and multiple definitions are |
4760 | // permitted (in separate TUs). Demote this to a declaration. |
4761 | New->demoteThisDefinitionToDeclaration(); |
4762 | |
4763 | // Make the canonical definition visible. |
4764 | if (auto *OldTD = Old->getDescribedVarTemplate()) |
4765 | makeMergedDefinitionVisible(ND: OldTD); |
4766 | makeMergedDefinitionVisible(ND: Old); |
4767 | return false; |
4768 | } else { |
4769 | Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New; |
4770 | notePreviousDefinition(Old, New: New->getLocation()); |
4771 | New->setInvalidDecl(); |
4772 | return true; |
4773 | } |
4774 | } |
4775 | |
4776 | Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, |
4777 | DeclSpec &DS, |
4778 | const ParsedAttributesView &DeclAttrs, |
4779 | RecordDecl *&AnonRecord) { |
4780 | return ParsedFreeStandingDeclSpec( |
4781 | S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord); |
4782 | } |
4783 | |
4784 | // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to |
4785 | // disambiguate entities defined in different scopes. |
4786 | // While the VS2015 ABI fixes potential miscompiles, it is also breaks |
4787 | // compatibility. |
4788 | // We will pick our mangling number depending on which version of MSVC is being |
4789 | // targeted. |
4790 | static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { |
4791 | return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) |
4792 | ? S->getMSCurManglingNumber() |
4793 | : S->getMSLastManglingNumber(); |
4794 | } |
4795 | |
4796 | void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { |
4797 | if (!Context.getLangOpts().CPlusPlus) |
4798 | return; |
4799 | |
4800 | if (isa<CXXRecordDecl>(Val: Tag->getParent())) { |
4801 | // If this tag is the direct child of a class, number it if |
4802 | // it is anonymous. |
4803 | if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) |
4804 | return; |
4805 | MangleNumberingContext &MCtx = |
4806 | Context.getManglingNumberContext(DC: Tag->getParent()); |
4807 | Context.setManglingNumber( |
4808 | ND: Tag, Number: MCtx.getManglingNumber( |
4809 | TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope))); |
4810 | return; |
4811 | } |
4812 | |
4813 | // If this tag isn't a direct child of a class, number it if it is local. |
4814 | MangleNumberingContext *MCtx; |
4815 | Decl *ManglingContextDecl; |
4816 | std::tie(args&: MCtx, args&: ManglingContextDecl) = |
4817 | getCurrentMangleNumberContext(DC: Tag->getDeclContext()); |
4818 | if (MCtx) { |
4819 | Context.setManglingNumber( |
4820 | ND: Tag, Number: MCtx->getManglingNumber( |
4821 | TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope))); |
4822 | } |
4823 | } |
4824 | |
4825 | namespace { |
4826 | struct NonCLikeKind { |
4827 | enum { |
4828 | None, |
4829 | BaseClass, |
4830 | DefaultMemberInit, |
4831 | Lambda, |
4832 | Friend, |
4833 | OtherMember, |
4834 | Invalid, |
4835 | } Kind = None; |
4836 | SourceRange Range; |
4837 | |
4838 | explicit operator bool() { return Kind != None; } |
4839 | }; |
4840 | } |
4841 | |
4842 | /// Determine whether a class is C-like, according to the rules of C++ |
4843 | /// [dcl.typedef] for anonymous classes with typedef names for linkage. |
4844 | static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { |
4845 | if (RD->isInvalidDecl()) |
4846 | return {.Kind: NonCLikeKind::Invalid, .Range: {}}; |
4847 | |
4848 | // C++ [dcl.typedef]p9: [P1766R1] |
4849 | // An unnamed class with a typedef name for linkage purposes shall not |
4850 | // |
4851 | // -- have any base classes |
4852 | if (RD->getNumBases()) |
4853 | return {.Kind: NonCLikeKind::BaseClass, |
4854 | .Range: SourceRange(RD->bases_begin()->getBeginLoc(), |
4855 | RD->bases_end()[-1].getEndLoc())}; |
4856 | bool Invalid = false; |
4857 | for (Decl *D : RD->decls()) { |
4858 | // Don't complain about things we already diagnosed. |
4859 | if (D->isInvalidDecl()) { |
4860 | Invalid = true; |
4861 | continue; |
4862 | } |
4863 | |
4864 | // -- have any [...] default member initializers |
4865 | if (auto *FD = dyn_cast<FieldDecl>(Val: D)) { |
4866 | if (FD->hasInClassInitializer()) { |
4867 | auto *Init = FD->getInClassInitializer(); |
4868 | return {.Kind: NonCLikeKind::DefaultMemberInit, |
4869 | .Range: Init ? Init->getSourceRange() : D->getSourceRange()}; |
4870 | } |
4871 | continue; |
4872 | } |
4873 | |
4874 | // FIXME: We don't allow friend declarations. This violates the wording of |
4875 | // P1766, but not the intent. |
4876 | if (isa<FriendDecl>(Val: D)) |
4877 | return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()}; |
4878 | |
4879 | // -- declare any members other than non-static data members, member |
4880 | // enumerations, or member classes, |
4881 | if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) || |
4882 | isa<EnumDecl>(Val: D)) |
4883 | continue; |
4884 | auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D); |
4885 | if (!MemberRD) { |
4886 | if (D->isImplicit()) |
4887 | continue; |
4888 | return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()}; |
4889 | } |
4890 | |
4891 | // -- contain a lambda-expression, |
4892 | if (MemberRD->isLambda()) |
4893 | return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()}; |
4894 | |
4895 | // and all member classes shall also satisfy these requirements |
4896 | // (recursively). |
4897 | if (MemberRD->isThisDeclarationADefinition()) { |
4898 | if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD)) |
4899 | return Kind; |
4900 | } |
4901 | } |
4902 | |
4903 | return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}}; |
4904 | } |
4905 | |
4906 | void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, |
4907 | TypedefNameDecl *NewTD) { |
4908 | if (TagFromDeclSpec->isInvalidDecl()) |
4909 | return; |
4910 | |
4911 | // Do nothing if the tag already has a name for linkage purposes. |
4912 | if (TagFromDeclSpec->hasNameForLinkage()) |
4913 | return; |
4914 | |
4915 | // A well-formed anonymous tag must always be a TagUseKind::Definition. |
4916 | assert(TagFromDeclSpec->isThisDeclarationADefinition()); |
4917 | |
4918 | // The type must match the tag exactly; no qualifiers allowed. |
4919 | if (!Context.hasSameType(T1: NewTD->getUnderlyingType(), |
4920 | T2: Context.getTagDeclType(Decl: TagFromDeclSpec))) { |
4921 | if (getLangOpts().CPlusPlus) |
4922 | Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD); |
4923 | return; |
4924 | } |
4925 | |
4926 | // C++ [dcl.typedef]p9: [P1766R1, applied as DR] |
4927 | // An unnamed class with a typedef name for linkage purposes shall [be |
4928 | // C-like]. |
4929 | // |
4930 | // FIXME: Also diagnose if we've already computed the linkage. That ideally |
4931 | // shouldn't happen, but there are constructs that the language rule doesn't |
4932 | // disallow for which we can't reasonably avoid computing linkage early. |
4933 | const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec); |
4934 | NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) |
4935 | : NonCLikeKind(); |
4936 | bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); |
4937 | if (NonCLike || ChangesLinkage) { |
4938 | if (NonCLike.Kind == NonCLikeKind::Invalid) |
4939 | return; |
4940 | |
4941 | unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; |
4942 | if (ChangesLinkage) { |
4943 | // If the linkage changes, we can't accept this as an extension. |
4944 | if (NonCLike.Kind == NonCLikeKind::None) |
4945 | DiagID = diag::err_typedef_changes_linkage; |
4946 | else |
4947 | DiagID = diag::err_non_c_like_anon_struct_in_typedef; |
4948 | } |
4949 | |
4950 | SourceLocation FixitLoc = |
4951 | getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart()); |
4952 | llvm::SmallString<40> TextToInsert; |
4953 | TextToInsert += ' '; |
4954 | TextToInsert += NewTD->getIdentifier()->getName(); |
4955 | |
4956 | Diag(Loc: FixitLoc, DiagID) |
4957 | << isa<TypeAliasDecl>(Val: NewTD) |
4958 | << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert); |
4959 | if (NonCLike.Kind != NonCLikeKind::None) { |
4960 | Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct) |
4961 | << NonCLike.Kind - 1 << NonCLike.Range; |
4962 | } |
4963 | Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here) |
4964 | << NewTD << isa<TypeAliasDecl>(Val: NewTD); |
4965 | |
4966 | if (ChangesLinkage) |
4967 | return; |
4968 | } |
4969 | |
4970 | // Otherwise, set this as the anon-decl typedef for the tag. |
4971 | TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); |
4972 | } |
4973 | |
4974 | static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) { |
4975 | DeclSpec::TST T = DS.getTypeSpecType(); |
4976 | switch (T) { |
4977 | case DeclSpec::TST_class: |
4978 | return 0; |
4979 | case DeclSpec::TST_struct: |
4980 | return 1; |
4981 | case DeclSpec::TST_interface: |
4982 | return 2; |
4983 | case DeclSpec::TST_union: |
4984 | return 3; |
4985 | case DeclSpec::TST_enum: |
4986 | if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) { |
4987 | if (ED->isScopedUsingClassTag()) |
4988 | return 5; |
4989 | if (ED->isScoped()) |
4990 | return 6; |
4991 | } |
4992 | return 4; |
4993 | default: |
4994 | llvm_unreachable("unexpected type specifier" ); |
4995 | } |
4996 | } |
4997 | |
4998 | Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, |
4999 | DeclSpec &DS, |
5000 | const ParsedAttributesView &DeclAttrs, |
5001 | MultiTemplateParamsArg TemplateParams, |
5002 | bool IsExplicitInstantiation, |
5003 | RecordDecl *&AnonRecord) { |
5004 | Decl *TagD = nullptr; |
5005 | TagDecl *Tag = nullptr; |
5006 | if (DS.getTypeSpecType() == DeclSpec::TST_class || |
5007 | DS.getTypeSpecType() == DeclSpec::TST_struct || |
5008 | DS.getTypeSpecType() == DeclSpec::TST_interface || |
5009 | DS.getTypeSpecType() == DeclSpec::TST_union || |
5010 | DS.getTypeSpecType() == DeclSpec::TST_enum) { |
5011 | TagD = DS.getRepAsDecl(); |
5012 | |
5013 | if (!TagD) // We probably had an error |
5014 | return nullptr; |
5015 | |
5016 | // Note that the above type specs guarantee that the |
5017 | // type rep is a Decl, whereas in many of the others |
5018 | // it's a Type. |
5019 | if (isa<TagDecl>(Val: TagD)) |
5020 | Tag = cast<TagDecl>(Val: TagD); |
5021 | else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD)) |
5022 | Tag = CTD->getTemplatedDecl(); |
5023 | } |
5024 | |
5025 | if (Tag) { |
5026 | handleTagNumbering(Tag, TagScope: S); |
5027 | Tag->setFreeStanding(); |
5028 | if (Tag->isInvalidDecl()) |
5029 | return Tag; |
5030 | } |
5031 | |
5032 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { |
5033 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from object |
5034 | // or incomplete types shall not be restrict-qualified." |
5035 | if (TypeQuals & DeclSpec::TQ_restrict) |
5036 | Diag(Loc: DS.getRestrictSpecLoc(), |
5037 | DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg) |
5038 | << DS.getSourceRange(); |
5039 | } |
5040 | |
5041 | if (DS.isInlineSpecified()) |
5042 | Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function) |
5043 | << getLangOpts().CPlusPlus17; |
5044 | |
5045 | if (DS.hasConstexprSpecifier()) { |
5046 | // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations |
5047 | // and definitions of functions and variables. |
5048 | // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to |
5049 | // the declaration of a function or function template |
5050 | if (Tag) |
5051 | Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag) |
5052 | << GetDiagnosticTypeSpecifierID(DS) |
5053 | << static_cast<int>(DS.getConstexprSpecifier()); |
5054 | else if (getLangOpts().C23) |
5055 | Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable); |
5056 | else |
5057 | Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind) |
5058 | << static_cast<int>(DS.getConstexprSpecifier()); |
5059 | // Don't emit warnings after this error. |
5060 | return TagD; |
5061 | } |
5062 | |
5063 | DiagnoseFunctionSpecifiers(DS); |
5064 | |
5065 | if (DS.isFriendSpecified()) { |
5066 | // If we're dealing with a decl but not a TagDecl, assume that |
5067 | // whatever routines created it handled the friendship aspect. |
5068 | if (TagD && !Tag) |
5069 | return nullptr; |
5070 | return ActOnFriendTypeDecl(S, DS, TemplateParams); |
5071 | } |
5072 | |
5073 | // Track whether this decl-specifier declares anything. |
5074 | bool DeclaresAnything = true; |
5075 | |
5076 | // Handle anonymous struct definitions. |
5077 | if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) { |
5078 | if (!Record->getDeclName() && Record->isCompleteDefinition() && |
5079 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { |
5080 | if (getLangOpts().CPlusPlus || |
5081 | Record->getDeclContext()->isRecord()) { |
5082 | // If CurContext is a DeclContext that can contain statements, |
5083 | // RecursiveASTVisitor won't visit the decls that |
5084 | // BuildAnonymousStructOrUnion() will put into CurContext. |
5085 | // Also store them here so that they can be part of the |
5086 | // DeclStmt that gets created in this case. |
5087 | // FIXME: Also return the IndirectFieldDecls created by |
5088 | // BuildAnonymousStructOr union, for the same reason? |
5089 | if (CurContext->isFunctionOrMethod()) |
5090 | AnonRecord = Record; |
5091 | return BuildAnonymousStructOrUnion(S, DS, AS, Record, |
5092 | Policy: Context.getPrintingPolicy()); |
5093 | } |
5094 | |
5095 | DeclaresAnything = false; |
5096 | } |
5097 | } |
5098 | |
5099 | // C11 6.7.2.1p2: |
5100 | // A struct-declaration that does not declare an anonymous structure or |
5101 | // anonymous union shall contain a struct-declarator-list. |
5102 | // |
5103 | // This rule also existed in C89 and C99; the grammar for struct-declaration |
5104 | // did not permit a struct-declaration without a struct-declarator-list. |
5105 | if (!getLangOpts().CPlusPlus && CurContext->isRecord() && |
5106 | DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { |
5107 | // Check for Microsoft C extension: anonymous struct/union member. |
5108 | // Handle 2 kinds of anonymous struct/union: |
5109 | // struct STRUCT; |
5110 | // union UNION; |
5111 | // and |
5112 | // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. |
5113 | // UNION_TYPE; <- where UNION_TYPE is a typedef union. |
5114 | if ((Tag && Tag->getDeclName()) || |
5115 | DS.getTypeSpecType() == DeclSpec::TST_typename) { |
5116 | RecordDecl *Record = nullptr; |
5117 | if (Tag) |
5118 | Record = dyn_cast<RecordDecl>(Val: Tag); |
5119 | else if (const RecordType *RT = |
5120 | DS.getRepAsType().get()->getAsStructureType()) |
5121 | Record = RT->getDecl(); |
5122 | else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) |
5123 | Record = UT->getDecl(); |
5124 | |
5125 | if (Record && getLangOpts().MicrosoftExt) { |
5126 | Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record) |
5127 | << Record->isUnion() << DS.getSourceRange(); |
5128 | return BuildMicrosoftCAnonymousStruct(S, DS, Record); |
5129 | } |
5130 | |
5131 | DeclaresAnything = false; |
5132 | } |
5133 | } |
5134 | |
5135 | // Skip all the checks below if we have a type error. |
5136 | if (DS.getTypeSpecType() == DeclSpec::TST_error || |
5137 | (TagD && TagD->isInvalidDecl())) |
5138 | return TagD; |
5139 | |
5140 | if (getLangOpts().CPlusPlus && |
5141 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) |
5142 | if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag)) |
5143 | if (Enum->enumerator_begin() == Enum->enumerator_end() && |
5144 | !Enum->getIdentifier() && !Enum->isInvalidDecl()) |
5145 | DeclaresAnything = false; |
5146 | |
5147 | if (!DS.isMissingDeclaratorOk()) { |
5148 | // Customize diagnostic for a typedef missing a name. |
5149 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) |
5150 | Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name) |
5151 | << DS.getSourceRange(); |
5152 | else |
5153 | DeclaresAnything = false; |
5154 | } |
5155 | |
5156 | if (DS.isModulePrivateSpecified() && |
5157 | Tag && Tag->getDeclContext()->isFunctionOrMethod()) |
5158 | Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class) |
5159 | << llvm::to_underlying(E: Tag->getTagKind()) |
5160 | << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc()); |
5161 | |
5162 | ActOnDocumentableDecl(D: TagD); |
5163 | |
5164 | // C 6.7/2: |
5165 | // A declaration [...] shall declare at least a declarator [...], a tag, |
5166 | // or the members of an enumeration. |
5167 | // C++ [dcl.dcl]p3: |
5168 | // [If there are no declarators], and except for the declaration of an |
5169 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more |
5170 | // names into the program, or shall redeclare a name introduced by a |
5171 | // previous declaration. |
5172 | if (!DeclaresAnything) { |
5173 | // In C, we allow this as a (popular) extension / bug. Don't bother |
5174 | // producing further diagnostics for redundant qualifiers after this. |
5175 | Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty()) |
5176 | ? diag::err_no_declarators |
5177 | : diag::ext_no_declarators) |
5178 | << DS.getSourceRange(); |
5179 | return TagD; |
5180 | } |
5181 | |
5182 | // C++ [dcl.stc]p1: |
5183 | // If a storage-class-specifier appears in a decl-specifier-seq, [...] the |
5184 | // init-declarator-list of the declaration shall not be empty. |
5185 | // C++ [dcl.fct.spec]p1: |
5186 | // If a cv-qualifier appears in a decl-specifier-seq, the |
5187 | // init-declarator-list of the declaration shall not be empty. |
5188 | // |
5189 | // Spurious qualifiers here appear to be valid in C. |
5190 | unsigned DiagID = diag::warn_standalone_specifier; |
5191 | if (getLangOpts().CPlusPlus) |
5192 | DiagID = diag::ext_standalone_specifier; |
5193 | |
5194 | // Note that a linkage-specification sets a storage class, but |
5195 | // 'extern "C" struct foo;' is actually valid and not theoretically |
5196 | // useless. |
5197 | if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { |
5198 | if (SCS == DeclSpec::SCS_mutable) |
5199 | // Since mutable is not a viable storage class specifier in C, there is |
5200 | // no reason to treat it as an extension. Instead, diagnose as an error. |
5201 | Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember); |
5202 | else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) |
5203 | Diag(Loc: DS.getStorageClassSpecLoc(), DiagID) |
5204 | << DeclSpec::getSpecifierName(S: SCS); |
5205 | } |
5206 | |
5207 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) |
5208 | Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID) |
5209 | << DeclSpec::getSpecifierName(S: TSCS); |
5210 | if (DS.getTypeQualifiers()) { |
5211 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) |
5212 | Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const" ; |
5213 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) |
5214 | Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile" ; |
5215 | // Restrict is covered above. |
5216 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) |
5217 | Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic" ; |
5218 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) |
5219 | Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned" ; |
5220 | } |
5221 | |
5222 | // Warn about ignored type attributes, for example: |
5223 | // __attribute__((aligned)) struct A; |
5224 | // Attributes should be placed after tag to apply to type declaration. |
5225 | if (!DS.getAttributes().empty() || !DeclAttrs.empty()) { |
5226 | DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); |
5227 | if (TypeSpecType == DeclSpec::TST_class || |
5228 | TypeSpecType == DeclSpec::TST_struct || |
5229 | TypeSpecType == DeclSpec::TST_interface || |
5230 | TypeSpecType == DeclSpec::TST_union || |
5231 | TypeSpecType == DeclSpec::TST_enum) { |
5232 | |
5233 | auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) { |
5234 | unsigned DiagnosticId = diag::warn_declspec_attribute_ignored; |
5235 | if (AL.isAlignas() && !getLangOpts().CPlusPlus) |
5236 | DiagnosticId = diag::warn_attribute_ignored; |
5237 | else if (AL.isRegularKeywordAttribute()) |
5238 | DiagnosticId = diag::err_declspec_keyword_has_no_effect; |
5239 | else |
5240 | DiagnosticId = diag::warn_declspec_attribute_ignored; |
5241 | Diag(Loc: AL.getLoc(), DiagID: DiagnosticId) |
5242 | << AL << GetDiagnosticTypeSpecifierID(DS); |
5243 | }; |
5244 | |
5245 | llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic); |
5246 | llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic); |
5247 | } |
5248 | } |
5249 | |
5250 | return TagD; |
5251 | } |
5252 | |
5253 | /// We are trying to inject an anonymous member into the given scope; |
5254 | /// check if there's an existing declaration that can't be overloaded. |
5255 | /// |
5256 | /// \return true if this is a forbidden redeclaration |
5257 | static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, |
5258 | DeclContext *Owner, |
5259 | DeclarationName Name, |
5260 | SourceLocation NameLoc, bool IsUnion, |
5261 | StorageClass SC) { |
5262 | LookupResult R(SemaRef, Name, NameLoc, |
5263 | Owner->isRecord() ? Sema::LookupMemberName |
5264 | : Sema::LookupOrdinaryName, |
5265 | RedeclarationKind::ForVisibleRedeclaration); |
5266 | if (!SemaRef.LookupName(R, S)) return false; |
5267 | |
5268 | // Pick a representative declaration. |
5269 | NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); |
5270 | assert(PrevDecl && "Expected a non-null Decl" ); |
5271 | |
5272 | if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S)) |
5273 | return false; |
5274 | |
5275 | if (SC == StorageClass::SC_None && |
5276 | PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) && |
5277 | (Owner->isFunctionOrMethod() || Owner->isRecord())) { |
5278 | if (!Owner->isRecord()) |
5279 | SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc); |
5280 | return false; |
5281 | } |
5282 | |
5283 | SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl) |
5284 | << IsUnion << Name; |
5285 | SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration); |
5286 | |
5287 | return true; |
5288 | } |
5289 | |
5290 | void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) { |
5291 | if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D)) |
5292 | DiagPlaceholderFieldDeclDefinitions(Record: RD); |
5293 | } |
5294 | |
5295 | void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) { |
5296 | if (!getLangOpts().CPlusPlus) |
5297 | return; |
5298 | |
5299 | // This function can be parsed before we have validated the |
5300 | // structure as an anonymous struct |
5301 | if (Record->isAnonymousStructOrUnion()) |
5302 | return; |
5303 | |
5304 | const NamedDecl *First = 0; |
5305 | for (const Decl *D : Record->decls()) { |
5306 | const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D); |
5307 | if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts())) |
5308 | continue; |
5309 | if (!First) |
5310 | First = ND; |
5311 | else |
5312 | DiagPlaceholderVariableDefinition(Loc: ND->getLocation()); |
5313 | } |
5314 | } |
5315 | |
5316 | /// InjectAnonymousStructOrUnionMembers - Inject the members of the |
5317 | /// anonymous struct or union AnonRecord into the owning context Owner |
5318 | /// and scope S. This routine will be invoked just after we realize |
5319 | /// that an unnamed union or struct is actually an anonymous union or |
5320 | /// struct, e.g., |
5321 | /// |
5322 | /// @code |
5323 | /// union { |
5324 | /// int i; |
5325 | /// float f; |
5326 | /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and |
5327 | /// // f into the surrounding scope.x |
5328 | /// @endcode |
5329 | /// |
5330 | /// This routine is recursive, injecting the names of nested anonymous |
5331 | /// structs/unions into the owning context and scope as well. |
5332 | static bool |
5333 | InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, |
5334 | RecordDecl *AnonRecord, AccessSpecifier AS, |
5335 | StorageClass SC, |
5336 | SmallVectorImpl<NamedDecl *> &Chaining) { |
5337 | bool Invalid = false; |
5338 | |
5339 | // Look every FieldDecl and IndirectFieldDecl with a name. |
5340 | for (auto *D : AnonRecord->decls()) { |
5341 | if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) && |
5342 | cast<NamedDecl>(Val: D)->getDeclName()) { |
5343 | ValueDecl *VD = cast<ValueDecl>(Val: D); |
5344 | if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, Name: VD->getDeclName(), |
5345 | NameLoc: VD->getLocation(), IsUnion: AnonRecord->isUnion(), |
5346 | SC)) { |
5347 | // C++ [class.union]p2: |
5348 | // The names of the members of an anonymous union shall be |
5349 | // distinct from the names of any other entity in the |
5350 | // scope in which the anonymous union is declared. |
5351 | Invalid = true; |
5352 | } else { |
5353 | // C++ [class.union]p2: |
5354 | // For the purpose of name lookup, after the anonymous union |
5355 | // definition, the members of the anonymous union are |
5356 | // considered to have been defined in the scope in which the |
5357 | // anonymous union is declared. |
5358 | unsigned OldChainingSize = Chaining.size(); |
5359 | if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD)) |
5360 | Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end()); |
5361 | else |
5362 | Chaining.push_back(Elt: VD); |
5363 | |
5364 | assert(Chaining.size() >= 2); |
5365 | NamedDecl **NamedChain = |
5366 | new (SemaRef.Context)NamedDecl*[Chaining.size()]; |
5367 | for (unsigned i = 0; i < Chaining.size(); i++) |
5368 | NamedChain[i] = Chaining[i]; |
5369 | |
5370 | IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( |
5371 | C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(), |
5372 | T: VD->getType(), CH: {NamedChain, Chaining.size()}); |
5373 | |
5374 | for (const auto *Attr : VD->attrs()) |
5375 | IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context)); |
5376 | |
5377 | IndirectField->setAccess(AS); |
5378 | IndirectField->setImplicit(); |
5379 | SemaRef.PushOnScopeChains(D: IndirectField, S); |
5380 | |
5381 | // That includes picking up the appropriate access specifier. |
5382 | if (AS != AS_none) IndirectField->setAccess(AS); |
5383 | |
5384 | Chaining.resize(N: OldChainingSize); |
5385 | } |
5386 | } |
5387 | } |
5388 | |
5389 | return Invalid; |
5390 | } |
5391 | |
5392 | /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to |
5393 | /// a VarDecl::StorageClass. Any error reporting is up to the caller: |
5394 | /// illegal input values are mapped to SC_None. |
5395 | static StorageClass |
5396 | StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { |
5397 | DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); |
5398 | assert(StorageClassSpec != DeclSpec::SCS_typedef && |
5399 | "Parser allowed 'typedef' as storage class VarDecl." ); |
5400 | switch (StorageClassSpec) { |
5401 | case DeclSpec::SCS_unspecified: return SC_None; |
5402 | case DeclSpec::SCS_extern: |
5403 | if (DS.isExternInLinkageSpec()) |
5404 | return SC_None; |
5405 | return SC_Extern; |
5406 | case DeclSpec::SCS_static: return SC_Static; |
5407 | case DeclSpec::SCS_auto: return SC_Auto; |
5408 | case DeclSpec::SCS_register: return SC_Register; |
5409 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; |
5410 | // Illegal SCSs map to None: error reporting is up to the caller. |
5411 | case DeclSpec::SCS_mutable: // Fall through. |
5412 | case DeclSpec::SCS_typedef: return SC_None; |
5413 | } |
5414 | llvm_unreachable("unknown storage class specifier" ); |
5415 | } |
5416 | |
5417 | static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { |
5418 | assert(Record->hasInClassInitializer()); |
5419 | |
5420 | for (const auto *I : Record->decls()) { |
5421 | const auto *FD = dyn_cast<FieldDecl>(Val: I); |
5422 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I)) |
5423 | FD = IFD->getAnonField(); |
5424 | if (FD && FD->hasInClassInitializer()) |
5425 | return FD->getLocation(); |
5426 | } |
5427 | |
5428 | llvm_unreachable("couldn't find in-class initializer" ); |
5429 | } |
5430 | |
5431 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, |
5432 | SourceLocation DefaultInitLoc) { |
5433 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) |
5434 | return; |
5435 | |
5436 | S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization); |
5437 | S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0; |
5438 | } |
5439 | |
5440 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, |
5441 | CXXRecordDecl *AnonUnion) { |
5442 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) |
5443 | return; |
5444 | |
5445 | checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion)); |
5446 | } |
5447 | |
5448 | Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, |
5449 | AccessSpecifier AS, |
5450 | RecordDecl *Record, |
5451 | const PrintingPolicy &Policy) { |
5452 | DeclContext *Owner = Record->getDeclContext(); |
5453 | |
5454 | // Diagnose whether this anonymous struct/union is an extension. |
5455 | if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) |
5456 | Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union); |
5457 | else if (!Record->isUnion() && getLangOpts().CPlusPlus) |
5458 | Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct); |
5459 | else if (!Record->isUnion() && !getLangOpts().C11) |
5460 | Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct); |
5461 | |
5462 | // C and C++ require different kinds of checks for anonymous |
5463 | // structs/unions. |
5464 | bool Invalid = false; |
5465 | if (getLangOpts().CPlusPlus) { |
5466 | const char *PrevSpec = nullptr; |
5467 | if (Record->isUnion()) { |
5468 | // C++ [class.union]p6: |
5469 | // C++17 [class.union.anon]p2: |
5470 | // Anonymous unions declared in a named namespace or in the |
5471 | // global namespace shall be declared static. |
5472 | unsigned DiagID; |
5473 | DeclContext *OwnerScope = Owner->getRedeclContext(); |
5474 | if (DS.getStorageClassSpec() != DeclSpec::SCS_static && |
5475 | (OwnerScope->isTranslationUnit() || |
5476 | (OwnerScope->isNamespace() && |
5477 | !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) { |
5478 | Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static) |
5479 | << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static " ); |
5480 | |
5481 | // Recover by adding 'static'. |
5482 | DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(), |
5483 | PrevSpec, DiagID, Policy); |
5484 | } |
5485 | // C++ [class.union]p6: |
5486 | // A storage class is not allowed in a declaration of an |
5487 | // anonymous union in a class scope. |
5488 | else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && |
5489 | isa<RecordDecl>(Val: Owner)) { |
5490 | Diag(Loc: DS.getStorageClassSpecLoc(), |
5491 | DiagID: diag::err_anonymous_union_with_storage_spec) |
5492 | << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc()); |
5493 | |
5494 | // Recover by removing the storage specifier. |
5495 | DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified, |
5496 | Loc: SourceLocation(), |
5497 | PrevSpec, DiagID, Policy: Context.getPrintingPolicy()); |
5498 | } |
5499 | } |
5500 | |
5501 | // Ignore const/volatile/restrict qualifiers. |
5502 | if (DS.getTypeQualifiers()) { |
5503 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) |
5504 | Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified) |
5505 | << Record->isUnion() << "const" |
5506 | << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc()); |
5507 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) |
5508 | Diag(Loc: DS.getVolatileSpecLoc(), |
5509 | DiagID: diag::ext_anonymous_struct_union_qualified) |
5510 | << Record->isUnion() << "volatile" |
5511 | << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc()); |
5512 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) |
5513 | Diag(Loc: DS.getRestrictSpecLoc(), |
5514 | DiagID: diag::ext_anonymous_struct_union_qualified) |
5515 | << Record->isUnion() << "restrict" |
5516 | << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc()); |
5517 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) |
5518 | Diag(Loc: DS.getAtomicSpecLoc(), |
5519 | DiagID: diag::ext_anonymous_struct_union_qualified) |
5520 | << Record->isUnion() << "_Atomic" |
5521 | << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc()); |
5522 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) |
5523 | Diag(Loc: DS.getUnalignedSpecLoc(), |
5524 | DiagID: diag::ext_anonymous_struct_union_qualified) |
5525 | << Record->isUnion() << "__unaligned" |
5526 | << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc()); |
5527 | |
5528 | DS.ClearTypeQualifiers(); |
5529 | } |
5530 | |
5531 | // C++ [class.union]p2: |
5532 | // The member-specification of an anonymous union shall only |
5533 | // define non-static data members. [Note: nested types and |
5534 | // functions cannot be declared within an anonymous union. ] |
5535 | for (auto *Mem : Record->decls()) { |
5536 | // Ignore invalid declarations; we already diagnosed them. |
5537 | if (Mem->isInvalidDecl()) |
5538 | continue; |
5539 | |
5540 | if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) { |
5541 | // C++ [class.union]p3: |
5542 | // An anonymous union shall not have private or protected |
5543 | // members (clause 11). |
5544 | assert(FD->getAccess() != AS_none); |
5545 | if (FD->getAccess() != AS_public) { |
5546 | Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member) |
5547 | << Record->isUnion() << (FD->getAccess() == AS_protected); |
5548 | Invalid = true; |
5549 | } |
5550 | |
5551 | // C++ [class.union]p1 |
5552 | // An object of a class with a non-trivial constructor, a non-trivial |
5553 | // copy constructor, a non-trivial destructor, or a non-trivial copy |
5554 | // assignment operator cannot be a member of a union, nor can an |
5555 | // array of such objects. |
5556 | if (CheckNontrivialField(FD)) |
5557 | Invalid = true; |
5558 | } else if (Mem->isImplicit()) { |
5559 | // Any implicit members are fine. |
5560 | } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) { |
5561 | // This is a type that showed up in an |
5562 | // elaborated-type-specifier inside the anonymous struct or |
5563 | // union, but which actually declares a type outside of the |
5564 | // anonymous struct or union. It's okay. |
5565 | } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) { |
5566 | if (!MemRecord->isAnonymousStructOrUnion() && |
5567 | MemRecord->getDeclName()) { |
5568 | // Visual C++ allows type definition in anonymous struct or union. |
5569 | if (getLangOpts().MicrosoftExt) |
5570 | Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type) |
5571 | << Record->isUnion(); |
5572 | else { |
5573 | // This is a nested type declaration. |
5574 | Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type) |
5575 | << Record->isUnion(); |
5576 | Invalid = true; |
5577 | } |
5578 | } else { |
5579 | // This is an anonymous type definition within another anonymous type. |
5580 | // This is a popular extension, provided by Plan9, MSVC and GCC, but |
5581 | // not part of standard C++. |
5582 | Diag(Loc: MemRecord->getLocation(), |
5583 | DiagID: diag::ext_anonymous_record_with_anonymous_type) |
5584 | << Record->isUnion(); |
5585 | } |
5586 | } else if (isa<AccessSpecDecl>(Val: Mem)) { |
5587 | // Any access specifier is fine. |
5588 | } else if (isa<StaticAssertDecl>(Val: Mem)) { |
5589 | // In C++1z, static_assert declarations are also fine. |
5590 | } else { |
5591 | // We have something that isn't a non-static data |
5592 | // member. Complain about it. |
5593 | unsigned DK = diag::err_anonymous_record_bad_member; |
5594 | if (isa<TypeDecl>(Val: Mem)) |
5595 | DK = diag::err_anonymous_record_with_type; |
5596 | else if (isa<FunctionDecl>(Val: Mem)) |
5597 | DK = diag::err_anonymous_record_with_function; |
5598 | else if (isa<VarDecl>(Val: Mem)) |
5599 | DK = diag::err_anonymous_record_with_static; |
5600 | |
5601 | // Visual C++ allows type definition in anonymous struct or union. |
5602 | if (getLangOpts().MicrosoftExt && |
5603 | DK == diag::err_anonymous_record_with_type) |
5604 | Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type) |
5605 | << Record->isUnion(); |
5606 | else { |
5607 | Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion(); |
5608 | Invalid = true; |
5609 | } |
5610 | } |
5611 | } |
5612 | |
5613 | // C++11 [class.union]p8 (DR1460): |
5614 | // At most one variant member of a union may have a |
5615 | // brace-or-equal-initializer. |
5616 | if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() && |
5617 | Owner->isRecord()) |
5618 | checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner), |
5619 | AnonUnion: cast<CXXRecordDecl>(Val: Record)); |
5620 | } |
5621 | |
5622 | if (!Record->isUnion() && !Owner->isRecord()) { |
5623 | Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member) |
5624 | << getLangOpts().CPlusPlus; |
5625 | Invalid = true; |
5626 | } |
5627 | |
5628 | // C++ [dcl.dcl]p3: |
5629 | // [If there are no declarators], and except for the declaration of an |
5630 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more |
5631 | // names into the program |
5632 | // C++ [class.mem]p2: |
5633 | // each such member-declaration shall either declare at least one member |
5634 | // name of the class or declare at least one unnamed bit-field |
5635 | // |
5636 | // For C this is an error even for a named struct, and is diagnosed elsewhere. |
5637 | if (getLangOpts().CPlusPlus && Record->field_empty()) |
5638 | Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange(); |
5639 | |
5640 | // Mock up a declarator. |
5641 | Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member); |
5642 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); |
5643 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc); |
5644 | assert(TInfo && "couldn't build declarator info for anonymous struct/union" ); |
5645 | |
5646 | // Create a declaration for this anonymous struct/union. |
5647 | NamedDecl *Anon = nullptr; |
5648 | if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) { |
5649 | Anon = FieldDecl::Create( |
5650 | C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(), |
5651 | /*IdentifierInfo=*/Id: nullptr, T: Context.getTypeDeclType(Decl: Record), TInfo, |
5652 | /*BitWidth=*/BW: nullptr, /*Mutable=*/false, |
5653 | /*InitStyle=*/ICIS_NoInit); |
5654 | Anon->setAccess(AS); |
5655 | ProcessDeclAttributes(S, D: Anon, PD: Dc); |
5656 | |
5657 | if (getLangOpts().CPlusPlus) |
5658 | FieldCollector->Add(D: cast<FieldDecl>(Val: Anon)); |
5659 | } else { |
5660 | DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); |
5661 | if (SCSpec == DeclSpec::SCS_mutable) { |
5662 | // mutable can only appear on non-static class members, so it's always |
5663 | // an error here |
5664 | Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember); |
5665 | Invalid = true; |
5666 | SC = SC_None; |
5667 | } |
5668 | |
5669 | Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(), |
5670 | IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr, |
5671 | T: Context.getTypeDeclType(Decl: Record), TInfo, S: SC); |
5672 | if (Invalid) |
5673 | Anon->setInvalidDecl(); |
5674 | |
5675 | ProcessDeclAttributes(S, D: Anon, PD: Dc); |
5676 | |
5677 | // Default-initialize the implicit variable. This initialization will be |
5678 | // trivial in almost all cases, except if a union member has an in-class |
5679 | // initializer: |
5680 | // union { int n = 0; }; |
5681 | ActOnUninitializedDecl(dcl: Anon); |
5682 | } |
5683 | Anon->setImplicit(); |
5684 | |
5685 | // Mark this as an anonymous struct/union type. |
5686 | Record->setAnonymousStructOrUnion(true); |
5687 | |
5688 | // Add the anonymous struct/union object to the current |
5689 | // context. We'll be referencing this object when we refer to one of |
5690 | // its members. |
5691 | Owner->addDecl(D: Anon); |
5692 | |
5693 | // Inject the members of the anonymous struct/union into the owning |
5694 | // context and into the identifier resolver chain for name lookup |
5695 | // purposes. |
5696 | SmallVector<NamedDecl*, 2> Chain; |
5697 | Chain.push_back(Elt: Anon); |
5698 | |
5699 | if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC, |
5700 | Chaining&: Chain)) |
5701 | Invalid = true; |
5702 | |
5703 | if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) { |
5704 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { |
5705 | MangleNumberingContext *MCtx; |
5706 | Decl *ManglingContextDecl; |
5707 | std::tie(args&: MCtx, args&: ManglingContextDecl) = |
5708 | getCurrentMangleNumberContext(DC: NewVD->getDeclContext()); |
5709 | if (MCtx) { |
5710 | Context.setManglingNumber( |
5711 | ND: NewVD, Number: MCtx->getManglingNumber( |
5712 | VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S))); |
5713 | Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD)); |
5714 | } |
5715 | } |
5716 | } |
5717 | |
5718 | if (Invalid) |
5719 | Anon->setInvalidDecl(); |
5720 | |
5721 | return Anon; |
5722 | } |
5723 | |
5724 | Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, |
5725 | RecordDecl *Record) { |
5726 | assert(Record && "expected a record!" ); |
5727 | |
5728 | // Mock up a declarator. |
5729 | Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName); |
5730 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc); |
5731 | assert(TInfo && "couldn't build declarator info for anonymous struct" ); |
5732 | |
5733 | auto *ParentDecl = cast<RecordDecl>(Val: CurContext); |
5734 | QualType RecTy = Context.getTypeDeclType(Decl: Record); |
5735 | |
5736 | // Create a declaration for this anonymous struct. |
5737 | NamedDecl *Anon = |
5738 | FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(), |
5739 | /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo, |
5740 | /*BitWidth=*/BW: nullptr, /*Mutable=*/false, |
5741 | /*InitStyle=*/ICIS_NoInit); |
5742 | Anon->setImplicit(); |
5743 | |
5744 | // Add the anonymous struct object to the current context. |
5745 | CurContext->addDecl(D: Anon); |
5746 | |
5747 | // Inject the members of the anonymous struct into the current |
5748 | // context and into the identifier resolver chain for name lookup |
5749 | // purposes. |
5750 | SmallVector<NamedDecl*, 2> Chain; |
5751 | Chain.push_back(Elt: Anon); |
5752 | |
5753 | RecordDecl *RecordDef = Record->getDefinition(); |
5754 | if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy, |
5755 | DiagID: diag::err_field_incomplete_or_sizeless) || |
5756 | InjectAnonymousStructOrUnionMembers( |
5757 | SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none, |
5758 | SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) { |
5759 | Anon->setInvalidDecl(); |
5760 | ParentDecl->setInvalidDecl(); |
5761 | } |
5762 | |
5763 | return Anon; |
5764 | } |
5765 | |
5766 | DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { |
5767 | return GetNameFromUnqualifiedId(Name: D.getName()); |
5768 | } |
5769 | |
5770 | DeclarationNameInfo |
5771 | Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { |
5772 | DeclarationNameInfo NameInfo; |
5773 | NameInfo.setLoc(Name.StartLocation); |
5774 | |
5775 | switch (Name.getKind()) { |
5776 | |
5777 | case UnqualifiedIdKind::IK_ImplicitSelfParam: |
5778 | case UnqualifiedIdKind::IK_Identifier: |
5779 | NameInfo.setName(Name.Identifier); |
5780 | return NameInfo; |
5781 | |
5782 | case UnqualifiedIdKind::IK_DeductionGuideName: { |
5783 | // C++ [temp.deduct.guide]p3: |
5784 | // The simple-template-id shall name a class template specialization. |
5785 | // The template-name shall be the same identifier as the template-name |
5786 | // of the simple-template-id. |
5787 | // These together intend to imply that the template-name shall name a |
5788 | // class template. |
5789 | // FIXME: template<typename T> struct X {}; |
5790 | // template<typename T> using Y = X<T>; |
5791 | // Y(int) -> Y<int>; |
5792 | // satisfies these rules but does not name a class template. |
5793 | TemplateName TN = Name.TemplateName.get().get(); |
5794 | auto *Template = TN.getAsTemplateDecl(); |
5795 | if (!Template || !isa<ClassTemplateDecl>(Val: Template)) { |
5796 | Diag(Loc: Name.StartLocation, |
5797 | DiagID: diag::err_deduction_guide_name_not_class_template) |
5798 | << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN; |
5799 | if (Template) |
5800 | NoteTemplateLocation(Decl: *Template); |
5801 | return DeclarationNameInfo(); |
5802 | } |
5803 | |
5804 | NameInfo.setName( |
5805 | Context.DeclarationNames.getCXXDeductionGuideName(TD: Template)); |
5806 | return NameInfo; |
5807 | } |
5808 | |
5809 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
5810 | NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( |
5811 | Op: Name.OperatorFunctionId.Operator)); |
5812 | NameInfo.setCXXOperatorNameRange(SourceRange( |
5813 | Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); |
5814 | return NameInfo; |
5815 | |
5816 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
5817 | NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( |
5818 | II: Name.Identifier)); |
5819 | NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); |
5820 | return NameInfo; |
5821 | |
5822 | case UnqualifiedIdKind::IK_ConversionFunctionId: { |
5823 | TypeSourceInfo *TInfo; |
5824 | QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo); |
5825 | if (Ty.isNull()) |
5826 | return DeclarationNameInfo(); |
5827 | NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( |
5828 | Ty: Context.getCanonicalType(T: Ty))); |
5829 | NameInfo.setNamedTypeInfo(TInfo); |
5830 | return NameInfo; |
5831 | } |
5832 | |
5833 | case UnqualifiedIdKind::IK_ConstructorName: { |
5834 | TypeSourceInfo *TInfo; |
5835 | QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo); |
5836 | if (Ty.isNull()) |
5837 | return DeclarationNameInfo(); |
5838 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( |
5839 | Ty: Context.getCanonicalType(T: Ty))); |
5840 | NameInfo.setNamedTypeInfo(TInfo); |
5841 | return NameInfo; |
5842 | } |
5843 | |
5844 | case UnqualifiedIdKind::IK_ConstructorTemplateId: { |
5845 | // In well-formed code, we can only have a constructor |
5846 | // template-id that refers to the current context, so go there |
5847 | // to find the actual type being constructed. |
5848 | CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext); |
5849 | if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) |
5850 | return DeclarationNameInfo(); |
5851 | |
5852 | // Determine the type of the class being constructed. |
5853 | QualType CurClassType = Context.getTypeDeclType(Decl: CurClass); |
5854 | |
5855 | // FIXME: Check two things: that the template-id names the same type as |
5856 | // CurClassType, and that the template-id does not occur when the name |
5857 | // was qualified. |
5858 | |
5859 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( |
5860 | Ty: Context.getCanonicalType(T: CurClassType))); |
5861 | // FIXME: should we retrieve TypeSourceInfo? |
5862 | NameInfo.setNamedTypeInfo(nullptr); |
5863 | return NameInfo; |
5864 | } |
5865 | |
5866 | case UnqualifiedIdKind::IK_DestructorName: { |
5867 | TypeSourceInfo *TInfo; |
5868 | QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo); |
5869 | if (Ty.isNull()) |
5870 | return DeclarationNameInfo(); |
5871 | NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( |
5872 | Ty: Context.getCanonicalType(T: Ty))); |
5873 | NameInfo.setNamedTypeInfo(TInfo); |
5874 | return NameInfo; |
5875 | } |
5876 | |
5877 | case UnqualifiedIdKind::IK_TemplateId: { |
5878 | TemplateName TName = Name.TemplateId->Template.get(); |
5879 | SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; |
5880 | return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc); |
5881 | } |
5882 | |
5883 | } // switch (Name.getKind()) |
5884 | |
5885 | llvm_unreachable("Unknown name kind" ); |
5886 | } |
5887 | |
5888 | static QualType getCoreType(QualType Ty) { |
5889 | do { |
5890 | if (Ty->isPointerType() || Ty->isReferenceType()) |
5891 | Ty = Ty->getPointeeType(); |
5892 | else if (Ty->isArrayType()) |
5893 | Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); |
5894 | else |
5895 | return Ty.withoutLocalFastQualifiers(); |
5896 | } while (true); |
5897 | } |
5898 | |
5899 | /// hasSimilarParameters - Determine whether the C++ functions Declaration |
5900 | /// and Definition have "nearly" matching parameters. This heuristic is |
5901 | /// used to improve diagnostics in the case where an out-of-line function |
5902 | /// definition doesn't match any declaration within the class or namespace. |
5903 | /// Also sets Params to the list of indices to the parameters that differ |
5904 | /// between the declaration and the definition. If hasSimilarParameters |
5905 | /// returns true and Params is empty, then all of the parameters match. |
5906 | static bool hasSimilarParameters(ASTContext &Context, |
5907 | FunctionDecl *Declaration, |
5908 | FunctionDecl *Definition, |
5909 | SmallVectorImpl<unsigned> &Params) { |
5910 | Params.clear(); |
5911 | if (Declaration->param_size() != Definition->param_size()) |
5912 | return false; |
5913 | for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { |
5914 | QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType(); |
5915 | QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType(); |
5916 | |
5917 | // The parameter types are identical |
5918 | if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy)) |
5919 | continue; |
5920 | |
5921 | QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy); |
5922 | QualType DefParamBaseTy = getCoreType(Ty: DefParamTy); |
5923 | const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); |
5924 | const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); |
5925 | |
5926 | if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) || |
5927 | (DeclTyName && DeclTyName == DefTyName)) |
5928 | Params.push_back(Elt: Idx); |
5929 | else // The two parameters aren't even close |
5930 | return false; |
5931 | } |
5932 | |
5933 | return true; |
5934 | } |
5935 | |
5936 | /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given |
5937 | /// declarator needs to be rebuilt in the current instantiation. |
5938 | /// Any bits of declarator which appear before the name are valid for |
5939 | /// consideration here. That's specifically the type in the decl spec |
5940 | /// and the base type in any member-pointer chunks. |
5941 | static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, |
5942 | DeclarationName Name) { |
5943 | // The types we specifically need to rebuild are: |
5944 | // - typenames, typeofs, and decltypes |
5945 | // - types which will become injected class names |
5946 | // Of course, we also need to rebuild any type referencing such a |
5947 | // type. It's safest to just say "dependent", but we call out a |
5948 | // few cases here. |
5949 | |
5950 | DeclSpec &DS = D.getMutableDeclSpec(); |
5951 | switch (DS.getTypeSpecType()) { |
5952 | case DeclSpec::TST_typename: |
5953 | case DeclSpec::TST_typeofType: |
5954 | case DeclSpec::TST_typeof_unqualType: |
5955 | #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait: |
5956 | #include "clang/Basic/TransformTypeTraits.def" |
5957 | case DeclSpec::TST_atomic: { |
5958 | // Grab the type from the parser. |
5959 | TypeSourceInfo *TSI = nullptr; |
5960 | QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI); |
5961 | if (T.isNull() || !T->isInstantiationDependentType()) break; |
5962 | |
5963 | // Make sure there's a type source info. This isn't really much |
5964 | // of a waste; most dependent types should have type source info |
5965 | // attached already. |
5966 | if (!TSI) |
5967 | TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc()); |
5968 | |
5969 | // Rebuild the type in the current instantiation. |
5970 | TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name); |
5971 | if (!TSI) return true; |
5972 | |
5973 | // Store the new type back in the decl spec. |
5974 | ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI); |
5975 | DS.UpdateTypeRep(Rep: LocType); |
5976 | break; |
5977 | } |
5978 | |
5979 | case DeclSpec::TST_decltype: |
5980 | case DeclSpec::TST_typeof_unqualExpr: |
5981 | case DeclSpec::TST_typeofExpr: { |
5982 | Expr *E = DS.getRepAsExpr(); |
5983 | ExprResult Result = S.RebuildExprInCurrentInstantiation(E); |
5984 | if (Result.isInvalid()) return true; |
5985 | DS.UpdateExprRep(Rep: Result.get()); |
5986 | break; |
5987 | } |
5988 | |
5989 | default: |
5990 | // Nothing to do for these decl specs. |
5991 | break; |
5992 | } |
5993 | |
5994 | // It doesn't matter what order we do this in. |
5995 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { |
5996 | DeclaratorChunk &Chunk = D.getTypeObject(i: I); |
5997 | |
5998 | // The only type information in the declarator which can come |
5999 | // before the declaration name is the base type of a member |
6000 | // pointer. |
6001 | if (Chunk.Kind != DeclaratorChunk::MemberPointer) |
6002 | continue; |
6003 | |
6004 | // Rebuild the scope specifier in-place. |
6005 | CXXScopeSpec &SS = Chunk.Mem.Scope(); |
6006 | if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) |
6007 | return true; |
6008 | } |
6009 | |
6010 | return false; |
6011 | } |
6012 | |
6013 | /// Returns true if the declaration is declared in a system header or from a |
6014 | /// system macro. |
6015 | static bool (SourceManager &SM, const Decl *D) { |
6016 | return SM.isInSystemHeader(Loc: D->getLocation()) || |
6017 | SM.isInSystemMacro(loc: D->getLocation()); |
6018 | } |
6019 | |
6020 | void Sema::warnOnReservedIdentifier(const NamedDecl *D) { |
6021 | // Avoid warning twice on the same identifier, and don't warn on redeclaration |
6022 | // of system decl. |
6023 | if (D->getPreviousDecl() || D->isImplicit()) |
6024 | return; |
6025 | ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts()); |
6026 | if (Status != ReservedIdentifierStatus::NotReserved && |
6027 | !isFromSystemHeader(SM&: Context.getSourceManager(), D)) { |
6028 | Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol) |
6029 | << D << static_cast<int>(Status); |
6030 | } |
6031 | } |
6032 | |
6033 | Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { |
6034 | D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); |
6035 | |
6036 | // Check if we are in an `omp begin/end declare variant` scope. Handle this |
6037 | // declaration only if the `bind_to_declaration` extension is set. |
6038 | SmallVector<FunctionDecl *, 4> Bases; |
6039 | if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope()) |
6040 | if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive( |
6041 | TP: llvm::omp::TraitProperty:: |
6042 | implementation_extension_bind_to_declaration)) |
6043 | OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( |
6044 | S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases); |
6045 | |
6046 | Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg()); |
6047 | |
6048 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && |
6049 | Dcl && Dcl->getDeclContext()->isFileContext()) |
6050 | Dcl->setTopLevelDeclInObjCContainer(); |
6051 | |
6052 | if (!Bases.empty()) |
6053 | OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl, |
6054 | Bases); |
6055 | |
6056 | return Dcl; |
6057 | } |
6058 | |
6059 | bool Sema::DiagnoseClassNameShadow(DeclContext *DC, |
6060 | DeclarationNameInfo NameInfo) { |
6061 | DeclarationName Name = NameInfo.getName(); |
6062 | |
6063 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC); |
6064 | while (Record && Record->isAnonymousStructOrUnion()) |
6065 | Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent()); |
6066 | if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { |
6067 | Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name; |
6068 | return true; |
6069 | } |
6070 | |
6071 | return false; |
6072 | } |
6073 | |
6074 | bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, |
6075 | DeclarationName Name, |
6076 | SourceLocation Loc, |
6077 | TemplateIdAnnotation *TemplateId, |
6078 | bool IsMemberSpecialization) { |
6079 | assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration " |
6080 | "without nested-name-specifier" ); |
6081 | DeclContext *Cur = CurContext; |
6082 | while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur)) |
6083 | Cur = Cur->getParent(); |
6084 | |
6085 | // If the user provided a superfluous scope specifier that refers back to the |
6086 | // class in which the entity is already declared, diagnose and ignore it. |
6087 | // |
6088 | // class X { |
6089 | // void X::f(); |
6090 | // }; |
6091 | // |
6092 | // Note, it was once ill-formed to give redundant qualification in all |
6093 | // contexts, but that rule was removed by DR482. |
6094 | if (Cur->Equals(DC)) { |
6095 | if (Cur->isRecord()) { |
6096 | Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification |
6097 | : diag::err_member_extra_qualification) |
6098 | << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange()); |
6099 | SS.clear(); |
6100 | } else { |
6101 | Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name; |
6102 | } |
6103 | return false; |
6104 | } |
6105 | |
6106 | // Check whether the qualifying scope encloses the scope of the original |
6107 | // declaration. For a template-id, we perform the checks in |
6108 | // CheckTemplateSpecializationScope. |
6109 | if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) { |
6110 | if (Cur->isRecord()) |
6111 | Diag(Loc, DiagID: diag::err_member_qualification) |
6112 | << Name << SS.getRange(); |
6113 | else if (isa<TranslationUnitDecl>(Val: DC)) |
6114 | Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope) |
6115 | << Name << SS.getRange(); |
6116 | else if (isa<FunctionDecl>(Val: Cur)) |
6117 | Diag(Loc, DiagID: diag::err_invalid_declarator_in_function) |
6118 | << Name << SS.getRange(); |
6119 | else if (isa<BlockDecl>(Val: Cur)) |
6120 | Diag(Loc, DiagID: diag::err_invalid_declarator_in_block) |
6121 | << Name << SS.getRange(); |
6122 | else if (isa<ExportDecl>(Val: Cur)) { |
6123 | if (!isa<NamespaceDecl>(Val: DC)) |
6124 | Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name) |
6125 | << Name << SS.getRange(); |
6126 | else |
6127 | // The cases that DC is not NamespaceDecl should be handled in |
6128 | // CheckRedeclarationExported. |
6129 | return false; |
6130 | } else |
6131 | Diag(Loc, DiagID: diag::err_invalid_declarator_scope) |
6132 | << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange(); |
6133 | |
6134 | return true; |
6135 | } |
6136 | |
6137 | if (Cur->isRecord()) { |
6138 | // Cannot qualify members within a class. |
6139 | Diag(Loc, DiagID: diag::err_member_qualification) |
6140 | << Name << SS.getRange(); |
6141 | SS.clear(); |
6142 | |
6143 | // C++ constructors and destructors with incorrect scopes can break |
6144 | // our AST invariants by having the wrong underlying types. If |
6145 | // that's the case, then drop this declaration entirely. |
6146 | if ((Name.getNameKind() == DeclarationName::CXXConstructorName || |
6147 | Name.getNameKind() == DeclarationName::CXXDestructorName) && |
6148 | !Context.hasSameType(T1: Name.getCXXNameType(), |
6149 | T2: Context.getTypeDeclType(Decl: cast<CXXRecordDecl>(Val: Cur)))) |
6150 | return true; |
6151 | |
6152 | return false; |
6153 | } |
6154 | |
6155 | // C++23 [temp.names]p5: |
6156 | // The keyword template shall not appear immediately after a declarative |
6157 | // nested-name-specifier. |
6158 | // |
6159 | // First check the template-id (if any), and then check each component of the |
6160 | // nested-name-specifier in reverse order. |
6161 | // |
6162 | // FIXME: nested-name-specifiers in friend declarations are declarative, |
6163 | // but we don't call diagnoseQualifiedDeclaration for them. We should. |
6164 | if (TemplateId && TemplateId->TemplateKWLoc.isValid()) |
6165 | Diag(Loc, DiagID: diag::ext_template_after_declarative_nns) |
6166 | << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc); |
6167 | |
6168 | NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); |
6169 | do { |
6170 | if (SpecLoc.getNestedNameSpecifier()->getKind() == |
6171 | NestedNameSpecifier::TypeSpecWithTemplate) |
6172 | Diag(Loc, DiagID: diag::ext_template_after_declarative_nns) |
6173 | << FixItHint::CreateRemoval( |
6174 | RemoveRange: SpecLoc.getTypeLoc().getTemplateKeywordLoc()); |
6175 | |
6176 | if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) { |
6177 | if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) { |
6178 | // C++23 [expr.prim.id.qual]p3: |
6179 | // [...] If a nested-name-specifier N is declarative and has a |
6180 | // simple-template-id with a template argument list A that involves a |
6181 | // template parameter, let T be the template nominated by N without A. |
6182 | // T shall be a class template. |
6183 | if (TST->isDependentType() && TST->isTypeAlias()) |
6184 | Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns) |
6185 | << SpecLoc.getLocalSourceRange(); |
6186 | } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) { |
6187 | // C++23 [expr.prim.id.qual]p2: |
6188 | // [...] A declarative nested-name-specifier shall not have a |
6189 | // computed-type-specifier. |
6190 | // |
6191 | // CWG2858 changed this from 'decltype-specifier' to |
6192 | // 'computed-type-specifier'. |
6193 | Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns) |
6194 | << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange(); |
6195 | } |
6196 | } |
6197 | } while ((SpecLoc = SpecLoc.getPrefix())); |
6198 | |
6199 | return false; |
6200 | } |
6201 | |
6202 | NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, |
6203 | MultiTemplateParamsArg TemplateParamLists) { |
6204 | // TODO: consider using NameInfo for diagnostic. |
6205 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); |
6206 | DeclarationName Name = NameInfo.getName(); |
6207 | |
6208 | // All of these full declarators require an identifier. If it doesn't have |
6209 | // one, the ParsedFreeStandingDeclSpec action should be used. |
6210 | if (D.isDecompositionDeclarator()) { |
6211 | return ActOnDecompositionDeclarator(S, D, TemplateParamLists); |
6212 | } else if (!Name) { |
6213 | if (!D.isInvalidType()) // Reject this if we think it is valid. |
6214 | Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident) |
6215 | << D.getDeclSpec().getSourceRange() << D.getSourceRange(); |
6216 | return nullptr; |
6217 | } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType)) |
6218 | return nullptr; |
6219 | |
6220 | DeclContext *DC = CurContext; |
6221 | if (D.getCXXScopeSpec().isInvalid()) |
6222 | D.setInvalidType(); |
6223 | else if (D.getCXXScopeSpec().isSet()) { |
6224 | if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(), |
6225 | UPPC: UPPC_DeclarationQualifier)) |
6226 | return nullptr; |
6227 | |
6228 | bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); |
6229 | DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext); |
6230 | if (!DC || isa<EnumDecl>(Val: DC)) { |
6231 | // If we could not compute the declaration context, it's because the |
6232 | // declaration context is dependent but does not refer to a class, |
6233 | // class template, or class template partial specialization. Complain |
6234 | // and return early, to avoid the coming semantic disaster. |
6235 | Diag(Loc: D.getIdentifierLoc(), |
6236 | DiagID: diag::err_template_qualified_declarator_no_match) |
6237 | << D.getCXXScopeSpec().getScopeRep() |
6238 | << D.getCXXScopeSpec().getRange(); |
6239 | return nullptr; |
6240 | } |
6241 | bool IsDependentContext = DC->isDependentContext(); |
6242 | |
6243 | if (!IsDependentContext && |
6244 | RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC)) |
6245 | return nullptr; |
6246 | |
6247 | // If a class is incomplete, do not parse entities inside it. |
6248 | if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) { |
6249 | Diag(Loc: D.getIdentifierLoc(), |
6250 | DiagID: diag::err_member_def_undefined_record) |
6251 | << Name << DC << D.getCXXScopeSpec().getRange(); |
6252 | return nullptr; |
6253 | } |
6254 | if (!D.getDeclSpec().isFriendSpecified()) { |
6255 | TemplateIdAnnotation *TemplateId = |
6256 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId |
6257 | ? D.getName().TemplateId |
6258 | : nullptr; |
6259 | if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name, |
6260 | Loc: D.getIdentifierLoc(), TemplateId, |
6261 | /*IsMemberSpecialization=*/false)) { |
6262 | if (DC->isRecord()) |
6263 | return nullptr; |
6264 | |
6265 | D.setInvalidType(); |
6266 | } |
6267 | } |
6268 | |
6269 | // Check whether we need to rebuild the type of the given |
6270 | // declaration in the current instantiation. |
6271 | if (EnteringContext && IsDependentContext && |
6272 | TemplateParamLists.size() != 0) { |
6273 | ContextRAII SavedContext(*this, DC); |
6274 | if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name)) |
6275 | D.setInvalidType(); |
6276 | } |
6277 | } |
6278 | |
6279 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D); |
6280 | QualType R = TInfo->getType(); |
6281 | |
6282 | if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo, |
6283 | UPPC: UPPC_DeclarationType)) |
6284 | D.setInvalidType(); |
6285 | |
6286 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, |
6287 | forRedeclarationInCurContext()); |
6288 | |
6289 | // See if this is a redefinition of a variable in the same scope. |
6290 | if (!D.getCXXScopeSpec().isSet()) { |
6291 | bool IsLinkageLookup = false; |
6292 | bool CreateBuiltins = false; |
6293 | |
6294 | // If the declaration we're planning to build will be a function |
6295 | // or object with linkage, then look for another declaration with |
6296 | // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). |
6297 | // |
6298 | // If the declaration we're planning to build will be declared with |
6299 | // external linkage in the translation unit, create any builtin with |
6300 | // the same name. |
6301 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) |
6302 | /* Do nothing*/; |
6303 | else if (CurContext->isFunctionOrMethod() && |
6304 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || |
6305 | R->isFunctionType())) { |
6306 | IsLinkageLookup = true; |
6307 | CreateBuiltins = |
6308 | CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); |
6309 | } else if (CurContext->getRedeclContext()->isTranslationUnit() && |
6310 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) |
6311 | CreateBuiltins = true; |
6312 | |
6313 | if (IsLinkageLookup) { |
6314 | Previous.clear(Kind: LookupRedeclarationWithLinkage); |
6315 | Previous.setRedeclarationKind( |
6316 | RedeclarationKind::ForExternalRedeclaration); |
6317 | } |
6318 | |
6319 | LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins); |
6320 | } else { // Something like "int foo::x;" |
6321 | LookupQualifiedName(R&: Previous, LookupCtx: DC); |
6322 | |
6323 | // C++ [dcl.meaning]p1: |
6324 | // When the declarator-id is qualified, the declaration shall refer to a |
6325 | // previously declared member of the class or namespace to which the |
6326 | // qualifier refers (or, in the case of a namespace, of an element of the |
6327 | // inline namespace set of that namespace (7.3.1)) or to a specialization |
6328 | // thereof; [...] |
6329 | // |
6330 | // Note that we already checked the context above, and that we do not have |
6331 | // enough information to make sure that Previous contains the declaration |
6332 | // we want to match. For example, given: |
6333 | // |
6334 | // class X { |
6335 | // void f(); |
6336 | // void f(float); |
6337 | // }; |
6338 | // |
6339 | // void X::f(int) { } // ill-formed |
6340 | // |
6341 | // In this case, Previous will point to the overload set |
6342 | // containing the two f's declared in X, but neither of them |
6343 | // matches. |
6344 | |
6345 | RemoveUsingDecls(R&: Previous); |
6346 | } |
6347 | |
6348 | if (auto *TPD = Previous.getAsSingle<NamedDecl>(); |
6349 | TPD && TPD->isTemplateParameter()) { |
6350 | // Older versions of clang allowed the names of function/variable templates |
6351 | // to shadow the names of their template parameters. For the compatibility |
6352 | // purposes we detect such cases and issue a default-to-error warning that |
6353 | // can be disabled with -Wno-strict-primary-template-shadow. |
6354 | if (!D.isInvalidType()) { |
6355 | bool AllowForCompatibility = false; |
6356 | if (Scope *DeclParent = S->getDeclParent(); |
6357 | Scope *TemplateParamParent = S->getTemplateParamParent()) { |
6358 | AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) && |
6359 | TemplateParamParent->isDeclScope(D: TPD); |
6360 | } |
6361 | DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD, |
6362 | SupportedForCompatibility: AllowForCompatibility); |
6363 | } |
6364 | |
6365 | // Just pretend that we didn't see the previous declaration. |
6366 | Previous.clear(); |
6367 | } |
6368 | |
6369 | if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) |
6370 | // Forget that the previous declaration is the injected-class-name. |
6371 | Previous.clear(); |
6372 | |
6373 | // In C++, the previous declaration we find might be a tag type |
6374 | // (class or enum). In this case, the new declaration will hide the |
6375 | // tag type. Note that this applies to functions, function templates, and |
6376 | // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. |
6377 | if (Previous.isSingleTagDecl() && |
6378 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && |
6379 | (TemplateParamLists.size() == 0 || R->isFunctionType())) |
6380 | Previous.clear(); |
6381 | |
6382 | // Check that there are no default arguments other than in the parameters |
6383 | // of a function declaration (C++ only). |
6384 | if (getLangOpts().CPlusPlus) |
6385 | CheckExtraCXXDefaultArguments(D); |
6386 | |
6387 | /// Get the innermost enclosing declaration scope. |
6388 | S = S->getDeclParent(); |
6389 | |
6390 | NamedDecl *New; |
6391 | |
6392 | bool AddToScope = true; |
6393 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { |
6394 | if (TemplateParamLists.size()) { |
6395 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef); |
6396 | return nullptr; |
6397 | } |
6398 | |
6399 | New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); |
6400 | } else if (R->isFunctionType()) { |
6401 | New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, |
6402 | TemplateParamLists, |
6403 | AddToScope); |
6404 | } else { |
6405 | New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, |
6406 | AddToScope); |
6407 | } |
6408 | |
6409 | if (!New) |
6410 | return nullptr; |
6411 | |
6412 | // If this has an identifier and is not a function template specialization, |
6413 | // add it to the scope stack. |
6414 | if (New->getDeclName() && AddToScope) |
6415 | PushOnScopeChains(D: New, S); |
6416 | |
6417 | if (OpenMP().isInOpenMPDeclareTargetContext()) |
6418 | OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New); |
6419 | |
6420 | return New; |
6421 | } |
6422 | |
6423 | /// Helper method to turn variable array types into constant array |
6424 | /// types in certain situations which would otherwise be errors (for |
6425 | /// GCC compatibility). |
6426 | static QualType TryToFixInvalidVariablyModifiedType(QualType T, |
6427 | ASTContext &Context, |
6428 | bool &SizeIsNegative, |
6429 | llvm::APSInt &Oversized) { |
6430 | // This method tries to turn a variable array into a constant |
6431 | // array even when the size isn't an ICE. This is necessary |
6432 | // for compatibility with code that depends on gcc's buggy |
6433 | // constant expression folding, like struct {char x[(int)(char*)2];} |
6434 | SizeIsNegative = false; |
6435 | Oversized = 0; |
6436 | |
6437 | if (T->isDependentType()) |
6438 | return QualType(); |
6439 | |
6440 | QualifierCollector Qs; |
6441 | const Type *Ty = Qs.strip(type: T); |
6442 | |
6443 | if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) { |
6444 | QualType Pointee = PTy->getPointeeType(); |
6445 | QualType FixedType = |
6446 | TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative, |
6447 | Oversized); |
6448 | if (FixedType.isNull()) return FixedType; |
6449 | FixedType = Context.getPointerType(T: FixedType); |
6450 | return Qs.apply(Context, QT: FixedType); |
6451 | } |
6452 | if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) { |
6453 | QualType Inner = PTy->getInnerType(); |
6454 | QualType FixedType = |
6455 | TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative, |
6456 | Oversized); |
6457 | if (FixedType.isNull()) return FixedType; |
6458 | FixedType = Context.getParenType(NamedType: FixedType); |
6459 | return Qs.apply(Context, QT: FixedType); |
6460 | } |
6461 | |
6462 | const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T); |
6463 | if (!VLATy) |
6464 | return QualType(); |
6465 | |
6466 | QualType ElemTy = VLATy->getElementType(); |
6467 | if (ElemTy->isVariablyModifiedType()) { |
6468 | ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context, |
6469 | SizeIsNegative, Oversized); |
6470 | if (ElemTy.isNull()) |
6471 | return QualType(); |
6472 | } |
6473 | |
6474 | Expr::EvalResult Result; |
6475 | if (!VLATy->getSizeExpr() || |
6476 | !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context)) |
6477 | return QualType(); |
6478 | |
6479 | llvm::APSInt Res = Result.Val.getInt(); |
6480 | |
6481 | // Check whether the array size is negative. |
6482 | if (Res.isSigned() && Res.isNegative()) { |
6483 | SizeIsNegative = true; |
6484 | return QualType(); |
6485 | } |
6486 | |
6487 | // Check whether the array is too large to be addressed. |
6488 | unsigned ActiveSizeBits = |
6489 | (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && |
6490 | !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) |
6491 | ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res) |
6492 | : Res.getActiveBits(); |
6493 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { |
6494 | Oversized = Res; |
6495 | return QualType(); |
6496 | } |
6497 | |
6498 | QualType FoldedArrayType = Context.getConstantArrayType( |
6499 | EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
6500 | return Qs.apply(Context, QT: FoldedArrayType); |
6501 | } |
6502 | |
6503 | static void |
6504 | FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { |
6505 | SrcTL = SrcTL.getUnqualifiedLoc(); |
6506 | DstTL = DstTL.getUnqualifiedLoc(); |
6507 | if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { |
6508 | PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); |
6509 | FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(), |
6510 | DstTL: DstPTL.getPointeeLoc()); |
6511 | DstPTL.setStarLoc(SrcPTL.getStarLoc()); |
6512 | return; |
6513 | } |
6514 | if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { |
6515 | ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); |
6516 | FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(), |
6517 | DstTL: DstPTL.getInnerLoc()); |
6518 | DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); |
6519 | DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); |
6520 | return; |
6521 | } |
6522 | ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); |
6523 | ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); |
6524 | TypeLoc SrcElemTL = SrcATL.getElementLoc(); |
6525 | TypeLoc DstElemTL = DstATL.getElementLoc(); |
6526 | if (VariableArrayTypeLoc SrcElemATL = |
6527 | SrcElemTL.getAs<VariableArrayTypeLoc>()) { |
6528 | ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); |
6529 | FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL); |
6530 | } else { |
6531 | DstElemTL.initializeFullCopy(Other: SrcElemTL); |
6532 | } |
6533 | DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); |
6534 | DstATL.setSizeExpr(SrcATL.getSizeExpr()); |
6535 | DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); |
6536 | } |
6537 | |
6538 | /// Helper method to turn variable array types into constant array |
6539 | /// types in certain situations which would otherwise be errors (for |
6540 | /// GCC compatibility). |
6541 | static TypeSourceInfo* |
6542 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, |
6543 | ASTContext &Context, |
6544 | bool &SizeIsNegative, |
6545 | llvm::APSInt &Oversized) { |
6546 | QualType FixedTy |
6547 | = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context, |
6548 | SizeIsNegative, Oversized); |
6549 | if (FixedTy.isNull()) |
6550 | return nullptr; |
6551 | TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy); |
6552 | FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(), |
6553 | DstTL: FixedTInfo->getTypeLoc()); |
6554 | return FixedTInfo; |
6555 | } |
6556 | |
6557 | bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, |
6558 | QualType &T, SourceLocation Loc, |
6559 | unsigned FailedFoldDiagID) { |
6560 | bool SizeIsNegative; |
6561 | llvm::APSInt Oversized; |
6562 | TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( |
6563 | TInfo, Context, SizeIsNegative, Oversized); |
6564 | if (FixedTInfo) { |
6565 | Diag(Loc, DiagID: diag::ext_vla_folded_to_constant); |
6566 | TInfo = FixedTInfo; |
6567 | T = FixedTInfo->getType(); |
6568 | return true; |
6569 | } |
6570 | |
6571 | if (SizeIsNegative) |
6572 | Diag(Loc, DiagID: diag::err_typecheck_negative_array_size); |
6573 | else if (Oversized.getBoolValue()) |
6574 | Diag(Loc, DiagID: diag::err_array_too_large) << toString(I: Oversized, Radix: 10); |
6575 | else if (FailedFoldDiagID) |
6576 | Diag(Loc, DiagID: FailedFoldDiagID); |
6577 | return false; |
6578 | } |
6579 | |
6580 | void |
6581 | Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { |
6582 | if (!getLangOpts().CPlusPlus && |
6583 | ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) |
6584 | // Don't need to track declarations in the TU in C. |
6585 | return; |
6586 | |
6587 | // Note that we have a locally-scoped external with this name. |
6588 | Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND); |
6589 | } |
6590 | |
6591 | NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { |
6592 | // FIXME: We can have multiple results via __attribute__((overloadable)). |
6593 | auto Result = Context.getExternCContextDecl()->lookup(Name); |
6594 | return Result.empty() ? nullptr : *Result.begin(); |
6595 | } |
6596 | |
6597 | void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { |
6598 | // FIXME: We should probably indicate the identifier in question to avoid |
6599 | // confusion for constructs like "virtual int a(), b;" |
6600 | if (DS.isVirtualSpecified()) |
6601 | Diag(Loc: DS.getVirtualSpecLoc(), |
6602 | DiagID: diag::err_virtual_non_function); |
6603 | |
6604 | if (DS.hasExplicitSpecifier()) |
6605 | Diag(Loc: DS.getExplicitSpecLoc(), |
6606 | DiagID: diag::err_explicit_non_function); |
6607 | |
6608 | if (DS.isNoreturnSpecified()) |
6609 | Diag(Loc: DS.getNoreturnSpecLoc(), |
6610 | DiagID: diag::err_noreturn_non_function); |
6611 | } |
6612 | |
6613 | NamedDecl* |
6614 | Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, |
6615 | TypeSourceInfo *TInfo, LookupResult &Previous) { |
6616 | // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). |
6617 | if (D.getCXXScopeSpec().isSet()) { |
6618 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator) |
6619 | << D.getCXXScopeSpec().getRange(); |
6620 | D.setInvalidType(); |
6621 | // Pretend we didn't see the scope specifier. |
6622 | DC = CurContext; |
6623 | Previous.clear(); |
6624 | } |
6625 | |
6626 | DiagnoseFunctionSpecifiers(DS: D.getDeclSpec()); |
6627 | |
6628 | if (D.getDeclSpec().isInlineSpecified()) |
6629 | Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function) |
6630 | << getLangOpts().CPlusPlus17; |
6631 | if (D.getDeclSpec().hasConstexprSpecifier()) |
6632 | Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr) |
6633 | << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); |
6634 | |
6635 | if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) { |
6636 | if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) |
6637 | Diag(Loc: D.getName().StartLocation, |
6638 | DiagID: diag::err_deduction_guide_invalid_specifier) |
6639 | << "typedef" ; |
6640 | else |
6641 | Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier) |
6642 | << D.getName().getSourceRange(); |
6643 | return nullptr; |
6644 | } |
6645 | |
6646 | TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo); |
6647 | if (!NewTD) return nullptr; |
6648 | |
6649 | // Handle attributes prior to checking for duplicates in MergeVarDecl |
6650 | ProcessDeclAttributes(S, D: NewTD, PD: D); |
6651 | |
6652 | CheckTypedefForVariablyModifiedType(S, D: NewTD); |
6653 | |
6654 | bool Redeclaration = D.isRedeclaration(); |
6655 | NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration); |
6656 | D.setRedeclaration(Redeclaration); |
6657 | return ND; |
6658 | } |
6659 | |
6660 | void |
6661 | Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { |
6662 | // C99 6.7.7p2: If a typedef name specifies a variably modified type |
6663 | // then it shall have block scope. |
6664 | // Note that variably modified types must be fixed before merging the decl so |
6665 | // that redeclarations will match. |
6666 | TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); |
6667 | QualType T = TInfo->getType(); |
6668 | if (T->isVariablyModifiedType()) { |
6669 | setFunctionHasBranchProtectedScope(); |
6670 | |
6671 | if (S->getFnParent() == nullptr) { |
6672 | bool SizeIsNegative; |
6673 | llvm::APSInt Oversized; |
6674 | TypeSourceInfo *FixedTInfo = |
6675 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, |
6676 | SizeIsNegative, |
6677 | Oversized); |
6678 | if (FixedTInfo) { |
6679 | Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant); |
6680 | NewTD->setTypeSourceInfo(FixedTInfo); |
6681 | } else { |
6682 | if (SizeIsNegative) |
6683 | Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size); |
6684 | else if (T->isVariableArrayType()) |
6685 | Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope); |
6686 | else if (Oversized.getBoolValue()) |
6687 | Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large) |
6688 | << toString(I: Oversized, Radix: 10); |
6689 | else |
6690 | Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope); |
6691 | NewTD->setInvalidDecl(); |
6692 | } |
6693 | } |
6694 | } |
6695 | } |
6696 | |
6697 | NamedDecl* |
6698 | Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, |
6699 | LookupResult &Previous, bool &Redeclaration) { |
6700 | |
6701 | // Find the shadowed declaration before filtering for scope. |
6702 | NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous); |
6703 | |
6704 | // Merge the decl with the existing one if appropriate. If the decl is |
6705 | // in an outer scope, it isn't the same thing. |
6706 | FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false, |
6707 | /*AllowInlineNamespace*/false); |
6708 | filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous); |
6709 | if (!Previous.empty()) { |
6710 | Redeclaration = true; |
6711 | MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous); |
6712 | } else { |
6713 | inferGslPointerAttribute(TD: NewTD); |
6714 | } |
6715 | |
6716 | if (ShadowedDecl && !Redeclaration) |
6717 | CheckShadow(D: NewTD, ShadowedDecl, R: Previous); |
6718 | |
6719 | // If this is the C FILE type, notify the AST context. |
6720 | if (IdentifierInfo *II = NewTD->getIdentifier()) |
6721 | if (!NewTD->isInvalidDecl() && |
6722 | NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { |
6723 | switch (II->getNotableIdentifierID()) { |
6724 | case tok::NotableIdentifierKind::FILE: |
6725 | Context.setFILEDecl(NewTD); |
6726 | break; |
6727 | case tok::NotableIdentifierKind::jmp_buf: |
6728 | Context.setjmp_bufDecl(NewTD); |
6729 | break; |
6730 | case tok::NotableIdentifierKind::sigjmp_buf: |
6731 | Context.setsigjmp_bufDecl(NewTD); |
6732 | break; |
6733 | case tok::NotableIdentifierKind::ucontext_t: |
6734 | Context.setucontext_tDecl(NewTD); |
6735 | break; |
6736 | case tok::NotableIdentifierKind::float_t: |
6737 | case tok::NotableIdentifierKind::double_t: |
6738 | NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context)); |
6739 | break; |
6740 | default: |
6741 | break; |
6742 | } |
6743 | } |
6744 | |
6745 | return NewTD; |
6746 | } |
6747 | |
6748 | /// Determines whether the given declaration is an out-of-scope |
6749 | /// previous declaration. |
6750 | /// |
6751 | /// This routine should be invoked when name lookup has found a |
6752 | /// previous declaration (PrevDecl) that is not in the scope where a |
6753 | /// new declaration by the same name is being introduced. If the new |
6754 | /// declaration occurs in a local scope, previous declarations with |
6755 | /// linkage may still be considered previous declarations (C99 |
6756 | /// 6.2.2p4-5, C++ [basic.link]p6). |
6757 | /// |
6758 | /// \param PrevDecl the previous declaration found by name |
6759 | /// lookup |
6760 | /// |
6761 | /// \param DC the context in which the new declaration is being |
6762 | /// declared. |
6763 | /// |
6764 | /// \returns true if PrevDecl is an out-of-scope previous declaration |
6765 | /// for a new delcaration with the same name. |
6766 | static bool |
6767 | isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, |
6768 | ASTContext &Context) { |
6769 | if (!PrevDecl) |
6770 | return false; |
6771 | |
6772 | if (!PrevDecl->hasLinkage()) |
6773 | return false; |
6774 | |
6775 | if (Context.getLangOpts().CPlusPlus) { |
6776 | // C++ [basic.link]p6: |
6777 | // If there is a visible declaration of an entity with linkage |
6778 | // having the same name and type, ignoring entities declared |
6779 | // outside the innermost enclosing namespace scope, the block |
6780 | // scope declaration declares that same entity and receives the |
6781 | // linkage of the previous declaration. |
6782 | DeclContext *OuterContext = DC->getRedeclContext(); |
6783 | if (!OuterContext->isFunctionOrMethod()) |
6784 | // This rule only applies to block-scope declarations. |
6785 | return false; |
6786 | |
6787 | DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); |
6788 | if (PrevOuterContext->isRecord()) |
6789 | // We found a member function: ignore it. |
6790 | return false; |
6791 | |
6792 | // Find the innermost enclosing namespace for the new and |
6793 | // previous declarations. |
6794 | OuterContext = OuterContext->getEnclosingNamespaceContext(); |
6795 | PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); |
6796 | |
6797 | // The previous declaration is in a different namespace, so it |
6798 | // isn't the same function. |
6799 | if (!OuterContext->Equals(DC: PrevOuterContext)) |
6800 | return false; |
6801 | } |
6802 | |
6803 | return true; |
6804 | } |
6805 | |
6806 | static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { |
6807 | CXXScopeSpec &SS = D.getCXXScopeSpec(); |
6808 | if (!SS.isSet()) return; |
6809 | DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context)); |
6810 | } |
6811 | |
6812 | void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { |
6813 | if (Decl->getType().hasAddressSpace()) |
6814 | return; |
6815 | if (Decl->getType()->isDependentType()) |
6816 | return; |
6817 | if (VarDecl *Var = dyn_cast<VarDecl>(Val: Decl)) { |
6818 | QualType Type = Var->getType(); |
6819 | if (Type->isSamplerT() || Type->isVoidType()) |
6820 | return; |
6821 | LangAS ImplAS = LangAS::opencl_private; |
6822 | // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the |
6823 | // __opencl_c_program_scope_global_variables feature, the address space |
6824 | // for a variable at program scope or a static or extern variable inside |
6825 | // a function are inferred to be __global. |
6826 | if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) && |
6827 | Var->hasGlobalStorage()) |
6828 | ImplAS = LangAS::opencl_global; |
6829 | // If the original type from a decayed type is an array type and that array |
6830 | // type has no address space yet, deduce it now. |
6831 | if (auto DT = dyn_cast<DecayedType>(Val&: Type)) { |
6832 | auto OrigTy = DT->getOriginalType(); |
6833 | if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { |
6834 | // Add the address space to the original array type and then propagate |
6835 | // that to the element type through `getAsArrayType`. |
6836 | OrigTy = Context.getAddrSpaceQualType(T: OrigTy, AddressSpace: ImplAS); |
6837 | OrigTy = QualType(Context.getAsArrayType(T: OrigTy), 0); |
6838 | // Re-generate the decayed type. |
6839 | Type = Context.getDecayedType(T: OrigTy); |
6840 | } |
6841 | } |
6842 | Type = Context.getAddrSpaceQualType(T: Type, AddressSpace: ImplAS); |
6843 | // Apply any qualifiers (including address space) from the array type to |
6844 | // the element type. This implements C99 6.7.3p8: "If the specification of |
6845 | // an array type includes any type qualifiers, the element type is so |
6846 | // qualified, not the array type." |
6847 | if (Type->isArrayType()) |
6848 | Type = QualType(Context.getAsArrayType(T: Type), 0); |
6849 | Decl->setType(Type); |
6850 | } |
6851 | } |
6852 | |
6853 | static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { |
6854 | // Ensure that an auto decl is deduced otherwise the checks below might cache |
6855 | // the wrong linkage. |
6856 | assert(S.ParsingInitForAutoVars.count(&ND) == 0); |
6857 | |
6858 | // 'weak' only applies to declarations with external linkage. |
6859 | if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { |
6860 | if (!ND.isExternallyVisible()) { |
6861 | S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static); |
6862 | ND.dropAttr<WeakAttr>(); |
6863 | } |
6864 | } |
6865 | if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { |
6866 | if (ND.isExternallyVisible()) { |
6867 | S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static); |
6868 | ND.dropAttrs<WeakRefAttr, AliasAttr>(); |
6869 | } |
6870 | } |
6871 | |
6872 | if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) { |
6873 | if (VD->hasInit()) { |
6874 | if (const auto *Attr = VD->getAttr<AliasAttr>()) { |
6875 | assert(VD->isThisDeclarationADefinition() && |
6876 | !VD->isExternallyVisible() && "Broken AliasAttr handled late!" ); |
6877 | S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0; |
6878 | VD->dropAttr<AliasAttr>(); |
6879 | } |
6880 | } |
6881 | } |
6882 | |
6883 | // 'selectany' only applies to externally visible variable declarations. |
6884 | // It does not apply to functions. |
6885 | if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { |
6886 | if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) { |
6887 | S.Diag(Loc: Attr->getLocation(), |
6888 | DiagID: diag::err_attribute_selectany_non_extern_data); |
6889 | ND.dropAttr<SelectAnyAttr>(); |
6890 | } |
6891 | } |
6892 | |
6893 | if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) { |
6894 | if (!ND.isExternallyVisible()) |
6895 | S.Diag(Loc: Attr->getLocation(), |
6896 | DiagID: diag::warn_attribute_hybrid_patchable_non_extern); |
6897 | } |
6898 | if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) { |
6899 | auto *VD = dyn_cast<VarDecl>(Val: &ND); |
6900 | bool IsAnonymousNS = false; |
6901 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); |
6902 | if (VD) { |
6903 | const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext()); |
6904 | while (NS && !IsAnonymousNS) { |
6905 | IsAnonymousNS = NS->isAnonymousNamespace(); |
6906 | NS = dyn_cast<NamespaceDecl>(Val: NS->getParent()); |
6907 | } |
6908 | } |
6909 | // dll attributes require external linkage. Static locals may have external |
6910 | // linkage but still cannot be explicitly imported or exported. |
6911 | // In Microsoft mode, a variable defined in anonymous namespace must have |
6912 | // external linkage in order to be exported. |
6913 | bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; |
6914 | if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || |
6915 | (!AnonNSInMicrosoftMode && |
6916 | (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { |
6917 | S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern) |
6918 | << &ND << Attr; |
6919 | ND.setInvalidDecl(); |
6920 | } |
6921 | } |
6922 | |
6923 | // Check the attributes on the function type, if any. |
6924 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) { |
6925 | // Don't declare this variable in the second operand of the for-statement; |
6926 | // GCC miscompiles that by ending its lifetime before evaluating the |
6927 | // third operand. See gcc.gnu.org/PR86769. |
6928 | AttributedTypeLoc ATL; |
6929 | for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); |
6930 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); |
6931 | TL = ATL.getModifiedLoc()) { |
6932 | // The [[lifetimebound]] attribute can be applied to the implicit object |
6933 | // parameter of a non-static member function (other than a ctor or dtor) |
6934 | // by applying it to the function type. |
6935 | if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { |
6936 | const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD); |
6937 | if (!MD || MD->isStatic()) { |
6938 | S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param) |
6939 | << !MD << A->getRange(); |
6940 | } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) { |
6941 | S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor) |
6942 | << isa<CXXDestructorDecl>(Val: MD) << A->getRange(); |
6943 | } |
6944 | } |
6945 | } |
6946 | } |
6947 | } |
6948 | |
6949 | static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, |
6950 | NamedDecl *NewDecl, |
6951 | bool IsSpecialization, |
6952 | bool IsDefinition) { |
6953 | if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) |
6954 | return; |
6955 | |
6956 | bool IsTemplate = false; |
6957 | if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) { |
6958 | OldDecl = OldTD->getTemplatedDecl(); |
6959 | IsTemplate = true; |
6960 | if (!IsSpecialization) |
6961 | IsDefinition = false; |
6962 | } |
6963 | if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) { |
6964 | NewDecl = NewTD->getTemplatedDecl(); |
6965 | IsTemplate = true; |
6966 | } |
6967 | |
6968 | if (!OldDecl || !NewDecl) |
6969 | return; |
6970 | |
6971 | const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); |
6972 | const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); |
6973 | const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); |
6974 | const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); |
6975 | |
6976 | // dllimport and dllexport are inheritable attributes so we have to exclude |
6977 | // inherited attribute instances. |
6978 | bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || |
6979 | (NewExportAttr && !NewExportAttr->isInherited()); |
6980 | |
6981 | // A redeclaration is not allowed to add a dllimport or dllexport attribute, |
6982 | // the only exception being explicit specializations. |
6983 | // Implicitly generated declarations are also excluded for now because there |
6984 | // is no other way to switch these to use dllimport or dllexport. |
6985 | bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; |
6986 | |
6987 | if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { |
6988 | // Allow with a warning for free functions and global variables. |
6989 | bool JustWarn = false; |
6990 | if (!OldDecl->isCXXClassMember()) { |
6991 | auto *VD = dyn_cast<VarDecl>(Val: OldDecl); |
6992 | if (VD && !VD->getDescribedVarTemplate()) |
6993 | JustWarn = true; |
6994 | auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl); |
6995 | if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) |
6996 | JustWarn = true; |
6997 | } |
6998 | |
6999 | // We cannot change a declaration that's been used because IR has already |
7000 | // been emitted. Dllimported functions will still work though (modulo |
7001 | // address equality) as they can use the thunk. |
7002 | if (OldDecl->isUsed()) |
7003 | if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr) |
7004 | JustWarn = false; |
7005 | |
7006 | unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration |
7007 | : diag::err_attribute_dll_redeclaration; |
7008 | S.Diag(Loc: NewDecl->getLocation(), DiagID) |
7009 | << NewDecl |
7010 | << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); |
7011 | S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration); |
7012 | if (!JustWarn) { |
7013 | NewDecl->setInvalidDecl(); |
7014 | return; |
7015 | } |
7016 | } |
7017 | |
7018 | // A redeclaration is not allowed to drop a dllimport attribute, the only |
7019 | // exceptions being inline function definitions (except for function |
7020 | // templates), local extern declarations, qualified friend declarations or |
7021 | // special MSVC extension: in the last case, the declaration is treated as if |
7022 | // it were marked dllexport. |
7023 | bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; |
7024 | bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); |
7025 | if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) { |
7026 | // Ignore static data because out-of-line definitions are diagnosed |
7027 | // separately. |
7028 | IsStaticDataMember = VD->isStaticDataMember(); |
7029 | IsDefinition = VD->isThisDeclarationADefinition(S.Context) != |
7030 | VarDecl::DeclarationOnly; |
7031 | } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) { |
7032 | IsInline = FD->isInlined(); |
7033 | IsQualifiedFriend = FD->getQualifier() && |
7034 | FD->getFriendObjectKind() == Decl::FOK_Declared; |
7035 | } |
7036 | |
7037 | if (OldImportAttr && !HasNewAttr && |
7038 | (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && |
7039 | !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { |
7040 | if (IsMicrosoftABI && IsDefinition) { |
7041 | if (IsSpecialization) { |
7042 | S.Diag( |
7043 | Loc: NewDecl->getLocation(), |
7044 | DiagID: diag::err_attribute_dllimport_function_specialization_definition); |
7045 | S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute); |
7046 | NewDecl->dropAttr<DLLImportAttr>(); |
7047 | } else { |
7048 | S.Diag(Loc: NewDecl->getLocation(), |
7049 | DiagID: diag::warn_redeclaration_without_import_attribute) |
7050 | << NewDecl; |
7051 | S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration); |
7052 | NewDecl->dropAttr<DLLImportAttr>(); |
7053 | NewDecl->addAttr(A: DLLExportAttr::CreateImplicit( |
7054 | Ctx&: S.Context, Range: NewImportAttr->getRange())); |
7055 | } |
7056 | } else if (IsMicrosoftABI && IsSpecialization) { |
7057 | assert(!IsDefinition); |
7058 | // MSVC allows this. Keep the inherited attribute. |
7059 | } else { |
7060 | S.Diag(Loc: NewDecl->getLocation(), |
7061 | DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored) |
7062 | << NewDecl << OldImportAttr; |
7063 | S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration); |
7064 | S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute); |
7065 | OldDecl->dropAttr<DLLImportAttr>(); |
7066 | NewDecl->dropAttr<DLLImportAttr>(); |
7067 | } |
7068 | } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { |
7069 | // In MinGW, seeing a function declared inline drops the dllimport |
7070 | // attribute. |
7071 | OldDecl->dropAttr<DLLImportAttr>(); |
7072 | NewDecl->dropAttr<DLLImportAttr>(); |
7073 | S.Diag(Loc: NewDecl->getLocation(), |
7074 | DiagID: diag::warn_dllimport_dropped_from_inline_function) |
7075 | << NewDecl << OldImportAttr; |
7076 | } |
7077 | |
7078 | // A specialization of a class template member function is processed here |
7079 | // since it's a redeclaration. If the parent class is dllexport, the |
7080 | // specialization inherits that attribute. This doesn't happen automatically |
7081 | // since the parent class isn't instantiated until later. |
7082 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) { |
7083 | if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && |
7084 | !NewImportAttr && !NewExportAttr) { |
7085 | if (const DLLExportAttr *ParentExportAttr = |
7086 | MD->getParent()->getAttr<DLLExportAttr>()) { |
7087 | DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context); |
7088 | NewAttr->setInherited(true); |
7089 | NewDecl->addAttr(A: NewAttr); |
7090 | } |
7091 | } |
7092 | } |
7093 | } |
7094 | |
7095 | /// Given that we are within the definition of the given function, |
7096 | /// will that definition behave like C99's 'inline', where the |
7097 | /// definition is discarded except for optimization purposes? |
7098 | static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { |
7099 | // Try to avoid calling GetGVALinkageForFunction. |
7100 | |
7101 | // All cases of this require the 'inline' keyword. |
7102 | if (!FD->isInlined()) return false; |
7103 | |
7104 | // This is only possible in C++ with the gnu_inline attribute. |
7105 | if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) |
7106 | return false; |
7107 | |
7108 | // Okay, go ahead and call the relatively-more-expensive function. |
7109 | return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; |
7110 | } |
7111 | |
7112 | /// Determine whether a variable is extern "C" prior to attaching |
7113 | /// an initializer. We can't just call isExternC() here, because that |
7114 | /// will also compute and cache whether the declaration is externally |
7115 | /// visible, which might change when we attach the initializer. |
7116 | /// |
7117 | /// This can only be used if the declaration is known to not be a |
7118 | /// redeclaration of an internal linkage declaration. |
7119 | /// |
7120 | /// For instance: |
7121 | /// |
7122 | /// auto x = []{}; |
7123 | /// |
7124 | /// Attaching the initializer here makes this declaration not externally |
7125 | /// visible, because its type has internal linkage. |
7126 | /// |
7127 | /// FIXME: This is a hack. |
7128 | template<typename T> |
7129 | static bool isIncompleteDeclExternC(Sema &S, const T *D) { |
7130 | if (S.getLangOpts().CPlusPlus) { |
7131 | // In C++, the overloadable attribute negates the effects of extern "C". |
7132 | if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) |
7133 | return false; |
7134 | |
7135 | // So do CUDA's host/device attributes. |
7136 | if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || |
7137 | D->template hasAttr<CUDAHostAttr>())) |
7138 | return false; |
7139 | } |
7140 | return D->isExternC(); |
7141 | } |
7142 | |
7143 | static bool shouldConsiderLinkage(const VarDecl *VD) { |
7144 | const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); |
7145 | if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) || |
7146 | isa<OMPDeclareMapperDecl>(Val: DC)) |
7147 | return VD->hasExternalStorage(); |
7148 | if (DC->isFileContext()) |
7149 | return true; |
7150 | if (DC->isRecord()) |
7151 | return false; |
7152 | if (DC->getDeclKind() == Decl::HLSLBuffer) |
7153 | return false; |
7154 | |
7155 | if (isa<RequiresExprBodyDecl>(Val: DC)) |
7156 | return false; |
7157 | llvm_unreachable("Unexpected context" ); |
7158 | } |
7159 | |
7160 | static bool shouldConsiderLinkage(const FunctionDecl *FD) { |
7161 | const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); |
7162 | if (DC->isFileContext() || DC->isFunctionOrMethod() || |
7163 | isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC)) |
7164 | return true; |
7165 | if (DC->isRecord()) |
7166 | return false; |
7167 | llvm_unreachable("Unexpected context" ); |
7168 | } |
7169 | |
7170 | static bool hasParsedAttr(Scope *S, const Declarator &PD, |
7171 | ParsedAttr::Kind Kind) { |
7172 | // Check decl attributes on the DeclSpec. |
7173 | if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind)) |
7174 | return true; |
7175 | |
7176 | // Walk the declarator structure, checking decl attributes that were in a type |
7177 | // position to the decl itself. |
7178 | for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { |
7179 | if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind)) |
7180 | return true; |
7181 | } |
7182 | |
7183 | // Finally, check attributes on the decl itself. |
7184 | return PD.getAttributes().hasAttribute(K: Kind) || |
7185 | PD.getDeclarationAttributes().hasAttribute(K: Kind); |
7186 | } |
7187 | |
7188 | bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { |
7189 | if (!DC->isFunctionOrMethod()) |
7190 | return false; |
7191 | |
7192 | // If this is a local extern function or variable declared within a function |
7193 | // template, don't add it into the enclosing namespace scope until it is |
7194 | // instantiated; it might have a dependent type right now. |
7195 | if (DC->isDependentContext()) |
7196 | return true; |
7197 | |
7198 | // C++11 [basic.link]p7: |
7199 | // When a block scope declaration of an entity with linkage is not found to |
7200 | // refer to some other declaration, then that entity is a member of the |
7201 | // innermost enclosing namespace. |
7202 | // |
7203 | // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a |
7204 | // semantically-enclosing namespace, not a lexically-enclosing one. |
7205 | while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC)) |
7206 | DC = DC->getParent(); |
7207 | return true; |
7208 | } |
7209 | |
7210 | /// Returns true if given declaration has external C language linkage. |
7211 | static bool isDeclExternC(const Decl *D) { |
7212 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
7213 | return FD->isExternC(); |
7214 | if (const auto *VD = dyn_cast<VarDecl>(Val: D)) |
7215 | return VD->isExternC(); |
7216 | |
7217 | llvm_unreachable("Unknown type of decl!" ); |
7218 | } |
7219 | |
7220 | /// Returns true if there hasn't been any invalid type diagnosed. |
7221 | static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { |
7222 | DeclContext *DC = NewVD->getDeclContext(); |
7223 | QualType R = NewVD->getType(); |
7224 | |
7225 | // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. |
7226 | // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function |
7227 | // argument. |
7228 | if (R->isImageType() || R->isPipeType()) { |
7229 | Se.Diag(Loc: NewVD->getLocation(), |
7230 | DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter) |
7231 | << R; |
7232 | NewVD->setInvalidDecl(); |
7233 | return false; |
7234 | } |
7235 | |
7236 | // OpenCL v1.2 s6.9.r: |
7237 | // The event type cannot be used to declare a program scope variable. |
7238 | // OpenCL v2.0 s6.9.q: |
7239 | // The clk_event_t and reserve_id_t types cannot be declared in program |
7240 | // scope. |
7241 | if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { |
7242 | if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { |
7243 | Se.Diag(Loc: NewVD->getLocation(), |
7244 | DiagID: diag::err_invalid_type_for_program_scope_var) |
7245 | << R; |
7246 | NewVD->setInvalidDecl(); |
7247 | return false; |
7248 | } |
7249 | } |
7250 | |
7251 | // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. |
7252 | if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers" , |
7253 | LO: Se.getLangOpts())) { |
7254 | QualType NR = R.getCanonicalType(); |
7255 | while (NR->isPointerType() || NR->isMemberFunctionPointerType() || |
7256 | NR->isReferenceType()) { |
7257 | if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || |
7258 | NR->isFunctionReferenceType()) { |
7259 | Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer) |
7260 | << NR->isReferenceType(); |
7261 | NewVD->setInvalidDecl(); |
7262 | return false; |
7263 | } |
7264 | NR = NR->getPointeeType(); |
7265 | } |
7266 | } |
7267 | |
7268 | if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16" , |
7269 | LO: Se.getLangOpts())) { |
7270 | // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and |
7271 | // half array type (unless the cl_khr_fp16 extension is enabled). |
7272 | if (Se.Context.getBaseElementType(QT: R)->isHalfType()) { |
7273 | Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R; |
7274 | NewVD->setInvalidDecl(); |
7275 | return false; |
7276 | } |
7277 | } |
7278 | |
7279 | // OpenCL v1.2 s6.9.r: |
7280 | // The event type cannot be used with the __local, __constant and __global |
7281 | // address space qualifiers. |
7282 | if (R->isEventT()) { |
7283 | if (R.getAddressSpace() != LangAS::opencl_private) { |
7284 | Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual); |
7285 | NewVD->setInvalidDecl(); |
7286 | return false; |
7287 | } |
7288 | } |
7289 | |
7290 | if (R->isSamplerT()) { |
7291 | // OpenCL v1.2 s6.9.b p4: |
7292 | // The sampler type cannot be used with the __local and __global address |
7293 | // space qualifiers. |
7294 | if (R.getAddressSpace() == LangAS::opencl_local || |
7295 | R.getAddressSpace() == LangAS::opencl_global) { |
7296 | Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace); |
7297 | NewVD->setInvalidDecl(); |
7298 | } |
7299 | |
7300 | // OpenCL v1.2 s6.12.14.1: |
7301 | // A global sampler must be declared with either the constant address |
7302 | // space qualifier or with the const qualifier. |
7303 | if (DC->isTranslationUnit() && |
7304 | !(R.getAddressSpace() == LangAS::opencl_constant || |
7305 | R.isConstQualified())) { |
7306 | Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler); |
7307 | NewVD->setInvalidDecl(); |
7308 | } |
7309 | if (NewVD->isInvalidDecl()) |
7310 | return false; |
7311 | } |
7312 | |
7313 | return true; |
7314 | } |
7315 | |
7316 | template <typename AttrTy> |
7317 | static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { |
7318 | const TypedefNameDecl *TND = TT->getDecl(); |
7319 | if (const auto *Attribute = TND->getAttr<AttrTy>()) { |
7320 | AttrTy *Clone = Attribute->clone(S.Context); |
7321 | Clone->setInherited(true); |
7322 | D->addAttr(A: Clone); |
7323 | } |
7324 | } |
7325 | |
7326 | // This function emits warning and a corresponding note based on the |
7327 | // ReadOnlyPlacementAttr attribute. The warning checks that all global variable |
7328 | // declarations of an annotated type must be const qualified. |
7329 | void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) { |
7330 | QualType VarType = VD->getType().getCanonicalType(); |
7331 | |
7332 | // Ignore local declarations (for now) and those with const qualification. |
7333 | // TODO: Local variables should not be allowed if their type declaration has |
7334 | // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch. |
7335 | if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified()) |
7336 | return; |
7337 | |
7338 | if (VarType->isArrayType()) { |
7339 | // Retrieve element type for array declarations. |
7340 | VarType = S.getASTContext().getBaseElementType(QT: VarType); |
7341 | } |
7342 | |
7343 | const RecordDecl *RD = VarType->getAsRecordDecl(); |
7344 | |
7345 | // Check if the record declaration is present and if it has any attributes. |
7346 | if (RD == nullptr) |
7347 | return; |
7348 | |
7349 | if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) { |
7350 | S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD; |
7351 | S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement); |
7352 | return; |
7353 | } |
7354 | } |
7355 | |
7356 | NamedDecl *Sema::ActOnVariableDeclarator( |
7357 | Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, |
7358 | LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, |
7359 | bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { |
7360 | QualType R = TInfo->getType(); |
7361 | DeclarationName Name = GetNameForDeclarator(D).getName(); |
7362 | |
7363 | IdentifierInfo *II = Name.getAsIdentifierInfo(); |
7364 | bool IsPlaceholderVariable = false; |
7365 | |
7366 | if (D.isDecompositionDeclarator()) { |
7367 | // Take the name of the first declarator as our name for diagnostic |
7368 | // purposes. |
7369 | auto &Decomp = D.getDecompositionDeclarator(); |
7370 | if (!Decomp.bindings().empty()) { |
7371 | II = Decomp.bindings()[0].Name; |
7372 | Name = II; |
7373 | } |
7374 | } else if (!II) { |
7375 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name; |
7376 | return nullptr; |
7377 | } |
7378 | |
7379 | |
7380 | DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); |
7381 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec()); |
7382 | |
7383 | if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) && |
7384 | SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) { |
7385 | IsPlaceholderVariable = true; |
7386 | if (!Previous.empty()) { |
7387 | NamedDecl *PrevDecl = *Previous.begin(); |
7388 | bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals( |
7389 | DC: DC->getRedeclContext()); |
7390 | if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) |
7391 | DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc()); |
7392 | } |
7393 | } |
7394 | |
7395 | // dllimport globals without explicit storage class are treated as extern. We |
7396 | // have to change the storage class this early to get the right DeclContext. |
7397 | if (SC == SC_None && !DC->isRecord() && |
7398 | hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) && |
7399 | !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport)) |
7400 | SC = SC_Extern; |
7401 | |
7402 | DeclContext *OriginalDC = DC; |
7403 | bool IsLocalExternDecl = SC == SC_Extern && |
7404 | adjustContextForLocalExternDecl(DC); |
7405 | |
7406 | if (SCSpec == DeclSpec::SCS_mutable) { |
7407 | // mutable can only appear on non-static class members, so it's always |
7408 | // an error here |
7409 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember); |
7410 | D.setInvalidType(); |
7411 | SC = SC_None; |
7412 | } |
7413 | |
7414 | if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && |
7415 | !D.getAsmLabel() && !getSourceManager().isInSystemMacro( |
7416 | loc: D.getDeclSpec().getStorageClassSpecLoc())) { |
7417 | // In C++11, the 'register' storage class specifier is deprecated. |
7418 | // Suppress the warning in system macros, it's used in macros in some |
7419 | // popular C system headers, such as in glibc's htonl() macro. |
7420 | Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(), |
7421 | DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class |
7422 | : diag::warn_deprecated_register) |
7423 | << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc()); |
7424 | } |
7425 | |
7426 | DiagnoseFunctionSpecifiers(DS: D.getDeclSpec()); |
7427 | |
7428 | if (!DC->isRecord() && S->getFnParent() == nullptr) { |
7429 | // C99 6.9p2: The storage-class specifiers auto and register shall not |
7430 | // appear in the declaration specifiers in an external declaration. |
7431 | // Global Register+Asm is a GNU extension we support. |
7432 | if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { |
7433 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope); |
7434 | D.setInvalidType(); |
7435 | } |
7436 | } |
7437 | |
7438 | // If this variable has a VLA type and an initializer, try to |
7439 | // fold to a constant-sized type. This is otherwise invalid. |
7440 | if (D.hasInitializer() && R->isVariableArrayType()) |
7441 | tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(), |
7442 | /*DiagID=*/FailedFoldDiagID: 0); |
7443 | |
7444 | if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) { |
7445 | const AutoType *AT = TL.getTypePtr(); |
7446 | CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc()); |
7447 | } |
7448 | |
7449 | bool IsMemberSpecialization = false; |
7450 | bool IsVariableTemplateSpecialization = false; |
7451 | bool IsPartialSpecialization = false; |
7452 | bool IsVariableTemplate = false; |
7453 | VarDecl *NewVD = nullptr; |
7454 | VarTemplateDecl *NewTemplate = nullptr; |
7455 | TemplateParameterList *TemplateParams = nullptr; |
7456 | if (!getLangOpts().CPlusPlus) { |
7457 | NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(), |
7458 | Id: II, T: R, TInfo, S: SC); |
7459 | |
7460 | if (R->getContainedDeducedType()) |
7461 | ParsingInitForAutoVars.insert(Ptr: NewVD); |
7462 | |
7463 | if (D.isInvalidType()) |
7464 | NewVD->setInvalidDecl(); |
7465 | |
7466 | if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && |
7467 | NewVD->hasLocalStorage()) |
7468 | checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(), |
7469 | UseContext: NTCUC_AutoVar, NonTrivialKind: NTCUK_Destruct); |
7470 | } else { |
7471 | bool Invalid = false; |
7472 | // Match up the template parameter lists with the scope specifier, then |
7473 | // determine whether we have a template or a template specialization. |
7474 | TemplateParams = MatchTemplateParametersToScopeSpecifier( |
7475 | DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(), |
7476 | SS: D.getCXXScopeSpec(), |
7477 | TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId |
7478 | ? D.getName().TemplateId |
7479 | : nullptr, |
7480 | ParamLists: TemplateParamLists, |
7481 | /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid); |
7482 | |
7483 | if (TemplateParams) { |
7484 | if (!TemplateParams->size() && |
7485 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { |
7486 | // There is an extraneous 'template<>' for this variable. Complain |
7487 | // about it, but allow the declaration of the variable. |
7488 | Diag(Loc: TemplateParams->getTemplateLoc(), |
7489 | DiagID: diag::err_template_variable_noparams) |
7490 | << II |
7491 | << SourceRange(TemplateParams->getTemplateLoc(), |
7492 | TemplateParams->getRAngleLoc()); |
7493 | TemplateParams = nullptr; |
7494 | } else { |
7495 | // Check that we can declare a template here. |
7496 | if (CheckTemplateDeclScope(S, TemplateParams)) |
7497 | return nullptr; |
7498 | |
7499 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { |
7500 | // This is an explicit specialization or a partial specialization. |
7501 | IsVariableTemplateSpecialization = true; |
7502 | IsPartialSpecialization = TemplateParams->size() > 0; |
7503 | } else { // if (TemplateParams->size() > 0) |
7504 | // This is a template declaration. |
7505 | IsVariableTemplate = true; |
7506 | |
7507 | // Only C++1y supports variable templates (N3651). |
7508 | Diag(Loc: D.getIdentifierLoc(), |
7509 | DiagID: getLangOpts().CPlusPlus14 |
7510 | ? diag::warn_cxx11_compat_variable_template |
7511 | : diag::ext_variable_template); |
7512 | } |
7513 | } |
7514 | } else { |
7515 | // Check that we can declare a member specialization here. |
7516 | if (!TemplateParamLists.empty() && IsMemberSpecialization && |
7517 | CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back())) |
7518 | return nullptr; |
7519 | assert((Invalid || |
7520 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && |
7521 | "should have a 'template<>' for this decl" ); |
7522 | } |
7523 | |
7524 | bool IsExplicitSpecialization = |
7525 | IsVariableTemplateSpecialization && !IsPartialSpecialization; |
7526 | |
7527 | // C++ [temp.expl.spec]p2: |
7528 | // The declaration in an explicit-specialization shall not be an |
7529 | // export-declaration. An explicit specialization shall not use a |
7530 | // storage-class-specifier other than thread_local. |
7531 | // |
7532 | // We use the storage-class-specifier from DeclSpec because we may have |
7533 | // added implicit 'extern' for declarations with __declspec(dllimport)! |
7534 | if (SCSpec != DeclSpec::SCS_unspecified && |
7535 | (IsExplicitSpecialization || IsMemberSpecialization)) { |
7536 | Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(), |
7537 | DiagID: diag::ext_explicit_specialization_storage_class) |
7538 | << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc()); |
7539 | } |
7540 | |
7541 | if (CurContext->isRecord()) { |
7542 | if (SC == SC_Static) { |
7543 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) { |
7544 | // Walk up the enclosing DeclContexts to check for any that are |
7545 | // incompatible with static data members. |
7546 | const DeclContext *FunctionOrMethod = nullptr; |
7547 | const CXXRecordDecl *AnonStruct = nullptr; |
7548 | for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { |
7549 | if (Ctxt->isFunctionOrMethod()) { |
7550 | FunctionOrMethod = Ctxt; |
7551 | break; |
7552 | } |
7553 | const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt); |
7554 | if (ParentDecl && !ParentDecl->getDeclName()) { |
7555 | AnonStruct = ParentDecl; |
7556 | break; |
7557 | } |
7558 | } |
7559 | if (FunctionOrMethod) { |
7560 | // C++ [class.static.data]p5: A local class shall not have static |
7561 | // data members. |
7562 | Diag(Loc: D.getIdentifierLoc(), |
7563 | DiagID: diag::err_static_data_member_not_allowed_in_local_class) |
7564 | << Name << RD->getDeclName() |
7565 | << llvm::to_underlying(E: RD->getTagKind()); |
7566 | } else if (AnonStruct) { |
7567 | // C++ [class.static.data]p4: Unnamed classes and classes contained |
7568 | // directly or indirectly within unnamed classes shall not contain |
7569 | // static data members. |
7570 | Diag(Loc: D.getIdentifierLoc(), |
7571 | DiagID: diag::err_static_data_member_not_allowed_in_anon_struct) |
7572 | << Name << llvm::to_underlying(E: AnonStruct->getTagKind()); |
7573 | Invalid = true; |
7574 | } else if (RD->isUnion()) { |
7575 | // C++98 [class.union]p1: If a union contains a static data member, |
7576 | // the program is ill-formed. C++11 drops this restriction. |
7577 | Diag(Loc: D.getIdentifierLoc(), |
7578 | DiagID: getLangOpts().CPlusPlus11 |
7579 | ? diag::warn_cxx98_compat_static_data_member_in_union |
7580 | : diag::ext_static_data_member_in_union) |
7581 | << Name; |
7582 | } |
7583 | } |
7584 | } else if (IsVariableTemplate || IsPartialSpecialization) { |
7585 | // There is no such thing as a member field template. |
7586 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member) |
7587 | << II << TemplateParams->getSourceRange(); |
7588 | // Recover by pretending this is a static data member template. |
7589 | SC = SC_Static; |
7590 | } |
7591 | } else if (DC->isRecord()) { |
7592 | // This is an out-of-line definition of a static data member. |
7593 | switch (SC) { |
7594 | case SC_None: |
7595 | break; |
7596 | case SC_Static: |
7597 | Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(), |
7598 | DiagID: diag::err_static_out_of_line) |
7599 | << FixItHint::CreateRemoval( |
7600 | RemoveRange: D.getDeclSpec().getStorageClassSpecLoc()); |
7601 | break; |
7602 | case SC_Auto: |
7603 | case SC_Register: |
7604 | case SC_Extern: |
7605 | // [dcl.stc] p2: The auto or register specifiers shall be applied only |
7606 | // to names of variables declared in a block or to function parameters. |
7607 | // [dcl.stc] p6: The extern specifier cannot be used in the declaration |
7608 | // of class members |
7609 | |
7610 | Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(), |
7611 | DiagID: diag::err_storage_class_for_static_member) |
7612 | << FixItHint::CreateRemoval( |
7613 | RemoveRange: D.getDeclSpec().getStorageClassSpecLoc()); |
7614 | break; |
7615 | case SC_PrivateExtern: |
7616 | llvm_unreachable("C storage class in c++!" ); |
7617 | } |
7618 | } |
7619 | |
7620 | if (IsVariableTemplateSpecialization) { |
7621 | SourceLocation TemplateKWLoc = |
7622 | TemplateParamLists.size() > 0 |
7623 | ? TemplateParamLists[0]->getTemplateLoc() |
7624 | : SourceLocation(); |
7625 | DeclResult Res = ActOnVarTemplateSpecialization( |
7626 | S, D, DI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC, |
7627 | IsPartialSpecialization); |
7628 | if (Res.isInvalid()) |
7629 | return nullptr; |
7630 | NewVD = cast<VarDecl>(Val: Res.get()); |
7631 | AddToScope = false; |
7632 | } else if (D.isDecompositionDeclarator()) { |
7633 | NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), |
7634 | LSquareLoc: D.getIdentifierLoc(), T: R, TInfo, S: SC, |
7635 | Bindings); |
7636 | } else |
7637 | NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), |
7638 | IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC); |
7639 | |
7640 | // If this is supposed to be a variable template, create it as such. |
7641 | if (IsVariableTemplate) { |
7642 | NewTemplate = |
7643 | VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name, |
7644 | Params: TemplateParams, Decl: NewVD); |
7645 | NewVD->setDescribedVarTemplate(NewTemplate); |
7646 | } |
7647 | |
7648 | // If this decl has an auto type in need of deduction, make a note of the |
7649 | // Decl so we can diagnose uses of it in its own initializer. |
7650 | if (R->getContainedDeducedType()) |
7651 | ParsingInitForAutoVars.insert(Ptr: NewVD); |
7652 | |
7653 | if (D.isInvalidType() || Invalid) { |
7654 | NewVD->setInvalidDecl(); |
7655 | if (NewTemplate) |
7656 | NewTemplate->setInvalidDecl(); |
7657 | } |
7658 | |
7659 | SetNestedNameSpecifier(S&: *this, DD: NewVD, D); |
7660 | |
7661 | // If we have any template parameter lists that don't directly belong to |
7662 | // the variable (matching the scope specifier), store them. |
7663 | // An explicit variable template specialization does not own any template |
7664 | // parameter lists. |
7665 | unsigned VDTemplateParamLists = |
7666 | (TemplateParams && !IsExplicitSpecialization) ? 1 : 0; |
7667 | if (TemplateParamLists.size() > VDTemplateParamLists) |
7668 | NewVD->setTemplateParameterListsInfo( |
7669 | Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists)); |
7670 | } |
7671 | |
7672 | if (D.getDeclSpec().isInlineSpecified()) { |
7673 | if (!getLangOpts().CPlusPlus) { |
7674 | Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function) |
7675 | << 0; |
7676 | } else if (CurContext->isFunctionOrMethod()) { |
7677 | // 'inline' is not allowed on block scope variable declaration. |
7678 | Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), |
7679 | DiagID: diag::err_inline_declaration_block_scope) << Name |
7680 | << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc()); |
7681 | } else { |
7682 | Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), |
7683 | DiagID: getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable |
7684 | : diag::ext_inline_variable); |
7685 | NewVD->setInlineSpecified(); |
7686 | } |
7687 | } |
7688 | |
7689 | // Set the lexical context. If the declarator has a C++ scope specifier, the |
7690 | // lexical context will be different from the semantic context. |
7691 | NewVD->setLexicalDeclContext(CurContext); |
7692 | if (NewTemplate) |
7693 | NewTemplate->setLexicalDeclContext(CurContext); |
7694 | |
7695 | if (IsLocalExternDecl) { |
7696 | if (D.isDecompositionDeclarator()) |
7697 | for (auto *B : Bindings) |
7698 | B->setLocalExternDecl(); |
7699 | else |
7700 | NewVD->setLocalExternDecl(); |
7701 | } |
7702 | |
7703 | bool EmitTLSUnsupportedError = false; |
7704 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { |
7705 | // C++11 [dcl.stc]p4: |
7706 | // When thread_local is applied to a variable of block scope the |
7707 | // storage-class-specifier static is implied if it does not appear |
7708 | // explicitly. |
7709 | // Core issue: 'static' is not implied if the variable is declared |
7710 | // 'extern'. |
7711 | if (NewVD->hasLocalStorage() && |
7712 | (SCSpec != DeclSpec::SCS_unspecified || |
7713 | TSCS != DeclSpec::TSCS_thread_local || |
7714 | !DC->isFunctionOrMethod())) |
7715 | Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(), |
7716 | DiagID: diag::err_thread_non_global) |
7717 | << DeclSpec::getSpecifierName(S: TSCS); |
7718 | else if (!Context.getTargetInfo().isTLSSupported()) { |
7719 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice || |
7720 | getLangOpts().SYCLIsDevice) { |
7721 | // Postpone error emission until we've collected attributes required to |
7722 | // figure out whether it's a host or device variable and whether the |
7723 | // error should be ignored. |
7724 | EmitTLSUnsupportedError = true; |
7725 | // We still need to mark the variable as TLS so it shows up in AST with |
7726 | // proper storage class for other tools to use even if we're not going |
7727 | // to emit any code for it. |
7728 | NewVD->setTSCSpec(TSCS); |
7729 | } else |
7730 | Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(), |
7731 | DiagID: diag::err_thread_unsupported); |
7732 | } else |
7733 | NewVD->setTSCSpec(TSCS); |
7734 | } |
7735 | |
7736 | switch (D.getDeclSpec().getConstexprSpecifier()) { |
7737 | case ConstexprSpecKind::Unspecified: |
7738 | break; |
7739 | |
7740 | case ConstexprSpecKind::Consteval: |
7741 | Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), |
7742 | DiagID: diag::err_constexpr_wrong_decl_kind) |
7743 | << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); |
7744 | [[fallthrough]]; |
7745 | |
7746 | case ConstexprSpecKind::Constexpr: |
7747 | NewVD->setConstexpr(true); |
7748 | // C++1z [dcl.spec.constexpr]p1: |
7749 | // A static data member declared with the constexpr specifier is |
7750 | // implicitly an inline variable. |
7751 | if (NewVD->isStaticDataMember() && |
7752 | (getLangOpts().CPlusPlus17 || |
7753 | Context.getTargetInfo().getCXXABI().isMicrosoft())) |
7754 | NewVD->setImplicitlyInline(); |
7755 | break; |
7756 | |
7757 | case ConstexprSpecKind::Constinit: |
7758 | if (!NewVD->hasGlobalStorage()) |
7759 | Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), |
7760 | DiagID: diag::err_constinit_local_variable); |
7761 | else |
7762 | NewVD->addAttr( |
7763 | A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(), |
7764 | S: ConstInitAttr::Keyword_constinit)); |
7765 | break; |
7766 | } |
7767 | |
7768 | // C99 6.7.4p3 |
7769 | // An inline definition of a function with external linkage shall |
7770 | // not contain a definition of a modifiable object with static or |
7771 | // thread storage duration... |
7772 | // We only apply this when the function is required to be defined |
7773 | // elsewhere, i.e. when the function is not 'extern inline'. Note |
7774 | // that a local variable with thread storage duration still has to |
7775 | // be marked 'static'. Also note that it's possible to get these |
7776 | // semantics in C++ using __attribute__((gnu_inline)). |
7777 | if (SC == SC_Static && S->getFnParent() != nullptr && |
7778 | !NewVD->getType().isConstQualified()) { |
7779 | FunctionDecl *CurFD = getCurFunctionDecl(); |
7780 | if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) { |
7781 | Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(), |
7782 | DiagID: diag::warn_static_local_in_extern_inline); |
7783 | MaybeSuggestAddingStaticToDecl(D: CurFD); |
7784 | } |
7785 | } |
7786 | |
7787 | if (D.getDeclSpec().isModulePrivateSpecified()) { |
7788 | if (IsVariableTemplateSpecialization) |
7789 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization) |
7790 | << (IsPartialSpecialization ? 1 : 0) |
7791 | << FixItHint::CreateRemoval( |
7792 | RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc()); |
7793 | else if (IsMemberSpecialization) |
7794 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization) |
7795 | << 2 |
7796 | << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc()); |
7797 | else if (NewVD->hasLocalStorage()) |
7798 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local) |
7799 | << 0 << NewVD |
7800 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) |
7801 | << FixItHint::CreateRemoval( |
7802 | RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc()); |
7803 | else { |
7804 | NewVD->setModulePrivate(); |
7805 | if (NewTemplate) |
7806 | NewTemplate->setModulePrivate(); |
7807 | for (auto *B : Bindings) |
7808 | B->setModulePrivate(); |
7809 | } |
7810 | } |
7811 | |
7812 | if (getLangOpts().OpenCL) { |
7813 | deduceOpenCLAddressSpace(Decl: NewVD); |
7814 | |
7815 | DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); |
7816 | if (TSC != TSCS_unspecified) { |
7817 | Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(), |
7818 | DiagID: diag::err_opencl_unknown_type_specifier) |
7819 | << getLangOpts().getOpenCLVersionString() |
7820 | << DeclSpec::getSpecifierName(S: TSC) << 1; |
7821 | NewVD->setInvalidDecl(); |
7822 | } |
7823 | } |
7824 | |
7825 | // WebAssembly tables are always in address space 1 (wasm_var). Don't apply |
7826 | // address space if the table has local storage (semantic checks elsewhere |
7827 | // will produce an error anyway). |
7828 | if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) { |
7829 | if (ATy && ATy->getElementType().isWebAssemblyReferenceType() && |
7830 | !NewVD->hasLocalStorage()) { |
7831 | QualType Type = Context.getAddrSpaceQualType( |
7832 | T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1)); |
7833 | NewVD->setType(Type); |
7834 | } |
7835 | } |
7836 | |
7837 | // Handle attributes prior to checking for duplicates in MergeVarDecl |
7838 | ProcessDeclAttributes(S, D: NewVD, PD: D); |
7839 | |
7840 | // FIXME: This is probably the wrong location to be doing this and we should |
7841 | // probably be doing this for more attributes (especially for function |
7842 | // pointer attributes such as format, warn_unused_result, etc.). Ideally |
7843 | // the code to copy attributes would be generated by TableGen. |
7844 | if (R->isFunctionPointerType()) |
7845 | if (const auto *TT = R->getAs<TypedefType>()) |
7846 | copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT); |
7847 | |
7848 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice || |
7849 | getLangOpts().SYCLIsDevice) { |
7850 | if (EmitTLSUnsupportedError && |
7851 | ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) || |
7852 | (getLangOpts().OpenMPIsTargetDevice && |
7853 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD)))) |
7854 | Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(), |
7855 | DiagID: diag::err_thread_unsupported); |
7856 | |
7857 | if (EmitTLSUnsupportedError && |
7858 | (LangOpts.SYCLIsDevice || |
7859 | (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice))) |
7860 | targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported); |
7861 | // CUDA B.2.5: "__shared__ and __constant__ variables have implied static |
7862 | // storage [duration]." |
7863 | if (SC == SC_None && S->getFnParent() != nullptr && |
7864 | (NewVD->hasAttr<CUDASharedAttr>() || |
7865 | NewVD->hasAttr<CUDAConstantAttr>())) { |
7866 | NewVD->setStorageClass(SC_Static); |
7867 | } |
7868 | } |
7869 | |
7870 | // Ensure that dllimport globals without explicit storage class are treated as |
7871 | // extern. The storage class is set above using parsed attributes. Now we can |
7872 | // check the VarDecl itself. |
7873 | assert(!NewVD->hasAttr<DLLImportAttr>() || |
7874 | NewVD->getAttr<DLLImportAttr>()->isInherited() || |
7875 | NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); |
7876 | |
7877 | // In auto-retain/release, infer strong retension for variables of |
7878 | // retainable type. |
7879 | if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD)) |
7880 | NewVD->setInvalidDecl(); |
7881 | |
7882 | // Handle GNU asm-label extension (encoded as an attribute). |
7883 | if (Expr *E = (Expr*)D.getAsmLabel()) { |
7884 | // The parser guarantees this is a string. |
7885 | StringLiteral *SE = cast<StringLiteral>(Val: E); |
7886 | StringRef Label = SE->getString(); |
7887 | if (S->getFnParent() != nullptr) { |
7888 | switch (SC) { |
7889 | case SC_None: |
7890 | case SC_Auto: |
7891 | Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label; |
7892 | break; |
7893 | case SC_Register: |
7894 | // Local Named register |
7895 | if (!Context.getTargetInfo().isValidGCCRegisterName(Name: Label) && |
7896 | DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl())) |
7897 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label; |
7898 | break; |
7899 | case SC_Static: |
7900 | case SC_Extern: |
7901 | case SC_PrivateExtern: |
7902 | break; |
7903 | } |
7904 | } else if (SC == SC_Register) { |
7905 | // Global Named register |
7906 | if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) { |
7907 | const auto &TI = Context.getTargetInfo(); |
7908 | bool HasSizeMismatch; |
7909 | |
7910 | if (!TI.isValidGCCRegisterName(Name: Label)) |
7911 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label; |
7912 | else if (!TI.validateGlobalRegisterVariable(RegName: Label, |
7913 | RegSize: Context.getTypeSize(T: R), |
7914 | HasSizeMismatch)) |
7915 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label; |
7916 | else if (HasSizeMismatch) |
7917 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label; |
7918 | } |
7919 | |
7920 | if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) { |
7921 | Diag(Loc: D.getBeginLoc(), DiagID: diag::err_asm_bad_register_type); |
7922 | NewVD->setInvalidDecl(true); |
7923 | } |
7924 | } |
7925 | |
7926 | NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label, |
7927 | /*IsLiteralLabel=*/true, |
7928 | Range: SE->getStrTokenLoc(TokNum: 0))); |
7929 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { |
7930 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = |
7931 | ExtnameUndeclaredIdentifiers.find(Val: NewVD->getIdentifier()); |
7932 | if (I != ExtnameUndeclaredIdentifiers.end()) { |
7933 | if (isDeclExternC(D: NewVD)) { |
7934 | NewVD->addAttr(A: I->second); |
7935 | ExtnameUndeclaredIdentifiers.erase(I); |
7936 | } else |
7937 | Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied) |
7938 | << /*Variable*/1 << NewVD; |
7939 | } |
7940 | } |
7941 | |
7942 | // Find the shadowed declaration before filtering for scope. |
7943 | NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() |
7944 | ? getShadowedDeclaration(D: NewVD, R: Previous) |
7945 | : nullptr; |
7946 | |
7947 | // Don't consider existing declarations that are in a different |
7948 | // scope and are out-of-semantic-context declarations (if the new |
7949 | // declaration has linkage). |
7950 | FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD), |
7951 | AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() || |
7952 | IsMemberSpecialization || |
7953 | IsVariableTemplateSpecialization); |
7954 | |
7955 | // Check whether the previous declaration is in the same block scope. This |
7956 | // affects whether we merge types with it, per C++11 [dcl.array]p3. |
7957 | if (getLangOpts().CPlusPlus && |
7958 | NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) |
7959 | NewVD->setPreviousDeclInSameBlockScope( |
7960 | Previous.isSingleResult() && !Previous.isShadowed() && |
7961 | isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false)); |
7962 | |
7963 | if (!getLangOpts().CPlusPlus) { |
7964 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); |
7965 | } else { |
7966 | // If this is an explicit specialization of a static data member, check it. |
7967 | if (IsMemberSpecialization && !IsVariableTemplateSpecialization && |
7968 | !NewVD->isInvalidDecl() && CheckMemberSpecialization(Member: NewVD, Previous)) |
7969 | NewVD->setInvalidDecl(); |
7970 | |
7971 | // Merge the decl with the existing one if appropriate. |
7972 | if (!Previous.empty()) { |
7973 | if (Previous.isSingleResult() && |
7974 | isa<FieldDecl>(Val: Previous.getFoundDecl()) && |
7975 | D.getCXXScopeSpec().isSet()) { |
7976 | // The user tried to define a non-static data member |
7977 | // out-of-line (C++ [dcl.meaning]p1). |
7978 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line) |
7979 | << D.getCXXScopeSpec().getRange(); |
7980 | Previous.clear(); |
7981 | NewVD->setInvalidDecl(); |
7982 | } |
7983 | } else if (D.getCXXScopeSpec().isSet() && |
7984 | !IsVariableTemplateSpecialization) { |
7985 | // No previous declaration in the qualifying scope. |
7986 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member) |
7987 | << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true) |
7988 | << D.getCXXScopeSpec().getRange(); |
7989 | NewVD->setInvalidDecl(); |
7990 | } |
7991 | |
7992 | if (!IsPlaceholderVariable) |
7993 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); |
7994 | |
7995 | // CheckVariableDeclaration will set NewVD as invalid if something is in |
7996 | // error like WebAssembly tables being declared as arrays with a non-zero |
7997 | // size, but then parsing continues and emits further errors on that line. |
7998 | // To avoid that we check here if it happened and return nullptr. |
7999 | if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl()) |
8000 | return nullptr; |
8001 | |
8002 | if (NewTemplate) { |
8003 | VarTemplateDecl *PrevVarTemplate = |
8004 | NewVD->getPreviousDecl() |
8005 | ? NewVD->getPreviousDecl()->getDescribedVarTemplate() |
8006 | : nullptr; |
8007 | |
8008 | // Check the template parameter list of this declaration, possibly |
8009 | // merging in the template parameter list from the previous variable |
8010 | // template declaration. |
8011 | if (CheckTemplateParameterList( |
8012 | NewParams: TemplateParams, |
8013 | OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() |
8014 | : nullptr, |
8015 | TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && |
8016 | DC->isDependentContext()) |
8017 | ? TPC_ClassTemplateMember |
8018 | : TPC_VarTemplate)) |
8019 | NewVD->setInvalidDecl(); |
8020 | |
8021 | // If we are providing an explicit specialization of a static variable |
8022 | // template, make a note of that. |
8023 | if (PrevVarTemplate && |
8024 | PrevVarTemplate->getInstantiatedFromMemberTemplate()) |
8025 | PrevVarTemplate->setMemberSpecialization(); |
8026 | } |
8027 | } |
8028 | |
8029 | // Diagnose shadowed variables iff this isn't a redeclaration. |
8030 | if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration()) |
8031 | CheckShadow(D: NewVD, ShadowedDecl, R: Previous); |
8032 | |
8033 | ProcessPragmaWeak(S, D: NewVD); |
8034 | |
8035 | // If this is the first declaration of an extern C variable, update |
8036 | // the map of such variables. |
8037 | if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && |
8038 | isIncompleteDeclExternC(S&: *this, D: NewVD)) |
8039 | RegisterLocallyScopedExternCDecl(ND: NewVD, S); |
8040 | |
8041 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { |
8042 | MangleNumberingContext *MCtx; |
8043 | Decl *ManglingContextDecl; |
8044 | std::tie(args&: MCtx, args&: ManglingContextDecl) = |
8045 | getCurrentMangleNumberContext(DC: NewVD->getDeclContext()); |
8046 | if (MCtx) { |
8047 | Context.setManglingNumber( |
8048 | ND: NewVD, Number: MCtx->getManglingNumber( |
8049 | VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S))); |
8050 | Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD)); |
8051 | } |
8052 | } |
8053 | |
8054 | // Special handling of variable named 'main'. |
8055 | if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr(Str: "main" ) && |
8056 | NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && |
8057 | !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { |
8058 | |
8059 | // C++ [basic.start.main]p3 |
8060 | // A program that declares a variable main at global scope is ill-formed. |
8061 | if (getLangOpts().CPlusPlus) |
8062 | Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable); |
8063 | |
8064 | // In C, and external-linkage variable named main results in undefined |
8065 | // behavior. |
8066 | else if (NewVD->hasExternalFormalLinkage()) |
8067 | Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined); |
8068 | } |
8069 | |
8070 | if (D.isRedeclaration() && !Previous.empty()) { |
8071 | NamedDecl *Prev = Previous.getRepresentativeDecl(); |
8072 | checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization, |
8073 | IsDefinition: D.isFunctionDefinition()); |
8074 | } |
8075 | |
8076 | if (NewTemplate) { |
8077 | if (NewVD->isInvalidDecl()) |
8078 | NewTemplate->setInvalidDecl(); |
8079 | ActOnDocumentableDecl(D: NewTemplate); |
8080 | return NewTemplate; |
8081 | } |
8082 | |
8083 | if (IsMemberSpecialization && !NewVD->isInvalidDecl()) |
8084 | CompleteMemberSpecialization(Member: NewVD, Previous); |
8085 | |
8086 | emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD); |
8087 | |
8088 | return NewVD; |
8089 | } |
8090 | |
8091 | /// Enum describing the %select options in diag::warn_decl_shadow. |
8092 | enum ShadowedDeclKind { |
8093 | SDK_Local, |
8094 | SDK_Global, |
8095 | SDK_StaticMember, |
8096 | SDK_Field, |
8097 | SDK_Typedef, |
8098 | SDK_Using, |
8099 | SDK_StructuredBinding |
8100 | }; |
8101 | |
8102 | /// Determine what kind of declaration we're shadowing. |
8103 | static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, |
8104 | const DeclContext *OldDC) { |
8105 | if (isa<TypeAliasDecl>(Val: ShadowedDecl)) |
8106 | return SDK_Using; |
8107 | else if (isa<TypedefDecl>(Val: ShadowedDecl)) |
8108 | return SDK_Typedef; |
8109 | else if (isa<BindingDecl>(Val: ShadowedDecl)) |
8110 | return SDK_StructuredBinding; |
8111 | else if (isa<RecordDecl>(Val: OldDC)) |
8112 | return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember; |
8113 | |
8114 | return OldDC->isFileContext() ? SDK_Global : SDK_Local; |
8115 | } |
8116 | |
8117 | /// Return the location of the capture if the given lambda captures the given |
8118 | /// variable \p VD, or an invalid source location otherwise. |
8119 | static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, |
8120 | const VarDecl *VD) { |
8121 | for (const Capture &Capture : LSI->Captures) { |
8122 | if (Capture.isVariableCapture() && Capture.getVariable() == VD) |
8123 | return Capture.getLocation(); |
8124 | } |
8125 | return SourceLocation(); |
8126 | } |
8127 | |
8128 | static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, |
8129 | const LookupResult &R) { |
8130 | // Only diagnose if we're shadowing an unambiguous field or variable. |
8131 | if (R.getResultKind() != LookupResult::Found) |
8132 | return false; |
8133 | |
8134 | // Return false if warning is ignored. |
8135 | return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc()); |
8136 | } |
8137 | |
8138 | NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, |
8139 | const LookupResult &R) { |
8140 | if (!shouldWarnIfShadowedDecl(Diags, R)) |
8141 | return nullptr; |
8142 | |
8143 | // Don't diagnose declarations at file scope. |
8144 | if (D->hasGlobalStorage() && !D->isStaticLocal()) |
8145 | return nullptr; |
8146 | |
8147 | NamedDecl *ShadowedDecl = R.getFoundDecl(); |
8148 | return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl |
8149 | : nullptr; |
8150 | } |
8151 | |
8152 | NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, |
8153 | const LookupResult &R) { |
8154 | // Don't warn if typedef declaration is part of a class |
8155 | if (D->getDeclContext()->isRecord()) |
8156 | return nullptr; |
8157 | |
8158 | if (!shouldWarnIfShadowedDecl(Diags, R)) |
8159 | return nullptr; |
8160 | |
8161 | NamedDecl *ShadowedDecl = R.getFoundDecl(); |
8162 | return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr; |
8163 | } |
8164 | |
8165 | NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, |
8166 | const LookupResult &R) { |
8167 | if (!shouldWarnIfShadowedDecl(Diags, R)) |
8168 | return nullptr; |
8169 | |
8170 | NamedDecl *ShadowedDecl = R.getFoundDecl(); |
8171 | return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl |
8172 | : nullptr; |
8173 | } |
8174 | |
8175 | void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, |
8176 | const LookupResult &R) { |
8177 | DeclContext *NewDC = D->getDeclContext(); |
8178 | |
8179 | if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) { |
8180 | // Fields are not shadowed by variables in C++ static methods. |
8181 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDC)) |
8182 | if (MD->isStatic()) |
8183 | return; |
8184 | |
8185 | // Fields shadowed by constructor parameters are a special case. Usually |
8186 | // the constructor initializes the field with the parameter. |
8187 | if (isa<CXXConstructorDecl>(Val: NewDC)) |
8188 | if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) { |
8189 | // Remember that this was shadowed so we can either warn about its |
8190 | // modification or its existence depending on warning settings. |
8191 | ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD}); |
8192 | return; |
8193 | } |
8194 | } |
8195 | |
8196 | if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl)) |
8197 | if (shadowedVar->isExternC()) { |
8198 | // For shadowing external vars, make sure that we point to the global |
8199 | // declaration, not a locally scoped extern declaration. |
8200 | for (auto *I : shadowedVar->redecls()) |
8201 | if (I->isFileVarDecl()) { |
8202 | ShadowedDecl = I; |
8203 | break; |
8204 | } |
8205 | } |
8206 | |
8207 | DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); |
8208 | |
8209 | unsigned WarningDiag = diag::warn_decl_shadow; |
8210 | SourceLocation CaptureLoc; |
8211 | if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) { |
8212 | if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) { |
8213 | if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) { |
8214 | if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl)) { |
8215 | const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction()); |
8216 | if (RD->getLambdaCaptureDefault() == LCD_None) { |
8217 | // Try to avoid warnings for lambdas with an explicit capture |
8218 | // list. Warn only when the lambda captures the shadowed decl |
8219 | // explicitly. |
8220 | CaptureLoc = getCaptureLocation(LSI, VD); |
8221 | if (CaptureLoc.isInvalid()) |
8222 | WarningDiag = diag::warn_decl_shadow_uncaptured_local; |
8223 | } else { |
8224 | // Remember that this was shadowed so we can avoid the warning if |
8225 | // the shadowed decl isn't captured and the warning settings allow |
8226 | // it. |
8227 | cast<LambdaScopeInfo>(Val: getCurFunction()) |
8228 | ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD}); |
8229 | return; |
8230 | } |
8231 | } |
8232 | if (isa<FieldDecl>(Val: ShadowedDecl)) { |
8233 | // If lambda can capture this, then emit default shadowing warning, |
8234 | // Otherwise it is not really a shadowing case since field is not |
8235 | // available in lambda's body. |
8236 | // At this point we don't know that lambda can capture this, so |
8237 | // remember that this was shadowed and delay until we know. |
8238 | cast<LambdaScopeInfo>(Val: getCurFunction()) |
8239 | ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl}); |
8240 | return; |
8241 | } |
8242 | } |
8243 | if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl); |
8244 | VD && VD->hasLocalStorage()) { |
8245 | // A variable can't shadow a local variable in an enclosing scope, if |
8246 | // they are separated by a non-capturing declaration context. |
8247 | for (DeclContext *ParentDC = NewDC; |
8248 | ParentDC && !ParentDC->Equals(DC: OldDC); |
8249 | ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) { |
8250 | // Only block literals, captured statements, and lambda expressions |
8251 | // can capture; other scopes don't. |
8252 | if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) && |
8253 | !isLambdaCallOperator(DC: ParentDC)) { |
8254 | return; |
8255 | } |
8256 | } |
8257 | } |
8258 | } |
8259 | } |
8260 | |
8261 | // Never warn about shadowing a placeholder variable. |
8262 | if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts())) |
8263 | return; |
8264 | |
8265 | // Only warn about certain kinds of shadowing for class members. |
8266 | if (NewDC && NewDC->isRecord()) { |
8267 | // In particular, don't warn about shadowing non-class members. |
8268 | if (!OldDC->isRecord()) |
8269 | return; |
8270 | |
8271 | // TODO: should we warn about static data members shadowing |
8272 | // static data members from base classes? |
8273 | |
8274 | // TODO: don't diagnose for inaccessible shadowed members. |
8275 | // This is hard to do perfectly because we might friend the |
8276 | // shadowing context, but that's just a false negative. |
8277 | } |
8278 | |
8279 | |
8280 | DeclarationName Name = R.getLookupName(); |
8281 | |
8282 | // Emit warning and note. |
8283 | ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); |
8284 | Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC; |
8285 | if (!CaptureLoc.isInvalid()) |
8286 | Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here) |
8287 | << Name << /*explicitly*/ 1; |
8288 | Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration); |
8289 | } |
8290 | |
8291 | void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { |
8292 | for (const auto &Shadow : LSI->ShadowingDecls) { |
8293 | const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl; |
8294 | // Try to avoid the warning when the shadowed decl isn't captured. |
8295 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); |
8296 | if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl)) { |
8297 | SourceLocation CaptureLoc = getCaptureLocation(LSI, VD); |
8298 | Diag(Loc: Shadow.VD->getLocation(), |
8299 | DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local |
8300 | : diag::warn_decl_shadow) |
8301 | << Shadow.VD->getDeclName() |
8302 | << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; |
8303 | if (CaptureLoc.isValid()) |
8304 | Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here) |
8305 | << Shadow.VD->getDeclName() << /*explicitly*/ 0; |
8306 | Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration); |
8307 | } else if (isa<FieldDecl>(Val: ShadowedDecl)) { |
8308 | Diag(Loc: Shadow.VD->getLocation(), |
8309 | DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow |
8310 | : diag::warn_decl_shadow_uncaptured_local) |
8311 | << Shadow.VD->getDeclName() |
8312 | << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; |
8313 | Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration); |
8314 | } |
8315 | } |
8316 | } |
8317 | |
8318 | void Sema::CheckShadow(Scope *S, VarDecl *D) { |
8319 | if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation())) |
8320 | return; |
8321 | |
8322 | LookupResult R(*this, D->getDeclName(), D->getLocation(), |
8323 | Sema::LookupOrdinaryName, |
8324 | RedeclarationKind::ForVisibleRedeclaration); |
8325 | LookupName(R, S); |
8326 | if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) |
8327 | CheckShadow(D, ShadowedDecl, R); |
8328 | } |
8329 | |
8330 | /// Check if 'E', which is an expression that is about to be modified, refers |
8331 | /// to a constructor parameter that shadows a field. |
8332 | void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { |
8333 | // Quickly ignore expressions that can't be shadowing ctor parameters. |
8334 | if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) |
8335 | return; |
8336 | E = E->IgnoreParenImpCasts(); |
8337 | auto *DRE = dyn_cast<DeclRefExpr>(Val: E); |
8338 | if (!DRE) |
8339 | return; |
8340 | const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl()); |
8341 | auto I = ShadowingDecls.find(Val: D); |
8342 | if (I == ShadowingDecls.end()) |
8343 | return; |
8344 | const NamedDecl *ShadowedDecl = I->second; |
8345 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); |
8346 | Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC; |
8347 | Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D; |
8348 | Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration); |
8349 | |
8350 | // Avoid issuing multiple warnings about the same decl. |
8351 | ShadowingDecls.erase(I); |
8352 | } |
8353 | |
8354 | /// Check for conflict between this global or extern "C" declaration and |
8355 | /// previous global or extern "C" declarations. This is only used in C++. |
8356 | template<typename T> |
8357 | static bool checkGlobalOrExternCConflict( |
8358 | Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { |
8359 | assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"" ); |
8360 | NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName()); |
8361 | |
8362 | if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { |
8363 | // The common case: this global doesn't conflict with any extern "C" |
8364 | // declaration. |
8365 | return false; |
8366 | } |
8367 | |
8368 | if (Prev) { |
8369 | if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { |
8370 | // Both the old and new declarations have C language linkage. This is a |
8371 | // redeclaration. |
8372 | Previous.clear(); |
8373 | Previous.addDecl(D: Prev); |
8374 | return true; |
8375 | } |
8376 | |
8377 | // This is a global, non-extern "C" declaration, and there is a previous |
8378 | // non-global extern "C" declaration. Diagnose if this is a variable |
8379 | // declaration. |
8380 | if (!isa<VarDecl>(ND)) |
8381 | return false; |
8382 | } else { |
8383 | // The declaration is extern "C". Check for any declaration in the |
8384 | // translation unit which might conflict. |
8385 | if (IsGlobal) { |
8386 | // We have already performed the lookup into the translation unit. |
8387 | IsGlobal = false; |
8388 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); |
8389 | I != E; ++I) { |
8390 | if (isa<VarDecl>(Val: *I)) { |
8391 | Prev = *I; |
8392 | break; |
8393 | } |
8394 | } |
8395 | } else { |
8396 | DeclContext::lookup_result R = |
8397 | S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName()); |
8398 | for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); |
8399 | I != E; ++I) { |
8400 | if (isa<VarDecl>(Val: *I)) { |
8401 | Prev = *I; |
8402 | break; |
8403 | } |
8404 | // FIXME: If we have any other entity with this name in global scope, |
8405 | // the declaration is ill-formed, but that is a defect: it breaks the |
8406 | // 'stat' hack, for instance. Only variables can have mangled name |
8407 | // clashes with extern "C" declarations, so only they deserve a |
8408 | // diagnostic. |
8409 | } |
8410 | } |
8411 | |
8412 | if (!Prev) |
8413 | return false; |
8414 | } |
8415 | |
8416 | // Use the first declaration's location to ensure we point at something which |
8417 | // is lexically inside an extern "C" linkage-spec. |
8418 | assert(Prev && "should have found a previous declaration to diagnose" ); |
8419 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev)) |
8420 | Prev = FD->getFirstDecl(); |
8421 | else |
8422 | Prev = cast<VarDecl>(Val: Prev)->getFirstDecl(); |
8423 | |
8424 | S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) |
8425 | << IsGlobal << ND; |
8426 | S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict) |
8427 | << IsGlobal; |
8428 | return false; |
8429 | } |
8430 | |
8431 | /// Apply special rules for handling extern "C" declarations. Returns \c true |
8432 | /// if we have found that this is a redeclaration of some prior entity. |
8433 | /// |
8434 | /// Per C++ [dcl.link]p6: |
8435 | /// Two declarations [for a function or variable] with C language linkage |
8436 | /// with the same name that appear in different scopes refer to the same |
8437 | /// [entity]. An entity with C language linkage shall not be declared with |
8438 | /// the same name as an entity in global scope. |
8439 | template<typename T> |
8440 | static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, |
8441 | LookupResult &Previous) { |
8442 | if (!S.getLangOpts().CPlusPlus) { |
8443 | // In C, when declaring a global variable, look for a corresponding 'extern' |
8444 | // variable declared in function scope. We don't need this in C++, because |
8445 | // we find local extern decls in the surrounding file-scope DeclContext. |
8446 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { |
8447 | if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) { |
8448 | Previous.clear(); |
8449 | Previous.addDecl(D: Prev); |
8450 | return true; |
8451 | } |
8452 | } |
8453 | return false; |
8454 | } |
8455 | |
8456 | // A declaration in the translation unit can conflict with an extern "C" |
8457 | // declaration. |
8458 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) |
8459 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); |
8460 | |
8461 | // An extern "C" declaration can conflict with a declaration in the |
8462 | // translation unit or can be a redeclaration of an extern "C" declaration |
8463 | // in another scope. |
8464 | if (isIncompleteDeclExternC(S,ND)) |
8465 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); |
8466 | |
8467 | // Neither global nor extern "C": nothing to do. |
8468 | return false; |
8469 | } |
8470 | |
8471 | static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, |
8472 | QualType T) { |
8473 | QualType CanonT = SemaRef.Context.getCanonicalType(T); |
8474 | // C23 6.7.1p5: An object declared with storage-class specifier constexpr or |
8475 | // any of its members, even recursively, shall not have an atomic type, or a |
8476 | // variably modified type, or a type that is volatile or restrict qualified. |
8477 | if (CanonT->isVariablyModifiedType()) { |
8478 | SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T; |
8479 | return true; |
8480 | } |
8481 | |
8482 | // Arrays are qualified by their element type, so get the base type (this |
8483 | // works on non-arrays as well). |
8484 | CanonT = SemaRef.Context.getBaseElementType(QT: CanonT); |
8485 | |
8486 | if (CanonT->isAtomicType() || CanonT.isVolatileQualified() || |
8487 | CanonT.isRestrictQualified()) { |
8488 | SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T; |
8489 | return true; |
8490 | } |
8491 | |
8492 | if (CanonT->isRecordType()) { |
8493 | const RecordDecl *RD = CanonT->getAsRecordDecl(); |
8494 | if (llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) { |
8495 | return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType()); |
8496 | })) |
8497 | return true; |
8498 | } |
8499 | |
8500 | return false; |
8501 | } |
8502 | |
8503 | void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { |
8504 | // If the decl is already known invalid, don't check it. |
8505 | if (NewVD->isInvalidDecl()) |
8506 | return; |
8507 | |
8508 | QualType T = NewVD->getType(); |
8509 | |
8510 | // Defer checking an 'auto' type until its initializer is attached. |
8511 | if (T->isUndeducedType()) |
8512 | return; |
8513 | |
8514 | if (NewVD->hasAttrs()) |
8515 | CheckAlignasUnderalignment(D: NewVD); |
8516 | |
8517 | if (T->isObjCObjectType()) { |
8518 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object) |
8519 | << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*" ); |
8520 | T = Context.getObjCObjectPointerType(OIT: T); |
8521 | NewVD->setType(T); |
8522 | } |
8523 | |
8524 | // Emit an error if an address space was applied to decl with local storage. |
8525 | // This includes arrays of objects with address space qualifiers, but not |
8526 | // automatic variables that point to other address spaces. |
8527 | // ISO/IEC TR 18037 S5.1.2 |
8528 | if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && |
8529 | T.getAddressSpace() != LangAS::Default) { |
8530 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0; |
8531 | NewVD->setInvalidDecl(); |
8532 | return; |
8533 | } |
8534 | |
8535 | // OpenCL v1.2 s6.8 - The static qualifier is valid only in program |
8536 | // scope. |
8537 | if (getLangOpts().OpenCLVersion == 120 && |
8538 | !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers" , |
8539 | LO: getLangOpts()) && |
8540 | NewVD->isStaticLocal()) { |
8541 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope); |
8542 | NewVD->setInvalidDecl(); |
8543 | return; |
8544 | } |
8545 | |
8546 | if (getLangOpts().OpenCL) { |
8547 | if (!diagnoseOpenCLTypes(Se&: *this, NewVD)) |
8548 | return; |
8549 | |
8550 | // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. |
8551 | if (NewVD->hasAttr<BlocksAttr>()) { |
8552 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type); |
8553 | return; |
8554 | } |
8555 | |
8556 | if (T->isBlockPointerType()) { |
8557 | // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and |
8558 | // can't use 'extern' storage class. |
8559 | if (!T.isConstQualified()) { |
8560 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration) |
8561 | << 0 /*const*/; |
8562 | NewVD->setInvalidDecl(); |
8563 | return; |
8564 | } |
8565 | if (NewVD->hasExternalStorage()) { |
8566 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration); |
8567 | NewVD->setInvalidDecl(); |
8568 | return; |
8569 | } |
8570 | } |
8571 | |
8572 | // FIXME: Adding local AS in C++ for OpenCL might make sense. |
8573 | if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || |
8574 | NewVD->hasExternalStorage()) { |
8575 | if (!T->isSamplerT() && !T->isDependentType() && |
8576 | !(T.getAddressSpace() == LangAS::opencl_constant || |
8577 | (T.getAddressSpace() == LangAS::opencl_global && |
8578 | getOpenCLOptions().areProgramScopeVariablesSupported( |
8579 | Opts: getLangOpts())))) { |
8580 | int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; |
8581 | if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts())) |
8582 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space) |
8583 | << Scope << "global or constant" ; |
8584 | else |
8585 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space) |
8586 | << Scope << "constant" ; |
8587 | NewVD->setInvalidDecl(); |
8588 | return; |
8589 | } |
8590 | } else { |
8591 | if (T.getAddressSpace() == LangAS::opencl_global) { |
8592 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable) |
8593 | << 1 /*is any function*/ << "global" ; |
8594 | NewVD->setInvalidDecl(); |
8595 | return; |
8596 | } |
8597 | if (T.getAddressSpace() == LangAS::opencl_constant || |
8598 | T.getAddressSpace() == LangAS::opencl_local) { |
8599 | FunctionDecl *FD = getCurFunctionDecl(); |
8600 | // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables |
8601 | // in functions. |
8602 | if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { |
8603 | if (T.getAddressSpace() == LangAS::opencl_constant) |
8604 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable) |
8605 | << 0 /*non-kernel only*/ << "constant" ; |
8606 | else |
8607 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable) |
8608 | << 0 /*non-kernel only*/ << "local" ; |
8609 | NewVD->setInvalidDecl(); |
8610 | return; |
8611 | } |
8612 | // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be |
8613 | // in the outermost scope of a kernel function. |
8614 | if (FD && FD->hasAttr<OpenCLKernelAttr>()) { |
8615 | if (!getCurScope()->isFunctionScope()) { |
8616 | if (T.getAddressSpace() == LangAS::opencl_constant) |
8617 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope) |
8618 | << "constant" ; |
8619 | else |
8620 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope) |
8621 | << "local" ; |
8622 | NewVD->setInvalidDecl(); |
8623 | return; |
8624 | } |
8625 | } |
8626 | } else if (T.getAddressSpace() != LangAS::opencl_private && |
8627 | // If we are parsing a template we didn't deduce an addr |
8628 | // space yet. |
8629 | T.getAddressSpace() != LangAS::Default) { |
8630 | // Do not allow other address spaces on automatic variable. |
8631 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1; |
8632 | NewVD->setInvalidDecl(); |
8633 | return; |
8634 | } |
8635 | } |
8636 | } |
8637 | |
8638 | if (NewVD->hasLocalStorage() && T.isObjCGCWeak() |
8639 | && !NewVD->hasAttr<BlocksAttr>()) { |
8640 | if (getLangOpts().getGC() != LangOptions::NonGC) |
8641 | Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local); |
8642 | else { |
8643 | assert(!getLangOpts().ObjCAutoRefCount); |
8644 | Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local); |
8645 | } |
8646 | } |
8647 | |
8648 | // WebAssembly tables must be static with a zero length and can't be |
8649 | // declared within functions. |
8650 | if (T->isWebAssemblyTableType()) { |
8651 | if (getCurScope()->getParent()) { // Parent is null at top-level |
8652 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function); |
8653 | NewVD->setInvalidDecl(); |
8654 | return; |
8655 | } |
8656 | if (NewVD->getStorageClass() != SC_Static) { |
8657 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static); |
8658 | NewVD->setInvalidDecl(); |
8659 | return; |
8660 | } |
8661 | const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr()); |
8662 | if (!ATy || ATy->getZExtSize() != 0) { |
8663 | Diag(Loc: NewVD->getLocation(), |
8664 | DiagID: diag::err_typecheck_wasm_table_must_have_zero_length); |
8665 | NewVD->setInvalidDecl(); |
8666 | return; |
8667 | } |
8668 | } |
8669 | |
8670 | bool isVM = T->isVariablyModifiedType(); |
8671 | if (isVM || NewVD->hasAttr<CleanupAttr>() || |
8672 | NewVD->hasAttr<BlocksAttr>()) |
8673 | setFunctionHasBranchProtectedScope(); |
8674 | |
8675 | if ((isVM && NewVD->hasLinkage()) || |
8676 | (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { |
8677 | bool SizeIsNegative; |
8678 | llvm::APSInt Oversized; |
8679 | TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( |
8680 | TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); |
8681 | QualType FixedT; |
8682 | if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) |
8683 | FixedT = FixedTInfo->getType(); |
8684 | else if (FixedTInfo) { |
8685 | // Type and type-as-written are canonically different. We need to fix up |
8686 | // both types separately. |
8687 | FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, |
8688 | Oversized); |
8689 | } |
8690 | if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { |
8691 | const VariableArrayType *VAT = Context.getAsVariableArrayType(T); |
8692 | // FIXME: This won't give the correct result for |
8693 | // int a[10][n]; |
8694 | SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); |
8695 | |
8696 | if (NewVD->isFileVarDecl()) |
8697 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope) |
8698 | << SizeRange; |
8699 | else if (NewVD->isStaticLocal()) |
8700 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage) |
8701 | << SizeRange; |
8702 | else |
8703 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage) |
8704 | << SizeRange; |
8705 | NewVD->setInvalidDecl(); |
8706 | return; |
8707 | } |
8708 | |
8709 | if (!FixedTInfo) { |
8710 | if (NewVD->isFileVarDecl()) |
8711 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope); |
8712 | else |
8713 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage); |
8714 | NewVD->setInvalidDecl(); |
8715 | return; |
8716 | } |
8717 | |
8718 | Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant); |
8719 | NewVD->setType(FixedT); |
8720 | NewVD->setTypeSourceInfo(FixedTInfo); |
8721 | } |
8722 | |
8723 | if (T->isVoidType()) { |
8724 | // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names |
8725 | // of objects and functions. |
8726 | if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { |
8727 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type) |
8728 | << T; |
8729 | NewVD->setInvalidDecl(); |
8730 | return; |
8731 | } |
8732 | } |
8733 | |
8734 | if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { |
8735 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_nonlocal); |
8736 | NewVD->setInvalidDecl(); |
8737 | return; |
8738 | } |
8739 | |
8740 | if (!NewVD->hasLocalStorage() && T->isSizelessType() && |
8741 | !T.isWebAssemblyReferenceType()) { |
8742 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T; |
8743 | NewVD->setInvalidDecl(); |
8744 | return; |
8745 | } |
8746 | |
8747 | if (isVM && NewVD->hasAttr<BlocksAttr>()) { |
8748 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_vm); |
8749 | NewVD->setInvalidDecl(); |
8750 | return; |
8751 | } |
8752 | |
8753 | if (getLangOpts().C23 && NewVD->isConstexpr() && |
8754 | CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) { |
8755 | NewVD->setInvalidDecl(); |
8756 | return; |
8757 | } |
8758 | |
8759 | if (NewVD->isConstexpr() && !T->isDependentType() && |
8760 | RequireLiteralType(Loc: NewVD->getLocation(), T, |
8761 | DiagID: diag::err_constexpr_var_non_literal)) { |
8762 | NewVD->setInvalidDecl(); |
8763 | return; |
8764 | } |
8765 | |
8766 | // PPC MMA non-pointer types are not allowed as non-local variable types. |
8767 | if (Context.getTargetInfo().getTriple().isPPC64() && |
8768 | !NewVD->isLocalVarDecl() && |
8769 | PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) { |
8770 | NewVD->setInvalidDecl(); |
8771 | return; |
8772 | } |
8773 | |
8774 | // Check that SVE types are only used in functions with SVE available. |
8775 | if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) { |
8776 | const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext); |
8777 | llvm::StringMap<bool> CallerFeatureMap; |
8778 | Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD); |
8779 | |
8780 | if (!Builtin::evaluateRequiredTargetFeatures(RequiredFatures: "sve" , TargetFetureMap: CallerFeatureMap)) { |
8781 | if (!Builtin::evaluateRequiredTargetFeatures(RequiredFatures: "sme" , TargetFetureMap: CallerFeatureMap)) { |
8782 | Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sve_vector_in_non_sve_target) << T; |
8783 | NewVD->setInvalidDecl(); |
8784 | return; |
8785 | } else if (!IsArmStreamingFunction(FD, |
8786 | /*IncludeLocallyStreaming=*/true)) { |
8787 | Diag(Loc: NewVD->getLocation(), |
8788 | DiagID: diag::err_sve_vector_in_non_streaming_function) |
8789 | << T; |
8790 | NewVD->setInvalidDecl(); |
8791 | return; |
8792 | } |
8793 | } |
8794 | } |
8795 | |
8796 | if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) { |
8797 | const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext); |
8798 | llvm::StringMap<bool> CallerFeatureMap; |
8799 | Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD); |
8800 | RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext), |
8801 | FeatureMap: CallerFeatureMap); |
8802 | } |
8803 | } |
8804 | |
8805 | bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { |
8806 | CheckVariableDeclarationType(NewVD); |
8807 | |
8808 | // If the decl is already known invalid, don't check it. |
8809 | if (NewVD->isInvalidDecl()) |
8810 | return false; |
8811 | |
8812 | // If we did not find anything by this name, look for a non-visible |
8813 | // extern "C" declaration with the same name. |
8814 | if (Previous.empty() && |
8815 | checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous)) |
8816 | Previous.setShadowed(); |
8817 | |
8818 | if (!Previous.empty()) { |
8819 | MergeVarDecl(New: NewVD, Previous); |
8820 | return true; |
8821 | } |
8822 | return false; |
8823 | } |
8824 | |
8825 | bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { |
8826 | llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; |
8827 | |
8828 | // Look for methods in base classes that this method might override. |
8829 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, |
8830 | /*DetectVirtual=*/false); |
8831 | auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { |
8832 | CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); |
8833 | DeclarationName Name = MD->getDeclName(); |
8834 | |
8835 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { |
8836 | // We really want to find the base class destructor here. |
8837 | QualType T = Context.getTypeDeclType(Decl: BaseRecord); |
8838 | CanQualType CT = Context.getCanonicalType(T); |
8839 | Name = Context.DeclarationNames.getCXXDestructorName(Ty: CT); |
8840 | } |
8841 | |
8842 | for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { |
8843 | CXXMethodDecl *BaseMD = |
8844 | dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl()); |
8845 | if (!BaseMD || !BaseMD->isVirtual() || |
8846 | IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, |
8847 | /*ConsiderCudaAttrs=*/true)) |
8848 | continue; |
8849 | if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD)) |
8850 | continue; |
8851 | if (Overridden.insert(Ptr: BaseMD).second) { |
8852 | MD->addOverriddenMethod(MD: BaseMD); |
8853 | CheckOverridingFunctionReturnType(New: MD, Old: BaseMD); |
8854 | CheckOverridingFunctionAttributes(New: MD, Old: BaseMD); |
8855 | CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD); |
8856 | CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD); |
8857 | } |
8858 | |
8859 | // A method can only override one function from each base class. We |
8860 | // don't track indirectly overridden methods from bases of bases. |
8861 | return true; |
8862 | } |
8863 | |
8864 | return false; |
8865 | }; |
8866 | |
8867 | DC->lookupInBases(BaseMatches: VisitBase, Paths); |
8868 | return !Overridden.empty(); |
8869 | } |
8870 | |
8871 | namespace { |
8872 | // Struct for holding all of the extra arguments needed by |
8873 | // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. |
8874 | struct ActOnFDArgs { |
8875 | Scope *S; |
8876 | Declarator &D; |
8877 | MultiTemplateParamsArg TemplateParamLists; |
8878 | bool AddToScope; |
8879 | }; |
8880 | } // end anonymous namespace |
8881 | |
8882 | namespace { |
8883 | |
8884 | // Callback to only accept typo corrections that have a non-zero edit distance. |
8885 | // Also only accept corrections that have the same parent decl. |
8886 | class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { |
8887 | public: |
8888 | DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, |
8889 | CXXRecordDecl *Parent) |
8890 | : Context(Context), OriginalFD(TypoFD), |
8891 | ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} |
8892 | |
8893 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
8894 | if (candidate.getEditDistance() == 0) |
8895 | return false; |
8896 | |
8897 | SmallVector<unsigned, 1> MismatchedParams; |
8898 | for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), |
8899 | CDeclEnd = candidate.end(); |
8900 | CDecl != CDeclEnd; ++CDecl) { |
8901 | FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl); |
8902 | |
8903 | if (FD && !FD->hasBody() && |
8904 | hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) { |
8905 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) { |
8906 | CXXRecordDecl *Parent = MD->getParent(); |
8907 | if (Parent && Parent->getCanonicalDecl() == ExpectedParent) |
8908 | return true; |
8909 | } else if (!ExpectedParent) { |
8910 | return true; |
8911 | } |
8912 | } |
8913 | } |
8914 | |
8915 | return false; |
8916 | } |
8917 | |
8918 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
8919 | return std::make_unique<DifferentNameValidatorCCC>(args&: *this); |
8920 | } |
8921 | |
8922 | private: |
8923 | ASTContext &Context; |
8924 | FunctionDecl *OriginalFD; |
8925 | CXXRecordDecl *ExpectedParent; |
8926 | }; |
8927 | |
8928 | } // end anonymous namespace |
8929 | |
8930 | void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { |
8931 | TypoCorrectedFunctionDefinitions.insert(Ptr: F); |
8932 | } |
8933 | |
8934 | /// Generate diagnostics for an invalid function redeclaration. |
8935 | /// |
8936 | /// This routine handles generating the diagnostic messages for an invalid |
8937 | /// function redeclaration, including finding possible similar declarations |
8938 | /// or performing typo correction if there are no previous declarations with |
8939 | /// the same name. |
8940 | /// |
8941 | /// Returns a NamedDecl iff typo correction was performed and substituting in |
8942 | /// the new declaration name does not cause new errors. |
8943 | static NamedDecl *DiagnoseInvalidRedeclaration( |
8944 | Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, |
8945 | ActOnFDArgs &, bool IsLocalFriend, Scope *S) { |
8946 | DeclarationName Name = NewFD->getDeclName(); |
8947 | DeclContext *NewDC = NewFD->getDeclContext(); |
8948 | SmallVector<unsigned, 1> MismatchedParams; |
8949 | SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; |
8950 | TypoCorrection Correction; |
8951 | bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); |
8952 | unsigned DiagMsg = |
8953 | IsLocalFriend ? diag::err_no_matching_local_friend : |
8954 | NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : |
8955 | diag::err_member_decl_does_not_match; |
8956 | LookupResult Prev(SemaRef, Name, NewFD->getLocation(), |
8957 | IsLocalFriend ? Sema::LookupLocalFriendName |
8958 | : Sema::LookupOrdinaryName, |
8959 | RedeclarationKind::ForVisibleRedeclaration); |
8960 | |
8961 | NewFD->setInvalidDecl(); |
8962 | if (IsLocalFriend) |
8963 | SemaRef.LookupName(R&: Prev, S); |
8964 | else |
8965 | SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC); |
8966 | assert(!Prev.isAmbiguous() && |
8967 | "Cannot have an ambiguity in previous-declaration lookup" ); |
8968 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD); |
8969 | DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, |
8970 | MD ? MD->getParent() : nullptr); |
8971 | if (!Prev.empty()) { |
8972 | for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); |
8973 | Func != FuncEnd; ++Func) { |
8974 | FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func); |
8975 | if (FD && |
8976 | hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) { |
8977 | // Add 1 to the index so that 0 can mean the mismatch didn't |
8978 | // involve a parameter |
8979 | unsigned ParamNum = |
8980 | MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; |
8981 | NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum)); |
8982 | } |
8983 | } |
8984 | // If the qualified name lookup yielded nothing, try typo correction |
8985 | } else if ((Correction = SemaRef.CorrectTypo( |
8986 | Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S, |
8987 | SS: &ExtraArgs.D.getCXXScopeSpec(), CCC, Mode: Sema::CTK_ErrorRecovery, |
8988 | MemberContext: IsLocalFriend ? nullptr : NewDC))) { |
8989 | // Set up everything for the call to ActOnFunctionDeclarator |
8990 | ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(), |
8991 | IdLoc: ExtraArgs.D.getIdentifierLoc()); |
8992 | Previous.clear(); |
8993 | Previous.setLookupName(Correction.getCorrection()); |
8994 | for (TypoCorrection::decl_iterator CDecl = Correction.begin(), |
8995 | CDeclEnd = Correction.end(); |
8996 | CDecl != CDeclEnd; ++CDecl) { |
8997 | FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl); |
8998 | if (FD && !FD->hasBody() && |
8999 | hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) { |
9000 | Previous.addDecl(D: FD); |
9001 | } |
9002 | } |
9003 | bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); |
9004 | |
9005 | NamedDecl *Result; |
9006 | // Retry building the function declaration with the new previous |
9007 | // declarations, and with errors suppressed. |
9008 | { |
9009 | // Trap errors. |
9010 | Sema::SFINAETrap Trap(SemaRef); |
9011 | |
9012 | // TODO: Refactor ActOnFunctionDeclarator so that we can call only the |
9013 | // pieces need to verify the typo-corrected C++ declaration and hopefully |
9014 | // eliminate the need for the parameter pack ExtraArgs. |
9015 | Result = SemaRef.ActOnFunctionDeclarator( |
9016 | S: ExtraArgs.S, D&: ExtraArgs.D, |
9017 | DC: Correction.getCorrectionDecl()->getDeclContext(), |
9018 | TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists, |
9019 | AddToScope&: ExtraArgs.AddToScope); |
9020 | |
9021 | if (Trap.hasErrorOccurred()) |
9022 | Result = nullptr; |
9023 | } |
9024 | |
9025 | if (Result) { |
9026 | // Determine which correction we picked. |
9027 | Decl *Canonical = Result->getCanonicalDecl(); |
9028 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); |
9029 | I != E; ++I) |
9030 | if ((*I)->getCanonicalDecl() == Canonical) |
9031 | Correction.setCorrectionDecl(*I); |
9032 | |
9033 | // Let Sema know about the correction. |
9034 | SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result); |
9035 | SemaRef.diagnoseTypo( |
9036 | Correction, |
9037 | TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend |
9038 | ? diag::err_no_matching_local_friend_suggest |
9039 | : diag::err_member_decl_does_not_match_suggest) |
9040 | << Name << NewDC << IsDefinition); |
9041 | return Result; |
9042 | } |
9043 | |
9044 | // Pretend the typo correction never occurred |
9045 | ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(), |
9046 | IdLoc: ExtraArgs.D.getIdentifierLoc()); |
9047 | ExtraArgs.D.setRedeclaration(wasRedeclaration); |
9048 | Previous.clear(); |
9049 | Previous.setLookupName(Name); |
9050 | } |
9051 | |
9052 | SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg) |
9053 | << Name << NewDC << IsDefinition << NewFD->getLocation(); |
9054 | |
9055 | bool NewFDisConst = false; |
9056 | if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD)) |
9057 | NewFDisConst = NewMD->isConst(); |
9058 | |
9059 | for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator |
9060 | NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); |
9061 | NearMatch != NearMatchEnd; ++NearMatch) { |
9062 | FunctionDecl *FD = NearMatch->first; |
9063 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD); |
9064 | bool FDisConst = MD && MD->isConst(); |
9065 | bool IsMember = MD || !IsLocalFriend; |
9066 | |
9067 | // FIXME: These notes are poorly worded for the local friend case. |
9068 | if (unsigned Idx = NearMatch->second) { |
9069 | ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1); |
9070 | SourceLocation Loc = FDParam->getTypeSpecStartLoc(); |
9071 | if (Loc.isInvalid()) Loc = FD->getLocation(); |
9072 | SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match |
9073 | : diag::note_local_decl_close_param_match) |
9074 | << Idx << FDParam->getType() |
9075 | << NewFD->getParamDecl(i: Idx - 1)->getType(); |
9076 | } else if (FDisConst != NewFDisConst) { |
9077 | auto DB = SemaRef.Diag(Loc: FD->getLocation(), |
9078 | DiagID: diag::note_member_def_close_const_match) |
9079 | << NewFDisConst << FD->getSourceRange().getEnd(); |
9080 | if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst) |
9081 | DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1), |
9082 | Code: " const" ); |
9083 | else if (FTI.hasMethodTypeQualifiers() && |
9084 | FTI.getConstQualifierLoc().isValid()) |
9085 | DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc()); |
9086 | } else { |
9087 | SemaRef.Diag(Loc: FD->getLocation(), |
9088 | DiagID: IsMember ? diag::note_member_def_close_match |
9089 | : diag::note_local_decl_close_match); |
9090 | } |
9091 | } |
9092 | return nullptr; |
9093 | } |
9094 | |
9095 | static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { |
9096 | switch (D.getDeclSpec().getStorageClassSpec()) { |
9097 | default: llvm_unreachable("Unknown storage class!" ); |
9098 | case DeclSpec::SCS_auto: |
9099 | case DeclSpec::SCS_register: |
9100 | case DeclSpec::SCS_mutable: |
9101 | SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(), |
9102 | DiagID: diag::err_typecheck_sclass_func); |
9103 | D.getMutableDeclSpec().ClearStorageClassSpecs(); |
9104 | D.setInvalidType(); |
9105 | break; |
9106 | case DeclSpec::SCS_unspecified: break; |
9107 | case DeclSpec::SCS_extern: |
9108 | if (D.getDeclSpec().isExternInLinkageSpec()) |
9109 | return SC_None; |
9110 | return SC_Extern; |
9111 | case DeclSpec::SCS_static: { |
9112 | if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { |
9113 | // C99 6.7.1p5: |
9114 | // The declaration of an identifier for a function that has |
9115 | // block scope shall have no explicit storage-class specifier |
9116 | // other than extern |
9117 | // See also (C++ [dcl.stc]p4). |
9118 | SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(), |
9119 | DiagID: diag::err_static_block_func); |
9120 | break; |
9121 | } else |
9122 | return SC_Static; |
9123 | } |
9124 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; |
9125 | } |
9126 | |
9127 | // No explicit storage class has already been returned |
9128 | return SC_None; |
9129 | } |
9130 | |
9131 | static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, |
9132 | DeclContext *DC, QualType &R, |
9133 | TypeSourceInfo *TInfo, |
9134 | StorageClass SC, |
9135 | bool &IsVirtualOkay) { |
9136 | DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); |
9137 | DeclarationName Name = NameInfo.getName(); |
9138 | |
9139 | FunctionDecl *NewFD = nullptr; |
9140 | bool isInline = D.getDeclSpec().isInlineSpecified(); |
9141 | |
9142 | ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); |
9143 | if (ConstexprKind == ConstexprSpecKind::Constinit || |
9144 | (SemaRef.getLangOpts().C23 && |
9145 | ConstexprKind == ConstexprSpecKind::Constexpr)) { |
9146 | |
9147 | if (SemaRef.getLangOpts().C23) |
9148 | SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), |
9149 | DiagID: diag::err_c23_constexpr_not_variable); |
9150 | else |
9151 | SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), |
9152 | DiagID: diag::err_constexpr_wrong_decl_kind) |
9153 | << static_cast<int>(ConstexprKind); |
9154 | ConstexprKind = ConstexprSpecKind::Unspecified; |
9155 | D.getMutableDeclSpec().ClearConstexprSpec(); |
9156 | } |
9157 | |
9158 | if (!SemaRef.getLangOpts().CPlusPlus) { |
9159 | // Determine whether the function was written with a prototype. This is |
9160 | // true when: |
9161 | // - there is a prototype in the declarator, or |
9162 | // - the type R of the function is some kind of typedef or other non- |
9163 | // attributed reference to a type name (which eventually refers to a |
9164 | // function type). Note, we can't always look at the adjusted type to |
9165 | // check this case because attributes may cause a non-function |
9166 | // declarator to still have a function type. e.g., |
9167 | // typedef void func(int a); |
9168 | // __attribute__((noreturn)) func other_func; // This has a prototype |
9169 | bool HasPrototype = |
9170 | (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || |
9171 | (D.getDeclSpec().isTypeRep() && |
9172 | SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr) |
9173 | ->isFunctionProtoType()) || |
9174 | (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); |
9175 | assert( |
9176 | (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) && |
9177 | "Strict prototypes are required" ); |
9178 | |
9179 | NewFD = FunctionDecl::Create( |
9180 | C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC, |
9181 | UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype, |
9182 | ConstexprKind: ConstexprSpecKind::Unspecified, |
9183 | /*TrailingRequiresClause=*/nullptr); |
9184 | if (D.isInvalidType()) |
9185 | NewFD->setInvalidDecl(); |
9186 | |
9187 | return NewFD; |
9188 | } |
9189 | |
9190 | ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); |
9191 | Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); |
9192 | |
9193 | SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R); |
9194 | |
9195 | if (Name.getNameKind() == DeclarationName::CXXConstructorName) { |
9196 | // This is a C++ constructor declaration. |
9197 | assert(DC->isRecord() && |
9198 | "Constructors can only be declared in a member context" ); |
9199 | |
9200 | R = SemaRef.CheckConstructorDeclarator(D, R, SC); |
9201 | return CXXConstructorDecl::Create( |
9202 | C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R, |
9203 | TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), |
9204 | isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, |
9205 | Inherited: InheritedConstructor(), TrailingRequiresClause); |
9206 | |
9207 | } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { |
9208 | // This is a C++ destructor declaration. |
9209 | if (DC->isRecord()) { |
9210 | R = SemaRef.CheckDestructorDeclarator(D, R, SC); |
9211 | CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC); |
9212 | CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( |
9213 | C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, |
9214 | UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline, |
9215 | /*isImplicitlyDeclared=*/false, ConstexprKind, |
9216 | TrailingRequiresClause); |
9217 | // User defined destructors start as not selected if the class definition is still |
9218 | // not done. |
9219 | if (Record->isBeingDefined()) |
9220 | NewDD->setIneligibleOrNotSelected(true); |
9221 | |
9222 | // If the destructor needs an implicit exception specification, set it |
9223 | // now. FIXME: It'd be nice to be able to create the right type to start |
9224 | // with, but the type needs to reference the destructor declaration. |
9225 | if (SemaRef.getLangOpts().CPlusPlus11) |
9226 | SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD); |
9227 | |
9228 | IsVirtualOkay = true; |
9229 | return NewDD; |
9230 | |
9231 | } else { |
9232 | SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member); |
9233 | D.setInvalidType(); |
9234 | |
9235 | // Create a FunctionDecl to satisfy the function definition parsing |
9236 | // code path. |
9237 | return FunctionDecl::Create( |
9238 | C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R, |
9239 | TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, |
9240 | /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause); |
9241 | } |
9242 | |
9243 | } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { |
9244 | if (!DC->isRecord()) { |
9245 | SemaRef.Diag(Loc: D.getIdentifierLoc(), |
9246 | DiagID: diag::err_conv_function_not_member); |
9247 | return nullptr; |
9248 | } |
9249 | |
9250 | SemaRef.CheckConversionDeclarator(D, R, SC); |
9251 | if (D.isInvalidType()) |
9252 | return nullptr; |
9253 | |
9254 | IsVirtualOkay = true; |
9255 | return CXXConversionDecl::Create( |
9256 | C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R, |
9257 | TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline, |
9258 | ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(), |
9259 | TrailingRequiresClause); |
9260 | |
9261 | } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { |
9262 | if (TrailingRequiresClause) |
9263 | SemaRef.Diag(Loc: TrailingRequiresClause->getBeginLoc(), |
9264 | DiagID: diag::err_trailing_requires_clause_on_deduction_guide) |
9265 | << TrailingRequiresClause->getSourceRange(); |
9266 | if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC)) |
9267 | return nullptr; |
9268 | return CXXDeductionGuideDecl::Create(C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), |
9269 | ES: ExplicitSpecifier, NameInfo, T: R, TInfo, |
9270 | EndLocation: D.getEndLoc()); |
9271 | } else if (DC->isRecord()) { |
9272 | // If the name of the function is the same as the name of the record, |
9273 | // then this must be an invalid constructor that has a return type. |
9274 | // (The parser checks for a return type and makes the declarator a |
9275 | // constructor if it has no return type). |
9276 | if (Name.getAsIdentifierInfo() && |
9277 | Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){ |
9278 | SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type) |
9279 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) |
9280 | << SourceRange(D.getIdentifierLoc()); |
9281 | return nullptr; |
9282 | } |
9283 | |
9284 | // This is a C++ method declaration. |
9285 | CXXMethodDecl *Ret = CXXMethodDecl::Create( |
9286 | C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R, |
9287 | TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline, |
9288 | ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause); |
9289 | IsVirtualOkay = !Ret->isStatic(); |
9290 | return Ret; |
9291 | } else { |
9292 | bool isFriend = |
9293 | SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); |
9294 | if (!isFriend && SemaRef.CurContext->isRecord()) |
9295 | return nullptr; |
9296 | |
9297 | // Determine whether the function was written with a |
9298 | // prototype. This true when: |
9299 | // - we're in C++ (where every function has a prototype), |
9300 | return FunctionDecl::Create( |
9301 | C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC, |
9302 | UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, |
9303 | hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); |
9304 | } |
9305 | } |
9306 | |
9307 | enum OpenCLParamType { |
9308 | ValidKernelParam, |
9309 | PtrPtrKernelParam, |
9310 | PtrKernelParam, |
9311 | InvalidAddrSpacePtrKernelParam, |
9312 | InvalidKernelParam, |
9313 | RecordKernelParam |
9314 | }; |
9315 | |
9316 | static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { |
9317 | // Size dependent types are just typedefs to normal integer types |
9318 | // (e.g. unsigned long), so we cannot distinguish them from other typedefs to |
9319 | // integers other than by their names. |
9320 | StringRef SizeTypeNames[] = {"size_t" , "intptr_t" , "uintptr_t" , "ptrdiff_t" }; |
9321 | |
9322 | // Remove typedefs one by one until we reach a typedef |
9323 | // for a size dependent type. |
9324 | QualType DesugaredTy = Ty; |
9325 | do { |
9326 | ArrayRef<StringRef> Names(SizeTypeNames); |
9327 | auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString()); |
9328 | if (Names.end() != Match) |
9329 | return true; |
9330 | |
9331 | Ty = DesugaredTy; |
9332 | DesugaredTy = Ty.getSingleStepDesugaredType(Context: C); |
9333 | } while (DesugaredTy != Ty); |
9334 | |
9335 | return false; |
9336 | } |
9337 | |
9338 | static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { |
9339 | if (PT->isDependentType()) |
9340 | return InvalidKernelParam; |
9341 | |
9342 | if (PT->isPointerType() || PT->isReferenceType()) { |
9343 | QualType PointeeType = PT->getPointeeType(); |
9344 | if (PointeeType.getAddressSpace() == LangAS::opencl_generic || |
9345 | PointeeType.getAddressSpace() == LangAS::opencl_private || |
9346 | PointeeType.getAddressSpace() == LangAS::Default) |
9347 | return InvalidAddrSpacePtrKernelParam; |
9348 | |
9349 | if (PointeeType->isPointerType()) { |
9350 | // This is a pointer to pointer parameter. |
9351 | // Recursively check inner type. |
9352 | OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType); |
9353 | if (ParamKind == InvalidAddrSpacePtrKernelParam || |
9354 | ParamKind == InvalidKernelParam) |
9355 | return ParamKind; |
9356 | |
9357 | // OpenCL v3.0 s6.11.a: |
9358 | // A restriction to pass pointers to pointers only applies to OpenCL C |
9359 | // v1.2 or below. |
9360 | if (S.getLangOpts().getOpenCLCompatibleVersion() > 120) |
9361 | return ValidKernelParam; |
9362 | |
9363 | return PtrPtrKernelParam; |
9364 | } |
9365 | |
9366 | // C++ for OpenCL v1.0 s2.4: |
9367 | // Moreover the types used in parameters of the kernel functions must be: |
9368 | // Standard layout types for pointer parameters. The same applies to |
9369 | // reference if an implementation supports them in kernel parameters. |
9370 | if (S.getLangOpts().OpenCLCPlusPlus && |
9371 | !S.getOpenCLOptions().isAvailableOption( |
9372 | Ext: "__cl_clang_non_portable_kernel_param_types" , LO: S.getLangOpts())) { |
9373 | auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl(); |
9374 | bool IsStandardLayoutType = true; |
9375 | if (CXXRec) { |
9376 | // If template type is not ODR-used its definition is only available |
9377 | // in the template definition not its instantiation. |
9378 | // FIXME: This logic doesn't work for types that depend on template |
9379 | // parameter (PR58590). |
9380 | if (!CXXRec->hasDefinition()) |
9381 | CXXRec = CXXRec->getTemplateInstantiationPattern(); |
9382 | if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout()) |
9383 | IsStandardLayoutType = false; |
9384 | } |
9385 | if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() && |
9386 | !IsStandardLayoutType) |
9387 | return InvalidKernelParam; |
9388 | } |
9389 | |
9390 | // OpenCL v1.2 s6.9.p: |
9391 | // A restriction to pass pointers only applies to OpenCL C v1.2 or below. |
9392 | if (S.getLangOpts().getOpenCLCompatibleVersion() > 120) |
9393 | return ValidKernelParam; |
9394 | |
9395 | return PtrKernelParam; |
9396 | } |
9397 | |
9398 | // OpenCL v1.2 s6.9.k: |
9399 | // Arguments to kernel functions in a program cannot be declared with the |
9400 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and |
9401 | // uintptr_t or a struct and/or union that contain fields declared to be one |
9402 | // of these built-in scalar types. |
9403 | if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT)) |
9404 | return InvalidKernelParam; |
9405 | |
9406 | if (PT->isImageType()) |
9407 | return PtrKernelParam; |
9408 | |
9409 | if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) |
9410 | return InvalidKernelParam; |
9411 | |
9412 | // OpenCL extension spec v1.2 s9.5: |
9413 | // This extension adds support for half scalar and vector types as built-in |
9414 | // types that can be used for arithmetic operations, conversions etc. |
9415 | if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16" , LO: S.getLangOpts()) && |
9416 | PT->isHalfType()) |
9417 | return InvalidKernelParam; |
9418 | |
9419 | // Look into an array argument to check if it has a forbidden type. |
9420 | if (PT->isArrayType()) { |
9421 | const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); |
9422 | // Call ourself to check an underlying type of an array. Since the |
9423 | // getPointeeOrArrayElementType returns an innermost type which is not an |
9424 | // array, this recursive call only happens once. |
9425 | return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0)); |
9426 | } |
9427 | |
9428 | // C++ for OpenCL v1.0 s2.4: |
9429 | // Moreover the types used in parameters of the kernel functions must be: |
9430 | // Trivial and standard-layout types C++17 [basic.types] (plain old data |
9431 | // types) for parameters passed by value; |
9432 | if (S.getLangOpts().OpenCLCPlusPlus && |
9433 | !S.getOpenCLOptions().isAvailableOption( |
9434 | Ext: "__cl_clang_non_portable_kernel_param_types" , LO: S.getLangOpts()) && |
9435 | !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context)) |
9436 | return InvalidKernelParam; |
9437 | |
9438 | if (PT->isRecordType()) |
9439 | return RecordKernelParam; |
9440 | |
9441 | return ValidKernelParam; |
9442 | } |
9443 | |
9444 | static void checkIsValidOpenCLKernelParameter( |
9445 | Sema &S, |
9446 | Declarator &D, |
9447 | ParmVarDecl *Param, |
9448 | llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { |
9449 | QualType PT = Param->getType(); |
9450 | |
9451 | // Cache the valid types we encounter to avoid rechecking structs that are |
9452 | // used again |
9453 | if (ValidTypes.count(Ptr: PT.getTypePtr())) |
9454 | return; |
9455 | |
9456 | switch (getOpenCLKernelParameterType(S, PT)) { |
9457 | case PtrPtrKernelParam: |
9458 | // OpenCL v3.0 s6.11.a: |
9459 | // A kernel function argument cannot be declared as a pointer to a pointer |
9460 | // type. [...] This restriction only applies to OpenCL C 1.2 or below. |
9461 | S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param); |
9462 | D.setInvalidType(); |
9463 | return; |
9464 | |
9465 | case InvalidAddrSpacePtrKernelParam: |
9466 | // OpenCL v1.0 s6.5: |
9467 | // __kernel function arguments declared to be a pointer of a type can point |
9468 | // to one of the following address spaces only : __global, __local or |
9469 | // __constant. |
9470 | S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space); |
9471 | D.setInvalidType(); |
9472 | return; |
9473 | |
9474 | // OpenCL v1.2 s6.9.k: |
9475 | // Arguments to kernel functions in a program cannot be declared with the |
9476 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and |
9477 | // uintptr_t or a struct and/or union that contain fields declared to be |
9478 | // one of these built-in scalar types. |
9479 | |
9480 | case InvalidKernelParam: |
9481 | // OpenCL v1.2 s6.8 n: |
9482 | // A kernel function argument cannot be declared |
9483 | // of event_t type. |
9484 | // Do not diagnose half type since it is diagnosed as invalid argument |
9485 | // type for any function elsewhere. |
9486 | if (!PT->isHalfType()) { |
9487 | S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT; |
9488 | |
9489 | // Explain what typedefs are involved. |
9490 | const TypedefType *Typedef = nullptr; |
9491 | while ((Typedef = PT->getAs<TypedefType>())) { |
9492 | SourceLocation Loc = Typedef->getDecl()->getLocation(); |
9493 | // SourceLocation may be invalid for a built-in type. |
9494 | if (Loc.isValid()) |
9495 | S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT; |
9496 | PT = Typedef->desugar(); |
9497 | } |
9498 | } |
9499 | |
9500 | D.setInvalidType(); |
9501 | return; |
9502 | |
9503 | case PtrKernelParam: |
9504 | case ValidKernelParam: |
9505 | ValidTypes.insert(Ptr: PT.getTypePtr()); |
9506 | return; |
9507 | |
9508 | case RecordKernelParam: |
9509 | break; |
9510 | } |
9511 | |
9512 | // Track nested structs we will inspect |
9513 | SmallVector<const Decl *, 4> VisitStack; |
9514 | |
9515 | // Track where we are in the nested structs. Items will migrate from |
9516 | // VisitStack to HistoryStack as we do the DFS for bad field. |
9517 | SmallVector<const FieldDecl *, 4> HistoryStack; |
9518 | HistoryStack.push_back(Elt: nullptr); |
9519 | |
9520 | // At this point we already handled everything except of a RecordType or |
9521 | // an ArrayType of a RecordType. |
9522 | assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type." ); |
9523 | const RecordType *RecTy = |
9524 | PT->getPointeeOrArrayElementType()->getAs<RecordType>(); |
9525 | const RecordDecl *OrigRecDecl = RecTy->getDecl(); |
9526 | |
9527 | VisitStack.push_back(Elt: RecTy->getDecl()); |
9528 | assert(VisitStack.back() && "First decl null?" ); |
9529 | |
9530 | do { |
9531 | const Decl *Next = VisitStack.pop_back_val(); |
9532 | if (!Next) { |
9533 | assert(!HistoryStack.empty()); |
9534 | // Found a marker, we have gone up a level |
9535 | if (const FieldDecl *Hist = HistoryStack.pop_back_val()) |
9536 | ValidTypes.insert(Ptr: Hist->getType().getTypePtr()); |
9537 | |
9538 | continue; |
9539 | } |
9540 | |
9541 | // Adds everything except the original parameter declaration (which is not a |
9542 | // field itself) to the history stack. |
9543 | const RecordDecl *RD; |
9544 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) { |
9545 | HistoryStack.push_back(Elt: Field); |
9546 | |
9547 | QualType FieldTy = Field->getType(); |
9548 | // Other field types (known to be valid or invalid) are handled while we |
9549 | // walk around RecordDecl::fields(). |
9550 | assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && |
9551 | "Unexpected type." ); |
9552 | const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); |
9553 | |
9554 | RD = FieldRecTy->castAs<RecordType>()->getDecl(); |
9555 | } else { |
9556 | RD = cast<RecordDecl>(Val: Next); |
9557 | } |
9558 | |
9559 | // Add a null marker so we know when we've gone back up a level |
9560 | VisitStack.push_back(Elt: nullptr); |
9561 | |
9562 | for (const auto *FD : RD->fields()) { |
9563 | QualType QT = FD->getType(); |
9564 | |
9565 | if (ValidTypes.count(Ptr: QT.getTypePtr())) |
9566 | continue; |
9567 | |
9568 | OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT); |
9569 | if (ParamType == ValidKernelParam) |
9570 | continue; |
9571 | |
9572 | if (ParamType == RecordKernelParam) { |
9573 | VisitStack.push_back(Elt: FD); |
9574 | continue; |
9575 | } |
9576 | |
9577 | // OpenCL v1.2 s6.9.p: |
9578 | // Arguments to kernel functions that are declared to be a struct or union |
9579 | // do not allow OpenCL objects to be passed as elements of the struct or |
9580 | // union. This restriction was lifted in OpenCL v2.0 with the introduction |
9581 | // of SVM. |
9582 | if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || |
9583 | ParamType == InvalidAddrSpacePtrKernelParam) { |
9584 | S.Diag(Loc: Param->getLocation(), |
9585 | DiagID: diag::err_record_with_pointers_kernel_param) |
9586 | << PT->isUnionType() |
9587 | << PT; |
9588 | } else { |
9589 | S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT; |
9590 | } |
9591 | |
9592 | S.Diag(Loc: OrigRecDecl->getLocation(), DiagID: diag::note_within_field_of_type) |
9593 | << OrigRecDecl->getDeclName(); |
9594 | |
9595 | // We have an error, now let's go back up through history and show where |
9596 | // the offending field came from |
9597 | for (ArrayRef<const FieldDecl *>::const_iterator |
9598 | I = HistoryStack.begin() + 1, |
9599 | E = HistoryStack.end(); |
9600 | I != E; ++I) { |
9601 | const FieldDecl *OuterField = *I; |
9602 | S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type) |
9603 | << OuterField->getType(); |
9604 | } |
9605 | |
9606 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here) |
9607 | << QT->isPointerType() |
9608 | << QT; |
9609 | D.setInvalidType(); |
9610 | return; |
9611 | } |
9612 | } while (!VisitStack.empty()); |
9613 | } |
9614 | |
9615 | /// Find the DeclContext in which a tag is implicitly declared if we see an |
9616 | /// elaborated type specifier in the specified context, and lookup finds |
9617 | /// nothing. |
9618 | static DeclContext *getTagInjectionContext(DeclContext *DC) { |
9619 | while (!DC->isFileContext() && !DC->isFunctionOrMethod()) |
9620 | DC = DC->getParent(); |
9621 | return DC; |
9622 | } |
9623 | |
9624 | /// Find the Scope in which a tag is implicitly declared if we see an |
9625 | /// elaborated type specifier in the specified context, and lookup finds |
9626 | /// nothing. |
9627 | static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { |
9628 | while (S->isClassScope() || |
9629 | (LangOpts.CPlusPlus && |
9630 | S->isFunctionPrototypeScope()) || |
9631 | ((S->getFlags() & Scope::DeclScope) == 0) || |
9632 | (S->getEntity() && S->getEntity()->isTransparentContext())) |
9633 | S = S->getParent(); |
9634 | return S; |
9635 | } |
9636 | |
9637 | /// Determine whether a declaration matches a known function in namespace std. |
9638 | static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, |
9639 | unsigned BuiltinID) { |
9640 | switch (BuiltinID) { |
9641 | case Builtin::BI__GetExceptionInfo: |
9642 | // No type checking whatsoever. |
9643 | return Ctx.getTargetInfo().getCXXABI().isMicrosoft(); |
9644 | |
9645 | case Builtin::BIaddressof: |
9646 | case Builtin::BI__addressof: |
9647 | case Builtin::BIforward: |
9648 | case Builtin::BIforward_like: |
9649 | case Builtin::BImove: |
9650 | case Builtin::BImove_if_noexcept: |
9651 | case Builtin::BIas_const: { |
9652 | // Ensure that we don't treat the algorithm |
9653 | // OutputIt std::move(InputIt, InputIt, OutputIt) |
9654 | // as the builtin std::move. |
9655 | const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); |
9656 | return FPT->getNumParams() == 1 && !FPT->isVariadic(); |
9657 | } |
9658 | |
9659 | default: |
9660 | return false; |
9661 | } |
9662 | } |
9663 | |
9664 | NamedDecl* |
9665 | Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, |
9666 | TypeSourceInfo *TInfo, LookupResult &Previous, |
9667 | MultiTemplateParamsArg TemplateParamListsRef, |
9668 | bool &AddToScope) { |
9669 | QualType R = TInfo->getType(); |
9670 | |
9671 | assert(R->isFunctionType()); |
9672 | if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) |
9673 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call); |
9674 | |
9675 | SmallVector<TemplateParameterList *, 4> TemplateParamLists; |
9676 | llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef); |
9677 | if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { |
9678 | if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() && |
9679 | Invented->getDepth() == TemplateParamLists.back()->getDepth()) |
9680 | TemplateParamLists.back() = Invented; |
9681 | else |
9682 | TemplateParamLists.push_back(Elt: Invented); |
9683 | } |
9684 | |
9685 | // TODO: consider using NameInfo for diagnostic. |
9686 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); |
9687 | DeclarationName Name = NameInfo.getName(); |
9688 | StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D); |
9689 | |
9690 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) |
9691 | Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(), |
9692 | DiagID: diag::err_invalid_thread) |
9693 | << DeclSpec::getSpecifierName(S: TSCS); |
9694 | |
9695 | if (D.isFirstDeclarationOfMember()) |
9696 | adjustMemberFunctionCC( |
9697 | T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()), |
9698 | IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc()); |
9699 | |
9700 | bool isFriend = false; |
9701 | FunctionTemplateDecl *FunctionTemplate = nullptr; |
9702 | bool isMemberSpecialization = false; |
9703 | bool isFunctionTemplateSpecialization = false; |
9704 | |
9705 | bool HasExplicitTemplateArgs = false; |
9706 | TemplateArgumentListInfo TemplateArgs; |
9707 | |
9708 | bool isVirtualOkay = false; |
9709 | |
9710 | DeclContext *OriginalDC = DC; |
9711 | bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); |
9712 | |
9713 | FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC, |
9714 | IsVirtualOkay&: isVirtualOkay); |
9715 | if (!NewFD) return nullptr; |
9716 | |
9717 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) |
9718 | NewFD->setTopLevelDeclInObjCContainer(); |
9719 | |
9720 | // Set the lexical context. If this is a function-scope declaration, or has a |
9721 | // C++ scope specifier, or is the object of a friend declaration, the lexical |
9722 | // context will be different from the semantic context. |
9723 | NewFD->setLexicalDeclContext(CurContext); |
9724 | |
9725 | if (IsLocalExternDecl) |
9726 | NewFD->setLocalExternDecl(); |
9727 | |
9728 | if (getLangOpts().CPlusPlus) { |
9729 | // The rules for implicit inlines changed in C++20 for methods and friends |
9730 | // with an in-class definition (when such a definition is not attached to |
9731 | // the global module). User-specified 'inline' overrides this (set when |
9732 | // the function decl is created above). |
9733 | // FIXME: We need a better way to separate C++ standard and clang modules. |
9734 | bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules || |
9735 | !NewFD->getOwningModule() || |
9736 | NewFD->isFromExplicitGlobalModule() || |
9737 | NewFD->getOwningModule()->isHeaderLikeModule(); |
9738 | bool isInline = D.getDeclSpec().isInlineSpecified(); |
9739 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); |
9740 | bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); |
9741 | isFriend = D.getDeclSpec().isFriendSpecified(); |
9742 | if (isFriend && !isInline && D.isFunctionDefinition()) { |
9743 | // Pre-C++20 [class.friend]p5 |
9744 | // A function can be defined in a friend declaration of a |
9745 | // class . . . . Such a function is implicitly inline. |
9746 | // Post C++20 [class.friend]p7 |
9747 | // Such a function is implicitly an inline function if it is attached |
9748 | // to the global module. |
9749 | NewFD->setImplicitlyInline(ImplicitInlineCXX20); |
9750 | } |
9751 | |
9752 | // If this is a method defined in an __interface, and is not a constructor |
9753 | // or an overloaded operator, then set the pure flag (isVirtual will already |
9754 | // return true). |
9755 | if (const CXXRecordDecl *Parent = |
9756 | dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) { |
9757 | if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided()) |
9758 | NewFD->setIsPureVirtual(true); |
9759 | |
9760 | // C++ [class.union]p2 |
9761 | // A union can have member functions, but not virtual functions. |
9762 | if (isVirtual && Parent->isUnion()) { |
9763 | Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union); |
9764 | NewFD->setInvalidDecl(); |
9765 | } |
9766 | if ((Parent->isClass() || Parent->isStruct()) && |
9767 | Parent->hasAttr<SYCLSpecialClassAttr>() && |
9768 | NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() && |
9769 | NewFD->getName() == "__init" && D.isFunctionDefinition()) { |
9770 | if (auto *Def = Parent->getDefinition()) |
9771 | Def->setInitMethod(true); |
9772 | } |
9773 | } |
9774 | |
9775 | SetNestedNameSpecifier(S&: *this, DD: NewFD, D); |
9776 | isMemberSpecialization = false; |
9777 | isFunctionTemplateSpecialization = false; |
9778 | if (D.isInvalidType()) |
9779 | NewFD->setInvalidDecl(); |
9780 | |
9781 | // Match up the template parameter lists with the scope specifier, then |
9782 | // determine whether we have a template or a template specialization. |
9783 | bool Invalid = false; |
9784 | TemplateIdAnnotation *TemplateId = |
9785 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId |
9786 | ? D.getName().TemplateId |
9787 | : nullptr; |
9788 | TemplateParameterList *TemplateParams = |
9789 | MatchTemplateParametersToScopeSpecifier( |
9790 | DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(), |
9791 | SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend, |
9792 | IsMemberSpecialization&: isMemberSpecialization, Invalid); |
9793 | if (TemplateParams) { |
9794 | // Check that we can declare a template here. |
9795 | if (CheckTemplateDeclScope(S, TemplateParams)) |
9796 | NewFD->setInvalidDecl(); |
9797 | |
9798 | if (TemplateParams->size() > 0) { |
9799 | // This is a function template |
9800 | |
9801 | // A destructor cannot be a template. |
9802 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { |
9803 | Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template); |
9804 | NewFD->setInvalidDecl(); |
9805 | // Function template with explicit template arguments. |
9806 | } else if (TemplateId) { |
9807 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec) |
9808 | << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); |
9809 | NewFD->setInvalidDecl(); |
9810 | } |
9811 | |
9812 | // If we're adding a template to a dependent context, we may need to |
9813 | // rebuilding some of the types used within the template parameter list, |
9814 | // now that we know what the current instantiation is. |
9815 | if (DC->isDependentContext()) { |
9816 | ContextRAII SavedContext(*this, DC); |
9817 | if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams)) |
9818 | Invalid = true; |
9819 | } |
9820 | |
9821 | FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC, |
9822 | L: NewFD->getLocation(), |
9823 | Name, Params: TemplateParams, |
9824 | Decl: NewFD); |
9825 | FunctionTemplate->setLexicalDeclContext(CurContext); |
9826 | NewFD->setDescribedFunctionTemplate(FunctionTemplate); |
9827 | |
9828 | // For source fidelity, store the other template param lists. |
9829 | if (TemplateParamLists.size() > 1) { |
9830 | NewFD->setTemplateParameterListsInfo(Context, |
9831 | TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists) |
9832 | .drop_back(N: 1)); |
9833 | } |
9834 | } else { |
9835 | // This is a function template specialization. |
9836 | isFunctionTemplateSpecialization = true; |
9837 | // For source fidelity, store all the template param lists. |
9838 | if (TemplateParamLists.size() > 0) |
9839 | NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists); |
9840 | |
9841 | // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". |
9842 | if (isFriend) { |
9843 | // We want to remove the "template<>", found here. |
9844 | SourceRange RemoveRange = TemplateParams->getSourceRange(); |
9845 | |
9846 | // If we remove the template<> and the name is not a |
9847 | // template-id, we're actually silently creating a problem: |
9848 | // the friend declaration will refer to an untemplated decl, |
9849 | // and clearly the user wants a template specialization. So |
9850 | // we need to insert '<>' after the name. |
9851 | SourceLocation InsertLoc; |
9852 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { |
9853 | InsertLoc = D.getName().getSourceRange().getEnd(); |
9854 | InsertLoc = getLocForEndOfToken(Loc: InsertLoc); |
9855 | } |
9856 | |
9857 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend) |
9858 | << Name << RemoveRange |
9859 | << FixItHint::CreateRemoval(RemoveRange) |
9860 | << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>" ); |
9861 | Invalid = true; |
9862 | |
9863 | // Recover by faking up an empty template argument list. |
9864 | HasExplicitTemplateArgs = true; |
9865 | TemplateArgs.setLAngleLoc(InsertLoc); |
9866 | TemplateArgs.setRAngleLoc(InsertLoc); |
9867 | } |
9868 | } |
9869 | } else { |
9870 | // Check that we can declare a template here. |
9871 | if (!TemplateParamLists.empty() && isMemberSpecialization && |
9872 | CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back())) |
9873 | NewFD->setInvalidDecl(); |
9874 | |
9875 | // All template param lists were matched against the scope specifier: |
9876 | // this is NOT (an explicit specialization of) a template. |
9877 | if (TemplateParamLists.size() > 0) |
9878 | // For source fidelity, store all the template param lists. |
9879 | NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists); |
9880 | |
9881 | // "friend void foo<>(int);" is an implicit specialization decl. |
9882 | if (isFriend && TemplateId) |
9883 | isFunctionTemplateSpecialization = true; |
9884 | } |
9885 | |
9886 | // If this is a function template specialization and the unqualified-id of |
9887 | // the declarator-id is a template-id, convert the template argument list |
9888 | // into our AST format and check for unexpanded packs. |
9889 | if (isFunctionTemplateSpecialization && TemplateId) { |
9890 | HasExplicitTemplateArgs = true; |
9891 | |
9892 | TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); |
9893 | TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); |
9894 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), |
9895 | TemplateId->NumArgs); |
9896 | translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs); |
9897 | |
9898 | // FIXME: Should we check for unexpanded packs if this was an (invalid) |
9899 | // declaration of a function template partial specialization? Should we |
9900 | // consider the unexpanded pack context to be a partial specialization? |
9901 | for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) { |
9902 | if (DiagnoseUnexpandedParameterPack( |
9903 | Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration |
9904 | : UPPC_ExplicitSpecialization)) |
9905 | NewFD->setInvalidDecl(); |
9906 | } |
9907 | } |
9908 | |
9909 | if (Invalid) { |
9910 | NewFD->setInvalidDecl(); |
9911 | if (FunctionTemplate) |
9912 | FunctionTemplate->setInvalidDecl(); |
9913 | } |
9914 | |
9915 | // C++ [dcl.fct.spec]p5: |
9916 | // The virtual specifier shall only be used in declarations of |
9917 | // nonstatic class member functions that appear within a |
9918 | // member-specification of a class declaration; see 10.3. |
9919 | // |
9920 | if (isVirtual && !NewFD->isInvalidDecl()) { |
9921 | if (!isVirtualOkay) { |
9922 | Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), |
9923 | DiagID: diag::err_virtual_non_function); |
9924 | } else if (!CurContext->isRecord()) { |
9925 | // 'virtual' was specified outside of the class. |
9926 | Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), |
9927 | DiagID: diag::err_virtual_out_of_class) |
9928 | << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc()); |
9929 | } else if (NewFD->getDescribedFunctionTemplate()) { |
9930 | // C++ [temp.mem]p3: |
9931 | // A member function template shall not be virtual. |
9932 | Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), |
9933 | DiagID: diag::err_virtual_member_function_template) |
9934 | << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc()); |
9935 | } else { |
9936 | // Okay: Add virtual to the method. |
9937 | NewFD->setVirtualAsWritten(true); |
9938 | } |
9939 | |
9940 | if (getLangOpts().CPlusPlus14 && |
9941 | NewFD->getReturnType()->isUndeducedType()) |
9942 | Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual); |
9943 | } |
9944 | |
9945 | // C++ [dcl.fct.spec]p3: |
9946 | // The inline specifier shall not appear on a block scope function |
9947 | // declaration. |
9948 | if (isInline && !NewFD->isInvalidDecl()) { |
9949 | if (CurContext->isFunctionOrMethod()) { |
9950 | // 'inline' is not allowed on block scope function declaration. |
9951 | Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), |
9952 | DiagID: diag::err_inline_declaration_block_scope) << Name |
9953 | << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc()); |
9954 | } |
9955 | } |
9956 | |
9957 | // C++ [dcl.fct.spec]p6: |
9958 | // The explicit specifier shall be used only in the declaration of a |
9959 | // constructor or conversion function within its class definition; |
9960 | // see 12.3.1 and 12.3.2. |
9961 | if (hasExplicit && !NewFD->isInvalidDecl() && |
9962 | !isa<CXXDeductionGuideDecl>(Val: NewFD)) { |
9963 | if (!CurContext->isRecord()) { |
9964 | // 'explicit' was specified outside of the class. |
9965 | Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(), |
9966 | DiagID: diag::err_explicit_out_of_class) |
9967 | << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange()); |
9968 | } else if (!isa<CXXConstructorDecl>(Val: NewFD) && |
9969 | !isa<CXXConversionDecl>(Val: NewFD)) { |
9970 | // 'explicit' was specified on a function that wasn't a constructor |
9971 | // or conversion function. |
9972 | Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(), |
9973 | DiagID: diag::err_explicit_non_ctor_or_conv_function) |
9974 | << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange()); |
9975 | } |
9976 | } |
9977 | |
9978 | ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); |
9979 | if (ConstexprKind != ConstexprSpecKind::Unspecified) { |
9980 | // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors |
9981 | // are implicitly inline. |
9982 | NewFD->setImplicitlyInline(); |
9983 | |
9984 | // C++11 [dcl.constexpr]p3: functions declared constexpr are required to |
9985 | // be either constructors or to return a literal type. Therefore, |
9986 | // destructors cannot be declared constexpr. |
9987 | if (isa<CXXDestructorDecl>(Val: NewFD) && |
9988 | (!getLangOpts().CPlusPlus20 || |
9989 | ConstexprKind == ConstexprSpecKind::Consteval)) { |
9990 | Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor) |
9991 | << static_cast<int>(ConstexprKind); |
9992 | NewFD->setConstexprKind(getLangOpts().CPlusPlus20 |
9993 | ? ConstexprSpecKind::Unspecified |
9994 | : ConstexprSpecKind::Constexpr); |
9995 | } |
9996 | // C++20 [dcl.constexpr]p2: An allocation function, or a |
9997 | // deallocation function shall not be declared with the consteval |
9998 | // specifier. |
9999 | if (ConstexprKind == ConstexprSpecKind::Consteval && |
10000 | (NewFD->getOverloadedOperator() == OO_New || |
10001 | NewFD->getOverloadedOperator() == OO_Array_New || |
10002 | NewFD->getOverloadedOperator() == OO_Delete || |
10003 | NewFD->getOverloadedOperator() == OO_Array_Delete)) { |
10004 | Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), |
10005 | DiagID: diag::err_invalid_consteval_decl_kind) |
10006 | << NewFD; |
10007 | NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); |
10008 | } |
10009 | } |
10010 | |
10011 | // If __module_private__ was specified, mark the function accordingly. |
10012 | if (D.getDeclSpec().isModulePrivateSpecified()) { |
10013 | if (isFunctionTemplateSpecialization) { |
10014 | SourceLocation ModulePrivateLoc |
10015 | = D.getDeclSpec().getModulePrivateSpecLoc(); |
10016 | Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization) |
10017 | << 0 |
10018 | << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc); |
10019 | } else { |
10020 | NewFD->setModulePrivate(); |
10021 | if (FunctionTemplate) |
10022 | FunctionTemplate->setModulePrivate(); |
10023 | } |
10024 | } |
10025 | |
10026 | if (isFriend) { |
10027 | if (FunctionTemplate) { |
10028 | FunctionTemplate->setObjectOfFriendDecl(); |
10029 | FunctionTemplate->setAccess(AS_public); |
10030 | } |
10031 | NewFD->setObjectOfFriendDecl(); |
10032 | NewFD->setAccess(AS_public); |
10033 | } |
10034 | |
10035 | // If a function is defined as defaulted or deleted, mark it as such now. |
10036 | // We'll do the relevant checks on defaulted / deleted functions later. |
10037 | switch (D.getFunctionDefinitionKind()) { |
10038 | case FunctionDefinitionKind::Declaration: |
10039 | case FunctionDefinitionKind::Definition: |
10040 | break; |
10041 | |
10042 | case FunctionDefinitionKind::Defaulted: |
10043 | NewFD->setDefaulted(); |
10044 | break; |
10045 | |
10046 | case FunctionDefinitionKind::Deleted: |
10047 | NewFD->setDeletedAsWritten(); |
10048 | break; |
10049 | } |
10050 | |
10051 | if (isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext && |
10052 | D.isFunctionDefinition() && !isInline) { |
10053 | // Pre C++20 [class.mfct]p2: |
10054 | // A member function may be defined (8.4) in its class definition, in |
10055 | // which case it is an inline member function (7.1.2) |
10056 | // Post C++20 [class.mfct]p1: |
10057 | // If a member function is attached to the global module and is defined |
10058 | // in its class definition, it is inline. |
10059 | NewFD->setImplicitlyInline(ImplicitInlineCXX20); |
10060 | } |
10061 | |
10062 | if (!isFriend && SC != SC_None) { |
10063 | // C++ [temp.expl.spec]p2: |
10064 | // The declaration in an explicit-specialization shall not be an |
10065 | // export-declaration. An explicit specialization shall not use a |
10066 | // storage-class-specifier other than thread_local. |
10067 | // |
10068 | // We diagnose friend declarations with storage-class-specifiers |
10069 | // elsewhere. |
10070 | if (isFunctionTemplateSpecialization || isMemberSpecialization) { |
10071 | Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(), |
10072 | DiagID: diag::ext_explicit_specialization_storage_class) |
10073 | << FixItHint::CreateRemoval( |
10074 | RemoveRange: D.getDeclSpec().getStorageClassSpecLoc()); |
10075 | } |
10076 | |
10077 | if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) { |
10078 | assert(isa<CXXMethodDecl>(NewFD) && |
10079 | "Out-of-line member function should be a CXXMethodDecl" ); |
10080 | // C++ [class.static]p1: |
10081 | // A data or function member of a class may be declared static |
10082 | // in a class definition, in which case it is a static member of |
10083 | // the class. |
10084 | |
10085 | // Complain about the 'static' specifier if it's on an out-of-line |
10086 | // member function definition. |
10087 | |
10088 | // MSVC permits the use of a 'static' storage specifier on an |
10089 | // out-of-line member function template declaration and class member |
10090 | // template declaration (MSVC versions before 2015), warn about this. |
10091 | Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(), |
10092 | DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) && |
10093 | cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) || |
10094 | (getLangOpts().MSVCCompat && |
10095 | NewFD->getDescribedFunctionTemplate())) |
10096 | ? diag::ext_static_out_of_line |
10097 | : diag::err_static_out_of_line) |
10098 | << FixItHint::CreateRemoval( |
10099 | RemoveRange: D.getDeclSpec().getStorageClassSpecLoc()); |
10100 | } |
10101 | } |
10102 | |
10103 | // C++11 [except.spec]p15: |
10104 | // A deallocation function with no exception-specification is treated |
10105 | // as if it were specified with noexcept(true). |
10106 | const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); |
10107 | if ((Name.getCXXOverloadedOperator() == OO_Delete || |
10108 | Name.getCXXOverloadedOperator() == OO_Array_Delete) && |
10109 | getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) |
10110 | NewFD->setType(Context.getFunctionType( |
10111 | ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(), |
10112 | EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept))); |
10113 | |
10114 | // C++20 [dcl.inline]/7 |
10115 | // If an inline function or variable that is attached to a named module |
10116 | // is declared in a definition domain, it shall be defined in that |
10117 | // domain. |
10118 | // So, if the current declaration does not have a definition, we must |
10119 | // check at the end of the TU (or when the PMF starts) to see that we |
10120 | // have a definition at that point. |
10121 | if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 && |
10122 | NewFD->isInNamedModule()) { |
10123 | PendingInlineFuncDecls.insert(Ptr: NewFD); |
10124 | } |
10125 | } |
10126 | |
10127 | // Filter out previous declarations that don't match the scope. |
10128 | FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD), |
10129 | AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() || |
10130 | isMemberSpecialization || |
10131 | isFunctionTemplateSpecialization); |
10132 | |
10133 | // Handle GNU asm-label extension (encoded as an attribute). |
10134 | if (Expr *E = (Expr*) D.getAsmLabel()) { |
10135 | // The parser guarantees this is a string. |
10136 | StringLiteral *SE = cast<StringLiteral>(Val: E); |
10137 | NewFD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(), |
10138 | /*IsLiteralLabel=*/true, |
10139 | Range: SE->getStrTokenLoc(TokNum: 0))); |
10140 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { |
10141 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = |
10142 | ExtnameUndeclaredIdentifiers.find(Val: NewFD->getIdentifier()); |
10143 | if (I != ExtnameUndeclaredIdentifiers.end()) { |
10144 | if (isDeclExternC(D: NewFD)) { |
10145 | NewFD->addAttr(A: I->second); |
10146 | ExtnameUndeclaredIdentifiers.erase(I); |
10147 | } else |
10148 | Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied) |
10149 | << /*Variable*/0 << NewFD; |
10150 | } |
10151 | } |
10152 | |
10153 | // Copy the parameter declarations from the declarator D to the function |
10154 | // declaration NewFD, if they are available. First scavenge them into Params. |
10155 | SmallVector<ParmVarDecl*, 16> Params; |
10156 | unsigned FTIIdx; |
10157 | if (D.isFunctionDeclarator(idx&: FTIIdx)) { |
10158 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun; |
10159 | |
10160 | // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs |
10161 | // function that takes no arguments, not a function that takes a |
10162 | // single void argument. |
10163 | // We let through "const void" here because Sema::GetTypeForDeclarator |
10164 | // already checks for that case. |
10165 | if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { |
10166 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { |
10167 | ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param); |
10168 | assert(Param->getDeclContext() != NewFD && "Was set before ?" ); |
10169 | Param->setDeclContext(NewFD); |
10170 | Params.push_back(Elt: Param); |
10171 | |
10172 | if (Param->isInvalidDecl()) |
10173 | NewFD->setInvalidDecl(); |
10174 | } |
10175 | } |
10176 | |
10177 | if (!getLangOpts().CPlusPlus) { |
10178 | // In C, find all the tag declarations from the prototype and move them |
10179 | // into the function DeclContext. Remove them from the surrounding tag |
10180 | // injection context of the function, which is typically but not always |
10181 | // the TU. |
10182 | DeclContext *PrototypeTagContext = |
10183 | getTagInjectionContext(DC: NewFD->getLexicalDeclContext()); |
10184 | for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { |
10185 | auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl); |
10186 | |
10187 | // We don't want to reparent enumerators. Look at their parent enum |
10188 | // instead. |
10189 | if (!TD) { |
10190 | if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl)) |
10191 | TD = cast<EnumDecl>(Val: ECD->getDeclContext()); |
10192 | } |
10193 | if (!TD) |
10194 | continue; |
10195 | DeclContext *TagDC = TD->getLexicalDeclContext(); |
10196 | if (!TagDC->containsDecl(D: TD)) |
10197 | continue; |
10198 | TagDC->removeDecl(D: TD); |
10199 | TD->setDeclContext(NewFD); |
10200 | NewFD->addDecl(D: TD); |
10201 | |
10202 | // Preserve the lexical DeclContext if it is not the surrounding tag |
10203 | // injection context of the FD. In this example, the semantic context of |
10204 | // E will be f and the lexical context will be S, while both the |
10205 | // semantic and lexical contexts of S will be f: |
10206 | // void f(struct S { enum E { a } f; } s); |
10207 | if (TagDC != PrototypeTagContext) |
10208 | TD->setLexicalDeclContext(TagDC); |
10209 | } |
10210 | } |
10211 | } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { |
10212 | // When we're declaring a function with a typedef, typeof, etc as in the |
10213 | // following example, we'll need to synthesize (unnamed) |
10214 | // parameters for use in the declaration. |
10215 | // |
10216 | // @code |
10217 | // typedef void fn(int); |
10218 | // fn f; |
10219 | // @endcode |
10220 | |
10221 | // Synthesize a parameter for each argument type. |
10222 | for (const auto &AI : FT->param_types()) { |
10223 | ParmVarDecl *Param = |
10224 | BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI); |
10225 | Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size()); |
10226 | Params.push_back(Elt: Param); |
10227 | } |
10228 | } else { |
10229 | assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && |
10230 | "Should not need args for typedef of non-prototype fn" ); |
10231 | } |
10232 | |
10233 | // Finally, we know we have the right number of parameters, install them. |
10234 | NewFD->setParams(Params); |
10235 | |
10236 | if (D.getDeclSpec().isNoreturnSpecified()) |
10237 | NewFD->addAttr( |
10238 | A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc())); |
10239 | |
10240 | // Functions returning a variably modified type violate C99 6.7.5.2p2 |
10241 | // because all functions have linkage. |
10242 | if (!NewFD->isInvalidDecl() && |
10243 | NewFD->getReturnType()->isVariablyModifiedType()) { |
10244 | Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl); |
10245 | NewFD->setInvalidDecl(); |
10246 | } |
10247 | |
10248 | // Apply an implicit SectionAttr if '#pragma clang section text' is active |
10249 | if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && |
10250 | !NewFD->hasAttr<SectionAttr>()) |
10251 | NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit( |
10252 | Ctx&: Context, Name: PragmaClangTextSection.SectionName, |
10253 | Range: PragmaClangTextSection.PragmaLocation)); |
10254 | |
10255 | // Apply an implicit SectionAttr if #pragma code_seg is active. |
10256 | if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && |
10257 | !NewFD->hasAttr<SectionAttr>()) { |
10258 | NewFD->addAttr(A: SectionAttr::CreateImplicit( |
10259 | Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(), |
10260 | Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate)); |
10261 | if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(), |
10262 | SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute | |
10263 | ASTContext::PSF_Read, |
10264 | TheDecl: NewFD)) |
10265 | NewFD->dropAttr<SectionAttr>(); |
10266 | } |
10267 | |
10268 | // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is |
10269 | // active. |
10270 | if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() && |
10271 | !NewFD->hasAttr<StrictGuardStackCheckAttr>()) |
10272 | NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit( |
10273 | Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation)); |
10274 | |
10275 | // Apply an implicit CodeSegAttr from class declspec or |
10276 | // apply an implicit SectionAttr from #pragma code_seg if active. |
10277 | if (!NewFD->hasAttr<CodeSegAttr>()) { |
10278 | if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD, |
10279 | IsDefinition: D.isFunctionDefinition())) { |
10280 | NewFD->addAttr(A: SAttr); |
10281 | } |
10282 | } |
10283 | |
10284 | // Handle attributes. |
10285 | ProcessDeclAttributes(S, D: NewFD, PD: D); |
10286 | const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); |
10287 | if (NewTVA && !NewTVA->isDefaultVersion() && |
10288 | !Context.getTargetInfo().hasFeature(Feature: "fmv" )) { |
10289 | // Don't add to scope fmv functions declarations if fmv disabled |
10290 | AddToScope = false; |
10291 | return NewFD; |
10292 | } |
10293 | |
10294 | if (getLangOpts().OpenCL || getLangOpts().HLSL) { |
10295 | // Neither OpenCL nor HLSL allow an address space qualifyer on a return |
10296 | // type. |
10297 | // |
10298 | // OpenCL v1.1 s6.5: Using an address space qualifier in a function return |
10299 | // type declaration will generate a compilation error. |
10300 | LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); |
10301 | if (AddressSpace != LangAS::Default) { |
10302 | Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space); |
10303 | NewFD->setInvalidDecl(); |
10304 | } |
10305 | } |
10306 | |
10307 | if (!getLangOpts().CPlusPlus) { |
10308 | // Perform semantic checking on the function declaration. |
10309 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) |
10310 | CheckMain(FD: NewFD, D: D.getDeclSpec()); |
10311 | |
10312 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) |
10313 | CheckMSVCRTEntryPoint(FD: NewFD); |
10314 | |
10315 | if (!NewFD->isInvalidDecl()) |
10316 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, |
10317 | IsMemberSpecialization: isMemberSpecialization, |
10318 | DeclIsDefn: D.isFunctionDefinition())); |
10319 | else if (!Previous.empty()) |
10320 | // Recover gracefully from an invalid redeclaration. |
10321 | D.setRedeclaration(true); |
10322 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || |
10323 | Previous.getResultKind() != LookupResult::FoundOverloaded) && |
10324 | "previous declaration set still overloaded" ); |
10325 | |
10326 | // Diagnose no-prototype function declarations with calling conventions that |
10327 | // don't support variadic calls. Only do this in C and do it after merging |
10328 | // possibly prototyped redeclarations. |
10329 | const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); |
10330 | if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) { |
10331 | CallingConv CC = FT->getExtInfo().getCC(); |
10332 | if (!supportsVariadicCall(CC)) { |
10333 | // Windows system headers sometimes accidentally use stdcall without |
10334 | // (void) parameters, so we relax this to a warning. |
10335 | int DiagID = |
10336 | CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; |
10337 | Diag(Loc: NewFD->getLocation(), DiagID) |
10338 | << FunctionType::getNameForCallConv(CC); |
10339 | } |
10340 | } |
10341 | |
10342 | if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || |
10343 | NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) |
10344 | checkNonTrivialCUnion(QT: NewFD->getReturnType(), |
10345 | Loc: NewFD->getReturnTypeSourceRange().getBegin(), |
10346 | UseContext: NTCUC_FunctionReturn, NonTrivialKind: NTCUK_Destruct|NTCUK_Copy); |
10347 | } else { |
10348 | // C++11 [replacement.functions]p3: |
10349 | // The program's definitions shall not be specified as inline. |
10350 | // |
10351 | // N.B. We diagnose declarations instead of definitions per LWG issue 2340. |
10352 | // |
10353 | // Suppress the diagnostic if the function is __attribute__((used)), since |
10354 | // that forces an external definition to be emitted. |
10355 | if (D.getDeclSpec().isInlineSpecified() && |
10356 | NewFD->isReplaceableGlobalAllocationFunction() && |
10357 | !NewFD->hasAttr<UsedAttr>()) |
10358 | Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), |
10359 | DiagID: diag::ext_operator_new_delete_declared_inline) |
10360 | << NewFD->getDeclName(); |
10361 | |
10362 | if (Expr *TRC = NewFD->getTrailingRequiresClause()) { |
10363 | // C++20 [dcl.decl.general]p4: |
10364 | // The optional requires-clause in an init-declarator or |
10365 | // member-declarator shall be present only if the declarator declares a |
10366 | // templated function. |
10367 | // |
10368 | // C++20 [temp.pre]p8: |
10369 | // An entity is templated if it is |
10370 | // - a template, |
10371 | // - an entity defined or created in a templated entity, |
10372 | // - a member of a templated entity, |
10373 | // - an enumerator for an enumeration that is a templated entity, or |
10374 | // - the closure type of a lambda-expression appearing in the |
10375 | // declaration of a templated entity. |
10376 | // |
10377 | // [Note 6: A local class, a local or block variable, or a friend |
10378 | // function defined in a templated entity is a templated entity. |
10379 | // — end note] |
10380 | // |
10381 | // A templated function is a function template or a function that is |
10382 | // templated. A templated class is a class template or a class that is |
10383 | // templated. A templated variable is a variable template or a variable |
10384 | // that is templated. |
10385 | if (!FunctionTemplate) { |
10386 | if (isFunctionTemplateSpecialization || isMemberSpecialization) { |
10387 | // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847): |
10388 | // An explicit specialization shall not have a trailing |
10389 | // requires-clause unless it declares a function template. |
10390 | // |
10391 | // Since a friend function template specialization cannot be |
10392 | // definition, and since a non-template friend declaration with a |
10393 | // trailing requires-clause must be a definition, we diagnose |
10394 | // friend function template specializations with trailing |
10395 | // requires-clauses on the same path as explicit specializations |
10396 | // even though they aren't necessarily prohibited by the same |
10397 | // language rule. |
10398 | Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause) |
10399 | << isFriend; |
10400 | } else if (isFriend && NewFD->isTemplated() && |
10401 | !D.isFunctionDefinition()) { |
10402 | // C++ [temp.friend]p9: |
10403 | // A non-template friend declaration with a requires-clause shall be |
10404 | // a definition. |
10405 | Diag(Loc: NewFD->getBeginLoc(), |
10406 | DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def); |
10407 | NewFD->setInvalidDecl(); |
10408 | } else if (!NewFD->isTemplated() || |
10409 | !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) { |
10410 | Diag(Loc: TRC->getBeginLoc(), |
10411 | DiagID: diag::err_constrained_non_templated_function); |
10412 | } |
10413 | } |
10414 | } |
10415 | |
10416 | // We do not add HD attributes to specializations here because |
10417 | // they may have different constexpr-ness compared to their |
10418 | // templates and, after maybeAddHostDeviceAttrs() is applied, |
10419 | // may end up with different effective targets. Instead, a |
10420 | // specialization inherits its target attributes from its template |
10421 | // in the CheckFunctionTemplateSpecialization() call below. |
10422 | if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) |
10423 | CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous); |
10424 | |
10425 | // Handle explicit specializations of function templates |
10426 | // and friend function declarations with an explicit |
10427 | // template argument list. |
10428 | if (isFunctionTemplateSpecialization) { |
10429 | bool isDependentSpecialization = false; |
10430 | if (isFriend) { |
10431 | // For friend function specializations, this is a dependent |
10432 | // specialization if its semantic context is dependent, its |
10433 | // type is dependent, or if its template-id is dependent. |
10434 | isDependentSpecialization = |
10435 | DC->isDependentContext() || NewFD->getType()->isDependentType() || |
10436 | (HasExplicitTemplateArgs && |
10437 | TemplateSpecializationType:: |
10438 | anyInstantiationDependentTemplateArguments( |
10439 | Args: TemplateArgs.arguments())); |
10440 | assert((!isDependentSpecialization || |
10441 | (HasExplicitTemplateArgs == isDependentSpecialization)) && |
10442 | "dependent friend function specialization without template " |
10443 | "args" ); |
10444 | } else { |
10445 | // For class-scope explicit specializations of function templates, |
10446 | // if the lexical context is dependent, then the specialization |
10447 | // is dependent. |
10448 | isDependentSpecialization = |
10449 | CurContext->isRecord() && CurContext->isDependentContext(); |
10450 | } |
10451 | |
10452 | TemplateArgumentListInfo *ExplicitTemplateArgs = |
10453 | HasExplicitTemplateArgs ? &TemplateArgs : nullptr; |
10454 | if (isDependentSpecialization) { |
10455 | // If it's a dependent specialization, it may not be possible |
10456 | // to determine the primary template (for explicit specializations) |
10457 | // or befriended declaration (for friends) until the enclosing |
10458 | // template is instantiated. In such cases, we store the declarations |
10459 | // found by name lookup and defer resolution until instantiation. |
10460 | if (CheckDependentFunctionTemplateSpecialization( |
10461 | FD: NewFD, ExplicitTemplateArgs, Previous)) |
10462 | NewFD->setInvalidDecl(); |
10463 | } else if (!NewFD->isInvalidDecl()) { |
10464 | if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs, |
10465 | Previous)) |
10466 | NewFD->setInvalidDecl(); |
10467 | } |
10468 | } else if (isMemberSpecialization && isa<CXXMethodDecl>(Val: NewFD)) { |
10469 | if (CheckMemberSpecialization(Member: NewFD, Previous)) |
10470 | NewFD->setInvalidDecl(); |
10471 | } |
10472 | |
10473 | // Perform semantic checking on the function declaration. |
10474 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) |
10475 | CheckMain(FD: NewFD, D: D.getDeclSpec()); |
10476 | |
10477 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) |
10478 | CheckMSVCRTEntryPoint(FD: NewFD); |
10479 | |
10480 | if (!NewFD->isInvalidDecl()) |
10481 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, |
10482 | IsMemberSpecialization: isMemberSpecialization, |
10483 | DeclIsDefn: D.isFunctionDefinition())); |
10484 | else if (!Previous.empty()) |
10485 | // Recover gracefully from an invalid redeclaration. |
10486 | D.setRedeclaration(true); |
10487 | |
10488 | assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() || |
10489 | !D.isRedeclaration() || |
10490 | Previous.getResultKind() != LookupResult::FoundOverloaded) && |
10491 | "previous declaration set still overloaded" ); |
10492 | |
10493 | NamedDecl *PrincipalDecl = (FunctionTemplate |
10494 | ? cast<NamedDecl>(Val: FunctionTemplate) |
10495 | : NewFD); |
10496 | |
10497 | if (isFriend && NewFD->getPreviousDecl()) { |
10498 | AccessSpecifier Access = AS_public; |
10499 | if (!NewFD->isInvalidDecl()) |
10500 | Access = NewFD->getPreviousDecl()->getAccess(); |
10501 | |
10502 | NewFD->setAccess(Access); |
10503 | if (FunctionTemplate) FunctionTemplate->setAccess(Access); |
10504 | } |
10505 | |
10506 | if (NewFD->isOverloadedOperator() && !DC->isRecord() && |
10507 | PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary)) |
10508 | PrincipalDecl->setNonMemberOperator(); |
10509 | |
10510 | // If we have a function template, check the template parameter |
10511 | // list. This will check and merge default template arguments. |
10512 | if (FunctionTemplate) { |
10513 | FunctionTemplateDecl *PrevTemplate = |
10514 | FunctionTemplate->getPreviousDecl(); |
10515 | CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(), |
10516 | OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters() |
10517 | : nullptr, |
10518 | TPC: D.getDeclSpec().isFriendSpecified() |
10519 | ? (D.isFunctionDefinition() |
10520 | ? TPC_FriendFunctionTemplateDefinition |
10521 | : TPC_FriendFunctionTemplate) |
10522 | : (D.getCXXScopeSpec().isSet() && |
10523 | DC && DC->isRecord() && |
10524 | DC->isDependentContext()) |
10525 | ? TPC_ClassTemplateMember |
10526 | : TPC_FunctionTemplate); |
10527 | } |
10528 | |
10529 | if (NewFD->isInvalidDecl()) { |
10530 | // Ignore all the rest of this. |
10531 | } else if (!D.isRedeclaration()) { |
10532 | struct ActOnFDArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists, |
10533 | .AddToScope: AddToScope }; |
10534 | // Fake up an access specifier if it's supposed to be a class member. |
10535 | if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext())) |
10536 | NewFD->setAccess(AS_public); |
10537 | |
10538 | // Qualified decls generally require a previous declaration. |
10539 | if (D.getCXXScopeSpec().isSet()) { |
10540 | // ...with the major exception of templated-scope or |
10541 | // dependent-scope friend declarations. |
10542 | |
10543 | // TODO: we currently also suppress this check in dependent |
10544 | // contexts because (1) the parameter depth will be off when |
10545 | // matching friend templates and (2) we might actually be |
10546 | // selecting a friend based on a dependent factor. But there |
10547 | // are situations where these conditions don't apply and we |
10548 | // can actually do this check immediately. |
10549 | // |
10550 | // Unless the scope is dependent, it's always an error if qualified |
10551 | // redeclaration lookup found nothing at all. Diagnose that now; |
10552 | // nothing will diagnose that error later. |
10553 | if (isFriend && |
10554 | (D.getCXXScopeSpec().getScopeRep()->isDependent() || |
10555 | (!Previous.empty() && CurContext->isDependentContext()))) { |
10556 | // ignore these |
10557 | } else if (NewFD->isCPUDispatchMultiVersion() || |
10558 | NewFD->isCPUSpecificMultiVersion()) { |
10559 | // ignore this, we allow the redeclaration behavior here to create new |
10560 | // versions of the function. |
10561 | } else { |
10562 | // The user tried to provide an out-of-line definition for a |
10563 | // function that is a member of a class or namespace, but there |
10564 | // was no such member function declared (C++ [class.mfct]p2, |
10565 | // C++ [namespace.memdef]p2). For example: |
10566 | // |
10567 | // class X { |
10568 | // void f() const; |
10569 | // }; |
10570 | // |
10571 | // void X::f() { } // ill-formed |
10572 | // |
10573 | // Complain about this problem, and attempt to suggest close |
10574 | // matches (e.g., those that differ only in cv-qualifiers and |
10575 | // whether the parameter types are references). |
10576 | |
10577 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( |
10578 | SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) { |
10579 | AddToScope = ExtraArgs.AddToScope; |
10580 | return Result; |
10581 | } |
10582 | } |
10583 | |
10584 | // Unqualified local friend declarations are required to resolve |
10585 | // to something. |
10586 | } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) { |
10587 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( |
10588 | SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) { |
10589 | AddToScope = ExtraArgs.AddToScope; |
10590 | return Result; |
10591 | } |
10592 | } |
10593 | } else if (!D.isFunctionDefinition() && |
10594 | isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() && |
10595 | !isFriend && !isFunctionTemplateSpecialization && |
10596 | !isMemberSpecialization) { |
10597 | // An out-of-line member function declaration must also be a |
10598 | // definition (C++ [class.mfct]p2). |
10599 | // Note that this is not the case for explicit specializations of |
10600 | // function templates or member functions of class templates, per |
10601 | // C++ [temp.expl.spec]p2. We also allow these declarations as an |
10602 | // extension for compatibility with old SWIG code which likes to |
10603 | // generate them. |
10604 | Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration) |
10605 | << D.getCXXScopeSpec().getRange(); |
10606 | } |
10607 | } |
10608 | |
10609 | if (getLangOpts().HLSL && D.isFunctionDefinition()) { |
10610 | // Any top level function could potentially be specified as an entry. |
10611 | if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier()) |
10612 | HLSL().ActOnTopLevelFunction(FD: NewFD); |
10613 | |
10614 | if (NewFD->hasAttr<HLSLShaderAttr>()) |
10615 | HLSL().CheckEntryPoint(FD: NewFD); |
10616 | } |
10617 | |
10618 | // If this is the first declaration of a library builtin function, add |
10619 | // attributes as appropriate. |
10620 | if (!D.isRedeclaration()) { |
10621 | if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { |
10622 | if (unsigned BuiltinID = II->getBuiltinID()) { |
10623 | bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID); |
10624 | if (!InStdNamespace && |
10625 | NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { |
10626 | if (NewFD->getLanguageLinkage() == CLanguageLinkage) { |
10627 | // Validate the type matches unless this builtin is specified as |
10628 | // matching regardless of its declared type. |
10629 | if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) { |
10630 | NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID)); |
10631 | } else { |
10632 | ASTContext::GetBuiltinTypeError Error; |
10633 | LookupNecessaryTypesForBuiltin(S, ID: BuiltinID); |
10634 | QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error); |
10635 | |
10636 | if (!Error && !BuiltinType.isNull() && |
10637 | Context.hasSameFunctionTypeIgnoringExceptionSpec( |
10638 | T: NewFD->getType(), U: BuiltinType)) |
10639 | NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID)); |
10640 | } |
10641 | } |
10642 | } else if (InStdNamespace && NewFD->isInStdNamespace() && |
10643 | isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) { |
10644 | NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID)); |
10645 | } |
10646 | } |
10647 | } |
10648 | } |
10649 | |
10650 | ProcessPragmaWeak(S, D: NewFD); |
10651 | checkAttributesAfterMerging(S&: *this, ND&: *NewFD); |
10652 | |
10653 | AddKnownFunctionAttributes(FD: NewFD); |
10654 | |
10655 | if (NewFD->hasAttr<OverloadableAttr>() && |
10656 | !NewFD->getType()->getAs<FunctionProtoType>()) { |
10657 | Diag(Loc: NewFD->getLocation(), |
10658 | DiagID: diag::err_attribute_overloadable_no_prototype) |
10659 | << NewFD; |
10660 | NewFD->dropAttr<OverloadableAttr>(); |
10661 | } |
10662 | |
10663 | // If there's a #pragma GCC visibility in scope, and this isn't a class |
10664 | // member, set the visibility of this function. |
10665 | if (!DC->isRecord() && NewFD->isExternallyVisible()) |
10666 | AddPushedVisibilityAttribute(RD: NewFD); |
10667 | |
10668 | // If there's a #pragma clang arc_cf_code_audited in scope, consider |
10669 | // marking the function. |
10670 | ObjC().AddCFAuditedAttribute(D: NewFD); |
10671 | |
10672 | // If this is a function definition, check if we have to apply any |
10673 | // attributes (i.e. optnone and no_builtin) due to a pragma. |
10674 | if (D.isFunctionDefinition()) { |
10675 | AddRangeBasedOptnone(FD: NewFD); |
10676 | AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD); |
10677 | AddSectionMSAllocText(FD: NewFD); |
10678 | ModifyFnAttributesMSPragmaOptimize(FD: NewFD); |
10679 | } |
10680 | |
10681 | // If this is the first declaration of an extern C variable, update |
10682 | // the map of such variables. |
10683 | if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && |
10684 | isIncompleteDeclExternC(S&: *this, D: NewFD)) |
10685 | RegisterLocallyScopedExternCDecl(ND: NewFD, S); |
10686 | |
10687 | // Set this FunctionDecl's range up to the right paren. |
10688 | NewFD->setRangeEnd(D.getSourceRange().getEnd()); |
10689 | |
10690 | if (D.isRedeclaration() && !Previous.empty()) { |
10691 | NamedDecl *Prev = Previous.getRepresentativeDecl(); |
10692 | checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD, |
10693 | IsSpecialization: isMemberSpecialization || |
10694 | isFunctionTemplateSpecialization, |
10695 | IsDefinition: D.isFunctionDefinition()); |
10696 | } |
10697 | |
10698 | if (getLangOpts().CUDA) { |
10699 | IdentifierInfo *II = NewFD->getIdentifier(); |
10700 | if (II && II->isStr(Str: CUDA().getConfigureFuncName()) && |
10701 | !NewFD->isInvalidDecl() && |
10702 | NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { |
10703 | if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) |
10704 | Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return) |
10705 | << CUDA().getConfigureFuncName(); |
10706 | Context.setcudaConfigureCallDecl(NewFD); |
10707 | } |
10708 | |
10709 | // Variadic functions, other than a *declaration* of printf, are not allowed |
10710 | // in device-side CUDA code, unless someone passed |
10711 | // -fcuda-allow-variadic-functions. |
10712 | if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && |
10713 | (NewFD->hasAttr<CUDADeviceAttr>() || |
10714 | NewFD->hasAttr<CUDAGlobalAttr>()) && |
10715 | !(II && II->isStr(Str: "printf" ) && NewFD->isExternC() && |
10716 | !D.isFunctionDefinition())) { |
10717 | Diag(Loc: NewFD->getLocation(), DiagID: diag::err_variadic_device_fn); |
10718 | } |
10719 | } |
10720 | |
10721 | MarkUnusedFileScopedDecl(D: NewFD); |
10722 | |
10723 | |
10724 | |
10725 | if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { |
10726 | // OpenCL v1.2 s6.8 static is invalid for kernel functions. |
10727 | if (SC == SC_Static) { |
10728 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel); |
10729 | D.setInvalidType(); |
10730 | } |
10731 | |
10732 | // OpenCL v1.2, s6.9 -- Kernels can only have return type void. |
10733 | if (!NewFD->getReturnType()->isVoidType()) { |
10734 | SourceRange RTRange = NewFD->getReturnTypeSourceRange(); |
10735 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type) |
10736 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void" ) |
10737 | : FixItHint()); |
10738 | D.setInvalidType(); |
10739 | } |
10740 | |
10741 | llvm::SmallPtrSet<const Type *, 16> ValidTypes; |
10742 | for (auto *Param : NewFD->parameters()) |
10743 | checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes); |
10744 | |
10745 | if (getLangOpts().OpenCLCPlusPlus) { |
10746 | if (DC->isRecord()) { |
10747 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel); |
10748 | D.setInvalidType(); |
10749 | } |
10750 | if (FunctionTemplate) { |
10751 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel); |
10752 | D.setInvalidType(); |
10753 | } |
10754 | } |
10755 | } |
10756 | |
10757 | if (getLangOpts().CPlusPlus) { |
10758 | // Precalculate whether this is a friend function template with a constraint |
10759 | // that depends on an enclosing template, per [temp.friend]p9. |
10760 | if (isFriend && FunctionTemplate && |
10761 | FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) { |
10762 | NewFD->setFriendConstraintRefersToEnclosingTemplate(true); |
10763 | |
10764 | // C++ [temp.friend]p9: |
10765 | // A friend function template with a constraint that depends on a |
10766 | // template parameter from an enclosing template shall be a definition. |
10767 | if (!D.isFunctionDefinition()) { |
10768 | Diag(Loc: NewFD->getBeginLoc(), |
10769 | DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def); |
10770 | NewFD->setInvalidDecl(); |
10771 | } |
10772 | } |
10773 | |
10774 | if (FunctionTemplate) { |
10775 | if (NewFD->isInvalidDecl()) |
10776 | FunctionTemplate->setInvalidDecl(); |
10777 | return FunctionTemplate; |
10778 | } |
10779 | |
10780 | if (isMemberSpecialization && !NewFD->isInvalidDecl()) |
10781 | CompleteMemberSpecialization(Member: NewFD, Previous); |
10782 | } |
10783 | |
10784 | for (const ParmVarDecl *Param : NewFD->parameters()) { |
10785 | QualType PT = Param->getType(); |
10786 | |
10787 | // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value |
10788 | // types. |
10789 | if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { |
10790 | if(const PipeType *PipeTy = PT->getAs<PipeType>()) { |
10791 | QualType ElemTy = PipeTy->getElementType(); |
10792 | if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { |
10793 | Diag(Loc: Param->getTypeSpecStartLoc(), DiagID: diag::err_reference_pipe_type ); |
10794 | D.setInvalidType(); |
10795 | } |
10796 | } |
10797 | } |
10798 | // WebAssembly tables can't be used as function parameters. |
10799 | if (Context.getTargetInfo().getTriple().isWasm()) { |
10800 | if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) { |
10801 | Diag(Loc: Param->getTypeSpecStartLoc(), |
10802 | DiagID: diag::err_wasm_table_as_function_parameter); |
10803 | D.setInvalidType(); |
10804 | } |
10805 | } |
10806 | } |
10807 | |
10808 | // Diagnose availability attributes. Availability cannot be used on functions |
10809 | // that are run during load/unload. |
10810 | if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { |
10811 | if (NewFD->hasAttr<ConstructorAttr>()) { |
10812 | Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer) |
10813 | << 1; |
10814 | NewFD->dropAttr<AvailabilityAttr>(); |
10815 | } |
10816 | if (NewFD->hasAttr<DestructorAttr>()) { |
10817 | Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer) |
10818 | << 2; |
10819 | NewFD->dropAttr<AvailabilityAttr>(); |
10820 | } |
10821 | } |
10822 | |
10823 | // Diagnose no_builtin attribute on function declaration that are not a |
10824 | // definition. |
10825 | // FIXME: We should really be doing this in |
10826 | // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to |
10827 | // the FunctionDecl and at this point of the code |
10828 | // FunctionDecl::isThisDeclarationADefinition() which always returns `false` |
10829 | // because Sema::ActOnStartOfFunctionDef has not been called yet. |
10830 | if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) |
10831 | switch (D.getFunctionDefinitionKind()) { |
10832 | case FunctionDefinitionKind::Defaulted: |
10833 | case FunctionDefinitionKind::Deleted: |
10834 | Diag(Loc: NBA->getLocation(), |
10835 | DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function) |
10836 | << NBA->getSpelling(); |
10837 | break; |
10838 | case FunctionDefinitionKind::Declaration: |
10839 | Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition) |
10840 | << NBA->getSpelling(); |
10841 | break; |
10842 | case FunctionDefinitionKind::Definition: |
10843 | break; |
10844 | } |
10845 | |
10846 | // Similar to no_builtin logic above, at this point of the code |
10847 | // FunctionDecl::isThisDeclarationADefinition() always returns `false` |
10848 | // because Sema::ActOnStartOfFunctionDef has not been called yet. |
10849 | if (Context.getTargetInfo().allowDebugInfoForExternalRef() && |
10850 | !NewFD->isInvalidDecl() && |
10851 | D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration) |
10852 | ExternalDeclarations.push_back(Elt: NewFD); |
10853 | |
10854 | return NewFD; |
10855 | } |
10856 | |
10857 | /// Return a CodeSegAttr from a containing class. The Microsoft docs say |
10858 | /// when __declspec(code_seg) "is applied to a class, all member functions of |
10859 | /// the class and nested classes -- this includes compiler-generated special |
10860 | /// member functions -- are put in the specified segment." |
10861 | /// The actual behavior is a little more complicated. The Microsoft compiler |
10862 | /// won't check outer classes if there is an active value from #pragma code_seg. |
10863 | /// The CodeSeg is always applied from the direct parent but only from outer |
10864 | /// classes when the #pragma code_seg stack is empty. See: |
10865 | /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer |
10866 | /// available since MS has removed the page. |
10867 | static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { |
10868 | const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD); |
10869 | if (!Method) |
10870 | return nullptr; |
10871 | const CXXRecordDecl *Parent = Method->getParent(); |
10872 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { |
10873 | Attr *NewAttr = SAttr->clone(C&: S.getASTContext()); |
10874 | NewAttr->setImplicit(true); |
10875 | return NewAttr; |
10876 | } |
10877 | |
10878 | // The Microsoft compiler won't check outer classes for the CodeSeg |
10879 | // when the #pragma code_seg stack is active. |
10880 | if (S.CodeSegStack.CurrentValue) |
10881 | return nullptr; |
10882 | |
10883 | while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) { |
10884 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { |
10885 | Attr *NewAttr = SAttr->clone(C&: S.getASTContext()); |
10886 | NewAttr->setImplicit(true); |
10887 | return NewAttr; |
10888 | } |
10889 | } |
10890 | return nullptr; |
10891 | } |
10892 | |
10893 | Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, |
10894 | bool IsDefinition) { |
10895 | if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD)) |
10896 | return A; |
10897 | if (!FD->hasAttr<SectionAttr>() && IsDefinition && |
10898 | CodeSegStack.CurrentValue) |
10899 | return SectionAttr::CreateImplicit( |
10900 | Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(), |
10901 | Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate); |
10902 | return nullptr; |
10903 | } |
10904 | |
10905 | bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, |
10906 | QualType NewT, QualType OldT) { |
10907 | if (!NewD->getLexicalDeclContext()->isDependentContext()) |
10908 | return true; |
10909 | |
10910 | // For dependently-typed local extern declarations and friends, we can't |
10911 | // perform a correct type check in general until instantiation: |
10912 | // |
10913 | // int f(); |
10914 | // template<typename T> void g() { T f(); } |
10915 | // |
10916 | // (valid if g() is only instantiated with T = int). |
10917 | if (NewT->isDependentType() && |
10918 | (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) |
10919 | return false; |
10920 | |
10921 | // Similarly, if the previous declaration was a dependent local extern |
10922 | // declaration, we don't really know its type yet. |
10923 | if (OldT->isDependentType() && OldD->isLocalExternDecl()) |
10924 | return false; |
10925 | |
10926 | return true; |
10927 | } |
10928 | |
10929 | bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { |
10930 | if (!D->getLexicalDeclContext()->isDependentContext()) |
10931 | return true; |
10932 | |
10933 | // Don't chain dependent friend function definitions until instantiation, to |
10934 | // permit cases like |
10935 | // |
10936 | // void func(); |
10937 | // template<typename T> class C1 { friend void func() {} }; |
10938 | // template<typename T> class C2 { friend void func() {} }; |
10939 | // |
10940 | // ... which is valid if only one of C1 and C2 is ever instantiated. |
10941 | // |
10942 | // FIXME: This need only apply to function definitions. For now, we proxy |
10943 | // this by checking for a file-scope function. We do not want this to apply |
10944 | // to friend declarations nominating member functions, because that gets in |
10945 | // the way of access checks. |
10946 | if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) |
10947 | return false; |
10948 | |
10949 | auto *VD = dyn_cast<ValueDecl>(Val: D); |
10950 | auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl); |
10951 | return !VD || !PrevVD || |
10952 | canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(), |
10953 | OldT: PrevVD->getType()); |
10954 | } |
10955 | |
10956 | /// Check the target or target_version attribute of the function for |
10957 | /// MultiVersion validity. |
10958 | /// |
10959 | /// Returns true if there was an error, false otherwise. |
10960 | static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { |
10961 | const auto *TA = FD->getAttr<TargetAttr>(); |
10962 | const auto *TVA = FD->getAttr<TargetVersionAttr>(); |
10963 | assert( |
10964 | (TA || TVA) && |
10965 | "MultiVersion candidate requires a target or target_version attribute" ); |
10966 | const TargetInfo &TargetInfo = S.Context.getTargetInfo(); |
10967 | enum ErrType { Feature = 0, Architecture = 1 }; |
10968 | |
10969 | if (TA) { |
10970 | ParsedTargetAttr ParseInfo = |
10971 | S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr()); |
10972 | if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) { |
10973 | S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option) |
10974 | << Architecture << ParseInfo.CPU; |
10975 | return true; |
10976 | } |
10977 | for (const auto &Feat : ParseInfo.Features) { |
10978 | auto BareFeat = StringRef{Feat}.substr(Start: 1); |
10979 | if (Feat[0] == '-') { |
10980 | S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option) |
10981 | << Feature << ("no-" + BareFeat).str(); |
10982 | return true; |
10983 | } |
10984 | |
10985 | if (!TargetInfo.validateCpuSupports(Name: BareFeat) || |
10986 | !TargetInfo.isValidFeatureName(Feature: BareFeat)) { |
10987 | S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option) |
10988 | << Feature << BareFeat; |
10989 | return true; |
10990 | } |
10991 | } |
10992 | } |
10993 | |
10994 | if (TVA) { |
10995 | llvm::SmallVector<StringRef, 8> Feats; |
10996 | TVA->getFeatures(Out&: Feats); |
10997 | for (const auto &Feat : Feats) { |
10998 | if (!TargetInfo.validateCpuSupports(Name: Feat)) { |
10999 | S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option) |
11000 | << Feature << Feat; |
11001 | return true; |
11002 | } |
11003 | } |
11004 | } |
11005 | return false; |
11006 | } |
11007 | |
11008 | // Provide a white-list of attributes that are allowed to be combined with |
11009 | // multiversion functions. |
11010 | static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, |
11011 | MultiVersionKind MVKind) { |
11012 | // Note: this list/diagnosis must match the list in |
11013 | // checkMultiversionAttributesAllSame. |
11014 | switch (Kind) { |
11015 | default: |
11016 | return false; |
11017 | case attr::ArmLocallyStreaming: |
11018 | return MVKind == MultiVersionKind::TargetVersion || |
11019 | MVKind == MultiVersionKind::TargetClones; |
11020 | case attr::Used: |
11021 | return MVKind == MultiVersionKind::Target; |
11022 | case attr::NonNull: |
11023 | case attr::NoThrow: |
11024 | return true; |
11025 | } |
11026 | } |
11027 | |
11028 | static bool checkNonMultiVersionCompatAttributes(Sema &S, |
11029 | const FunctionDecl *FD, |
11030 | const FunctionDecl *CausedFD, |
11031 | MultiVersionKind MVKind) { |
11032 | const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) { |
11033 | S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr) |
11034 | << static_cast<unsigned>(MVKind) << A; |
11035 | if (CausedFD) |
11036 | S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here); |
11037 | return true; |
11038 | }; |
11039 | |
11040 | for (const Attr *A : FD->attrs()) { |
11041 | switch (A->getKind()) { |
11042 | case attr::CPUDispatch: |
11043 | case attr::CPUSpecific: |
11044 | if (MVKind != MultiVersionKind::CPUDispatch && |
11045 | MVKind != MultiVersionKind::CPUSpecific) |
11046 | return Diagnose(S, A); |
11047 | break; |
11048 | case attr::Target: |
11049 | if (MVKind != MultiVersionKind::Target) |
11050 | return Diagnose(S, A); |
11051 | break; |
11052 | case attr::TargetVersion: |
11053 | if (MVKind != MultiVersionKind::TargetVersion && |
11054 | MVKind != MultiVersionKind::TargetClones) |
11055 | return Diagnose(S, A); |
11056 | break; |
11057 | case attr::TargetClones: |
11058 | if (MVKind != MultiVersionKind::TargetClones && |
11059 | MVKind != MultiVersionKind::TargetVersion) |
11060 | return Diagnose(S, A); |
11061 | break; |
11062 | default: |
11063 | if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind)) |
11064 | return Diagnose(S, A); |
11065 | break; |
11066 | } |
11067 | } |
11068 | return false; |
11069 | } |
11070 | |
11071 | bool Sema::areMultiversionVariantFunctionsCompatible( |
11072 | const FunctionDecl *OldFD, const FunctionDecl *NewFD, |
11073 | const PartialDiagnostic &NoProtoDiagID, |
11074 | const PartialDiagnosticAt &NoteCausedDiagIDAt, |
11075 | const PartialDiagnosticAt &NoSupportDiagIDAt, |
11076 | const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, |
11077 | bool ConstexprSupported, bool CLinkageMayDiffer) { |
11078 | enum DoesntSupport { |
11079 | FuncTemplates = 0, |
11080 | VirtFuncs = 1, |
11081 | DeducedReturn = 2, |
11082 | Constructors = 3, |
11083 | Destructors = 4, |
11084 | DeletedFuncs = 5, |
11085 | DefaultedFuncs = 6, |
11086 | ConstexprFuncs = 7, |
11087 | ConstevalFuncs = 8, |
11088 | Lambda = 9, |
11089 | }; |
11090 | enum Different { |
11091 | CallingConv = 0, |
11092 | ReturnType = 1, |
11093 | ConstexprSpec = 2, |
11094 | InlineSpec = 3, |
11095 | Linkage = 4, |
11096 | LanguageLinkage = 5, |
11097 | }; |
11098 | |
11099 | if (NoProtoDiagID.getDiagID() != 0 && OldFD && |
11100 | !OldFD->getType()->getAs<FunctionProtoType>()) { |
11101 | Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID); |
11102 | Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second); |
11103 | return true; |
11104 | } |
11105 | |
11106 | if (NoProtoDiagID.getDiagID() != 0 && |
11107 | !NewFD->getType()->getAs<FunctionProtoType>()) |
11108 | return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID); |
11109 | |
11110 | if (!TemplatesSupported && |
11111 | NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) |
11112 | return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second) |
11113 | << FuncTemplates; |
11114 | |
11115 | if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) { |
11116 | if (NewCXXFD->isVirtual()) |
11117 | return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second) |
11118 | << VirtFuncs; |
11119 | |
11120 | if (isa<CXXConstructorDecl>(Val: NewCXXFD)) |
11121 | return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second) |
11122 | << Constructors; |
11123 | |
11124 | if (isa<CXXDestructorDecl>(Val: NewCXXFD)) |
11125 | return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second) |
11126 | << Destructors; |
11127 | } |
11128 | |
11129 | if (NewFD->isDeleted()) |
11130 | return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second) |
11131 | << DeletedFuncs; |
11132 | |
11133 | if (NewFD->isDefaulted()) |
11134 | return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second) |
11135 | << DefaultedFuncs; |
11136 | |
11137 | if (!ConstexprSupported && NewFD->isConstexpr()) |
11138 | return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second) |
11139 | << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); |
11140 | |
11141 | QualType NewQType = Context.getCanonicalType(T: NewFD->getType()); |
11142 | const auto *NewType = cast<FunctionType>(Val&: NewQType); |
11143 | QualType NewReturnType = NewType->getReturnType(); |
11144 | |
11145 | if (NewReturnType->isUndeducedType()) |
11146 | return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second) |
11147 | << DeducedReturn; |
11148 | |
11149 | // Ensure the return type is identical. |
11150 | if (OldFD) { |
11151 | QualType OldQType = Context.getCanonicalType(T: OldFD->getType()); |
11152 | const auto *OldType = cast<FunctionType>(Val&: OldQType); |
11153 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); |
11154 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); |
11155 | |
11156 | const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>(); |
11157 | const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>(); |
11158 | |
11159 | bool ArmStreamingCCMismatched = false; |
11160 | if (OldFPT && NewFPT) { |
11161 | unsigned Diff = |
11162 | OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes(); |
11163 | // Arm-streaming, arm-streaming-compatible and non-streaming versions |
11164 | // cannot be mixed. |
11165 | if (Diff & (FunctionType::SME_PStateSMEnabledMask | |
11166 | FunctionType::SME_PStateSMCompatibleMask)) |
11167 | ArmStreamingCCMismatched = true; |
11168 | } |
11169 | |
11170 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched) |
11171 | return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv; |
11172 | |
11173 | QualType OldReturnType = OldType->getReturnType(); |
11174 | |
11175 | if (OldReturnType != NewReturnType) |
11176 | return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType; |
11177 | |
11178 | if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) |
11179 | return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec; |
11180 | |
11181 | if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) |
11182 | return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec; |
11183 | |
11184 | if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) |
11185 | return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage; |
11186 | |
11187 | if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) |
11188 | return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage; |
11189 | |
11190 | if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT, |
11191 | NewLoc: NewFD->getLocation())) |
11192 | return true; |
11193 | } |
11194 | return false; |
11195 | } |
11196 | |
11197 | static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, |
11198 | const FunctionDecl *NewFD, |
11199 | bool CausesMV, |
11200 | MultiVersionKind MVKind) { |
11201 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { |
11202 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported); |
11203 | if (OldFD) |
11204 | S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration); |
11205 | return true; |
11206 | } |
11207 | |
11208 | bool IsCPUSpecificCPUDispatchMVKind = |
11209 | MVKind == MultiVersionKind::CPUDispatch || |
11210 | MVKind == MultiVersionKind::CPUSpecific; |
11211 | |
11212 | if (CausesMV && OldFD && |
11213 | checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind)) |
11214 | return true; |
11215 | |
11216 | if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind)) |
11217 | return true; |
11218 | |
11219 | // Only allow transition to MultiVersion if it hasn't been used. |
11220 | if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) |
11221 | return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used); |
11222 | |
11223 | return S.areMultiversionVariantFunctionsCompatible( |
11224 | OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto), |
11225 | NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(), |
11226 | S.PDiag(DiagID: diag::note_multiversioning_caused_here)), |
11227 | NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(), |
11228 | S.PDiag(DiagID: diag::err_multiversion_doesnt_support) |
11229 | << static_cast<unsigned>(MVKind)), |
11230 | DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(), |
11231 | S.PDiag(DiagID: diag::err_multiversion_diff)), |
11232 | /*TemplatesSupported=*/false, |
11233 | /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind, |
11234 | /*CLinkageMayDiffer=*/false); |
11235 | } |
11236 | |
11237 | /// Check the validity of a multiversion function declaration that is the |
11238 | /// first of its kind. Also sets the multiversion'ness' of the function itself. |
11239 | /// |
11240 | /// This sets NewFD->isInvalidDecl() to true if there was an error. |
11241 | /// |
11242 | /// Returns true if there was an error, false otherwise. |
11243 | static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) { |
11244 | MultiVersionKind MVKind = FD->getMultiVersionKind(); |
11245 | assert(MVKind != MultiVersionKind::None && |
11246 | "Function lacks multiversion attribute" ); |
11247 | const auto *TA = FD->getAttr<TargetAttr>(); |
11248 | const auto *TVA = FD->getAttr<TargetVersionAttr>(); |
11249 | // The target attribute only causes MV if this declaration is the default, |
11250 | // otherwise it is treated as a normal function. |
11251 | if (TA && !TA->isDefaultVersion()) |
11252 | return false; |
11253 | // The target_version attribute only causes Multiversioning if this |
11254 | // declaration is NOT the default version. |
11255 | if (TVA && TVA->isDefaultVersion()) |
11256 | return false; |
11257 | |
11258 | if ((TA || TVA) && CheckMultiVersionValue(S, FD)) { |
11259 | FD->setInvalidDecl(); |
11260 | return true; |
11261 | } |
11262 | |
11263 | if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) { |
11264 | FD->setInvalidDecl(); |
11265 | return true; |
11266 | } |
11267 | |
11268 | FD->setIsMultiVersion(); |
11269 | return false; |
11270 | } |
11271 | |
11272 | static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { |
11273 | for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { |
11274 | if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) |
11275 | return true; |
11276 | } |
11277 | |
11278 | return false; |
11279 | } |
11280 | |
11281 | static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) { |
11282 | if (!From->getASTContext().getTargetInfo().getTriple().isAArch64()) |
11283 | return; |
11284 | |
11285 | MultiVersionKind MVKindFrom = From->getMultiVersionKind(); |
11286 | MultiVersionKind MVKindTo = To->getMultiVersionKind(); |
11287 | |
11288 | if (MVKindTo == MultiVersionKind::None && |
11289 | (MVKindFrom == MultiVersionKind::TargetVersion || |
11290 | MVKindFrom == MultiVersionKind::TargetClones)) |
11291 | To->addAttr(A: TargetVersionAttr::CreateImplicit( |
11292 | Ctx&: To->getASTContext(), NamesStr: "default" , Range: To->getSourceRange())); |
11293 | } |
11294 | |
11295 | static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, |
11296 | FunctionDecl *NewFD, |
11297 | bool &Redeclaration, |
11298 | NamedDecl *&OldDecl, |
11299 | LookupResult &Previous) { |
11300 | assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion" ); |
11301 | |
11302 | // The definitions should be allowed in any order. If we have discovered |
11303 | // a new target version and the preceeding was the default, then add the |
11304 | // corresponding attribute to it. |
11305 | patchDefaultTargetVersion(From: NewFD, To: OldFD); |
11306 | |
11307 | const auto *NewTA = NewFD->getAttr<TargetAttr>(); |
11308 | const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); |
11309 | const auto *OldTA = OldFD->getAttr<TargetAttr>(); |
11310 | |
11311 | // If the old decl is NOT MultiVersioned yet, and we don't cause that |
11312 | // to change, this is a simple redeclaration. |
11313 | if (NewTA && !NewTA->isDefaultVersion() && |
11314 | (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) |
11315 | return false; |
11316 | |
11317 | // The target_version attribute only causes Multiversioning if this |
11318 | // declaration is NOT the default version. |
11319 | if (NewTVA && NewTVA->isDefaultVersion()) |
11320 | return false; |
11321 | |
11322 | // Otherwise, this decl causes MultiVersioning. |
11323 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true, |
11324 | MVKind: NewTVA ? MultiVersionKind::TargetVersion |
11325 | : MultiVersionKind::Target)) { |
11326 | NewFD->setInvalidDecl(); |
11327 | return true; |
11328 | } |
11329 | |
11330 | if (CheckMultiVersionValue(S, FD: NewFD)) { |
11331 | NewFD->setInvalidDecl(); |
11332 | return true; |
11333 | } |
11334 | |
11335 | // If this is 'default', permit the forward declaration. |
11336 | if (NewTA && NewTA->isDefaultVersion() && !OldTA) { |
11337 | Redeclaration = true; |
11338 | OldDecl = OldFD; |
11339 | OldFD->setIsMultiVersion(); |
11340 | NewFD->setIsMultiVersion(); |
11341 | return false; |
11342 | } |
11343 | |
11344 | if (CheckMultiVersionValue(S, FD: OldFD)) { |
11345 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here); |
11346 | NewFD->setInvalidDecl(); |
11347 | return true; |
11348 | } |
11349 | |
11350 | if (NewTA) { |
11351 | ParsedTargetAttr OldParsed = |
11352 | S.getASTContext().getTargetInfo().parseTargetAttr( |
11353 | Str: OldTA->getFeaturesStr()); |
11354 | llvm::sort(C&: OldParsed.Features); |
11355 | ParsedTargetAttr NewParsed = |
11356 | S.getASTContext().getTargetInfo().parseTargetAttr( |
11357 | Str: NewTA->getFeaturesStr()); |
11358 | // Sort order doesn't matter, it just needs to be consistent. |
11359 | llvm::sort(C&: NewParsed.Features); |
11360 | if (OldParsed == NewParsed) { |
11361 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate); |
11362 | S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration); |
11363 | NewFD->setInvalidDecl(); |
11364 | return true; |
11365 | } |
11366 | } |
11367 | |
11368 | for (const auto *FD : OldFD->redecls()) { |
11369 | const auto *CurTA = FD->getAttr<TargetAttr>(); |
11370 | const auto *CurTVA = FD->getAttr<TargetVersionAttr>(); |
11371 | // We allow forward declarations before ANY multiversioning attributes, but |
11372 | // nothing after the fact. |
11373 | if (PreviousDeclsHaveMultiVersionAttribute(FD) && |
11374 | ((NewTA && (!CurTA || CurTA->isInherited())) || |
11375 | (NewTVA && (!CurTVA || CurTVA->isInherited())))) { |
11376 | S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl) |
11377 | << (NewTA ? 0 : 2); |
11378 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here); |
11379 | NewFD->setInvalidDecl(); |
11380 | return true; |
11381 | } |
11382 | } |
11383 | |
11384 | OldFD->setIsMultiVersion(); |
11385 | NewFD->setIsMultiVersion(); |
11386 | Redeclaration = false; |
11387 | OldDecl = nullptr; |
11388 | Previous.clear(); |
11389 | return false; |
11390 | } |
11391 | |
11392 | static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) { |
11393 | MultiVersionKind OldKind = Old->getMultiVersionKind(); |
11394 | MultiVersionKind NewKind = New->getMultiVersionKind(); |
11395 | |
11396 | if (OldKind == NewKind || OldKind == MultiVersionKind::None || |
11397 | NewKind == MultiVersionKind::None) |
11398 | return true; |
11399 | |
11400 | if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) { |
11401 | switch (OldKind) { |
11402 | case MultiVersionKind::TargetVersion: |
11403 | return NewKind == MultiVersionKind::TargetClones; |
11404 | case MultiVersionKind::TargetClones: |
11405 | return NewKind == MultiVersionKind::TargetVersion; |
11406 | default: |
11407 | return false; |
11408 | } |
11409 | } else { |
11410 | switch (OldKind) { |
11411 | case MultiVersionKind::CPUDispatch: |
11412 | return NewKind == MultiVersionKind::CPUSpecific; |
11413 | case MultiVersionKind::CPUSpecific: |
11414 | return NewKind == MultiVersionKind::CPUDispatch; |
11415 | default: |
11416 | return false; |
11417 | } |
11418 | } |
11419 | } |
11420 | |
11421 | /// Check the validity of a new function declaration being added to an existing |
11422 | /// multiversioned declaration collection. |
11423 | static bool CheckMultiVersionAdditionalDecl( |
11424 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, |
11425 | const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, |
11426 | const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, |
11427 | LookupResult &Previous) { |
11428 | |
11429 | // Disallow mixing of multiversioning types. |
11430 | if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) { |
11431 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed); |
11432 | S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration); |
11433 | NewFD->setInvalidDecl(); |
11434 | return true; |
11435 | } |
11436 | |
11437 | // Add the default target_version attribute if it's missing. |
11438 | patchDefaultTargetVersion(From: OldFD, To: NewFD); |
11439 | patchDefaultTargetVersion(From: NewFD, To: OldFD); |
11440 | |
11441 | const auto *NewTA = NewFD->getAttr<TargetAttr>(); |
11442 | const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); |
11443 | MultiVersionKind NewMVKind = NewFD->getMultiVersionKind(); |
11444 | [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind(); |
11445 | |
11446 | ParsedTargetAttr NewParsed; |
11447 | if (NewTA) { |
11448 | NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr( |
11449 | Str: NewTA->getFeaturesStr()); |
11450 | llvm::sort(C&: NewParsed.Features); |
11451 | } |
11452 | llvm::SmallVector<StringRef, 8> NewFeats; |
11453 | if (NewTVA) { |
11454 | NewTVA->getFeatures(Out&: NewFeats); |
11455 | llvm::sort(C&: NewFeats); |
11456 | } |
11457 | |
11458 | bool UseMemberUsingDeclRules = |
11459 | S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); |
11460 | |
11461 | bool MayNeedOverloadableChecks = |
11462 | AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD); |
11463 | |
11464 | // Next, check ALL non-invalid non-overloads to see if this is a redeclaration |
11465 | // of a previous member of the MultiVersion set. |
11466 | for (NamedDecl *ND : Previous) { |
11467 | FunctionDecl *CurFD = ND->getAsFunction(); |
11468 | if (!CurFD || CurFD->isInvalidDecl()) |
11469 | continue; |
11470 | if (MayNeedOverloadableChecks && |
11471 | S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules)) |
11472 | continue; |
11473 | |
11474 | switch (NewMVKind) { |
11475 | case MultiVersionKind::None: |
11476 | assert(OldMVKind == MultiVersionKind::TargetClones && |
11477 | "Only target_clones can be omitted in subsequent declarations" ); |
11478 | break; |
11479 | case MultiVersionKind::Target: { |
11480 | const auto *CurTA = CurFD->getAttr<TargetAttr>(); |
11481 | if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { |
11482 | NewFD->setIsMultiVersion(); |
11483 | Redeclaration = true; |
11484 | OldDecl = ND; |
11485 | return false; |
11486 | } |
11487 | |
11488 | ParsedTargetAttr CurParsed = |
11489 | S.getASTContext().getTargetInfo().parseTargetAttr( |
11490 | Str: CurTA->getFeaturesStr()); |
11491 | llvm::sort(C&: CurParsed.Features); |
11492 | if (CurParsed == NewParsed) { |
11493 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate); |
11494 | S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration); |
11495 | NewFD->setInvalidDecl(); |
11496 | return true; |
11497 | } |
11498 | break; |
11499 | } |
11500 | case MultiVersionKind::TargetVersion: { |
11501 | if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) { |
11502 | if (CurTVA->getName() == NewTVA->getName()) { |
11503 | NewFD->setIsMultiVersion(); |
11504 | Redeclaration = true; |
11505 | OldDecl = ND; |
11506 | return false; |
11507 | } |
11508 | llvm::SmallVector<StringRef, 8> CurFeats; |
11509 | CurTVA->getFeatures(Out&: CurFeats); |
11510 | llvm::sort(C&: CurFeats); |
11511 | |
11512 | if (CurFeats == NewFeats) { |
11513 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate); |
11514 | S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration); |
11515 | NewFD->setInvalidDecl(); |
11516 | return true; |
11517 | } |
11518 | } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) { |
11519 | // Default |
11520 | if (NewFeats.empty()) |
11521 | break; |
11522 | |
11523 | for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) { |
11524 | llvm::SmallVector<StringRef, 8> CurFeats; |
11525 | CurClones->getFeatures(Out&: CurFeats, Index: I); |
11526 | llvm::sort(C&: CurFeats); |
11527 | |
11528 | if (CurFeats == NewFeats) { |
11529 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate); |
11530 | S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration); |
11531 | NewFD->setInvalidDecl(); |
11532 | return true; |
11533 | } |
11534 | } |
11535 | } |
11536 | break; |
11537 | } |
11538 | case MultiVersionKind::TargetClones: { |
11539 | assert(NewClones && "MultiVersionKind does not match attribute type" ); |
11540 | if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) { |
11541 | if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || |
11542 | !std::equal(CurClones->featuresStrs_begin(), |
11543 | CurClones->featuresStrs_end(), |
11544 | NewClones->featuresStrs_begin())) { |
11545 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match); |
11546 | S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration); |
11547 | NewFD->setInvalidDecl(); |
11548 | return true; |
11549 | } |
11550 | } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) { |
11551 | llvm::SmallVector<StringRef, 8> CurFeats; |
11552 | CurTVA->getFeatures(Out&: CurFeats); |
11553 | llvm::sort(C&: CurFeats); |
11554 | |
11555 | // Default |
11556 | if (CurFeats.empty()) |
11557 | break; |
11558 | |
11559 | for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) { |
11560 | NewFeats.clear(); |
11561 | NewClones->getFeatures(Out&: NewFeats, Index: I); |
11562 | llvm::sort(C&: NewFeats); |
11563 | |
11564 | if (CurFeats == NewFeats) { |
11565 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate); |
11566 | S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration); |
11567 | NewFD->setInvalidDecl(); |
11568 | return true; |
11569 | } |
11570 | } |
11571 | break; |
11572 | } |
11573 | Redeclaration = true; |
11574 | OldDecl = CurFD; |
11575 | NewFD->setIsMultiVersion(); |
11576 | return false; |
11577 | } |
11578 | case MultiVersionKind::CPUSpecific: |
11579 | case MultiVersionKind::CPUDispatch: { |
11580 | const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); |
11581 | const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); |
11582 | // Handle CPUDispatch/CPUSpecific versions. |
11583 | // Only 1 CPUDispatch function is allowed, this will make it go through |
11584 | // the redeclaration errors. |
11585 | if (NewMVKind == MultiVersionKind::CPUDispatch && |
11586 | CurFD->hasAttr<CPUDispatchAttr>()) { |
11587 | if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && |
11588 | std::equal( |
11589 | CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), |
11590 | NewCPUDisp->cpus_begin(), |
11591 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { |
11592 | return Cur->getName() == New->getName(); |
11593 | })) { |
11594 | NewFD->setIsMultiVersion(); |
11595 | Redeclaration = true; |
11596 | OldDecl = ND; |
11597 | return false; |
11598 | } |
11599 | |
11600 | // If the declarations don't match, this is an error condition. |
11601 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch); |
11602 | S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration); |
11603 | NewFD->setInvalidDecl(); |
11604 | return true; |
11605 | } |
11606 | if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) { |
11607 | if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && |
11608 | std::equal( |
11609 | CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), |
11610 | NewCPUSpec->cpus_begin(), |
11611 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { |
11612 | return Cur->getName() == New->getName(); |
11613 | })) { |
11614 | NewFD->setIsMultiVersion(); |
11615 | Redeclaration = true; |
11616 | OldDecl = ND; |
11617 | return false; |
11618 | } |
11619 | |
11620 | // Only 1 version of CPUSpecific is allowed for each CPU. |
11621 | for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { |
11622 | for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { |
11623 | if (CurII == NewII) { |
11624 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs) |
11625 | << NewII; |
11626 | S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration); |
11627 | NewFD->setInvalidDecl(); |
11628 | return true; |
11629 | } |
11630 | } |
11631 | } |
11632 | } |
11633 | break; |
11634 | } |
11635 | } |
11636 | } |
11637 | |
11638 | // Else, this is simply a non-redecl case. Checking the 'value' is only |
11639 | // necessary in the Target case, since The CPUSpecific/Dispatch cases are |
11640 | // handled in the attribute adding step. |
11641 | if ((NewMVKind == MultiVersionKind::TargetVersion || |
11642 | NewMVKind == MultiVersionKind::Target) && |
11643 | CheckMultiVersionValue(S, FD: NewFD)) { |
11644 | NewFD->setInvalidDecl(); |
11645 | return true; |
11646 | } |
11647 | |
11648 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, |
11649 | CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) { |
11650 | NewFD->setInvalidDecl(); |
11651 | return true; |
11652 | } |
11653 | |
11654 | // Permit forward declarations in the case where these two are compatible. |
11655 | if (!OldFD->isMultiVersion()) { |
11656 | OldFD->setIsMultiVersion(); |
11657 | NewFD->setIsMultiVersion(); |
11658 | Redeclaration = true; |
11659 | OldDecl = OldFD; |
11660 | return false; |
11661 | } |
11662 | |
11663 | NewFD->setIsMultiVersion(); |
11664 | Redeclaration = false; |
11665 | OldDecl = nullptr; |
11666 | Previous.clear(); |
11667 | return false; |
11668 | } |
11669 | |
11670 | /// Check the validity of a mulitversion function declaration. |
11671 | /// Also sets the multiversion'ness' of the function itself. |
11672 | /// |
11673 | /// This sets NewFD->isInvalidDecl() to true if there was an error. |
11674 | /// |
11675 | /// Returns true if there was an error, false otherwise. |
11676 | static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, |
11677 | bool &Redeclaration, NamedDecl *&OldDecl, |
11678 | LookupResult &Previous) { |
11679 | const auto *NewTA = NewFD->getAttr<TargetAttr>(); |
11680 | const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); |
11681 | const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); |
11682 | const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); |
11683 | const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); |
11684 | MultiVersionKind MVKind = NewFD->getMultiVersionKind(); |
11685 | |
11686 | // Main isn't allowed to become a multiversion function, however it IS |
11687 | // permitted to have 'main' be marked with the 'target' optimization hint, |
11688 | // for 'target_version' only default is allowed. |
11689 | if (NewFD->isMain()) { |
11690 | if (MVKind != MultiVersionKind::None && |
11691 | !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) && |
11692 | !(MVKind == MultiVersionKind::TargetVersion && |
11693 | NewTVA->isDefaultVersion())) { |
11694 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main); |
11695 | NewFD->setInvalidDecl(); |
11696 | return true; |
11697 | } |
11698 | return false; |
11699 | } |
11700 | |
11701 | const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple(); |
11702 | |
11703 | // Target attribute on AArch64 is not used for multiversioning |
11704 | if (NewTA && T.isAArch64()) |
11705 | return false; |
11706 | |
11707 | // Target attribute on RISCV is not used for multiversioning |
11708 | if (NewTA && T.isRISCV()) |
11709 | return false; |
11710 | |
11711 | if (!OldDecl || !OldDecl->getAsFunction() || |
11712 | !OldDecl->getDeclContext()->getRedeclContext()->Equals( |
11713 | DC: NewFD->getDeclContext()->getRedeclContext())) { |
11714 | // If there's no previous declaration, AND this isn't attempting to cause |
11715 | // multiversioning, this isn't an error condition. |
11716 | if (MVKind == MultiVersionKind::None) |
11717 | return false; |
11718 | return CheckMultiVersionFirstFunction(S, FD: NewFD); |
11719 | } |
11720 | |
11721 | FunctionDecl *OldFD = OldDecl->getAsFunction(); |
11722 | |
11723 | if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) |
11724 | return false; |
11725 | |
11726 | // Multiversioned redeclarations aren't allowed to omit the attribute, except |
11727 | // for target_clones and target_version. |
11728 | if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None && |
11729 | OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones && |
11730 | OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) { |
11731 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl) |
11732 | << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); |
11733 | NewFD->setInvalidDecl(); |
11734 | return true; |
11735 | } |
11736 | |
11737 | if (!OldFD->isMultiVersion()) { |
11738 | switch (MVKind) { |
11739 | case MultiVersionKind::Target: |
11740 | case MultiVersionKind::TargetVersion: |
11741 | return CheckDeclarationCausesMultiVersioning( |
11742 | S, OldFD, NewFD, Redeclaration, OldDecl, Previous); |
11743 | case MultiVersionKind::TargetClones: |
11744 | if (OldFD->isUsed(CheckUsedAttr: false)) { |
11745 | NewFD->setInvalidDecl(); |
11746 | return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used); |
11747 | } |
11748 | OldFD->setIsMultiVersion(); |
11749 | break; |
11750 | |
11751 | case MultiVersionKind::CPUDispatch: |
11752 | case MultiVersionKind::CPUSpecific: |
11753 | case MultiVersionKind::None: |
11754 | break; |
11755 | } |
11756 | } |
11757 | |
11758 | // At this point, we have a multiversion function decl (in OldFD) AND an |
11759 | // appropriate attribute in the current function decl. Resolve that these are |
11760 | // still compatible with previous declarations. |
11761 | return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp, |
11762 | NewCPUSpec, NewClones, Redeclaration, |
11763 | OldDecl, Previous); |
11764 | } |
11765 | |
11766 | static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) { |
11767 | bool IsPure = NewFD->hasAttr<PureAttr>(); |
11768 | bool IsConst = NewFD->hasAttr<ConstAttr>(); |
11769 | |
11770 | // If there are no pure or const attributes, there's nothing to check. |
11771 | if (!IsPure && !IsConst) |
11772 | return; |
11773 | |
11774 | // If the function is marked both pure and const, we retain the const |
11775 | // attribute because it makes stronger guarantees than the pure attribute, and |
11776 | // we drop the pure attribute explicitly to prevent later confusion about |
11777 | // semantics. |
11778 | if (IsPure && IsConst) { |
11779 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr); |
11780 | NewFD->dropAttrs<PureAttr>(); |
11781 | } |
11782 | |
11783 | // Constructors and destructors are functions which return void, so are |
11784 | // handled here as well. |
11785 | if (NewFD->getReturnType()->isVoidType()) { |
11786 | S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void) |
11787 | << IsConst; |
11788 | NewFD->dropAttrs<PureAttr, ConstAttr>(); |
11789 | } |
11790 | } |
11791 | |
11792 | bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, |
11793 | LookupResult &Previous, |
11794 | bool IsMemberSpecialization, |
11795 | bool DeclIsDefn) { |
11796 | assert(!NewFD->getReturnType()->isVariablyModifiedType() && |
11797 | "Variably modified return types are not handled here" ); |
11798 | |
11799 | // Determine whether the type of this function should be merged with |
11800 | // a previous visible declaration. This never happens for functions in C++, |
11801 | // and always happens in C if the previous declaration was visible. |
11802 | bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && |
11803 | !Previous.isShadowed(); |
11804 | |
11805 | bool Redeclaration = false; |
11806 | NamedDecl *OldDecl = nullptr; |
11807 | bool MayNeedOverloadableChecks = false; |
11808 | |
11809 | // Merge or overload the declaration with an existing declaration of |
11810 | // the same name, if appropriate. |
11811 | if (!Previous.empty()) { |
11812 | // Determine whether NewFD is an overload of PrevDecl or |
11813 | // a declaration that requires merging. If it's an overload, |
11814 | // there's no more work to do here; we'll just add the new |
11815 | // function to the scope. |
11816 | if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) { |
11817 | NamedDecl *Candidate = Previous.getRepresentativeDecl(); |
11818 | if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) { |
11819 | Redeclaration = true; |
11820 | OldDecl = Candidate; |
11821 | } |
11822 | } else { |
11823 | MayNeedOverloadableChecks = true; |
11824 | switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl, |
11825 | /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) { |
11826 | case Ovl_Match: |
11827 | Redeclaration = true; |
11828 | break; |
11829 | |
11830 | case Ovl_NonFunction: |
11831 | Redeclaration = true; |
11832 | break; |
11833 | |
11834 | case Ovl_Overload: |
11835 | Redeclaration = false; |
11836 | break; |
11837 | } |
11838 | } |
11839 | } |
11840 | |
11841 | // Check for a previous extern "C" declaration with this name. |
11842 | if (!Redeclaration && |
11843 | checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) { |
11844 | if (!Previous.empty()) { |
11845 | // This is an extern "C" declaration with the same name as a previous |
11846 | // declaration, and thus redeclares that entity... |
11847 | Redeclaration = true; |
11848 | OldDecl = Previous.getFoundDecl(); |
11849 | MergeTypeWithPrevious = false; |
11850 | |
11851 | // ... except in the presence of __attribute__((overloadable)). |
11852 | if (OldDecl->hasAttr<OverloadableAttr>() || |
11853 | NewFD->hasAttr<OverloadableAttr>()) { |
11854 | if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) { |
11855 | MayNeedOverloadableChecks = true; |
11856 | Redeclaration = false; |
11857 | OldDecl = nullptr; |
11858 | } |
11859 | } |
11860 | } |
11861 | } |
11862 | |
11863 | if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous)) |
11864 | return Redeclaration; |
11865 | |
11866 | // PPC MMA non-pointer types are not allowed as function return types. |
11867 | if (Context.getTargetInfo().getTriple().isPPC64() && |
11868 | PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) { |
11869 | NewFD->setInvalidDecl(); |
11870 | } |
11871 | |
11872 | CheckConstPureAttributesUsage(S&: *this, NewFD); |
11873 | |
11874 | // C++ [dcl.spec.auto.general]p12: |
11875 | // Return type deduction for a templated function with a placeholder in its |
11876 | // declared type occurs when the definition is instantiated even if the |
11877 | // function body contains a return statement with a non-type-dependent |
11878 | // operand. |
11879 | // |
11880 | // C++ [temp.dep.expr]p3: |
11881 | // An id-expression is type-dependent if it is a template-id that is not a |
11882 | // concept-id and is dependent; or if its terminal name is: |
11883 | // - [...] |
11884 | // - associated by name lookup with one or more declarations of member |
11885 | // functions of a class that is the current instantiation declared with a |
11886 | // return type that contains a placeholder type, |
11887 | // - [...] |
11888 | // |
11889 | // If this is a templated function with a placeholder in its return type, |
11890 | // make the placeholder type dependent since it won't be deduced until the |
11891 | // definition is instantiated. We do this here because it needs to happen |
11892 | // for implicitly instantiated member functions/member function templates. |
11893 | if (getLangOpts().CPlusPlus14 && |
11894 | (NewFD->isDependentContext() && |
11895 | NewFD->getReturnType()->isUndeducedType())) { |
11896 | const FunctionProtoType *FPT = |
11897 | NewFD->getType()->castAs<FunctionProtoType>(); |
11898 | QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType()); |
11899 | NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(), |
11900 | EPI: FPT->getExtProtoInfo())); |
11901 | } |
11902 | |
11903 | // C++11 [dcl.constexpr]p8: |
11904 | // A constexpr specifier for a non-static member function that is not |
11905 | // a constructor declares that member function to be const. |
11906 | // |
11907 | // This needs to be delayed until we know whether this is an out-of-line |
11908 | // definition of a static member function. |
11909 | // |
11910 | // This rule is not present in C++1y, so we produce a backwards |
11911 | // compatibility warning whenever it happens in C++11. |
11912 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD); |
11913 | if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && |
11914 | !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) && |
11915 | !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) { |
11916 | CXXMethodDecl *OldMD = nullptr; |
11917 | if (OldDecl) |
11918 | OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction()); |
11919 | if (!OldMD || !OldMD->isStatic()) { |
11920 | const FunctionProtoType *FPT = |
11921 | MD->getType()->castAs<FunctionProtoType>(); |
11922 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
11923 | EPI.TypeQuals.addConst(); |
11924 | MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(), |
11925 | Args: FPT->getParamTypes(), EPI)); |
11926 | |
11927 | // Warn that we did this, if we're not performing template instantiation. |
11928 | // In that case, we'll have warned already when the template was defined. |
11929 | if (!inTemplateInstantiation()) { |
11930 | SourceLocation AddConstLoc; |
11931 | if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() |
11932 | .IgnoreParens().getAs<FunctionTypeLoc>()) |
11933 | AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc()); |
11934 | |
11935 | Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const) |
11936 | << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const" ); |
11937 | } |
11938 | } |
11939 | } |
11940 | |
11941 | if (Redeclaration) { |
11942 | // NewFD and OldDecl represent declarations that need to be |
11943 | // merged. |
11944 | if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious, |
11945 | NewDeclIsDefn: DeclIsDefn)) { |
11946 | NewFD->setInvalidDecl(); |
11947 | return Redeclaration; |
11948 | } |
11949 | |
11950 | Previous.clear(); |
11951 | Previous.addDecl(D: OldDecl); |
11952 | |
11953 | if (FunctionTemplateDecl *OldTemplateDecl = |
11954 | dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) { |
11955 | auto *OldFD = OldTemplateDecl->getTemplatedDecl(); |
11956 | FunctionTemplateDecl *NewTemplateDecl |
11957 | = NewFD->getDescribedFunctionTemplate(); |
11958 | assert(NewTemplateDecl && "Template/non-template mismatch" ); |
11959 | |
11960 | // The call to MergeFunctionDecl above may have created some state in |
11961 | // NewTemplateDecl that needs to be merged with OldTemplateDecl before we |
11962 | // can add it as a redeclaration. |
11963 | NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl); |
11964 | |
11965 | NewFD->setPreviousDeclaration(OldFD); |
11966 | if (NewFD->isCXXClassMember()) { |
11967 | NewFD->setAccess(OldTemplateDecl->getAccess()); |
11968 | NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); |
11969 | } |
11970 | |
11971 | // If this is an explicit specialization of a member that is a function |
11972 | // template, mark it as a member specialization. |
11973 | if (IsMemberSpecialization && |
11974 | NewTemplateDecl->getInstantiatedFromMemberTemplate()) { |
11975 | NewTemplateDecl->setMemberSpecialization(); |
11976 | assert(OldTemplateDecl->isMemberSpecialization()); |
11977 | // Explicit specializations of a member template do not inherit deleted |
11978 | // status from the parent member template that they are specializing. |
11979 | if (OldFD->isDeleted()) { |
11980 | // FIXME: This assert will not hold in the presence of modules. |
11981 | assert(OldFD->getCanonicalDecl() == OldFD); |
11982 | // FIXME: We need an update record for this AST mutation. |
11983 | OldFD->setDeletedAsWritten(D: false); |
11984 | } |
11985 | } |
11986 | |
11987 | } else { |
11988 | if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) { |
11989 | auto *OldFD = cast<FunctionDecl>(Val: OldDecl); |
11990 | // This needs to happen first so that 'inline' propagates. |
11991 | NewFD->setPreviousDeclaration(OldFD); |
11992 | if (NewFD->isCXXClassMember()) |
11993 | NewFD->setAccess(OldFD->getAccess()); |
11994 | } |
11995 | } |
11996 | } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && |
11997 | !NewFD->getAttr<OverloadableAttr>()) { |
11998 | assert((Previous.empty() || |
11999 | llvm::any_of(Previous, |
12000 | [](const NamedDecl *ND) { |
12001 | return ND->hasAttr<OverloadableAttr>(); |
12002 | })) && |
12003 | "Non-redecls shouldn't happen without overloadable present" ); |
12004 | |
12005 | auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) { |
12006 | const auto *FD = dyn_cast<FunctionDecl>(Val: ND); |
12007 | return FD && !FD->hasAttr<OverloadableAttr>(); |
12008 | }); |
12009 | |
12010 | if (OtherUnmarkedIter != Previous.end()) { |
12011 | Diag(Loc: NewFD->getLocation(), |
12012 | DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads); |
12013 | Diag(Loc: (*OtherUnmarkedIter)->getLocation(), |
12014 | DiagID: diag::note_attribute_overloadable_prev_overload) |
12015 | << false; |
12016 | |
12017 | NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context)); |
12018 | } |
12019 | } |
12020 | |
12021 | if (LangOpts.OpenMP) |
12022 | OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD); |
12023 | |
12024 | // Semantic checking for this function declaration (in isolation). |
12025 | |
12026 | if (getLangOpts().CPlusPlus) { |
12027 | // C++-specific checks. |
12028 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) { |
12029 | CheckConstructor(Constructor); |
12030 | } else if (CXXDestructorDecl *Destructor = |
12031 | dyn_cast<CXXDestructorDecl>(Val: NewFD)) { |
12032 | // We check here for invalid destructor names. |
12033 | // If we have a friend destructor declaration that is dependent, we can't |
12034 | // diagnose right away because cases like this are still valid: |
12035 | // template <class T> struct A { friend T::X::~Y(); }; |
12036 | // struct B { struct Y { ~Y(); }; using X = Y; }; |
12037 | // template struct A<B>; |
12038 | if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None || |
12039 | !Destructor->getFunctionObjectParameterType()->isDependentType()) { |
12040 | CXXRecordDecl *Record = Destructor->getParent(); |
12041 | QualType ClassType = Context.getTypeDeclType(Decl: Record); |
12042 | |
12043 | DeclarationName Name = Context.DeclarationNames.getCXXDestructorName( |
12044 | Ty: Context.getCanonicalType(T: ClassType)); |
12045 | if (NewFD->getDeclName() != Name) { |
12046 | Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name); |
12047 | NewFD->setInvalidDecl(); |
12048 | return Redeclaration; |
12049 | } |
12050 | } |
12051 | } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) { |
12052 | if (auto *TD = Guide->getDescribedFunctionTemplate()) |
12053 | CheckDeductionGuideTemplate(TD); |
12054 | |
12055 | // A deduction guide is not on the list of entities that can be |
12056 | // explicitly specialized. |
12057 | if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) |
12058 | Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized) |
12059 | << /*explicit specialization*/ 1; |
12060 | } |
12061 | |
12062 | // Find any virtual functions that this function overrides. |
12063 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) { |
12064 | if (!Method->isFunctionTemplateSpecialization() && |
12065 | !Method->getDescribedFunctionTemplate() && |
12066 | Method->isCanonicalDecl()) { |
12067 | AddOverriddenMethods(DC: Method->getParent(), MD: Method); |
12068 | } |
12069 | if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) |
12070 | // C++2a [class.virtual]p6 |
12071 | // A virtual method shall not have a requires-clause. |
12072 | Diag(Loc: NewFD->getTrailingRequiresClause()->getBeginLoc(), |
12073 | DiagID: diag::err_constrained_virtual_method); |
12074 | |
12075 | if (Method->isStatic()) |
12076 | checkThisInStaticMemberFunctionType(Method); |
12077 | } |
12078 | |
12079 | if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD)) |
12080 | ActOnConversionDeclarator(Conversion); |
12081 | |
12082 | // Extra checking for C++ overloaded operators (C++ [over.oper]). |
12083 | if (NewFD->isOverloadedOperator() && |
12084 | CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) { |
12085 | NewFD->setInvalidDecl(); |
12086 | return Redeclaration; |
12087 | } |
12088 | |
12089 | // Extra checking for C++0x literal operators (C++0x [over.literal]). |
12090 | if (NewFD->getLiteralIdentifier() && |
12091 | CheckLiteralOperatorDeclaration(FnDecl: NewFD)) { |
12092 | NewFD->setInvalidDecl(); |
12093 | return Redeclaration; |
12094 | } |
12095 | |
12096 | // In C++, check default arguments now that we have merged decls. Unless |
12097 | // the lexical context is the class, because in this case this is done |
12098 | // during delayed parsing anyway. |
12099 | if (!CurContext->isRecord()) |
12100 | CheckCXXDefaultArguments(FD: NewFD); |
12101 | |
12102 | // If this function is declared as being extern "C", then check to see if |
12103 | // the function returns a UDT (class, struct, or union type) that is not C |
12104 | // compatible, and if it does, warn the user. |
12105 | // But, issue any diagnostic on the first declaration only. |
12106 | if (Previous.empty() && NewFD->isExternC()) { |
12107 | QualType R = NewFD->getReturnType(); |
12108 | if (R->isIncompleteType() && !R->isVoidType()) |
12109 | Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete) |
12110 | << NewFD << R; |
12111 | else if (!R.isPODType(Context) && !R->isVoidType() && |
12112 | !R->isObjCObjectPointerType()) |
12113 | Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R; |
12114 | } |
12115 | |
12116 | // C++1z [dcl.fct]p6: |
12117 | // [...] whether the function has a non-throwing exception-specification |
12118 | // [is] part of the function type |
12119 | // |
12120 | // This results in an ABI break between C++14 and C++17 for functions whose |
12121 | // declared type includes an exception-specification in a parameter or |
12122 | // return type. (Exception specifications on the function itself are OK in |
12123 | // most cases, and exception specifications are not permitted in most other |
12124 | // contexts where they could make it into a mangling.) |
12125 | if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { |
12126 | auto HasNoexcept = [&](QualType T) -> bool { |
12127 | // Strip off declarator chunks that could be between us and a function |
12128 | // type. We don't need to look far, exception specifications are very |
12129 | // restricted prior to C++17. |
12130 | if (auto *RT = T->getAs<ReferenceType>()) |
12131 | T = RT->getPointeeType(); |
12132 | else if (T->isAnyPointerType()) |
12133 | T = T->getPointeeType(); |
12134 | else if (auto *MPT = T->getAs<MemberPointerType>()) |
12135 | T = MPT->getPointeeType(); |
12136 | if (auto *FPT = T->getAs<FunctionProtoType>()) |
12137 | if (FPT->isNothrow()) |
12138 | return true; |
12139 | return false; |
12140 | }; |
12141 | |
12142 | auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); |
12143 | bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); |
12144 | for (QualType T : FPT->param_types()) |
12145 | AnyNoexcept |= HasNoexcept(T); |
12146 | if (AnyNoexcept) |
12147 | Diag(Loc: NewFD->getLocation(), |
12148 | DiagID: diag::warn_cxx17_compat_exception_spec_in_signature) |
12149 | << NewFD; |
12150 | } |
12151 | |
12152 | if (!Redeclaration && LangOpts.CUDA) |
12153 | CUDA().checkTargetOverload(NewFD, Previous); |
12154 | } |
12155 | |
12156 | // Check if the function definition uses any AArch64 SME features without |
12157 | // having the '+sme' feature enabled and warn user if sme locally streaming |
12158 | // function returns or uses arguments with VL-based types. |
12159 | if (DeclIsDefn) { |
12160 | const auto *Attr = NewFD->getAttr<ArmNewAttr>(); |
12161 | bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>(); |
12162 | bool UsesZA = Attr && Attr->isNewZA(); |
12163 | bool UsesZT0 = Attr && Attr->isNewZT0(); |
12164 | |
12165 | if (NewFD->hasAttr<ArmLocallyStreamingAttr>()) { |
12166 | if (NewFD->getReturnType()->isSizelessVectorType()) |
12167 | Diag(Loc: NewFD->getLocation(), |
12168 | DiagID: diag::warn_sme_locally_streaming_has_vl_args_returns) |
12169 | << /*IsArg=*/false; |
12170 | if (llvm::any_of(Range: NewFD->parameters(), P: [](ParmVarDecl *P) { |
12171 | return P->getOriginalType()->isSizelessVectorType(); |
12172 | })) |
12173 | Diag(Loc: NewFD->getLocation(), |
12174 | DiagID: diag::warn_sme_locally_streaming_has_vl_args_returns) |
12175 | << /*IsArg=*/true; |
12176 | } |
12177 | if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) { |
12178 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
12179 | UsesSM |= |
12180 | EPI.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask; |
12181 | UsesZA |= FunctionType::getArmZAState(AttrBits: EPI.AArch64SMEAttributes) != |
12182 | FunctionType::ARM_None; |
12183 | UsesZT0 |= FunctionType::getArmZT0State(AttrBits: EPI.AArch64SMEAttributes) != |
12184 | FunctionType::ARM_None; |
12185 | } |
12186 | |
12187 | if (UsesSM || UsesZA) { |
12188 | llvm::StringMap<bool> FeatureMap; |
12189 | Context.getFunctionFeatureMap(FeatureMap, NewFD); |
12190 | if (!FeatureMap.contains(Key: "sme" )) { |
12191 | if (UsesSM) |
12192 | Diag(Loc: NewFD->getLocation(), |
12193 | DiagID: diag::err_sme_definition_using_sm_in_non_sme_target); |
12194 | else |
12195 | Diag(Loc: NewFD->getLocation(), |
12196 | DiagID: diag::err_sme_definition_using_za_in_non_sme_target); |
12197 | } |
12198 | } |
12199 | if (UsesZT0) { |
12200 | llvm::StringMap<bool> FeatureMap; |
12201 | Context.getFunctionFeatureMap(FeatureMap, NewFD); |
12202 | if (!FeatureMap.contains(Key: "sme2" )) { |
12203 | Diag(Loc: NewFD->getLocation(), |
12204 | DiagID: diag::err_sme_definition_using_zt0_in_non_sme2_target); |
12205 | } |
12206 | } |
12207 | } |
12208 | |
12209 | return Redeclaration; |
12210 | } |
12211 | |
12212 | void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { |
12213 | // C++11 [basic.start.main]p3: |
12214 | // A program that [...] declares main to be inline, static or |
12215 | // constexpr is ill-formed. |
12216 | // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall |
12217 | // appear in a declaration of main. |
12218 | // static main is not an error under C99, but we should warn about it. |
12219 | // We accept _Noreturn main as an extension. |
12220 | if (FD->getStorageClass() == SC_Static) |
12221 | Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus |
12222 | ? diag::err_static_main : diag::warn_static_main) |
12223 | << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc()); |
12224 | if (FD->isInlineSpecified()) |
12225 | Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main) |
12226 | << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc()); |
12227 | if (DS.isNoreturnSpecified()) { |
12228 | SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); |
12229 | SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc)); |
12230 | Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main); |
12231 | Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn) |
12232 | << FixItHint::CreateRemoval(RemoveRange: NoreturnRange); |
12233 | } |
12234 | if (FD->isConstexpr()) { |
12235 | Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main) |
12236 | << FD->isConsteval() |
12237 | << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc()); |
12238 | FD->setConstexprKind(ConstexprSpecKind::Unspecified); |
12239 | } |
12240 | |
12241 | if (getLangOpts().OpenCL) { |
12242 | Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main) |
12243 | << FD->hasAttr<OpenCLKernelAttr>(); |
12244 | FD->setInvalidDecl(); |
12245 | return; |
12246 | } |
12247 | |
12248 | // Functions named main in hlsl are default entries, but don't have specific |
12249 | // signatures they are required to conform to. |
12250 | if (getLangOpts().HLSL) |
12251 | return; |
12252 | |
12253 | QualType T = FD->getType(); |
12254 | assert(T->isFunctionType() && "function decl is not of function type" ); |
12255 | const FunctionType* FT = T->castAs<FunctionType>(); |
12256 | |
12257 | // Set default calling convention for main() |
12258 | if (FT->getCallConv() != CC_C) { |
12259 | FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C)); |
12260 | FD->setType(QualType(FT, 0)); |
12261 | T = Context.getCanonicalType(T: FD->getType()); |
12262 | } |
12263 | |
12264 | if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { |
12265 | // In C with GNU extensions we allow main() to have non-integer return |
12266 | // type, but we should warn about the extension, and we disable the |
12267 | // implicit-return-zero rule. |
12268 | |
12269 | // GCC in C mode accepts qualified 'int'. |
12270 | if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy)) |
12271 | FD->setHasImplicitReturnZero(true); |
12272 | else { |
12273 | Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint); |
12274 | SourceRange RTRange = FD->getReturnTypeSourceRange(); |
12275 | if (RTRange.isValid()) |
12276 | Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type) |
12277 | << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int" ); |
12278 | } |
12279 | } else { |
12280 | // In C and C++, main magically returns 0 if you fall off the end; |
12281 | // set the flag which tells us that. |
12282 | // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. |
12283 | |
12284 | // All the standards say that main() should return 'int'. |
12285 | if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy)) |
12286 | FD->setHasImplicitReturnZero(true); |
12287 | else { |
12288 | // Otherwise, this is just a flat-out error. |
12289 | SourceRange RTRange = FD->getReturnTypeSourceRange(); |
12290 | Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint) |
12291 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int" ) |
12292 | : FixItHint()); |
12293 | FD->setInvalidDecl(true); |
12294 | } |
12295 | } |
12296 | |
12297 | // Treat protoless main() as nullary. |
12298 | if (isa<FunctionNoProtoType>(Val: FT)) return; |
12299 | |
12300 | const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT); |
12301 | unsigned nparams = FTP->getNumParams(); |
12302 | assert(FD->getNumParams() == nparams); |
12303 | |
12304 | bool = (nparams > 3); |
12305 | |
12306 | if (FTP->isVariadic()) { |
12307 | Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main); |
12308 | // FIXME: if we had information about the location of the ellipsis, we |
12309 | // could add a FixIt hint to remove it as a parameter. |
12310 | } |
12311 | |
12312 | // Darwin passes an undocumented fourth argument of type char**. If |
12313 | // other platforms start sprouting these, the logic below will start |
12314 | // getting shifty. |
12315 | if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) |
12316 | HasExtraParameters = false; |
12317 | |
12318 | if (HasExtraParameters) { |
12319 | Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams; |
12320 | FD->setInvalidDecl(true); |
12321 | nparams = 3; |
12322 | } |
12323 | |
12324 | // FIXME: a lot of the following diagnostics would be improved |
12325 | // if we had some location information about types. |
12326 | |
12327 | QualType CharPP = |
12328 | Context.getPointerType(T: Context.getPointerType(T: Context.CharTy)); |
12329 | QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; |
12330 | |
12331 | for (unsigned i = 0; i < nparams; ++i) { |
12332 | QualType AT = FTP->getParamType(i); |
12333 | |
12334 | bool mismatch = true; |
12335 | |
12336 | if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i])) |
12337 | mismatch = false; |
12338 | else if (Expected[i] == CharPP) { |
12339 | // As an extension, the following forms are okay: |
12340 | // char const ** |
12341 | // char const * const * |
12342 | // char * const * |
12343 | |
12344 | QualifierCollector qs; |
12345 | const PointerType* PT; |
12346 | if ((PT = qs.strip(type: AT)->getAs<PointerType>()) && |
12347 | (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) && |
12348 | Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0), |
12349 | T2: Context.CharTy)) { |
12350 | qs.removeConst(); |
12351 | mismatch = !qs.empty(); |
12352 | } |
12353 | } |
12354 | |
12355 | if (mismatch) { |
12356 | Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i]; |
12357 | // TODO: suggest replacing given type with expected type |
12358 | FD->setInvalidDecl(true); |
12359 | } |
12360 | } |
12361 | |
12362 | if (nparams == 1 && !FD->isInvalidDecl()) { |
12363 | Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg); |
12364 | } |
12365 | |
12366 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { |
12367 | Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD; |
12368 | FD->setInvalidDecl(); |
12369 | } |
12370 | } |
12371 | |
12372 | static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { |
12373 | |
12374 | // Default calling convention for main and wmain is __cdecl |
12375 | if (FD->getName() == "main" || FD->getName() == "wmain" ) |
12376 | return false; |
12377 | |
12378 | // Default calling convention for MinGW is __cdecl |
12379 | const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); |
12380 | if (T.isWindowsGNUEnvironment()) |
12381 | return false; |
12382 | |
12383 | // Default calling convention for WinMain, wWinMain and DllMain |
12384 | // is __stdcall on 32 bit Windows |
12385 | if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) |
12386 | return true; |
12387 | |
12388 | return false; |
12389 | } |
12390 | |
12391 | void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { |
12392 | QualType T = FD->getType(); |
12393 | assert(T->isFunctionType() && "function decl is not of function type" ); |
12394 | const FunctionType *FT = T->castAs<FunctionType>(); |
12395 | |
12396 | // Set an implicit return of 'zero' if the function can return some integral, |
12397 | // enumeration, pointer or nullptr type. |
12398 | if (FT->getReturnType()->isIntegralOrEnumerationType() || |
12399 | FT->getReturnType()->isAnyPointerType() || |
12400 | FT->getReturnType()->isNullPtrType()) |
12401 | // DllMain is exempt because a return value of zero means it failed. |
12402 | if (FD->getName() != "DllMain" ) |
12403 | FD->setHasImplicitReturnZero(true); |
12404 | |
12405 | // Explicitly specified calling conventions are applied to MSVC entry points |
12406 | if (!hasExplicitCallingConv(T)) { |
12407 | if (isDefaultStdCall(FD, S&: *this)) { |
12408 | if (FT->getCallConv() != CC_X86StdCall) { |
12409 | FT = Context.adjustFunctionType( |
12410 | Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall)); |
12411 | FD->setType(QualType(FT, 0)); |
12412 | } |
12413 | } else if (FT->getCallConv() != CC_C) { |
12414 | FT = Context.adjustFunctionType(Fn: FT, |
12415 | EInfo: FT->getExtInfo().withCallingConv(cc: CC_C)); |
12416 | FD->setType(QualType(FT, 0)); |
12417 | } |
12418 | } |
12419 | |
12420 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { |
12421 | Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD; |
12422 | FD->setInvalidDecl(); |
12423 | } |
12424 | } |
12425 | |
12426 | bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) { |
12427 | // FIXME: Need strict checking. In C89, we need to check for |
12428 | // any assignment, increment, decrement, function-calls, or |
12429 | // commas outside of a sizeof. In C99, it's the same list, |
12430 | // except that the aforementioned are allowed in unevaluated |
12431 | // expressions. Everything else falls under the |
12432 | // "may accept other forms of constant expressions" exception. |
12433 | // |
12434 | // Regular C++ code will not end up here (exceptions: language extensions, |
12435 | // OpenCL C++ etc), so the constant expression rules there don't matter. |
12436 | if (Init->isValueDependent()) { |
12437 | assert(Init->containsErrors() && |
12438 | "Dependent code should only occur in error-recovery path." ); |
12439 | return true; |
12440 | } |
12441 | const Expr *Culprit; |
12442 | if (Init->isConstantInitializer(Ctx&: Context, ForRef: false, Culprit: &Culprit)) |
12443 | return false; |
12444 | Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange(); |
12445 | return true; |
12446 | } |
12447 | |
12448 | namespace { |
12449 | // Visits an initialization expression to see if OrigDecl is evaluated in |
12450 | // its own initialization and throws a warning if it does. |
12451 | class SelfReferenceChecker |
12452 | : public EvaluatedExprVisitor<SelfReferenceChecker> { |
12453 | Sema &S; |
12454 | Decl *OrigDecl; |
12455 | bool isRecordType; |
12456 | bool isPODType; |
12457 | bool isReferenceType; |
12458 | |
12459 | bool isInitList; |
12460 | llvm::SmallVector<unsigned, 4> InitFieldIndex; |
12461 | |
12462 | public: |
12463 | typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; |
12464 | |
12465 | SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), |
12466 | S(S), OrigDecl(OrigDecl) { |
12467 | isPODType = false; |
12468 | isRecordType = false; |
12469 | isReferenceType = false; |
12470 | isInitList = false; |
12471 | if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) { |
12472 | isPODType = VD->getType().isPODType(Context: S.Context); |
12473 | isRecordType = VD->getType()->isRecordType(); |
12474 | isReferenceType = VD->getType()->isReferenceType(); |
12475 | } |
12476 | } |
12477 | |
12478 | // For most expressions, just call the visitor. For initializer lists, |
12479 | // track the index of the field being initialized since fields are |
12480 | // initialized in order allowing use of previously initialized fields. |
12481 | void CheckExpr(Expr *E) { |
12482 | InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E); |
12483 | if (!InitList) { |
12484 | Visit(S: E); |
12485 | return; |
12486 | } |
12487 | |
12488 | // Track and increment the index here. |
12489 | isInitList = true; |
12490 | InitFieldIndex.push_back(Elt: 0); |
12491 | for (auto *Child : InitList->children()) { |
12492 | CheckExpr(E: cast<Expr>(Val: Child)); |
12493 | ++InitFieldIndex.back(); |
12494 | } |
12495 | InitFieldIndex.pop_back(); |
12496 | } |
12497 | |
12498 | // Returns true if MemberExpr is checked and no further checking is needed. |
12499 | // Returns false if additional checking is required. |
12500 | bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { |
12501 | llvm::SmallVector<FieldDecl*, 4> Fields; |
12502 | Expr *Base = E; |
12503 | bool ReferenceField = false; |
12504 | |
12505 | // Get the field members used. |
12506 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) { |
12507 | FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()); |
12508 | if (!FD) |
12509 | return false; |
12510 | Fields.push_back(Elt: FD); |
12511 | if (FD->getType()->isReferenceType()) |
12512 | ReferenceField = true; |
12513 | Base = ME->getBase()->IgnoreParenImpCasts(); |
12514 | } |
12515 | |
12516 | // Keep checking only if the base Decl is the same. |
12517 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base); |
12518 | if (!DRE || DRE->getDecl() != OrigDecl) |
12519 | return false; |
12520 | |
12521 | // A reference field can be bound to an unininitialized field. |
12522 | if (CheckReference && !ReferenceField) |
12523 | return true; |
12524 | |
12525 | // Convert FieldDecls to their index number. |
12526 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; |
12527 | for (const FieldDecl *I : llvm::reverse(C&: Fields)) |
12528 | UsedFieldIndex.push_back(Elt: I->getFieldIndex()); |
12529 | |
12530 | // See if a warning is needed by checking the first difference in index |
12531 | // numbers. If field being used has index less than the field being |
12532 | // initialized, then the use is safe. |
12533 | for (auto UsedIter = UsedFieldIndex.begin(), |
12534 | UsedEnd = UsedFieldIndex.end(), |
12535 | OrigIter = InitFieldIndex.begin(), |
12536 | OrigEnd = InitFieldIndex.end(); |
12537 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { |
12538 | if (*UsedIter < *OrigIter) |
12539 | return true; |
12540 | if (*UsedIter > *OrigIter) |
12541 | break; |
12542 | } |
12543 | |
12544 | // TODO: Add a different warning which will print the field names. |
12545 | HandleDeclRefExpr(DRE); |
12546 | return true; |
12547 | } |
12548 | |
12549 | // For most expressions, the cast is directly above the DeclRefExpr. |
12550 | // For conditional operators, the cast can be outside the conditional |
12551 | // operator if both expressions are DeclRefExpr's. |
12552 | void HandleValue(Expr *E) { |
12553 | E = E->IgnoreParens(); |
12554 | if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) { |
12555 | HandleDeclRefExpr(DRE); |
12556 | return; |
12557 | } |
12558 | |
12559 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) { |
12560 | Visit(S: CO->getCond()); |
12561 | HandleValue(E: CO->getTrueExpr()); |
12562 | HandleValue(E: CO->getFalseExpr()); |
12563 | return; |
12564 | } |
12565 | |
12566 | if (BinaryConditionalOperator *BCO = |
12567 | dyn_cast<BinaryConditionalOperator>(Val: E)) { |
12568 | Visit(S: BCO->getCond()); |
12569 | HandleValue(E: BCO->getFalseExpr()); |
12570 | return; |
12571 | } |
12572 | |
12573 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) { |
12574 | if (Expr *SE = OVE->getSourceExpr()) |
12575 | HandleValue(E: SE); |
12576 | return; |
12577 | } |
12578 | |
12579 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) { |
12580 | if (BO->getOpcode() == BO_Comma) { |
12581 | Visit(S: BO->getLHS()); |
12582 | HandleValue(E: BO->getRHS()); |
12583 | return; |
12584 | } |
12585 | } |
12586 | |
12587 | if (isa<MemberExpr>(Val: E)) { |
12588 | if (isInitList) { |
12589 | if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E), |
12590 | CheckReference: false /*CheckReference*/)) |
12591 | return; |
12592 | } |
12593 | |
12594 | Expr *Base = E->IgnoreParenImpCasts(); |
12595 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) { |
12596 | // Check for static member variables and don't warn on them. |
12597 | if (!isa<FieldDecl>(Val: ME->getMemberDecl())) |
12598 | return; |
12599 | Base = ME->getBase()->IgnoreParenImpCasts(); |
12600 | } |
12601 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) |
12602 | HandleDeclRefExpr(DRE); |
12603 | return; |
12604 | } |
12605 | |
12606 | Visit(S: E); |
12607 | } |
12608 | |
12609 | // Reference types not handled in HandleValue are handled here since all |
12610 | // uses of references are bad, not just r-value uses. |
12611 | void VisitDeclRefExpr(DeclRefExpr *E) { |
12612 | if (isReferenceType) |
12613 | HandleDeclRefExpr(DRE: E); |
12614 | } |
12615 | |
12616 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { |
12617 | if (E->getCastKind() == CK_LValueToRValue) { |
12618 | HandleValue(E: E->getSubExpr()); |
12619 | return; |
12620 | } |
12621 | |
12622 | Inherited::VisitImplicitCastExpr(S: E); |
12623 | } |
12624 | |
12625 | void VisitMemberExpr(MemberExpr *E) { |
12626 | if (isInitList) { |
12627 | if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/)) |
12628 | return; |
12629 | } |
12630 | |
12631 | // Don't warn on arrays since they can be treated as pointers. |
12632 | if (E->getType()->canDecayToPointerType()) return; |
12633 | |
12634 | // Warn when a non-static method call is followed by non-static member |
12635 | // field accesses, which is followed by a DeclRefExpr. |
12636 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl()); |
12637 | bool Warn = (MD && !MD->isStatic()); |
12638 | Expr *Base = E->getBase()->IgnoreParenImpCasts(); |
12639 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) { |
12640 | if (!isa<FieldDecl>(Val: ME->getMemberDecl())) |
12641 | Warn = false; |
12642 | Base = ME->getBase()->IgnoreParenImpCasts(); |
12643 | } |
12644 | |
12645 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) { |
12646 | if (Warn) |
12647 | HandleDeclRefExpr(DRE); |
12648 | return; |
12649 | } |
12650 | |
12651 | // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. |
12652 | // Visit that expression. |
12653 | Visit(S: Base); |
12654 | } |
12655 | |
12656 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { |
12657 | Expr *Callee = E->getCallee(); |
12658 | |
12659 | if (isa<UnresolvedLookupExpr>(Val: Callee)) |
12660 | return Inherited::VisitCXXOperatorCallExpr(S: E); |
12661 | |
12662 | Visit(S: Callee); |
12663 | for (auto Arg: E->arguments()) |
12664 | HandleValue(E: Arg->IgnoreParenImpCasts()); |
12665 | } |
12666 | |
12667 | void VisitUnaryOperator(UnaryOperator *E) { |
12668 | // For POD record types, addresses of its own members are well-defined. |
12669 | if (E->getOpcode() == UO_AddrOf && isRecordType && |
12670 | isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) { |
12671 | if (!isPODType) |
12672 | HandleValue(E: E->getSubExpr()); |
12673 | return; |
12674 | } |
12675 | |
12676 | if (E->isIncrementDecrementOp()) { |
12677 | HandleValue(E: E->getSubExpr()); |
12678 | return; |
12679 | } |
12680 | |
12681 | Inherited::VisitUnaryOperator(S: E); |
12682 | } |
12683 | |
12684 | void VisitObjCMessageExpr(ObjCMessageExpr *E) {} |
12685 | |
12686 | void VisitCXXConstructExpr(CXXConstructExpr *E) { |
12687 | if (E->getConstructor()->isCopyConstructor()) { |
12688 | Expr *ArgExpr = E->getArg(Arg: 0); |
12689 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr)) |
12690 | if (ILE->getNumInits() == 1) |
12691 | ArgExpr = ILE->getInit(Init: 0); |
12692 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr)) |
12693 | if (ICE->getCastKind() == CK_NoOp) |
12694 | ArgExpr = ICE->getSubExpr(); |
12695 | HandleValue(E: ArgExpr); |
12696 | return; |
12697 | } |
12698 | Inherited::VisitCXXConstructExpr(S: E); |
12699 | } |
12700 | |
12701 | void VisitCallExpr(CallExpr *E) { |
12702 | // Treat std::move as a use. |
12703 | if (E->isCallToStdMove()) { |
12704 | HandleValue(E: E->getArg(Arg: 0)); |
12705 | return; |
12706 | } |
12707 | |
12708 | Inherited::VisitCallExpr(CE: E); |
12709 | } |
12710 | |
12711 | void VisitBinaryOperator(BinaryOperator *E) { |
12712 | if (E->isCompoundAssignmentOp()) { |
12713 | HandleValue(E: E->getLHS()); |
12714 | Visit(S: E->getRHS()); |
12715 | return; |
12716 | } |
12717 | |
12718 | Inherited::VisitBinaryOperator(S: E); |
12719 | } |
12720 | |
12721 | // A custom visitor for BinaryConditionalOperator is needed because the |
12722 | // regular visitor would check the condition and true expression separately |
12723 | // but both point to the same place giving duplicate diagnostics. |
12724 | void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { |
12725 | Visit(S: E->getCond()); |
12726 | Visit(S: E->getFalseExpr()); |
12727 | } |
12728 | |
12729 | void HandleDeclRefExpr(DeclRefExpr *DRE) { |
12730 | Decl* ReferenceDecl = DRE->getDecl(); |
12731 | if (OrigDecl != ReferenceDecl) return; |
12732 | unsigned diag; |
12733 | if (isReferenceType) { |
12734 | diag = diag::warn_uninit_self_reference_in_reference_init; |
12735 | } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) { |
12736 | diag = diag::warn_static_self_reference_in_init; |
12737 | } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) || |
12738 | isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) || |
12739 | DRE->getDecl()->getType()->isRecordType()) { |
12740 | diag = diag::warn_uninit_self_reference_in_init; |
12741 | } else { |
12742 | // Local variables will be handled by the CFG analysis. |
12743 | return; |
12744 | } |
12745 | |
12746 | S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE, |
12747 | PD: S.PDiag(DiagID: diag) |
12748 | << DRE->getDecl() << OrigDecl->getLocation() |
12749 | << DRE->getSourceRange()); |
12750 | } |
12751 | }; |
12752 | |
12753 | /// CheckSelfReference - Warns if OrigDecl is used in expression E. |
12754 | static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, |
12755 | bool DirectInit) { |
12756 | // Parameters arguments are occassionially constructed with itself, |
12757 | // for instance, in recursive functions. Skip them. |
12758 | if (isa<ParmVarDecl>(Val: OrigDecl)) |
12759 | return; |
12760 | |
12761 | E = E->IgnoreParens(); |
12762 | |
12763 | // Skip checking T a = a where T is not a record or reference type. |
12764 | // Doing so is a way to silence uninitialized warnings. |
12765 | if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType()) |
12766 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) |
12767 | if (ICE->getCastKind() == CK_LValueToRValue) |
12768 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr())) |
12769 | if (DRE->getDecl() == OrigDecl) |
12770 | return; |
12771 | |
12772 | SelfReferenceChecker(S, OrigDecl).CheckExpr(E); |
12773 | } |
12774 | } // end anonymous namespace |
12775 | |
12776 | namespace { |
12777 | // Simple wrapper to add the name of a variable or (if no variable is |
12778 | // available) a DeclarationName into a diagnostic. |
12779 | struct VarDeclOrName { |
12780 | VarDecl *VDecl; |
12781 | DeclarationName Name; |
12782 | |
12783 | friend const Sema::SemaDiagnosticBuilder & |
12784 | operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { |
12785 | return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; |
12786 | } |
12787 | }; |
12788 | } // end anonymous namespace |
12789 | |
12790 | QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, |
12791 | DeclarationName Name, QualType Type, |
12792 | TypeSourceInfo *TSI, |
12793 | SourceRange Range, bool DirectInit, |
12794 | Expr *Init) { |
12795 | bool IsInitCapture = !VDecl; |
12796 | assert((!VDecl || !VDecl->isInitCapture()) && |
12797 | "init captures are expected to be deduced prior to initialization" ); |
12798 | |
12799 | VarDeclOrName VN{.VDecl: VDecl, .Name: Name}; |
12800 | |
12801 | DeducedType *Deduced = Type->getContainedDeducedType(); |
12802 | assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type" ); |
12803 | |
12804 | // Diagnose auto array declarations in C23, unless it's a supported extension. |
12805 | if (getLangOpts().C23 && Type->isArrayType() && |
12806 | !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) { |
12807 | Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed) |
12808 | << (int)Deduced->getContainedAutoType()->getKeyword() |
12809 | << /*in array decl*/ 23 << Range; |
12810 | return QualType(); |
12811 | } |
12812 | |
12813 | // C++11 [dcl.spec.auto]p3 |
12814 | if (!Init) { |
12815 | assert(VDecl && "no init for init capture deduction?" ); |
12816 | |
12817 | // Except for class argument deduction, and then for an initializing |
12818 | // declaration only, i.e. no static at class scope or extern. |
12819 | if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) || |
12820 | VDecl->hasExternalStorage() || |
12821 | VDecl->isStaticDataMember()) { |
12822 | Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init) |
12823 | << VDecl->getDeclName() << Type; |
12824 | return QualType(); |
12825 | } |
12826 | } |
12827 | |
12828 | ArrayRef<Expr*> DeduceInits; |
12829 | if (Init) |
12830 | DeduceInits = Init; |
12831 | |
12832 | auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init); |
12833 | if (DirectInit && PL) |
12834 | DeduceInits = PL->exprs(); |
12835 | |
12836 | if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) { |
12837 | assert(VDecl && "non-auto type for init capture deduction?" ); |
12838 | InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl); |
12839 | InitializationKind Kind = InitializationKind::CreateForInit( |
12840 | Loc: VDecl->getLocation(), DirectInit, Init); |
12841 | // FIXME: Initialization should not be taking a mutable list of inits. |
12842 | SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); |
12843 | return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, |
12844 | Init: InitsCopy); |
12845 | } |
12846 | |
12847 | if (DirectInit) { |
12848 | if (auto *IL = dyn_cast<InitListExpr>(Val: Init)) |
12849 | DeduceInits = IL->inits(); |
12850 | } |
12851 | |
12852 | // Deduction only works if we have exactly one source expression. |
12853 | if (DeduceInits.empty()) { |
12854 | // It isn't possible to write this directly, but it is possible to |
12855 | // end up in this situation with "auto x(some_pack...);" |
12856 | Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture |
12857 | ? diag::err_init_capture_no_expression |
12858 | : diag::err_auto_var_init_no_expression) |
12859 | << VN << Type << Range; |
12860 | return QualType(); |
12861 | } |
12862 | |
12863 | if (DeduceInits.size() > 1) { |
12864 | Diag(Loc: DeduceInits[1]->getBeginLoc(), |
12865 | DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions |
12866 | : diag::err_auto_var_init_multiple_expressions) |
12867 | << VN << Type << Range; |
12868 | return QualType(); |
12869 | } |
12870 | |
12871 | Expr *DeduceInit = DeduceInits[0]; |
12872 | if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) { |
12873 | Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture |
12874 | ? diag::err_init_capture_paren_braces |
12875 | : diag::err_auto_var_init_paren_braces) |
12876 | << isa<InitListExpr>(Val: Init) << VN << Type << Range; |
12877 | return QualType(); |
12878 | } |
12879 | |
12880 | // Expressions default to 'id' when we're in a debugger. |
12881 | bool DefaultedAnyToId = false; |
12882 | if (getLangOpts().DebuggerCastResultToId && |
12883 | Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { |
12884 | ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType()); |
12885 | if (Result.isInvalid()) { |
12886 | return QualType(); |
12887 | } |
12888 | Init = Result.get(); |
12889 | DefaultedAnyToId = true; |
12890 | } |
12891 | |
12892 | // C++ [dcl.decomp]p1: |
12893 | // If the assignment-expression [...] has array type A and no ref-qualifier |
12894 | // is present, e has type cv A |
12895 | if (VDecl && isa<DecompositionDecl>(Val: VDecl) && |
12896 | Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) && |
12897 | DeduceInit->getType()->isConstantArrayType()) |
12898 | return Context.getQualifiedType(T: DeduceInit->getType(), |
12899 | Qs: Type.getQualifiers()); |
12900 | |
12901 | QualType DeducedType; |
12902 | TemplateDeductionInfo Info(DeduceInit->getExprLoc()); |
12903 | TemplateDeductionResult Result = |
12904 | DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info); |
12905 | if (Result != TemplateDeductionResult::Success && |
12906 | Result != TemplateDeductionResult::AlreadyDiagnosed) { |
12907 | if (!IsInitCapture) |
12908 | DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit); |
12909 | else if (isa<InitListExpr>(Val: Init)) |
12910 | Diag(Loc: Range.getBegin(), |
12911 | DiagID: diag::err_init_capture_deduction_failure_from_init_list) |
12912 | << VN |
12913 | << (DeduceInit->getType().isNull() ? TSI->getType() |
12914 | : DeduceInit->getType()) |
12915 | << DeduceInit->getSourceRange(); |
12916 | else |
12917 | Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure) |
12918 | << VN << TSI->getType() |
12919 | << (DeduceInit->getType().isNull() ? TSI->getType() |
12920 | : DeduceInit->getType()) |
12921 | << DeduceInit->getSourceRange(); |
12922 | } |
12923 | |
12924 | // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using |
12925 | // 'id' instead of a specific object type prevents most of our usual |
12926 | // checks. |
12927 | // We only want to warn outside of template instantiations, though: |
12928 | // inside a template, the 'id' could have come from a parameter. |
12929 | if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && |
12930 | !DeducedType.isNull() && DeducedType->isObjCIdType()) { |
12931 | SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); |
12932 | Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range; |
12933 | } |
12934 | |
12935 | return DeducedType; |
12936 | } |
12937 | |
12938 | bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, |
12939 | Expr *Init) { |
12940 | assert(!Init || !Init->containsErrors()); |
12941 | QualType DeducedType = deduceVarTypeFromInitializer( |
12942 | VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(), |
12943 | Range: VDecl->getSourceRange(), DirectInit, Init); |
12944 | if (DeducedType.isNull()) { |
12945 | VDecl->setInvalidDecl(); |
12946 | return true; |
12947 | } |
12948 | |
12949 | VDecl->setType(DeducedType); |
12950 | assert(VDecl->isLinkageValid()); |
12951 | |
12952 | // In ARC, infer lifetime. |
12953 | if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl)) |
12954 | VDecl->setInvalidDecl(); |
12955 | |
12956 | if (getLangOpts().OpenCL) |
12957 | deduceOpenCLAddressSpace(Decl: VDecl); |
12958 | |
12959 | // If this is a redeclaration, check that the type we just deduced matches |
12960 | // the previously declared type. |
12961 | if (VarDecl *Old = VDecl->getPreviousDecl()) { |
12962 | // We never need to merge the type, because we cannot form an incomplete |
12963 | // array of auto, nor deduce such a type. |
12964 | MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false); |
12965 | } |
12966 | |
12967 | // Check the deduced type is valid for a variable declaration. |
12968 | CheckVariableDeclarationType(NewVD: VDecl); |
12969 | return VDecl->isInvalidDecl(); |
12970 | } |
12971 | |
12972 | void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, |
12973 | SourceLocation Loc) { |
12974 | if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init)) |
12975 | Init = EWC->getSubExpr(); |
12976 | |
12977 | if (auto *CE = dyn_cast<ConstantExpr>(Val: Init)) |
12978 | Init = CE->getSubExpr(); |
12979 | |
12980 | QualType InitType = Init->getType(); |
12981 | assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || |
12982 | InitType.hasNonTrivialToPrimitiveCopyCUnion()) && |
12983 | "shouldn't be called if type doesn't have a non-trivial C struct" ); |
12984 | if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) { |
12985 | for (auto *I : ILE->inits()) { |
12986 | if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && |
12987 | !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) |
12988 | continue; |
12989 | SourceLocation SL = I->getExprLoc(); |
12990 | checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc); |
12991 | } |
12992 | return; |
12993 | } |
12994 | |
12995 | if (isa<ImplicitValueInitExpr>(Val: Init)) { |
12996 | if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) |
12997 | checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NTCUC_DefaultInitializedObject, |
12998 | NonTrivialKind: NTCUK_Init); |
12999 | } else { |
13000 | // Assume all other explicit initializers involving copying some existing |
13001 | // object. |
13002 | // TODO: ignore any explicit initializers where we can guarantee |
13003 | // copy-elision. |
13004 | if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) |
13005 | checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NTCUC_CopyInit, NonTrivialKind: NTCUK_Copy); |
13006 | } |
13007 | } |
13008 | |
13009 | namespace { |
13010 | |
13011 | bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { |
13012 | // Ignore unavailable fields. A field can be marked as unavailable explicitly |
13013 | // in the source code or implicitly by the compiler if it is in a union |
13014 | // defined in a system header and has non-trivial ObjC ownership |
13015 | // qualifications. We don't want those fields to participate in determining |
13016 | // whether the containing union is non-trivial. |
13017 | return FD->hasAttr<UnavailableAttr>(); |
13018 | } |
13019 | |
13020 | struct DiagNonTrivalCUnionDefaultInitializeVisitor |
13021 | : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, |
13022 | void> { |
13023 | using Super = |
13024 | DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, |
13025 | void>; |
13026 | |
13027 | DiagNonTrivalCUnionDefaultInitializeVisitor( |
13028 | QualType OrigTy, SourceLocation OrigLoc, |
13029 | Sema::NonTrivialCUnionContext UseContext, Sema &S) |
13030 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} |
13031 | |
13032 | void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, |
13033 | const FieldDecl *FD, bool InNonTrivialUnion) { |
13034 | if (const auto *AT = S.Context.getAsArrayType(T: QT)) |
13035 | return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD, |
13036 | Args&: InNonTrivialUnion); |
13037 | return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion); |
13038 | } |
13039 | |
13040 | void visitARCStrong(QualType QT, const FieldDecl *FD, |
13041 | bool InNonTrivialUnion) { |
13042 | if (InNonTrivialUnion) |
13043 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union) |
13044 | << 1 << 0 << QT << FD->getName(); |
13045 | } |
13046 | |
13047 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { |
13048 | if (InNonTrivialUnion) |
13049 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union) |
13050 | << 1 << 0 << QT << FD->getName(); |
13051 | } |
13052 | |
13053 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { |
13054 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); |
13055 | if (RD->isUnion()) { |
13056 | if (OrigLoc.isValid()) { |
13057 | bool IsUnion = false; |
13058 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) |
13059 | IsUnion = OrigRD->isUnion(); |
13060 | S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context) |
13061 | << 0 << OrigTy << IsUnion << UseContext; |
13062 | // Reset OrigLoc so that this diagnostic is emitted only once. |
13063 | OrigLoc = SourceLocation(); |
13064 | } |
13065 | InNonTrivialUnion = true; |
13066 | } |
13067 | |
13068 | if (InNonTrivialUnion) |
13069 | S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union) |
13070 | << 0 << 0 << QT.getUnqualifiedType() << "" ; |
13071 | |
13072 | for (const FieldDecl *FD : RD->fields()) |
13073 | if (!shouldIgnoreForRecordTriviality(FD)) |
13074 | asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion); |
13075 | } |
13076 | |
13077 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} |
13078 | |
13079 | // The non-trivial C union type or the struct/union type that contains a |
13080 | // non-trivial C union. |
13081 | QualType OrigTy; |
13082 | SourceLocation OrigLoc; |
13083 | Sema::NonTrivialCUnionContext UseContext; |
13084 | Sema &S; |
13085 | }; |
13086 | |
13087 | struct DiagNonTrivalCUnionDestructedTypeVisitor |
13088 | : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { |
13089 | using Super = |
13090 | DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; |
13091 | |
13092 | DiagNonTrivalCUnionDestructedTypeVisitor( |
13093 | QualType OrigTy, SourceLocation OrigLoc, |
13094 | Sema::NonTrivialCUnionContext UseContext, Sema &S) |
13095 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} |
13096 | |
13097 | void visitWithKind(QualType::DestructionKind DK, QualType QT, |
13098 | const FieldDecl *FD, bool InNonTrivialUnion) { |
13099 | if (const auto *AT = S.Context.getAsArrayType(T: QT)) |
13100 | return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD, |
13101 | Args&: InNonTrivialUnion); |
13102 | return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion); |
13103 | } |
13104 | |
13105 | void visitARCStrong(QualType QT, const FieldDecl *FD, |
13106 | bool InNonTrivialUnion) { |
13107 | if (InNonTrivialUnion) |
13108 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union) |
13109 | << 1 << 1 << QT << FD->getName(); |
13110 | } |
13111 | |
13112 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { |
13113 | if (InNonTrivialUnion) |
13114 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union) |
13115 | << 1 << 1 << QT << FD->getName(); |
13116 | } |
13117 | |
13118 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { |
13119 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); |
13120 | if (RD->isUnion()) { |
13121 | if (OrigLoc.isValid()) { |
13122 | bool IsUnion = false; |
13123 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) |
13124 | IsUnion = OrigRD->isUnion(); |
13125 | S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context) |
13126 | << 1 << OrigTy << IsUnion << UseContext; |
13127 | // Reset OrigLoc so that this diagnostic is emitted only once. |
13128 | OrigLoc = SourceLocation(); |
13129 | } |
13130 | InNonTrivialUnion = true; |
13131 | } |
13132 | |
13133 | if (InNonTrivialUnion) |
13134 | S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union) |
13135 | << 0 << 1 << QT.getUnqualifiedType() << "" ; |
13136 | |
13137 | for (const FieldDecl *FD : RD->fields()) |
13138 | if (!shouldIgnoreForRecordTriviality(FD)) |
13139 | asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion); |
13140 | } |
13141 | |
13142 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} |
13143 | void visitCXXDestructor(QualType QT, const FieldDecl *FD, |
13144 | bool InNonTrivialUnion) {} |
13145 | |
13146 | // The non-trivial C union type or the struct/union type that contains a |
13147 | // non-trivial C union. |
13148 | QualType OrigTy; |
13149 | SourceLocation OrigLoc; |
13150 | Sema::NonTrivialCUnionContext UseContext; |
13151 | Sema &S; |
13152 | }; |
13153 | |
13154 | struct DiagNonTrivalCUnionCopyVisitor |
13155 | : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { |
13156 | using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; |
13157 | |
13158 | DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, |
13159 | Sema::NonTrivialCUnionContext UseContext, |
13160 | Sema &S) |
13161 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} |
13162 | |
13163 | void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, |
13164 | const FieldDecl *FD, bool InNonTrivialUnion) { |
13165 | if (const auto *AT = S.Context.getAsArrayType(T: QT)) |
13166 | return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD, |
13167 | Args&: InNonTrivialUnion); |
13168 | return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion); |
13169 | } |
13170 | |
13171 | void visitARCStrong(QualType QT, const FieldDecl *FD, |
13172 | bool InNonTrivialUnion) { |
13173 | if (InNonTrivialUnion) |
13174 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union) |
13175 | << 1 << 2 << QT << FD->getName(); |
13176 | } |
13177 | |
13178 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { |
13179 | if (InNonTrivialUnion) |
13180 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union) |
13181 | << 1 << 2 << QT << FD->getName(); |
13182 | } |
13183 | |
13184 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { |
13185 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); |
13186 | if (RD->isUnion()) { |
13187 | if (OrigLoc.isValid()) { |
13188 | bool IsUnion = false; |
13189 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) |
13190 | IsUnion = OrigRD->isUnion(); |
13191 | S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context) |
13192 | << 2 << OrigTy << IsUnion << UseContext; |
13193 | // Reset OrigLoc so that this diagnostic is emitted only once. |
13194 | OrigLoc = SourceLocation(); |
13195 | } |
13196 | InNonTrivialUnion = true; |
13197 | } |
13198 | |
13199 | if (InNonTrivialUnion) |
13200 | S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union) |
13201 | << 0 << 2 << QT.getUnqualifiedType() << "" ; |
13202 | |
13203 | for (const FieldDecl *FD : RD->fields()) |
13204 | if (!shouldIgnoreForRecordTriviality(FD)) |
13205 | asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion); |
13206 | } |
13207 | |
13208 | void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, |
13209 | const FieldDecl *FD, bool InNonTrivialUnion) {} |
13210 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} |
13211 | void visitVolatileTrivial(QualType QT, const FieldDecl *FD, |
13212 | bool InNonTrivialUnion) {} |
13213 | |
13214 | // The non-trivial C union type or the struct/union type that contains a |
13215 | // non-trivial C union. |
13216 | QualType OrigTy; |
13217 | SourceLocation OrigLoc; |
13218 | Sema::NonTrivialCUnionContext UseContext; |
13219 | Sema &S; |
13220 | }; |
13221 | |
13222 | } // namespace |
13223 | |
13224 | void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, |
13225 | NonTrivialCUnionContext UseContext, |
13226 | unsigned NonTrivialKind) { |
13227 | assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || |
13228 | QT.hasNonTrivialToPrimitiveDestructCUnion() || |
13229 | QT.hasNonTrivialToPrimitiveCopyCUnion()) && |
13230 | "shouldn't be called if type doesn't have a non-trivial C union" ); |
13231 | |
13232 | if ((NonTrivialKind & NTCUK_Init) && |
13233 | QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) |
13234 | DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) |
13235 | .visit(FT: QT, Args: nullptr, Args: false); |
13236 | if ((NonTrivialKind & NTCUK_Destruct) && |
13237 | QT.hasNonTrivialToPrimitiveDestructCUnion()) |
13238 | DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) |
13239 | .visit(FT: QT, Args: nullptr, Args: false); |
13240 | if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) |
13241 | DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) |
13242 | .visit(FT: QT, Args: nullptr, Args: false); |
13243 | } |
13244 | |
13245 | void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { |
13246 | // If there is no declaration, there was an error parsing it. Just ignore |
13247 | // the initializer. |
13248 | if (!RealDecl) { |
13249 | CorrectDelayedTyposInExpr(E: Init, InitDecl: dyn_cast_or_null<VarDecl>(Val: RealDecl)); |
13250 | return; |
13251 | } |
13252 | |
13253 | if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) { |
13254 | if (!Method->isInvalidDecl()) { |
13255 | // Pure-specifiers are handled in ActOnPureSpecifier. |
13256 | Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization) |
13257 | << Method->getDeclName() << Init->getSourceRange(); |
13258 | Method->setInvalidDecl(); |
13259 | } |
13260 | return; |
13261 | } |
13262 | |
13263 | VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl); |
13264 | if (!VDecl) { |
13265 | assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here" ); |
13266 | Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer); |
13267 | RealDecl->setInvalidDecl(); |
13268 | return; |
13269 | } |
13270 | |
13271 | if (VDecl->isInvalidDecl()) { |
13272 | ExprResult Res = CorrectDelayedTyposInExpr(E: Init, InitDecl: VDecl); |
13273 | SmallVector<Expr *> SubExprs; |
13274 | if (Res.isUsable()) |
13275 | SubExprs.push_back(Elt: Res.get()); |
13276 | ExprResult Recovery = |
13277 | CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs); |
13278 | if (Expr *E = Recovery.get()) |
13279 | VDecl->setInit(E); |
13280 | return; |
13281 | } |
13282 | |
13283 | // WebAssembly tables can't be used to initialise a variable. |
13284 | if (Init && !Init->getType().isNull() && |
13285 | Init->getType()->isWebAssemblyTableType()) { |
13286 | Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0; |
13287 | VDecl->setInvalidDecl(); |
13288 | return; |
13289 | } |
13290 | |
13291 | // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. |
13292 | if (VDecl->getType()->isUndeducedType()) { |
13293 | // Attempt typo correction early so that the type of the init expression can |
13294 | // be deduced based on the chosen correction if the original init contains a |
13295 | // TypoExpr. |
13296 | ExprResult Res = CorrectDelayedTyposInExpr(E: Init, InitDecl: VDecl); |
13297 | if (!Res.isUsable()) { |
13298 | // There are unresolved typos in Init, just drop them. |
13299 | // FIXME: improve the recovery strategy to preserve the Init. |
13300 | RealDecl->setInvalidDecl(); |
13301 | return; |
13302 | } |
13303 | if (Res.get()->containsErrors()) { |
13304 | // Invalidate the decl as we don't know the type for recovery-expr yet. |
13305 | RealDecl->setInvalidDecl(); |
13306 | VDecl->setInit(Res.get()); |
13307 | return; |
13308 | } |
13309 | Init = Res.get(); |
13310 | |
13311 | if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) |
13312 | return; |
13313 | } |
13314 | |
13315 | // dllimport cannot be used on variable definitions. |
13316 | if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { |
13317 | Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition); |
13318 | VDecl->setInvalidDecl(); |
13319 | return; |
13320 | } |
13321 | |
13322 | // C99 6.7.8p5. If the declaration of an identifier has block scope, and |
13323 | // the identifier has external or internal linkage, the declaration shall |
13324 | // have no initializer for the identifier. |
13325 | // C++14 [dcl.init]p5 is the same restriction for C++. |
13326 | if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { |
13327 | Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init); |
13328 | VDecl->setInvalidDecl(); |
13329 | return; |
13330 | } |
13331 | |
13332 | if (!VDecl->getType()->isDependentType()) { |
13333 | // A definition must end up with a complete type, which means it must be |
13334 | // complete with the restriction that an array type might be completed by |
13335 | // the initializer; note that later code assumes this restriction. |
13336 | QualType BaseDeclType = VDecl->getType(); |
13337 | if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType)) |
13338 | BaseDeclType = Array->getElementType(); |
13339 | if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType, |
13340 | DiagID: diag::err_typecheck_decl_incomplete_type)) { |
13341 | RealDecl->setInvalidDecl(); |
13342 | return; |
13343 | } |
13344 | |
13345 | // The variable can not have an abstract class type. |
13346 | if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(), |
13347 | DiagID: diag::err_abstract_type_in_decl, |
13348 | Args: AbstractVariableType)) |
13349 | VDecl->setInvalidDecl(); |
13350 | } |
13351 | |
13352 | // C++ [module.import/6] external definitions are not permitted in header |
13353 | // units. |
13354 | if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() && |
13355 | !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() && |
13356 | VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() && |
13357 | !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) && |
13358 | !VDecl->getInstantiatedFromStaticDataMember()) { |
13359 | Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit); |
13360 | VDecl->setInvalidDecl(); |
13361 | } |
13362 | |
13363 | // If adding the initializer will turn this declaration into a definition, |
13364 | // and we already have a definition for this variable, diagnose or otherwise |
13365 | // handle the situation. |
13366 | if (VarDecl *Def = VDecl->getDefinition()) |
13367 | if (Def != VDecl && |
13368 | (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && |
13369 | !VDecl->isThisDeclarationADemotedDefinition() && |
13370 | checkVarDeclRedefinition(Old: Def, New: VDecl)) |
13371 | return; |
13372 | |
13373 | if (getLangOpts().CPlusPlus) { |
13374 | // C++ [class.static.data]p4 |
13375 | // If a static data member is of const integral or const |
13376 | // enumeration type, its declaration in the class definition can |
13377 | // specify a constant-initializer which shall be an integral |
13378 | // constant expression (5.19). In that case, the member can appear |
13379 | // in integral constant expressions. The member shall still be |
13380 | // defined in a namespace scope if it is used in the program and the |
13381 | // namespace scope definition shall not contain an initializer. |
13382 | // |
13383 | // We already performed a redefinition check above, but for static |
13384 | // data members we also need to check whether there was an in-class |
13385 | // declaration with an initializer. |
13386 | if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { |
13387 | Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization) |
13388 | << VDecl->getDeclName(); |
13389 | Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(), |
13390 | DiagID: diag::note_previous_initializer) |
13391 | << 0; |
13392 | return; |
13393 | } |
13394 | |
13395 | if (VDecl->hasLocalStorage()) |
13396 | setFunctionHasBranchProtectedScope(); |
13397 | |
13398 | if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) { |
13399 | VDecl->setInvalidDecl(); |
13400 | return; |
13401 | } |
13402 | } |
13403 | |
13404 | // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside |
13405 | // a kernel function cannot be initialized." |
13406 | if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { |
13407 | Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init); |
13408 | VDecl->setInvalidDecl(); |
13409 | return; |
13410 | } |
13411 | |
13412 | // The LoaderUninitialized attribute acts as a definition (of undef). |
13413 | if (VDecl->hasAttr<LoaderUninitializedAttr>()) { |
13414 | Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init); |
13415 | VDecl->setInvalidDecl(); |
13416 | return; |
13417 | } |
13418 | |
13419 | // Get the decls type and save a reference for later, since |
13420 | // CheckInitializerTypes may change it. |
13421 | QualType DclT = VDecl->getType(), SavT = DclT; |
13422 | |
13423 | // Expressions default to 'id' when we're in a debugger |
13424 | // and we are assigning it to a variable of Objective-C pointer type. |
13425 | if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && |
13426 | Init->getType() == Context.UnknownAnyTy) { |
13427 | ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType()); |
13428 | if (Result.isInvalid()) { |
13429 | VDecl->setInvalidDecl(); |
13430 | return; |
13431 | } |
13432 | Init = Result.get(); |
13433 | } |
13434 | |
13435 | // Perform the initialization. |
13436 | ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init); |
13437 | bool IsParenListInit = false; |
13438 | if (!VDecl->isInvalidDecl()) { |
13439 | InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl); |
13440 | InitializationKind Kind = InitializationKind::CreateForInit( |
13441 | Loc: VDecl->getLocation(), DirectInit, Init); |
13442 | |
13443 | MultiExprArg Args = Init; |
13444 | if (CXXDirectInit) |
13445 | Args = MultiExprArg(CXXDirectInit->getExprs(), |
13446 | CXXDirectInit->getNumExprs()); |
13447 | |
13448 | // Try to correct any TypoExprs in the initialization arguments. |
13449 | for (size_t Idx = 0; Idx < Args.size(); ++Idx) { |
13450 | ExprResult Res = CorrectDelayedTyposInExpr( |
13451 | E: Args[Idx], InitDecl: VDecl, /*RecoverUncorrectedTypos=*/true, |
13452 | Filter: [this, Entity, Kind](Expr *E) { |
13453 | InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); |
13454 | return Init.Failed() ? ExprError() : E; |
13455 | }); |
13456 | if (Res.isInvalid()) { |
13457 | VDecl->setInvalidDecl(); |
13458 | } else if (Res.get() != Args[Idx]) { |
13459 | Args[Idx] = Res.get(); |
13460 | } |
13461 | } |
13462 | if (VDecl->isInvalidDecl()) |
13463 | return; |
13464 | |
13465 | InitializationSequence InitSeq(*this, Entity, Kind, Args, |
13466 | /*TopLevelOfInitList=*/false, |
13467 | /*TreatUnavailableAsInvalid=*/false); |
13468 | ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT); |
13469 | if (Result.isInvalid()) { |
13470 | // If the provided initializer fails to initialize the var decl, |
13471 | // we attach a recovery expr for better recovery. |
13472 | auto RecoveryExpr = |
13473 | CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args); |
13474 | if (RecoveryExpr.get()) |
13475 | VDecl->setInit(RecoveryExpr.get()); |
13476 | // In general, for error recovery purposes, the initializer doesn't play |
13477 | // part in the valid bit of the declaration. There are a few exceptions: |
13478 | // 1) if the var decl has a deduced auto type, and the type cannot be |
13479 | // deduced by an invalid initializer; |
13480 | // 2) if the var decl is a decomposition decl with a non-deduced type, |
13481 | // and the initialization fails (e.g. `int [a] = {1, 2};`); |
13482 | // Case 1) was already handled elsewhere. |
13483 | if (isa<DecompositionDecl>(Val: VDecl)) // Case 2) |
13484 | VDecl->setInvalidDecl(); |
13485 | return; |
13486 | } |
13487 | |
13488 | Init = Result.getAs<Expr>(); |
13489 | IsParenListInit = !InitSeq.steps().empty() && |
13490 | InitSeq.step_begin()->Kind == |
13491 | InitializationSequence::SK_ParenthesizedListInit; |
13492 | QualType VDeclType = VDecl->getType(); |
13493 | if (Init && !Init->getType().isNull() && |
13494 | !Init->getType()->isDependentType() && !VDeclType->isDependentType() && |
13495 | Context.getAsIncompleteArrayType(T: VDeclType) && |
13496 | Context.getAsIncompleteArrayType(T: Init->getType())) { |
13497 | // Bail out if it is not possible to deduce array size from the |
13498 | // initializer. |
13499 | Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type) |
13500 | << VDeclType; |
13501 | VDecl->setInvalidDecl(); |
13502 | return; |
13503 | } |
13504 | } |
13505 | |
13506 | // Check for self-references within variable initializers. |
13507 | // Variables declared within a function/method body (except for references) |
13508 | // are handled by a dataflow analysis. |
13509 | // This is undefined behavior in C++, but valid in C. |
13510 | if (getLangOpts().CPlusPlus) |
13511 | if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || |
13512 | VDecl->getType()->isReferenceType()) |
13513 | CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit); |
13514 | |
13515 | // If the type changed, it means we had an incomplete type that was |
13516 | // completed by the initializer. For example: |
13517 | // int ary[] = { 1, 3, 5 }; |
13518 | // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. |
13519 | if (!VDecl->isInvalidDecl() && (DclT != SavT)) |
13520 | VDecl->setType(DclT); |
13521 | |
13522 | if (!VDecl->isInvalidDecl()) { |
13523 | checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init); |
13524 | |
13525 | if (VDecl->hasAttr<BlocksAttr>()) |
13526 | ObjC().checkRetainCycles(Var: VDecl, Init); |
13527 | |
13528 | // It is safe to assign a weak reference into a strong variable. |
13529 | // Although this code can still have problems: |
13530 | // id x = self.weakProp; |
13531 | // id y = self.weakProp; |
13532 | // we do not warn to warn spuriously when 'x' and 'y' are on separate |
13533 | // paths through the function. This should be revisited if |
13534 | // -Wrepeated-use-of-weak is made flow-sensitive. |
13535 | if (FunctionScopeInfo *FSI = getCurFunction()) |
13536 | if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || |
13537 | VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && |
13538 | !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, |
13539 | Loc: Init->getBeginLoc())) |
13540 | FSI->markSafeWeakUse(E: Init); |
13541 | } |
13542 | |
13543 | // The initialization is usually a full-expression. |
13544 | // |
13545 | // FIXME: If this is a braced initialization of an aggregate, it is not |
13546 | // an expression, and each individual field initializer is a separate |
13547 | // full-expression. For instance, in: |
13548 | // |
13549 | // struct Temp { ~Temp(); }; |
13550 | // struct S { S(Temp); }; |
13551 | // struct T { S a, b; } t = { Temp(), Temp() } |
13552 | // |
13553 | // we should destroy the first Temp before constructing the second. |
13554 | ExprResult Result = |
13555 | ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(), |
13556 | /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr()); |
13557 | if (Result.isInvalid()) { |
13558 | VDecl->setInvalidDecl(); |
13559 | return; |
13560 | } |
13561 | Init = Result.get(); |
13562 | |
13563 | // Attach the initializer to the decl. |
13564 | VDecl->setInit(Init); |
13565 | |
13566 | if (VDecl->isLocalVarDecl()) { |
13567 | // Don't check the initializer if the declaration is malformed. |
13568 | if (VDecl->isInvalidDecl()) { |
13569 | // do nothing |
13570 | |
13571 | // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. |
13572 | // This is true even in C++ for OpenCL. |
13573 | } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { |
13574 | CheckForConstantInitializer(Init); |
13575 | |
13576 | // Otherwise, C++ does not restrict the initializer. |
13577 | } else if (getLangOpts().CPlusPlus) { |
13578 | // do nothing |
13579 | |
13580 | // C99 6.7.8p4: All the expressions in an initializer for an object that has |
13581 | // static storage duration shall be constant expressions or string literals. |
13582 | } else if (VDecl->getStorageClass() == SC_Static) { |
13583 | CheckForConstantInitializer(Init); |
13584 | |
13585 | // C89 is stricter than C99 for aggregate initializers. |
13586 | // C89 6.5.7p3: All the expressions [...] in an initializer list |
13587 | // for an object that has aggregate or union type shall be |
13588 | // constant expressions. |
13589 | } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && |
13590 | isa<InitListExpr>(Val: Init)) { |
13591 | CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant); |
13592 | } |
13593 | |
13594 | if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init)) |
13595 | if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens())) |
13596 | if (VDecl->hasLocalStorage()) |
13597 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); |
13598 | } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && |
13599 | VDecl->getLexicalDeclContext()->isRecord()) { |
13600 | // This is an in-class initialization for a static data member, e.g., |
13601 | // |
13602 | // struct S { |
13603 | // static const int value = 17; |
13604 | // }; |
13605 | |
13606 | // C++ [class.mem]p4: |
13607 | // A member-declarator can contain a constant-initializer only |
13608 | // if it declares a static member (9.4) of const integral or |
13609 | // const enumeration type, see 9.4.2. |
13610 | // |
13611 | // C++11 [class.static.data]p3: |
13612 | // If a non-volatile non-inline const static data member is of integral |
13613 | // or enumeration type, its declaration in the class definition can |
13614 | // specify a brace-or-equal-initializer in which every initializer-clause |
13615 | // that is an assignment-expression is a constant expression. A static |
13616 | // data member of literal type can be declared in the class definition |
13617 | // with the constexpr specifier; if so, its declaration shall specify a |
13618 | // brace-or-equal-initializer in which every initializer-clause that is |
13619 | // an assignment-expression is a constant expression. |
13620 | |
13621 | // Do nothing on dependent types. |
13622 | if (DclT->isDependentType()) { |
13623 | |
13624 | // Allow any 'static constexpr' members, whether or not they are of literal |
13625 | // type. We separately check that every constexpr variable is of literal |
13626 | // type. |
13627 | } else if (VDecl->isConstexpr()) { |
13628 | |
13629 | // Require constness. |
13630 | } else if (!DclT.isConstQualified()) { |
13631 | Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const) |
13632 | << Init->getSourceRange(); |
13633 | VDecl->setInvalidDecl(); |
13634 | |
13635 | // We allow integer constant expressions in all cases. |
13636 | } else if (DclT->isIntegralOrEnumerationType()) { |
13637 | // Check whether the expression is a constant expression. |
13638 | SourceLocation Loc; |
13639 | if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) |
13640 | // In C++11, a non-constexpr const static data member with an |
13641 | // in-class initializer cannot be volatile. |
13642 | Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile); |
13643 | else if (Init->isValueDependent()) |
13644 | ; // Nothing to check. |
13645 | else if (Init->isIntegerConstantExpr(Ctx: Context, Loc: &Loc)) |
13646 | ; // Ok, it's an ICE! |
13647 | else if (Init->getType()->isScopedEnumeralType() && |
13648 | Init->isCXX11ConstantExpr(Ctx: Context)) |
13649 | ; // Ok, it is a scoped-enum constant expression. |
13650 | else if (Init->isEvaluatable(Ctx: Context)) { |
13651 | // If we can constant fold the initializer through heroics, accept it, |
13652 | // but report this as a use of an extension for -pedantic. |
13653 | Diag(Loc, DiagID: diag::ext_in_class_initializer_non_constant) |
13654 | << Init->getSourceRange(); |
13655 | } else { |
13656 | // Otherwise, this is some crazy unknown case. Report the issue at the |
13657 | // location provided by the isIntegerConstantExpr failed check. |
13658 | Diag(Loc, DiagID: diag::err_in_class_initializer_non_constant) |
13659 | << Init->getSourceRange(); |
13660 | VDecl->setInvalidDecl(); |
13661 | } |
13662 | |
13663 | // We allow foldable floating-point constants as an extension. |
13664 | } else if (DclT->isFloatingType()) { // also permits complex, which is ok |
13665 | // In C++98, this is a GNU extension. In C++11, it is not, but we support |
13666 | // it anyway and provide a fixit to add the 'constexpr'. |
13667 | if (getLangOpts().CPlusPlus11) { |
13668 | Diag(Loc: VDecl->getLocation(), |
13669 | DiagID: diag::ext_in_class_initializer_float_type_cxx11) |
13670 | << DclT << Init->getSourceRange(); |
13671 | Diag(Loc: VDecl->getBeginLoc(), |
13672 | DiagID: diag::note_in_class_initializer_float_type_cxx11) |
13673 | << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr " ); |
13674 | } else { |
13675 | Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type) |
13676 | << DclT << Init->getSourceRange(); |
13677 | |
13678 | if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) { |
13679 | Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant) |
13680 | << Init->getSourceRange(); |
13681 | VDecl->setInvalidDecl(); |
13682 | } |
13683 | } |
13684 | |
13685 | // Suggest adding 'constexpr' in C++11 for literal types. |
13686 | } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) { |
13687 | Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type) |
13688 | << DclT << Init->getSourceRange() |
13689 | << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr " ); |
13690 | VDecl->setConstexpr(true); |
13691 | |
13692 | } else { |
13693 | Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type) |
13694 | << DclT << Init->getSourceRange(); |
13695 | VDecl->setInvalidDecl(); |
13696 | } |
13697 | } else if (VDecl->isFileVarDecl()) { |
13698 | // In C, extern is typically used to avoid tentative definitions when |
13699 | // declaring variables in headers, but adding an initializer makes it a |
13700 | // definition. This is somewhat confusing, so GCC and Clang both warn on it. |
13701 | // In C++, extern is often used to give implicitly static const variables |
13702 | // external linkage, so don't warn in that case. If selectany is present, |
13703 | // this might be header code intended for C and C++ inclusion, so apply the |
13704 | // C++ rules. |
13705 | if (VDecl->getStorageClass() == SC_Extern && |
13706 | ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || |
13707 | !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) && |
13708 | !(getLangOpts().CPlusPlus && VDecl->isExternC()) && |
13709 | !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind())) |
13710 | Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init); |
13711 | |
13712 | // In Microsoft C++ mode, a const variable defined in namespace scope has |
13713 | // external linkage by default if the variable is declared with |
13714 | // __declspec(dllexport). |
13715 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && |
13716 | getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && |
13717 | VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) |
13718 | VDecl->setStorageClass(SC_Extern); |
13719 | |
13720 | // C99 6.7.8p4. All file scoped initializers need to be constant. |
13721 | // Avoid duplicate diagnostics for constexpr variables. |
13722 | if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() && |
13723 | !VDecl->isConstexpr()) |
13724 | CheckForConstantInitializer(Init); |
13725 | } |
13726 | |
13727 | QualType InitType = Init->getType(); |
13728 | if (!InitType.isNull() && |
13729 | (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || |
13730 | InitType.hasNonTrivialToPrimitiveCopyCUnion())) |
13731 | checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc()); |
13732 | |
13733 | // We will represent direct-initialization similarly to copy-initialization: |
13734 | // int x(1); -as-> int x = 1; |
13735 | // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); |
13736 | // |
13737 | // Clients that want to distinguish between the two forms, can check for |
13738 | // direct initializer using VarDecl::getInitStyle(). |
13739 | // A major benefit is that clients that don't particularly care about which |
13740 | // exactly form was it (like the CodeGen) can handle both cases without |
13741 | // special case code. |
13742 | |
13743 | // C++ 8.5p11: |
13744 | // The form of initialization (using parentheses or '=') is generally |
13745 | // insignificant, but does matter when the entity being initialized has a |
13746 | // class type. |
13747 | if (CXXDirectInit) { |
13748 | assert(DirectInit && "Call-style initializer must be direct init." ); |
13749 | VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit |
13750 | : VarDecl::CallInit); |
13751 | } else if (DirectInit) { |
13752 | // This must be list-initialization. No other way is direct-initialization. |
13753 | VDecl->setInitStyle(VarDecl::ListInit); |
13754 | } |
13755 | |
13756 | if (LangOpts.OpenMP && |
13757 | (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) && |
13758 | VDecl->isFileVarDecl()) |
13759 | DeclsToCheckForDeferredDiags.insert(X: VDecl); |
13760 | CheckCompleteVariableDeclaration(VD: VDecl); |
13761 | } |
13762 | |
13763 | void Sema::ActOnInitializerError(Decl *D) { |
13764 | // Our main concern here is re-establishing invariants like "a |
13765 | // variable's type is either dependent or complete". |
13766 | if (!D || D->isInvalidDecl()) return; |
13767 | |
13768 | VarDecl *VD = dyn_cast<VarDecl>(Val: D); |
13769 | if (!VD) return; |
13770 | |
13771 | // Bindings are not usable if we can't make sense of the initializer. |
13772 | if (auto *DD = dyn_cast<DecompositionDecl>(Val: D)) |
13773 | for (auto *BD : DD->bindings()) |
13774 | BD->setInvalidDecl(); |
13775 | |
13776 | // Auto types are meaningless if we can't make sense of the initializer. |
13777 | if (VD->getType()->isUndeducedType()) { |
13778 | D->setInvalidDecl(); |
13779 | return; |
13780 | } |
13781 | |
13782 | QualType Ty = VD->getType(); |
13783 | if (Ty->isDependentType()) return; |
13784 | |
13785 | // Require a complete type. |
13786 | if (RequireCompleteType(Loc: VD->getLocation(), |
13787 | T: Context.getBaseElementType(QT: Ty), |
13788 | DiagID: diag::err_typecheck_decl_incomplete_type)) { |
13789 | VD->setInvalidDecl(); |
13790 | return; |
13791 | } |
13792 | |
13793 | // Require a non-abstract type. |
13794 | if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty, |
13795 | DiagID: diag::err_abstract_type_in_decl, |
13796 | Args: AbstractVariableType)) { |
13797 | VD->setInvalidDecl(); |
13798 | return; |
13799 | } |
13800 | |
13801 | // Don't bother complaining about constructors or destructors, |
13802 | // though. |
13803 | } |
13804 | |
13805 | void Sema::ActOnUninitializedDecl(Decl *RealDecl) { |
13806 | // If there is no declaration, there was an error parsing it. Just ignore it. |
13807 | if (!RealDecl) |
13808 | return; |
13809 | |
13810 | if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) { |
13811 | QualType Type = Var->getType(); |
13812 | |
13813 | // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. |
13814 | if (isa<DecompositionDecl>(Val: RealDecl)) { |
13815 | Diag(Loc: Var->getLocation(), DiagID: diag::err_decomp_decl_requires_init) << Var; |
13816 | Var->setInvalidDecl(); |
13817 | return; |
13818 | } |
13819 | |
13820 | if (Type->isUndeducedType() && |
13821 | DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr)) |
13822 | return; |
13823 | |
13824 | // C++11 [class.static.data]p3: A static data member can be declared with |
13825 | // the constexpr specifier; if so, its declaration shall specify |
13826 | // a brace-or-equal-initializer. |
13827 | // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to |
13828 | // the definition of a variable [...] or the declaration of a static data |
13829 | // member. |
13830 | if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && |
13831 | !Var->isThisDeclarationADemotedDefinition()) { |
13832 | if (Var->isStaticDataMember()) { |
13833 | // C++1z removes the relevant rule; the in-class declaration is always |
13834 | // a definition there. |
13835 | if (!getLangOpts().CPlusPlus17 && |
13836 | !Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
13837 | Diag(Loc: Var->getLocation(), |
13838 | DiagID: diag::err_constexpr_static_mem_var_requires_init) |
13839 | << Var; |
13840 | Var->setInvalidDecl(); |
13841 | return; |
13842 | } |
13843 | } else { |
13844 | Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl); |
13845 | Var->setInvalidDecl(); |
13846 | return; |
13847 | } |
13848 | } |
13849 | |
13850 | // OpenCL v1.1 s6.5.3: variables declared in the constant address space must |
13851 | // be initialized. |
13852 | if (!Var->isInvalidDecl() && |
13853 | Var->getType().getAddressSpace() == LangAS::opencl_constant && |
13854 | Var->getStorageClass() != SC_Extern && !Var->getInit()) { |
13855 | bool HasConstExprDefaultConstructor = false; |
13856 | if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { |
13857 | for (auto *Ctor : RD->ctors()) { |
13858 | if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && |
13859 | Ctor->getMethodQualifiers().getAddressSpace() == |
13860 | LangAS::opencl_constant) { |
13861 | HasConstExprDefaultConstructor = true; |
13862 | } |
13863 | } |
13864 | } |
13865 | if (!HasConstExprDefaultConstructor) { |
13866 | Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init); |
13867 | Var->setInvalidDecl(); |
13868 | return; |
13869 | } |
13870 | } |
13871 | |
13872 | if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { |
13873 | if (Var->getStorageClass() == SC_Extern) { |
13874 | Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl) |
13875 | << Var; |
13876 | Var->setInvalidDecl(); |
13877 | return; |
13878 | } |
13879 | if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(), |
13880 | DiagID: diag::err_typecheck_decl_incomplete_type)) { |
13881 | Var->setInvalidDecl(); |
13882 | return; |
13883 | } |
13884 | if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { |
13885 | if (!RD->hasTrivialDefaultConstructor()) { |
13886 | Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor); |
13887 | Var->setInvalidDecl(); |
13888 | return; |
13889 | } |
13890 | } |
13891 | // The declaration is uninitialized, no need for further checks. |
13892 | return; |
13893 | } |
13894 | |
13895 | VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); |
13896 | if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && |
13897 | Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) |
13898 | checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(), |
13899 | UseContext: NTCUC_DefaultInitializedObject, NonTrivialKind: NTCUK_Init); |
13900 | |
13901 | |
13902 | switch (DefKind) { |
13903 | case VarDecl::Definition: |
13904 | if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) |
13905 | break; |
13906 | |
13907 | // We have an out-of-line definition of a static data member |
13908 | // that has an in-class initializer, so we type-check this like |
13909 | // a declaration. |
13910 | // |
13911 | [[fallthrough]]; |
13912 | |
13913 | case VarDecl::DeclarationOnly: |
13914 | // It's only a declaration. |
13915 | |
13916 | // Block scope. C99 6.7p7: If an identifier for an object is |
13917 | // declared with no linkage (C99 6.2.2p6), the type for the |
13918 | // object shall be complete. |
13919 | if (!Type->isDependentType() && Var->isLocalVarDecl() && |
13920 | !Var->hasLinkage() && !Var->isInvalidDecl() && |
13921 | RequireCompleteType(Loc: Var->getLocation(), T: Type, |
13922 | DiagID: diag::err_typecheck_decl_incomplete_type)) |
13923 | Var->setInvalidDecl(); |
13924 | |
13925 | // Make sure that the type is not abstract. |
13926 | if (!Type->isDependentType() && !Var->isInvalidDecl() && |
13927 | RequireNonAbstractType(Loc: Var->getLocation(), T: Type, |
13928 | DiagID: diag::err_abstract_type_in_decl, |
13929 | Args: AbstractVariableType)) |
13930 | Var->setInvalidDecl(); |
13931 | if (!Type->isDependentType() && !Var->isInvalidDecl() && |
13932 | Var->getStorageClass() == SC_PrivateExtern) { |
13933 | Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern); |
13934 | Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern); |
13935 | } |
13936 | |
13937 | if (Context.getTargetInfo().allowDebugInfoForExternalRef() && |
13938 | !Var->isInvalidDecl()) |
13939 | ExternalDeclarations.push_back(Elt: Var); |
13940 | |
13941 | return; |
13942 | |
13943 | case VarDecl::TentativeDefinition: |
13944 | // File scope. C99 6.9.2p2: A declaration of an identifier for an |
13945 | // object that has file scope without an initializer, and without a |
13946 | // storage-class specifier or with the storage-class specifier "static", |
13947 | // constitutes a tentative definition. Note: A tentative definition with |
13948 | // external linkage is valid (C99 6.2.2p5). |
13949 | if (!Var->isInvalidDecl()) { |
13950 | if (const IncompleteArrayType *ArrayT |
13951 | = Context.getAsIncompleteArrayType(T: Type)) { |
13952 | if (RequireCompleteSizedType( |
13953 | Loc: Var->getLocation(), T: ArrayT->getElementType(), |
13954 | DiagID: diag::err_array_incomplete_or_sizeless_type)) |
13955 | Var->setInvalidDecl(); |
13956 | } else if (Var->getStorageClass() == SC_Static) { |
13957 | // C99 6.9.2p3: If the declaration of an identifier for an object is |
13958 | // a tentative definition and has internal linkage (C99 6.2.2p3), the |
13959 | // declared type shall not be an incomplete type. |
13960 | // NOTE: code such as the following |
13961 | // static struct s; |
13962 | // struct s { int a; }; |
13963 | // is accepted by gcc. Hence here we issue a warning instead of |
13964 | // an error and we do not invalidate the static declaration. |
13965 | // NOTE: to avoid multiple warnings, only check the first declaration. |
13966 | if (Var->isFirstDecl()) |
13967 | RequireCompleteType(Loc: Var->getLocation(), T: Type, |
13968 | DiagID: diag::ext_typecheck_decl_incomplete_type); |
13969 | } |
13970 | } |
13971 | |
13972 | // Record the tentative definition; we're done. |
13973 | if (!Var->isInvalidDecl()) |
13974 | TentativeDefinitions.push_back(LocalValue: Var); |
13975 | return; |
13976 | } |
13977 | |
13978 | // Provide a specific diagnostic for uninitialized variable |
13979 | // definitions with incomplete array type. |
13980 | if (Type->isIncompleteArrayType()) { |
13981 | if (Var->isConstexpr()) |
13982 | Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init) |
13983 | << Var; |
13984 | else |
13985 | Diag(Loc: Var->getLocation(), |
13986 | DiagID: diag::err_typecheck_incomplete_array_needs_initializer); |
13987 | Var->setInvalidDecl(); |
13988 | return; |
13989 | } |
13990 | |
13991 | // Provide a specific diagnostic for uninitialized variable |
13992 | // definitions with reference type. |
13993 | if (Type->isReferenceType()) { |
13994 | Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init) |
13995 | << Var << SourceRange(Var->getLocation(), Var->getLocation()); |
13996 | return; |
13997 | } |
13998 | |
13999 | // Do not attempt to type-check the default initializer for a |
14000 | // variable with dependent type. |
14001 | if (Type->isDependentType()) |
14002 | return; |
14003 | |
14004 | if (Var->isInvalidDecl()) |
14005 | return; |
14006 | |
14007 | if (!Var->hasAttr<AliasAttr>()) { |
14008 | if (RequireCompleteType(Loc: Var->getLocation(), |
14009 | T: Context.getBaseElementType(QT: Type), |
14010 | DiagID: diag::err_typecheck_decl_incomplete_type)) { |
14011 | Var->setInvalidDecl(); |
14012 | return; |
14013 | } |
14014 | } else { |
14015 | return; |
14016 | } |
14017 | |
14018 | // The variable can not have an abstract class type. |
14019 | if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type, |
14020 | DiagID: diag::err_abstract_type_in_decl, |
14021 | Args: AbstractVariableType)) { |
14022 | Var->setInvalidDecl(); |
14023 | return; |
14024 | } |
14025 | |
14026 | // Check for jumps past the implicit initializer. C++0x |
14027 | // clarifies that this applies to a "variable with automatic |
14028 | // storage duration", not a "local variable". |
14029 | // C++11 [stmt.dcl]p3 |
14030 | // A program that jumps from a point where a variable with automatic |
14031 | // storage duration is not in scope to a point where it is in scope is |
14032 | // ill-formed unless the variable has scalar type, class type with a |
14033 | // trivial default constructor and a trivial destructor, a cv-qualified |
14034 | // version of one of these types, or an array of one of the preceding |
14035 | // types and is declared without an initializer. |
14036 | if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { |
14037 | if (const RecordType *Record |
14038 | = Context.getBaseElementType(QT: Type)->getAs<RecordType>()) { |
14039 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record->getDecl()); |
14040 | // Mark the function (if we're in one) for further checking even if the |
14041 | // looser rules of C++11 do not require such checks, so that we can |
14042 | // diagnose incompatibilities with C++98. |
14043 | if (!CXXRecord->isPOD()) |
14044 | setFunctionHasBranchProtectedScope(); |
14045 | } |
14046 | } |
14047 | // In OpenCL, we can't initialize objects in the __local address space, |
14048 | // even implicitly, so don't synthesize an implicit initializer. |
14049 | if (getLangOpts().OpenCL && |
14050 | Var->getType().getAddressSpace() == LangAS::opencl_local) |
14051 | return; |
14052 | // C++03 [dcl.init]p9: |
14053 | // If no initializer is specified for an object, and the |
14054 | // object is of (possibly cv-qualified) non-POD class type (or |
14055 | // array thereof), the object shall be default-initialized; if |
14056 | // the object is of const-qualified type, the underlying class |
14057 | // type shall have a user-declared default |
14058 | // constructor. Otherwise, if no initializer is specified for |
14059 | // a non- static object, the object and its subobjects, if |
14060 | // any, have an indeterminate initial value); if the object |
14061 | // or any of its subobjects are of const-qualified type, the |
14062 | // program is ill-formed. |
14063 | // C++0x [dcl.init]p11: |
14064 | // If no initializer is specified for an object, the object is |
14065 | // default-initialized; [...]. |
14066 | InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); |
14067 | InitializationKind Kind |
14068 | = InitializationKind::CreateDefault(InitLoc: Var->getLocation()); |
14069 | |
14070 | InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt); |
14071 | ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: std::nullopt); |
14072 | |
14073 | if (Init.get()) { |
14074 | Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get())); |
14075 | // This is important for template substitution. |
14076 | Var->setInitStyle(VarDecl::CallInit); |
14077 | } else if (Init.isInvalid()) { |
14078 | // If default-init fails, attach a recovery-expr initializer to track |
14079 | // that initialization was attempted and failed. |
14080 | auto RecoveryExpr = |
14081 | CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {}); |
14082 | if (RecoveryExpr.get()) |
14083 | Var->setInit(RecoveryExpr.get()); |
14084 | } |
14085 | |
14086 | CheckCompleteVariableDeclaration(VD: Var); |
14087 | } |
14088 | } |
14089 | |
14090 | void Sema::ActOnCXXForRangeDecl(Decl *D) { |
14091 | // If there is no declaration, there was an error parsing it. Ignore it. |
14092 | if (!D) |
14093 | return; |
14094 | |
14095 | VarDecl *VD = dyn_cast<VarDecl>(Val: D); |
14096 | if (!VD) { |
14097 | Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var); |
14098 | D->setInvalidDecl(); |
14099 | return; |
14100 | } |
14101 | |
14102 | VD->setCXXForRangeDecl(true); |
14103 | |
14104 | // for-range-declaration cannot be given a storage class specifier. |
14105 | int Error = -1; |
14106 | switch (VD->getStorageClass()) { |
14107 | case SC_None: |
14108 | break; |
14109 | case SC_Extern: |
14110 | Error = 0; |
14111 | break; |
14112 | case SC_Static: |
14113 | Error = 1; |
14114 | break; |
14115 | case SC_PrivateExtern: |
14116 | Error = 2; |
14117 | break; |
14118 | case SC_Auto: |
14119 | Error = 3; |
14120 | break; |
14121 | case SC_Register: |
14122 | Error = 4; |
14123 | break; |
14124 | } |
14125 | |
14126 | // for-range-declaration cannot be given a storage class specifier con't. |
14127 | switch (VD->getTSCSpec()) { |
14128 | case TSCS_thread_local: |
14129 | Error = 6; |
14130 | break; |
14131 | case TSCS___thread: |
14132 | case TSCS__Thread_local: |
14133 | case TSCS_unspecified: |
14134 | break; |
14135 | } |
14136 | |
14137 | if (Error != -1) { |
14138 | Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class) |
14139 | << VD << Error; |
14140 | D->setInvalidDecl(); |
14141 | } |
14142 | } |
14143 | |
14144 | StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, |
14145 | IdentifierInfo *Ident, |
14146 | ParsedAttributes &Attrs) { |
14147 | // C++1y [stmt.iter]p1: |
14148 | // A range-based for statement of the form |
14149 | // for ( for-range-identifier : for-range-initializer ) statement |
14150 | // is equivalent to |
14151 | // for ( auto&& for-range-identifier : for-range-initializer ) statement |
14152 | DeclSpec DS(Attrs.getPool().getFactory()); |
14153 | |
14154 | const char *PrevSpec; |
14155 | unsigned DiagID; |
14156 | DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID, |
14157 | Policy: getPrintingPolicy()); |
14158 | |
14159 | Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit); |
14160 | D.SetIdentifier(Id: Ident, IdLoc: IdentLoc); |
14161 | D.takeAttributes(attrs&: Attrs); |
14162 | |
14163 | D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false), |
14164 | EndLoc: IdentLoc); |
14165 | Decl *Var = ActOnDeclarator(S, D); |
14166 | cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true); |
14167 | FinalizeDeclaration(D: Var); |
14168 | return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc, |
14169 | EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd() |
14170 | : IdentLoc); |
14171 | } |
14172 | |
14173 | void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { |
14174 | if (var->isInvalidDecl()) return; |
14175 | |
14176 | CUDA().MaybeAddConstantAttr(VD: var); |
14177 | |
14178 | if (getLangOpts().OpenCL) { |
14179 | // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an |
14180 | // initialiser |
14181 | if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && |
14182 | !var->hasInit()) { |
14183 | Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration) |
14184 | << 1 /*Init*/; |
14185 | var->setInvalidDecl(); |
14186 | return; |
14187 | } |
14188 | } |
14189 | |
14190 | // In Objective-C, don't allow jumps past the implicit initialization of a |
14191 | // local retaining variable. |
14192 | if (getLangOpts().ObjC && |
14193 | var->hasLocalStorage()) { |
14194 | switch (var->getType().getObjCLifetime()) { |
14195 | case Qualifiers::OCL_None: |
14196 | case Qualifiers::OCL_ExplicitNone: |
14197 | case Qualifiers::OCL_Autoreleasing: |
14198 | break; |
14199 | |
14200 | case Qualifiers::OCL_Weak: |
14201 | case Qualifiers::OCL_Strong: |
14202 | setFunctionHasBranchProtectedScope(); |
14203 | break; |
14204 | } |
14205 | } |
14206 | |
14207 | if (var->hasLocalStorage() && |
14208 | var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) |
14209 | setFunctionHasBranchProtectedScope(); |
14210 | |
14211 | // Warn about externally-visible variables being defined without a |
14212 | // prior declaration. We only want to do this for global |
14213 | // declarations, but we also specifically need to avoid doing it for |
14214 | // class members because the linkage of an anonymous class can |
14215 | // change if it's later given a typedef name. |
14216 | if (var->isThisDeclarationADefinition() && |
14217 | var->getDeclContext()->getRedeclContext()->isFileContext() && |
14218 | var->isExternallyVisible() && var->hasLinkage() && |
14219 | !var->isInline() && !var->getDescribedVarTemplate() && |
14220 | var->getStorageClass() != SC_Register && |
14221 | !isa<VarTemplatePartialSpecializationDecl>(Val: var) && |
14222 | !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) && |
14223 | !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations, |
14224 | Loc: var->getLocation())) { |
14225 | // Find a previous declaration that's not a definition. |
14226 | VarDecl *prev = var->getPreviousDecl(); |
14227 | while (prev && prev->isThisDeclarationADefinition()) |
14228 | prev = prev->getPreviousDecl(); |
14229 | |
14230 | if (!prev) { |
14231 | Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var; |
14232 | Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage) |
14233 | << /* variable */ 0; |
14234 | } |
14235 | } |
14236 | |
14237 | // Cache the result of checking for constant initialization. |
14238 | std::optional<bool> CacheHasConstInit; |
14239 | const Expr *CacheCulprit = nullptr; |
14240 | auto checkConstInit = [&]() mutable { |
14241 | if (!CacheHasConstInit) |
14242 | CacheHasConstInit = var->getInit()->isConstantInitializer( |
14243 | Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit); |
14244 | return *CacheHasConstInit; |
14245 | }; |
14246 | |
14247 | if (var->getTLSKind() == VarDecl::TLS_Static) { |
14248 | if (var->getType().isDestructedType()) { |
14249 | // GNU C++98 edits for __thread, [basic.start.term]p3: |
14250 | // The type of an object with thread storage duration shall not |
14251 | // have a non-trivial destructor. |
14252 | Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor); |
14253 | if (getLangOpts().CPlusPlus11) |
14254 | Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local); |
14255 | } else if (getLangOpts().CPlusPlus && var->hasInit()) { |
14256 | if (!checkConstInit()) { |
14257 | // GNU C++98 edits for __thread, [basic.start.init]p4: |
14258 | // An object of thread storage duration shall not require dynamic |
14259 | // initialization. |
14260 | // FIXME: Need strict checking here. |
14261 | Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init) |
14262 | << CacheCulprit->getSourceRange(); |
14263 | if (getLangOpts().CPlusPlus11) |
14264 | Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local); |
14265 | } |
14266 | } |
14267 | } |
14268 | |
14269 | |
14270 | if (!var->getType()->isStructureType() && var->hasInit() && |
14271 | isa<InitListExpr>(Val: var->getInit())) { |
14272 | const auto *ILE = cast<InitListExpr>(Val: var->getInit()); |
14273 | unsigned NumInits = ILE->getNumInits(); |
14274 | if (NumInits > 2) |
14275 | for (unsigned I = 0; I < NumInits; ++I) { |
14276 | const auto *Init = ILE->getInit(Init: I); |
14277 | if (!Init) |
14278 | break; |
14279 | const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts()); |
14280 | if (!SL) |
14281 | break; |
14282 | |
14283 | unsigned NumConcat = SL->getNumConcatenated(); |
14284 | // Diagnose missing comma in string array initialization. |
14285 | // Do not warn when all the elements in the initializer are concatenated |
14286 | // together. Do not warn for macros too. |
14287 | if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { |
14288 | bool OnlyOneMissingComma = true; |
14289 | for (unsigned J = I + 1; J < NumInits; ++J) { |
14290 | const auto *Init = ILE->getInit(Init: J); |
14291 | if (!Init) |
14292 | break; |
14293 | const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts()); |
14294 | if (!SLJ || SLJ->getNumConcatenated() > 1) { |
14295 | OnlyOneMissingComma = false; |
14296 | break; |
14297 | } |
14298 | } |
14299 | |
14300 | if (OnlyOneMissingComma) { |
14301 | SmallVector<FixItHint, 1> Hints; |
14302 | for (unsigned i = 0; i < NumConcat - 1; ++i) |
14303 | Hints.push_back(Elt: FixItHint::CreateInsertion( |
14304 | InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: "," )); |
14305 | |
14306 | Diag(Loc: SL->getStrTokenLoc(TokNum: 1), |
14307 | DiagID: diag::warn_concatenated_literal_array_init) |
14308 | << Hints; |
14309 | Diag(Loc: SL->getBeginLoc(), |
14310 | DiagID: diag::note_concatenated_string_literal_silence); |
14311 | } |
14312 | // In any case, stop now. |
14313 | break; |
14314 | } |
14315 | } |
14316 | } |
14317 | |
14318 | |
14319 | QualType type = var->getType(); |
14320 | |
14321 | if (var->hasAttr<BlocksAttr>()) |
14322 | getCurFunction()->addByrefBlockVar(VD: var); |
14323 | |
14324 | Expr *Init = var->getInit(); |
14325 | bool GlobalStorage = var->hasGlobalStorage(); |
14326 | bool IsGlobal = GlobalStorage && !var->isStaticLocal(); |
14327 | QualType baseType = Context.getBaseElementType(QT: type); |
14328 | bool HasConstInit = true; |
14329 | |
14330 | if (getLangOpts().C23 && var->isConstexpr() && !Init) |
14331 | Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init) |
14332 | << var; |
14333 | |
14334 | // Check whether the initializer is sufficiently constant. |
14335 | if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) && |
14336 | !type->isDependentType() && Init && !Init->isValueDependent() && |
14337 | (GlobalStorage || var->isConstexpr() || |
14338 | var->mightBeUsableInConstantExpressions(C: Context))) { |
14339 | // If this variable might have a constant initializer or might be usable in |
14340 | // constant expressions, check whether or not it actually is now. We can't |
14341 | // do this lazily, because the result might depend on things that change |
14342 | // later, such as which constexpr functions happen to be defined. |
14343 | SmallVector<PartialDiagnosticAt, 8> Notes; |
14344 | if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) { |
14345 | // Prior to C++11, in contexts where a constant initializer is required, |
14346 | // the set of valid constant initializers is described by syntactic rules |
14347 | // in [expr.const]p2-6. |
14348 | // FIXME: Stricter checking for these rules would be useful for constinit / |
14349 | // -Wglobal-constructors. |
14350 | HasConstInit = checkConstInit(); |
14351 | |
14352 | // Compute and cache the constant value, and remember that we have a |
14353 | // constant initializer. |
14354 | if (HasConstInit) { |
14355 | (void)var->checkForConstantInitialization(Notes); |
14356 | Notes.clear(); |
14357 | } else if (CacheCulprit) { |
14358 | Notes.emplace_back(Args: CacheCulprit->getExprLoc(), |
14359 | Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr)); |
14360 | Notes.back().second << CacheCulprit->getSourceRange(); |
14361 | } |
14362 | } else { |
14363 | // Evaluate the initializer to see if it's a constant initializer. |
14364 | HasConstInit = var->checkForConstantInitialization(Notes); |
14365 | } |
14366 | |
14367 | if (HasConstInit) { |
14368 | // FIXME: Consider replacing the initializer with a ConstantExpr. |
14369 | } else if (var->isConstexpr()) { |
14370 | SourceLocation DiagLoc = var->getLocation(); |
14371 | // If the note doesn't add any useful information other than a source |
14372 | // location, fold it into the primary diagnostic. |
14373 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == |
14374 | diag::note_invalid_subexpr_in_const_expr) { |
14375 | DiagLoc = Notes[0].first; |
14376 | Notes.clear(); |
14377 | } |
14378 | Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init) |
14379 | << var << Init->getSourceRange(); |
14380 | for (unsigned I = 0, N = Notes.size(); I != N; ++I) |
14381 | Diag(Loc: Notes[I].first, PD: Notes[I].second); |
14382 | } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { |
14383 | auto *Attr = var->getAttr<ConstInitAttr>(); |
14384 | Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed) |
14385 | << Init->getSourceRange(); |
14386 | Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here) |
14387 | << Attr->getRange() << Attr->isConstinit(); |
14388 | for (auto &it : Notes) |
14389 | Diag(Loc: it.first, PD: it.second); |
14390 | } else if (IsGlobal && |
14391 | !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor, |
14392 | Loc: var->getLocation())) { |
14393 | // Warn about globals which don't have a constant initializer. Don't |
14394 | // warn about globals with a non-trivial destructor because we already |
14395 | // warned about them. |
14396 | CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); |
14397 | if (!(RD && !RD->hasTrivialDestructor())) { |
14398 | // checkConstInit() here permits trivial default initialization even in |
14399 | // C++11 onwards, where such an initializer is not a constant initializer |
14400 | // but nonetheless doesn't require a global constructor. |
14401 | if (!checkConstInit()) |
14402 | Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor) |
14403 | << Init->getSourceRange(); |
14404 | } |
14405 | } |
14406 | } |
14407 | |
14408 | // Apply section attributes and pragmas to global variables. |
14409 | if (GlobalStorage && var->isThisDeclarationADefinition() && |
14410 | !inTemplateInstantiation()) { |
14411 | PragmaStack<StringLiteral *> *Stack = nullptr; |
14412 | int SectionFlags = ASTContext::PSF_Read; |
14413 | bool MSVCEnv = |
14414 | Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment(); |
14415 | std::optional<QualType::NonConstantStorageReason> Reason; |
14416 | if (HasConstInit && |
14417 | !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) { |
14418 | Stack = &ConstSegStack; |
14419 | } else { |
14420 | SectionFlags |= ASTContext::PSF_Write; |
14421 | Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack; |
14422 | } |
14423 | if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { |
14424 | if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) |
14425 | SectionFlags |= ASTContext::PSF_Implicit; |
14426 | UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var); |
14427 | } else if (Stack->CurrentValue) { |
14428 | if (Stack != &ConstSegStack && MSVCEnv && |
14429 | ConstSegStack.CurrentValue != ConstSegStack.DefaultValue && |
14430 | var->getType().isConstQualified()) { |
14431 | assert((!Reason || Reason != QualType::NonConstantStorageReason:: |
14432 | NonConstNonReferenceType) && |
14433 | "This case should've already been handled elsewhere" ); |
14434 | Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat) |
14435 | << var << ConstSegStack.CurrentValue << (int)(!HasConstInit |
14436 | ? QualType::NonConstantStorageReason::NonTrivialCtor |
14437 | : *Reason); |
14438 | } |
14439 | SectionFlags |= ASTContext::PSF_Implicit; |
14440 | auto SectionName = Stack->CurrentValue->getString(); |
14441 | var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName, |
14442 | Range: Stack->CurrentPragmaLocation, |
14443 | S: SectionAttr::Declspec_allocate)); |
14444 | if (UnifySection(SectionName, SectionFlags, TheDecl: var)) |
14445 | var->dropAttr<SectionAttr>(); |
14446 | } |
14447 | |
14448 | // Apply the init_seg attribute if this has an initializer. If the |
14449 | // initializer turns out to not be dynamic, we'll end up ignoring this |
14450 | // attribute. |
14451 | if (CurInitSeg && var->getInit()) |
14452 | var->addAttr(A: InitSegAttr::CreateImplicit(Ctx&: Context, Section: CurInitSeg->getString(), |
14453 | Range: CurInitSegLoc)); |
14454 | } |
14455 | |
14456 | // All the following checks are C++ only. |
14457 | if (!getLangOpts().CPlusPlus) { |
14458 | // If this variable must be emitted, add it as an initializer for the |
14459 | // current module. |
14460 | if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty()) |
14461 | Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var); |
14462 | return; |
14463 | } |
14464 | |
14465 | // Require the destructor. |
14466 | if (!type->isDependentType()) |
14467 | if (const RecordType *recordType = baseType->getAs<RecordType>()) |
14468 | FinalizeVarWithDestructor(VD: var, DeclInitType: recordType); |
14469 | |
14470 | // If this variable must be emitted, add it as an initializer for the current |
14471 | // module. |
14472 | if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty()) |
14473 | Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var); |
14474 | |
14475 | // Build the bindings if this is a structured binding declaration. |
14476 | if (auto *DD = dyn_cast<DecompositionDecl>(Val: var)) |
14477 | CheckCompleteDecompositionDeclaration(DD); |
14478 | } |
14479 | |
14480 | void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { |
14481 | assert(VD->isStaticLocal()); |
14482 | |
14483 | auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod()); |
14484 | |
14485 | // Find outermost function when VD is in lambda function. |
14486 | while (FD && !getDLLAttr(D: FD) && |
14487 | !FD->hasAttr<DLLExportStaticLocalAttr>() && |
14488 | !FD->hasAttr<DLLImportStaticLocalAttr>()) { |
14489 | FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod()); |
14490 | } |
14491 | |
14492 | if (!FD) |
14493 | return; |
14494 | |
14495 | // Static locals inherit dll attributes from their function. |
14496 | if (Attr *A = getDLLAttr(D: FD)) { |
14497 | auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext())); |
14498 | NewAttr->setInherited(true); |
14499 | VD->addAttr(A: NewAttr); |
14500 | } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { |
14501 | auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A); |
14502 | NewAttr->setInherited(true); |
14503 | VD->addAttr(A: NewAttr); |
14504 | |
14505 | // Export this function to enforce exporting this static variable even |
14506 | // if it is not used in this compilation unit. |
14507 | if (!FD->hasAttr<DLLExportAttr>()) |
14508 | FD->addAttr(A: NewAttr); |
14509 | |
14510 | } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { |
14511 | auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A); |
14512 | NewAttr->setInherited(true); |
14513 | VD->addAttr(A: NewAttr); |
14514 | } |
14515 | } |
14516 | |
14517 | void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) { |
14518 | assert(VD->getTLSKind()); |
14519 | |
14520 | // Perform TLS alignment check here after attributes attached to the variable |
14521 | // which may affect the alignment have been processed. Only perform the check |
14522 | // if the target has a maximum TLS alignment (zero means no constraints). |
14523 | if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { |
14524 | // Protect the check so that it's not performed on dependent types and |
14525 | // dependent alignments (we can't determine the alignment in that case). |
14526 | if (!VD->hasDependentAlignment()) { |
14527 | CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign); |
14528 | if (Context.getDeclAlign(D: VD) > MaxAlignChars) { |
14529 | Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum) |
14530 | << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD |
14531 | << (unsigned)MaxAlignChars.getQuantity(); |
14532 | } |
14533 | } |
14534 | } |
14535 | } |
14536 | |
14537 | void Sema::FinalizeDeclaration(Decl *ThisDecl) { |
14538 | // Note that we are no longer parsing the initializer for this declaration. |
14539 | ParsingInitForAutoVars.erase(Ptr: ThisDecl); |
14540 | |
14541 | VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl); |
14542 | if (!VD) |
14543 | return; |
14544 | |
14545 | // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active |
14546 | if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && |
14547 | !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { |
14548 | if (PragmaClangBSSSection.Valid) |
14549 | VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit( |
14550 | Ctx&: Context, Name: PragmaClangBSSSection.SectionName, |
14551 | Range: PragmaClangBSSSection.PragmaLocation)); |
14552 | if (PragmaClangDataSection.Valid) |
14553 | VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit( |
14554 | Ctx&: Context, Name: PragmaClangDataSection.SectionName, |
14555 | Range: PragmaClangDataSection.PragmaLocation)); |
14556 | if (PragmaClangRodataSection.Valid) |
14557 | VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit( |
14558 | Ctx&: Context, Name: PragmaClangRodataSection.SectionName, |
14559 | Range: PragmaClangRodataSection.PragmaLocation)); |
14560 | if (PragmaClangRelroSection.Valid) |
14561 | VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit( |
14562 | Ctx&: Context, Name: PragmaClangRelroSection.SectionName, |
14563 | Range: PragmaClangRelroSection.PragmaLocation)); |
14564 | } |
14565 | |
14566 | if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) { |
14567 | for (auto *BD : DD->bindings()) { |
14568 | FinalizeDeclaration(ThisDecl: BD); |
14569 | } |
14570 | } |
14571 | |
14572 | checkAttributesAfterMerging(S&: *this, ND&: *VD); |
14573 | |
14574 | if (VD->isStaticLocal()) |
14575 | CheckStaticLocalForDllExport(VD); |
14576 | |
14577 | if (VD->getTLSKind()) |
14578 | CheckThreadLocalForLargeAlignment(VD); |
14579 | |
14580 | // Perform check for initializers of device-side global variables. |
14581 | // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA |
14582 | // 7.5). We must also apply the same checks to all __shared__ |
14583 | // variables whether they are local or not. CUDA also allows |
14584 | // constant initializers for __constant__ and __device__ variables. |
14585 | if (getLangOpts().CUDA) |
14586 | CUDA().checkAllowedInitializer(VD); |
14587 | |
14588 | // Grab the dllimport or dllexport attribute off of the VarDecl. |
14589 | const InheritableAttr *DLLAttr = getDLLAttr(D: VD); |
14590 | |
14591 | // Imported static data members cannot be defined out-of-line. |
14592 | if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) { |
14593 | if (VD->isStaticDataMember() && VD->isOutOfLine() && |
14594 | VD->isThisDeclarationADefinition()) { |
14595 | // We allow definitions of dllimport class template static data members |
14596 | // with a warning. |
14597 | CXXRecordDecl *Context = |
14598 | cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext()); |
14599 | bool IsClassTemplateMember = |
14600 | isa<ClassTemplatePartialSpecializationDecl>(Val: Context) || |
14601 | Context->getDescribedClassTemplate(); |
14602 | |
14603 | Diag(Loc: VD->getLocation(), |
14604 | DiagID: IsClassTemplateMember |
14605 | ? diag::warn_attribute_dllimport_static_field_definition |
14606 | : diag::err_attribute_dllimport_static_field_definition); |
14607 | Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute); |
14608 | if (!IsClassTemplateMember) |
14609 | VD->setInvalidDecl(); |
14610 | } |
14611 | } |
14612 | |
14613 | // dllimport/dllexport variables cannot be thread local, their TLS index |
14614 | // isn't exported with the variable. |
14615 | if (DLLAttr && VD->getTLSKind()) { |
14616 | auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod()); |
14617 | if (F && getDLLAttr(D: F)) { |
14618 | assert(VD->isStaticLocal()); |
14619 | // But if this is a static local in a dlimport/dllexport function, the |
14620 | // function will never be inlined, which means the var would never be |
14621 | // imported, so having it marked import/export is safe. |
14622 | } else { |
14623 | Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD |
14624 | << DLLAttr; |
14625 | VD->setInvalidDecl(); |
14626 | } |
14627 | } |
14628 | |
14629 | if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { |
14630 | if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { |
14631 | Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition) |
14632 | << Attr; |
14633 | VD->dropAttr<UsedAttr>(); |
14634 | } |
14635 | } |
14636 | if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { |
14637 | if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { |
14638 | Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition) |
14639 | << Attr; |
14640 | VD->dropAttr<RetainAttr>(); |
14641 | } |
14642 | } |
14643 | |
14644 | const DeclContext *DC = VD->getDeclContext(); |
14645 | // If there's a #pragma GCC visibility in scope, and this isn't a class |
14646 | // member, set the visibility of this variable. |
14647 | if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) |
14648 | AddPushedVisibilityAttribute(RD: VD); |
14649 | |
14650 | // FIXME: Warn on unused var template partial specializations. |
14651 | if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD)) |
14652 | MarkUnusedFileScopedDecl(D: VD); |
14653 | |
14654 | // Now we have parsed the initializer and can update the table of magic |
14655 | // tag values. |
14656 | if (!VD->hasAttr<TypeTagForDatatypeAttr>() || |
14657 | !VD->getType()->isIntegralOrEnumerationType()) |
14658 | return; |
14659 | |
14660 | for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { |
14661 | const Expr *MagicValueExpr = VD->getInit(); |
14662 | if (!MagicValueExpr) { |
14663 | continue; |
14664 | } |
14665 | std::optional<llvm::APSInt> MagicValueInt; |
14666 | if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) { |
14667 | Diag(Loc: I->getRange().getBegin(), |
14668 | DiagID: diag::err_type_tag_for_datatype_not_ice) |
14669 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); |
14670 | continue; |
14671 | } |
14672 | if (MagicValueInt->getActiveBits() > 64) { |
14673 | Diag(Loc: I->getRange().getBegin(), |
14674 | DiagID: diag::err_type_tag_for_datatype_too_large) |
14675 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); |
14676 | continue; |
14677 | } |
14678 | uint64_t MagicValue = MagicValueInt->getZExtValue(); |
14679 | RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(), |
14680 | MagicValue, |
14681 | Type: I->getMatchingCType(), |
14682 | LayoutCompatible: I->getLayoutCompatible(), |
14683 | MustBeNull: I->getMustBeNull()); |
14684 | } |
14685 | } |
14686 | |
14687 | static bool hasDeducedAuto(DeclaratorDecl *DD) { |
14688 | auto *VD = dyn_cast<VarDecl>(Val: DD); |
14689 | return VD && !VD->getType()->hasAutoForTrailingReturnType(); |
14690 | } |
14691 | |
14692 | Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, |
14693 | ArrayRef<Decl *> Group) { |
14694 | SmallVector<Decl*, 8> Decls; |
14695 | |
14696 | if (DS.isTypeSpecOwned()) |
14697 | Decls.push_back(Elt: DS.getRepAsDecl()); |
14698 | |
14699 | DeclaratorDecl *FirstDeclaratorInGroup = nullptr; |
14700 | DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; |
14701 | bool DiagnosedMultipleDecomps = false; |
14702 | DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; |
14703 | bool DiagnosedNonDeducedAuto = false; |
14704 | |
14705 | for (Decl *D : Group) { |
14706 | if (!D) |
14707 | continue; |
14708 | // Check if the Decl has been declared in '#pragma omp declare target' |
14709 | // directive and has static storage duration. |
14710 | if (auto *VD = dyn_cast<VarDecl>(Val: D); |
14711 | LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() && |
14712 | VD->hasGlobalStorage()) |
14713 | OpenMP().ActOnOpenMPDeclareTargetInitializer(D); |
14714 | // For declarators, there are some additional syntactic-ish checks we need |
14715 | // to perform. |
14716 | if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) { |
14717 | if (!FirstDeclaratorInGroup) |
14718 | FirstDeclaratorInGroup = DD; |
14719 | if (!FirstDecompDeclaratorInGroup) |
14720 | FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D); |
14721 | if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && |
14722 | !hasDeducedAuto(DD)) |
14723 | FirstNonDeducedAutoInGroup = DD; |
14724 | |
14725 | if (FirstDeclaratorInGroup != DD) { |
14726 | // A decomposition declaration cannot be combined with any other |
14727 | // declaration in the same group. |
14728 | if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { |
14729 | Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(), |
14730 | DiagID: diag::err_decomp_decl_not_alone) |
14731 | << FirstDeclaratorInGroup->getSourceRange() |
14732 | << DD->getSourceRange(); |
14733 | DiagnosedMultipleDecomps = true; |
14734 | } |
14735 | |
14736 | // A declarator that uses 'auto' in any way other than to declare a |
14737 | // variable with a deduced type cannot be combined with any other |
14738 | // declarator in the same group. |
14739 | if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { |
14740 | Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(), |
14741 | DiagID: diag::err_auto_non_deduced_not_alone) |
14742 | << FirstNonDeducedAutoInGroup->getType() |
14743 | ->hasAutoForTrailingReturnType() |
14744 | << FirstDeclaratorInGroup->getSourceRange() |
14745 | << DD->getSourceRange(); |
14746 | DiagnosedNonDeducedAuto = true; |
14747 | } |
14748 | } |
14749 | } |
14750 | |
14751 | Decls.push_back(Elt: D); |
14752 | } |
14753 | |
14754 | if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) { |
14755 | if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) { |
14756 | handleTagNumbering(Tag, TagScope: S); |
14757 | if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && |
14758 | getLangOpts().CPlusPlus) |
14759 | Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup); |
14760 | } |
14761 | } |
14762 | |
14763 | return BuildDeclaratorGroup(Group: Decls); |
14764 | } |
14765 | |
14766 | Sema::DeclGroupPtrTy |
14767 | Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { |
14768 | // C++14 [dcl.spec.auto]p7: (DR1347) |
14769 | // If the type that replaces the placeholder type is not the same in each |
14770 | // deduction, the program is ill-formed. |
14771 | if (Group.size() > 1) { |
14772 | QualType Deduced; |
14773 | VarDecl *DeducedDecl = nullptr; |
14774 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { |
14775 | VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]); |
14776 | if (!D || D->isInvalidDecl()) |
14777 | break; |
14778 | DeducedType *DT = D->getType()->getContainedDeducedType(); |
14779 | if (!DT || DT->getDeducedType().isNull()) |
14780 | continue; |
14781 | if (Deduced.isNull()) { |
14782 | Deduced = DT->getDeducedType(); |
14783 | DeducedDecl = D; |
14784 | } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) { |
14785 | auto *AT = dyn_cast<AutoType>(Val: DT); |
14786 | auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), |
14787 | DiagID: diag::err_auto_different_deductions) |
14788 | << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced |
14789 | << DeducedDecl->getDeclName() << DT->getDeducedType() |
14790 | << D->getDeclName(); |
14791 | if (DeducedDecl->hasInit()) |
14792 | Dia << DeducedDecl->getInit()->getSourceRange(); |
14793 | if (D->getInit()) |
14794 | Dia << D->getInit()->getSourceRange(); |
14795 | D->setInvalidDecl(); |
14796 | break; |
14797 | } |
14798 | } |
14799 | } |
14800 | |
14801 | ActOnDocumentableDecls(Group); |
14802 | |
14803 | return DeclGroupPtrTy::make( |
14804 | P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size())); |
14805 | } |
14806 | |
14807 | void Sema::ActOnDocumentableDecl(Decl *D) { |
14808 | ActOnDocumentableDecls(Group: D); |
14809 | } |
14810 | |
14811 | void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { |
14812 | // Don't parse the comment if Doxygen diagnostics are ignored. |
14813 | if (Group.empty() || !Group[0]) |
14814 | return; |
14815 | |
14816 | if (Diags.isIgnored(DiagID: diag::warn_doc_param_not_found, |
14817 | Loc: Group[0]->getLocation()) && |
14818 | Diags.isIgnored(DiagID: diag::warn_unknown_comment_command_name, |
14819 | Loc: Group[0]->getLocation())) |
14820 | return; |
14821 | |
14822 | if (Group.size() >= 2) { |
14823 | // This is a decl group. Normally it will contain only declarations |
14824 | // produced from declarator list. But in case we have any definitions or |
14825 | // additional declaration references: |
14826 | // 'typedef struct S {} S;' |
14827 | // 'typedef struct S *S;' |
14828 | // 'struct S *pS;' |
14829 | // FinalizeDeclaratorGroup adds these as separate declarations. |
14830 | Decl *MaybeTagDecl = Group[0]; |
14831 | if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) { |
14832 | Group = Group.slice(N: 1); |
14833 | } |
14834 | } |
14835 | |
14836 | // FIMXE: We assume every Decl in the group is in the same file. |
14837 | // This is false when preprocessor constructs the group from decls in |
14838 | // different files (e. g. macros or #include). |
14839 | Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor()); |
14840 | } |
14841 | |
14842 | void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { |
14843 | // Check that there are no default arguments inside the type of this |
14844 | // parameter. |
14845 | if (getLangOpts().CPlusPlus) |
14846 | CheckExtraCXXDefaultArguments(D); |
14847 | |
14848 | // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). |
14849 | if (D.getCXXScopeSpec().isSet()) { |
14850 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator) |
14851 | << D.getCXXScopeSpec().getRange(); |
14852 | } |
14853 | |
14854 | // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a |
14855 | // simple identifier except [...irrelevant cases...]. |
14856 | switch (D.getName().getKind()) { |
14857 | case UnqualifiedIdKind::IK_Identifier: |
14858 | break; |
14859 | |
14860 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
14861 | case UnqualifiedIdKind::IK_ConversionFunctionId: |
14862 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
14863 | case UnqualifiedIdKind::IK_ConstructorName: |
14864 | case UnqualifiedIdKind::IK_DestructorName: |
14865 | case UnqualifiedIdKind::IK_ImplicitSelfParam: |
14866 | case UnqualifiedIdKind::IK_DeductionGuideName: |
14867 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name) |
14868 | << GetNameForDeclarator(D).getName(); |
14869 | break; |
14870 | |
14871 | case UnqualifiedIdKind::IK_TemplateId: |
14872 | case UnqualifiedIdKind::IK_ConstructorTemplateId: |
14873 | // GetNameForDeclarator would not produce a useful name in this case. |
14874 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id); |
14875 | break; |
14876 | } |
14877 | } |
14878 | |
14879 | static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, |
14880 | SourceLocation ExplicitThisLoc) { |
14881 | if (!ExplicitThisLoc.isValid()) |
14882 | return; |
14883 | assert(S.getLangOpts().CPlusPlus && |
14884 | "explicit parameter in non-cplusplus mode" ); |
14885 | if (!S.getLangOpts().CPlusPlus23) |
14886 | S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this) |
14887 | << P->getSourceRange(); |
14888 | |
14889 | // C++2b [dcl.fct/7] An explicit object parameter shall not be a function |
14890 | // parameter pack. |
14891 | if (P->isParameterPack()) { |
14892 | S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack) |
14893 | << P->getSourceRange(); |
14894 | return; |
14895 | } |
14896 | P->setExplicitObjectParameterLoc(ExplicitThisLoc); |
14897 | if (LambdaScopeInfo *LSI = S.getCurLambda()) |
14898 | LSI->ExplicitObjectParameter = P; |
14899 | } |
14900 | |
14901 | Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D, |
14902 | SourceLocation ExplicitThisLoc) { |
14903 | const DeclSpec &DS = D.getDeclSpec(); |
14904 | |
14905 | // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. |
14906 | |
14907 | // C++03 [dcl.stc]p2 also permits 'auto'. |
14908 | StorageClass SC = SC_None; |
14909 | if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { |
14910 | SC = SC_Register; |
14911 | // In C++11, the 'register' storage class specifier is deprecated. |
14912 | // In C++17, it is not allowed, but we tolerate it as an extension. |
14913 | if (getLangOpts().CPlusPlus11) { |
14914 | Diag(Loc: DS.getStorageClassSpecLoc(), |
14915 | DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class |
14916 | : diag::warn_deprecated_register) |
14917 | << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc()); |
14918 | } |
14919 | } else if (getLangOpts().CPlusPlus && |
14920 | DS.getStorageClassSpec() == DeclSpec::SCS_auto) { |
14921 | SC = SC_Auto; |
14922 | } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { |
14923 | Diag(Loc: DS.getStorageClassSpecLoc(), |
14924 | DiagID: diag::err_invalid_storage_class_in_func_decl); |
14925 | D.getMutableDeclSpec().ClearStorageClassSpecs(); |
14926 | } |
14927 | |
14928 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) |
14929 | Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread) |
14930 | << DeclSpec::getSpecifierName(S: TSCS); |
14931 | if (DS.isInlineSpecified()) |
14932 | Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function) |
14933 | << getLangOpts().CPlusPlus17; |
14934 | if (DS.hasConstexprSpecifier()) |
14935 | Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr) |
14936 | << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); |
14937 | |
14938 | DiagnoseFunctionSpecifiers(DS); |
14939 | |
14940 | CheckFunctionOrTemplateParamDeclarator(S, D); |
14941 | |
14942 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D); |
14943 | QualType parmDeclType = TInfo->getType(); |
14944 | |
14945 | // Check for redeclaration of parameters, e.g. int foo(int x, int x); |
14946 | const IdentifierInfo *II = D.getIdentifier(); |
14947 | if (II) { |
14948 | LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, |
14949 | RedeclarationKind::ForVisibleRedeclaration); |
14950 | LookupName(R, S); |
14951 | if (!R.empty()) { |
14952 | NamedDecl *PrevDecl = *R.begin(); |
14953 | if (R.isSingleResult() && PrevDecl->isTemplateParameter()) { |
14954 | // Maybe we will complain about the shadowed template parameter. |
14955 | DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl); |
14956 | // Just pretend that we didn't see the previous declaration. |
14957 | PrevDecl = nullptr; |
14958 | } |
14959 | if (PrevDecl && S->isDeclScope(D: PrevDecl)) { |
14960 | Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II; |
14961 | Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration); |
14962 | // Recover by removing the name |
14963 | II = nullptr; |
14964 | D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc()); |
14965 | D.setInvalidType(true); |
14966 | } |
14967 | } |
14968 | } |
14969 | |
14970 | // Temporarily put parameter variables in the translation unit, not |
14971 | // the enclosing context. This prevents them from accidentally |
14972 | // looking like class members in C++. |
14973 | ParmVarDecl *New = |
14974 | CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(), |
14975 | NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC); |
14976 | |
14977 | if (D.isInvalidType()) |
14978 | New->setInvalidDecl(); |
14979 | |
14980 | CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc); |
14981 | |
14982 | assert(S->isFunctionPrototypeScope()); |
14983 | assert(S->getFunctionPrototypeDepth() >= 1); |
14984 | New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1, |
14985 | parameterIndex: S->getNextFunctionPrototypeIndex()); |
14986 | |
14987 | // Add the parameter declaration into this scope. |
14988 | S->AddDecl(D: New); |
14989 | if (II) |
14990 | IdResolver.AddDecl(D: New); |
14991 | |
14992 | ProcessDeclAttributes(S, D: New, PD: D); |
14993 | |
14994 | if (D.getDeclSpec().isModulePrivateSpecified()) |
14995 | Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local) |
14996 | << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) |
14997 | << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc()); |
14998 | |
14999 | if (New->hasAttr<BlocksAttr>()) { |
15000 | Diag(Loc: New->getLocation(), DiagID: diag::err_block_on_nonlocal); |
15001 | } |
15002 | |
15003 | if (getLangOpts().OpenCL) |
15004 | deduceOpenCLAddressSpace(Decl: New); |
15005 | |
15006 | return New; |
15007 | } |
15008 | |
15009 | ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, |
15010 | SourceLocation Loc, |
15011 | QualType T) { |
15012 | /* FIXME: setting StartLoc == Loc. |
15013 | Would it be worth to modify callers so as to provide proper source |
15014 | location for the unnamed parameters, embedding the parameter's type? */ |
15015 | ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr, |
15016 | T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc), |
15017 | S: SC_None, DefArg: nullptr); |
15018 | Param->setImplicit(); |
15019 | return Param; |
15020 | } |
15021 | |
15022 | void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { |
15023 | // Don't diagnose unused-parameter errors in template instantiations; we |
15024 | // will already have done so in the template itself. |
15025 | if (inTemplateInstantiation()) |
15026 | return; |
15027 | |
15028 | for (const ParmVarDecl *Parameter : Parameters) { |
15029 | if (!Parameter->isReferenced() && Parameter->getDeclName() && |
15030 | !Parameter->hasAttr<UnusedAttr>() && |
15031 | !Parameter->getIdentifier()->isPlaceholder()) { |
15032 | Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter) |
15033 | << Parameter->getDeclName(); |
15034 | } |
15035 | } |
15036 | } |
15037 | |
15038 | void Sema::DiagnoseSizeOfParametersAndReturnValue( |
15039 | ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { |
15040 | if (LangOpts.NumLargeByValueCopy == 0) // No check. |
15041 | return; |
15042 | |
15043 | // Warn if the return value is pass-by-value and larger than the specified |
15044 | // threshold. |
15045 | if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { |
15046 | unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity(); |
15047 | if (Size > LangOpts.NumLargeByValueCopy) |
15048 | Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size; |
15049 | } |
15050 | |
15051 | // Warn if any parameter is pass-by-value and larger than the specified |
15052 | // threshold. |
15053 | for (const ParmVarDecl *Parameter : Parameters) { |
15054 | QualType T = Parameter->getType(); |
15055 | if (T->isDependentType() || !T.isPODType(Context)) |
15056 | continue; |
15057 | unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); |
15058 | if (Size > LangOpts.NumLargeByValueCopy) |
15059 | Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size) |
15060 | << Parameter << Size; |
15061 | } |
15062 | } |
15063 | |
15064 | ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, |
15065 | SourceLocation NameLoc, |
15066 | const IdentifierInfo *Name, QualType T, |
15067 | TypeSourceInfo *TSInfo, StorageClass SC) { |
15068 | // In ARC, infer a lifetime qualifier for appropriate parameter types. |
15069 | if (getLangOpts().ObjCAutoRefCount && |
15070 | T.getObjCLifetime() == Qualifiers::OCL_None && |
15071 | T->isObjCLifetimeType()) { |
15072 | |
15073 | Qualifiers::ObjCLifetime lifetime; |
15074 | |
15075 | // Special cases for arrays: |
15076 | // - if it's const, use __unsafe_unretained |
15077 | // - otherwise, it's an error |
15078 | if (T->isArrayType()) { |
15079 | if (!T.isConstQualified()) { |
15080 | if (DelayedDiagnostics.shouldDelayDiagnostics()) |
15081 | DelayedDiagnostics.add( |
15082 | diag: sema::DelayedDiagnostic::makeForbiddenType( |
15083 | loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false)); |
15084 | else |
15085 | Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership) |
15086 | << TSInfo->getTypeLoc().getSourceRange(); |
15087 | } |
15088 | lifetime = Qualifiers::OCL_ExplicitNone; |
15089 | } else { |
15090 | lifetime = T->getObjCARCImplicitLifetime(); |
15091 | } |
15092 | T = Context.getLifetimeQualifiedType(type: T, lifetime); |
15093 | } |
15094 | |
15095 | ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name, |
15096 | T: Context.getAdjustedParameterType(T), |
15097 | TInfo: TSInfo, S: SC, DefArg: nullptr); |
15098 | |
15099 | // Make a note if we created a new pack in the scope of a lambda, so that |
15100 | // we know that references to that pack must also be expanded within the |
15101 | // lambda scope. |
15102 | if (New->isParameterPack()) |
15103 | if (auto *LSI = getEnclosingLambda()) |
15104 | LSI->LocalPacks.push_back(Elt: New); |
15105 | |
15106 | if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || |
15107 | New->getType().hasNonTrivialToPrimitiveCopyCUnion()) |
15108 | checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(), |
15109 | UseContext: NTCUC_FunctionParam, NonTrivialKind: NTCUK_Destruct|NTCUK_Copy); |
15110 | |
15111 | // Parameter declarators cannot be interface types. All ObjC objects are |
15112 | // passed by reference. |
15113 | if (T->isObjCObjectType()) { |
15114 | SourceLocation TypeEndLoc = |
15115 | getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc()); |
15116 | Diag(Loc: NameLoc, |
15117 | DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T |
15118 | << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*" ); |
15119 | T = Context.getObjCObjectPointerType(OIT: T); |
15120 | New->setType(T); |
15121 | } |
15122 | |
15123 | // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage |
15124 | // duration shall not be qualified by an address-space qualifier." |
15125 | // Since all parameters have automatic store duration, they can not have |
15126 | // an address space. |
15127 | if (T.getAddressSpace() != LangAS::Default && |
15128 | // OpenCL allows function arguments declared to be an array of a type |
15129 | // to be qualified with an address space. |
15130 | !(getLangOpts().OpenCL && |
15131 | (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) && |
15132 | // WebAssembly allows reference types as parameters. Funcref in particular |
15133 | // lives in a different address space. |
15134 | !(T->isFunctionPointerType() && |
15135 | T.getAddressSpace() == LangAS::wasm_funcref)) { |
15136 | Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space); |
15137 | New->setInvalidDecl(); |
15138 | } |
15139 | |
15140 | // PPC MMA non-pointer types are not allowed as function argument types. |
15141 | if (Context.getTargetInfo().getTriple().isPPC64() && |
15142 | PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) { |
15143 | New->setInvalidDecl(); |
15144 | } |
15145 | |
15146 | return New; |
15147 | } |
15148 | |
15149 | void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, |
15150 | SourceLocation LocAfterDecls) { |
15151 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); |
15152 | |
15153 | // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration |
15154 | // in the declaration list shall have at least one declarator, those |
15155 | // declarators shall only declare identifiers from the identifier list, and |
15156 | // every identifier in the identifier list shall be declared. |
15157 | // |
15158 | // C89 3.7.1p5 "If a declarator includes an identifier list, only the |
15159 | // identifiers it names shall be declared in the declaration list." |
15160 | // |
15161 | // This is why we only diagnose in C99 and later. Note, the other conditions |
15162 | // listed are checked elsewhere. |
15163 | if (!FTI.hasPrototype) { |
15164 | for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { |
15165 | --i; |
15166 | if (FTI.Params[i].Param == nullptr) { |
15167 | if (getLangOpts().C99) { |
15168 | SmallString<256> Code; |
15169 | llvm::raw_svector_ostream(Code) |
15170 | << " int " << FTI.Params[i].Ident->getName() << ";\n" ; |
15171 | Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared) |
15172 | << FTI.Params[i].Ident |
15173 | << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code); |
15174 | } |
15175 | |
15176 | // Implicitly declare the argument as type 'int' for lack of a better |
15177 | // type. |
15178 | AttributeFactory attrs; |
15179 | DeclSpec DS(attrs); |
15180 | const char* PrevSpec; // unused |
15181 | unsigned DiagID; // unused |
15182 | DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec, |
15183 | DiagID, Policy: Context.getPrintingPolicy()); |
15184 | // Use the identifier location for the type source range. |
15185 | DS.SetRangeStart(FTI.Params[i].IdentLoc); |
15186 | DS.SetRangeEnd(FTI.Params[i].IdentLoc); |
15187 | Declarator ParamD(DS, ParsedAttributesView::none(), |
15188 | DeclaratorContext::KNRTypeList); |
15189 | ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc); |
15190 | FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD); |
15191 | } |
15192 | } |
15193 | } |
15194 | } |
15195 | |
15196 | Decl * |
15197 | Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, |
15198 | MultiTemplateParamsArg TemplateParameterLists, |
15199 | SkipBodyInfo *SkipBody, FnBodyKind BodyKind) { |
15200 | assert(getCurFunctionDecl() == nullptr && "Function parsing confused" ); |
15201 | assert(D.isFunctionDeclarator() && "Not a function declarator!" ); |
15202 | Scope *ParentScope = FnBodyScope->getParent(); |
15203 | |
15204 | // Check if we are in an `omp begin/end declare variant` scope. If we are, and |
15205 | // we define a non-templated function definition, we will create a declaration |
15206 | // instead (=BaseFD), and emit the definition with a mangled name afterwards. |
15207 | // The base function declaration will have the equivalent of an `omp declare |
15208 | // variant` annotation which specifies the mangled definition as a |
15209 | // specialization function under the OpenMP context defined as part of the |
15210 | // `omp begin declare variant`. |
15211 | SmallVector<FunctionDecl *, 4> Bases; |
15212 | if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope()) |
15213 | OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( |
15214 | S: ParentScope, D, TemplateParameterLists, Bases); |
15215 | |
15216 | D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); |
15217 | Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists); |
15218 | Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind); |
15219 | |
15220 | if (!Bases.empty()) |
15221 | OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl, |
15222 | Bases); |
15223 | |
15224 | return Dcl; |
15225 | } |
15226 | |
15227 | void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { |
15228 | Consumer.HandleInlineFunctionDefinition(D); |
15229 | } |
15230 | |
15231 | static bool FindPossiblePrototype(const FunctionDecl *FD, |
15232 | const FunctionDecl *&PossiblePrototype) { |
15233 | for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev; |
15234 | Prev = Prev->getPreviousDecl()) { |
15235 | // Ignore any declarations that occur in function or method |
15236 | // scope, because they aren't visible from the header. |
15237 | if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) |
15238 | continue; |
15239 | |
15240 | PossiblePrototype = Prev; |
15241 | return Prev->getType()->isFunctionProtoType(); |
15242 | } |
15243 | return false; |
15244 | } |
15245 | |
15246 | static bool |
15247 | ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, |
15248 | const FunctionDecl *&PossiblePrototype) { |
15249 | // Don't warn about invalid declarations. |
15250 | if (FD->isInvalidDecl()) |
15251 | return false; |
15252 | |
15253 | // Or declarations that aren't global. |
15254 | if (!FD->isGlobal()) |
15255 | return false; |
15256 | |
15257 | // Don't warn about C++ member functions. |
15258 | if (isa<CXXMethodDecl>(Val: FD)) |
15259 | return false; |
15260 | |
15261 | // Don't warn about 'main'. |
15262 | if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext())) |
15263 | if (IdentifierInfo *II = FD->getIdentifier()) |
15264 | if (II->isStr(Str: "main" ) || II->isStr(Str: "efi_main" )) |
15265 | return false; |
15266 | |
15267 | if (FD->isMSVCRTEntryPoint()) |
15268 | return false; |
15269 | |
15270 | // Don't warn about inline functions. |
15271 | if (FD->isInlined()) |
15272 | return false; |
15273 | |
15274 | // Don't warn about function templates. |
15275 | if (FD->getDescribedFunctionTemplate()) |
15276 | return false; |
15277 | |
15278 | // Don't warn about function template specializations. |
15279 | if (FD->isFunctionTemplateSpecialization()) |
15280 | return false; |
15281 | |
15282 | // Don't warn for OpenCL kernels. |
15283 | if (FD->hasAttr<OpenCLKernelAttr>()) |
15284 | return false; |
15285 | |
15286 | // Don't warn on explicitly deleted functions. |
15287 | if (FD->isDeleted()) |
15288 | return false; |
15289 | |
15290 | // Don't warn on implicitly local functions (such as having local-typed |
15291 | // parameters). |
15292 | if (!FD->isExternallyVisible()) |
15293 | return false; |
15294 | |
15295 | // If we were able to find a potential prototype, don't warn. |
15296 | if (FindPossiblePrototype(FD, PossiblePrototype)) |
15297 | return false; |
15298 | |
15299 | return true; |
15300 | } |
15301 | |
15302 | void |
15303 | Sema::CheckForFunctionRedefinition(FunctionDecl *FD, |
15304 | const FunctionDecl *EffectiveDefinition, |
15305 | SkipBodyInfo *SkipBody) { |
15306 | const FunctionDecl *Definition = EffectiveDefinition; |
15307 | if (!Definition && |
15308 | !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) |
15309 | return; |
15310 | |
15311 | if (Definition->getFriendObjectKind() != Decl::FOK_None) { |
15312 | if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { |
15313 | if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { |
15314 | // A merged copy of the same function, instantiated as a member of |
15315 | // the same class, is OK. |
15316 | if (declaresSameEntity(D1: OrigFD, D2: OrigDef) && |
15317 | declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()), |
15318 | D2: cast<Decl>(Val: FD->getLexicalDeclContext()))) |
15319 | return; |
15320 | } |
15321 | } |
15322 | } |
15323 | |
15324 | if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts())) |
15325 | return; |
15326 | |
15327 | // Don't emit an error when this is redefinition of a typo-corrected |
15328 | // definition. |
15329 | if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition)) |
15330 | return; |
15331 | |
15332 | // If we don't have a visible definition of the function, and it's inline or |
15333 | // a template, skip the new definition. |
15334 | if (SkipBody && !hasVisibleDefinition(D: Definition) && |
15335 | (Definition->getFormalLinkage() == Linkage::Internal || |
15336 | Definition->isInlined() || Definition->getDescribedFunctionTemplate() || |
15337 | Definition->getNumTemplateParameterLists())) { |
15338 | SkipBody->ShouldSkip = true; |
15339 | SkipBody->Previous = const_cast<FunctionDecl*>(Definition); |
15340 | if (auto *TD = Definition->getDescribedFunctionTemplate()) |
15341 | makeMergedDefinitionVisible(ND: TD); |
15342 | makeMergedDefinitionVisible(ND: const_cast<FunctionDecl*>(Definition)); |
15343 | return; |
15344 | } |
15345 | |
15346 | if (getLangOpts().GNUMode && Definition->isInlineSpecified() && |
15347 | Definition->getStorageClass() == SC_Extern) |
15348 | Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline) |
15349 | << FD << getLangOpts().CPlusPlus; |
15350 | else |
15351 | Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD; |
15352 | |
15353 | Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition); |
15354 | FD->setInvalidDecl(); |
15355 | } |
15356 | |
15357 | LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) { |
15358 | CXXRecordDecl *LambdaClass = CallOperator->getParent(); |
15359 | |
15360 | LambdaScopeInfo *LSI = PushLambdaScope(); |
15361 | LSI->CallOperator = CallOperator; |
15362 | LSI->Lambda = LambdaClass; |
15363 | LSI->ReturnType = CallOperator->getReturnType(); |
15364 | // This function in calls in situation where the context of the call operator |
15365 | // is not entered, so we set AfterParameterList to false, so that |
15366 | // `tryCaptureVariable` finds explicit captures in the appropriate context. |
15367 | LSI->AfterParameterList = false; |
15368 | const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); |
15369 | |
15370 | if (LCD == LCD_None) |
15371 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; |
15372 | else if (LCD == LCD_ByCopy) |
15373 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; |
15374 | else if (LCD == LCD_ByRef) |
15375 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; |
15376 | DeclarationNameInfo DNI = CallOperator->getNameInfo(); |
15377 | |
15378 | LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); |
15379 | LSI->Mutable = !CallOperator->isConst(); |
15380 | if (CallOperator->isExplicitObjectMemberFunction()) |
15381 | LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0); |
15382 | |
15383 | // Add the captures to the LSI so they can be noted as already |
15384 | // captured within tryCaptureVar. |
15385 | auto I = LambdaClass->field_begin(); |
15386 | for (const auto &C : LambdaClass->captures()) { |
15387 | if (C.capturesVariable()) { |
15388 | ValueDecl *VD = C.getCapturedVar(); |
15389 | if (VD->isInitCapture()) |
15390 | CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD); |
15391 | const bool ByRef = C.getCaptureKind() == LCK_ByRef; |
15392 | LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef, |
15393 | /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(), |
15394 | /*EllipsisLoc*/C.isPackExpansion() |
15395 | ? C.getEllipsisLoc() : SourceLocation(), |
15396 | CaptureType: I->getType(), /*Invalid*/false); |
15397 | |
15398 | } else if (C.capturesThis()) { |
15399 | LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(), |
15400 | ByCopy: C.getCaptureKind() == LCK_StarThis); |
15401 | } else { |
15402 | LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(), |
15403 | CaptureType: I->getType()); |
15404 | } |
15405 | ++I; |
15406 | } |
15407 | return LSI; |
15408 | } |
15409 | |
15410 | Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, |
15411 | SkipBodyInfo *SkipBody, |
15412 | FnBodyKind BodyKind) { |
15413 | if (!D) { |
15414 | // Parsing the function declaration failed in some way. Push on a fake scope |
15415 | // anyway so we can try to parse the function body. |
15416 | PushFunctionScope(); |
15417 | PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context); |
15418 | return D; |
15419 | } |
15420 | |
15421 | FunctionDecl *FD = nullptr; |
15422 | |
15423 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D)) |
15424 | FD = FunTmpl->getTemplatedDecl(); |
15425 | else |
15426 | FD = cast<FunctionDecl>(Val: D); |
15427 | |
15428 | // Do not push if it is a lambda because one is already pushed when building |
15429 | // the lambda in ActOnStartOfLambdaDefinition(). |
15430 | if (!isLambdaCallOperator(DC: FD)) |
15431 | // [expr.const]/p14.1 |
15432 | // An expression or conversion is in an immediate function context if it is |
15433 | // potentially evaluated and either: its innermost enclosing non-block scope |
15434 | // is a function parameter scope of an immediate function. |
15435 | PushExpressionEvaluationContext( |
15436 | NewContext: FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext |
15437 | : ExprEvalContexts.back().Context); |
15438 | |
15439 | // Each ExpressionEvaluationContextRecord also keeps track of whether the |
15440 | // context is nested in an immediate function context, so smaller contexts |
15441 | // that appear inside immediate functions (like variable initializers) are |
15442 | // considered to be inside an immediate function context even though by |
15443 | // themselves they are not immediate function contexts. But when a new |
15444 | // function is entered, we need to reset this tracking, since the entered |
15445 | // function might be not an immediate function. |
15446 | ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval(); |
15447 | ExprEvalContexts.back().InImmediateEscalatingFunctionContext = |
15448 | getLangOpts().CPlusPlus20 && FD->isImmediateEscalating(); |
15449 | |
15450 | // Check for defining attributes before the check for redefinition. |
15451 | if (const auto *Attr = FD->getAttr<AliasAttr>()) { |
15452 | Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0; |
15453 | FD->dropAttr<AliasAttr>(); |
15454 | FD->setInvalidDecl(); |
15455 | } |
15456 | if (const auto *Attr = FD->getAttr<IFuncAttr>()) { |
15457 | Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1; |
15458 | FD->dropAttr<IFuncAttr>(); |
15459 | FD->setInvalidDecl(); |
15460 | } |
15461 | if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) { |
15462 | if (!Context.getTargetInfo().hasFeature(Feature: "fmv" ) && |
15463 | !Attr->isDefaultVersion()) { |
15464 | // If function multi versioning disabled skip parsing function body |
15465 | // defined with non-default target_version attribute |
15466 | if (SkipBody) |
15467 | SkipBody->ShouldSkip = true; |
15468 | return nullptr; |
15469 | } |
15470 | } |
15471 | |
15472 | if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) { |
15473 | if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && |
15474 | Ctor->isDefaultConstructor() && |
15475 | Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
15476 | // If this is an MS ABI dllexport default constructor, instantiate any |
15477 | // default arguments. |
15478 | InstantiateDefaultCtorDefaultArgs(Ctor); |
15479 | } |
15480 | } |
15481 | |
15482 | // See if this is a redefinition. If 'will have body' (or similar) is already |
15483 | // set, then these checks were already performed when it was set. |
15484 | if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && |
15485 | !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { |
15486 | CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody); |
15487 | |
15488 | // If we're skipping the body, we're done. Don't enter the scope. |
15489 | if (SkipBody && SkipBody->ShouldSkip) |
15490 | return D; |
15491 | } |
15492 | |
15493 | // Mark this function as "will have a body eventually". This lets users to |
15494 | // call e.g. isInlineDefinitionExternallyVisible while we're still parsing |
15495 | // this function. |
15496 | FD->setWillHaveBody(); |
15497 | |
15498 | // If we are instantiating a generic lambda call operator, push |
15499 | // a LambdaScopeInfo onto the function stack. But use the information |
15500 | // that's already been calculated (ActOnLambdaExpr) to prime the current |
15501 | // LambdaScopeInfo. |
15502 | // When the template operator is being specialized, the LambdaScopeInfo, |
15503 | // has to be properly restored so that tryCaptureVariable doesn't try |
15504 | // and capture any new variables. In addition when calculating potential |
15505 | // captures during transformation of nested lambdas, it is necessary to |
15506 | // have the LSI properly restored. |
15507 | if (isGenericLambdaCallOperatorSpecialization(DC: FD)) { |
15508 | // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly |
15509 | // instantiated, explicitly specialized. |
15510 | if (FD->getTemplateSpecializationInfo() |
15511 | ->isExplicitInstantiationOrSpecialization()) { |
15512 | Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_spec); |
15513 | FD->setInvalidDecl(); |
15514 | PushFunctionScope(); |
15515 | } else { |
15516 | assert(inTemplateInstantiation() && |
15517 | "There should be an active template instantiation on the stack " |
15518 | "when instantiating a generic lambda!" ); |
15519 | RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D)); |
15520 | } |
15521 | } else { |
15522 | // Enter a new function scope |
15523 | PushFunctionScope(); |
15524 | } |
15525 | |
15526 | // Builtin functions cannot be defined. |
15527 | if (unsigned BuiltinID = FD->getBuiltinID()) { |
15528 | if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) && |
15529 | !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) { |
15530 | Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD; |
15531 | FD->setInvalidDecl(); |
15532 | } |
15533 | } |
15534 | |
15535 | // The return type of a function definition must be complete (C99 6.9.1p3). |
15536 | // C++23 [dcl.fct.def.general]/p2 |
15537 | // The type of [...] the return for a function definition |
15538 | // shall not be a (possibly cv-qualified) class type that is incomplete |
15539 | // or abstract within the function body unless the function is deleted. |
15540 | QualType ResultType = FD->getReturnType(); |
15541 | if (!ResultType->isDependentType() && !ResultType->isVoidType() && |
15542 | !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete && |
15543 | (RequireCompleteType(Loc: FD->getLocation(), T: ResultType, |
15544 | DiagID: diag::err_func_def_incomplete_result) || |
15545 | RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(), |
15546 | DiagID: diag::err_abstract_type_in_decl, |
15547 | Args: AbstractReturnType))) |
15548 | FD->setInvalidDecl(); |
15549 | |
15550 | if (FnBodyScope) |
15551 | PushDeclContext(S: FnBodyScope, DC: FD); |
15552 | |
15553 | // Check the validity of our function parameters |
15554 | if (BodyKind != FnBodyKind::Delete) |
15555 | CheckParmsForFunctionDef(Parameters: FD->parameters(), |
15556 | /*CheckParameterNames=*/true); |
15557 | |
15558 | // Add non-parameter declarations already in the function to the current |
15559 | // scope. |
15560 | if (FnBodyScope) { |
15561 | for (Decl *NPD : FD->decls()) { |
15562 | auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD); |
15563 | if (!NonParmDecl) |
15564 | continue; |
15565 | assert(!isa<ParmVarDecl>(NonParmDecl) && |
15566 | "parameters should not be in newly created FD yet" ); |
15567 | |
15568 | // If the decl has a name, make it accessible in the current scope. |
15569 | if (NonParmDecl->getDeclName()) |
15570 | PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false); |
15571 | |
15572 | // Similarly, dive into enums and fish their constants out, making them |
15573 | // accessible in this scope. |
15574 | if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) { |
15575 | for (auto *EI : ED->enumerators()) |
15576 | PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false); |
15577 | } |
15578 | } |
15579 | } |
15580 | |
15581 | // Introduce our parameters into the function scope |
15582 | for (auto *Param : FD->parameters()) { |
15583 | Param->setOwningFunction(FD); |
15584 | |
15585 | // If this has an identifier, add it to the scope stack. |
15586 | if (Param->getIdentifier() && FnBodyScope) { |
15587 | CheckShadow(S: FnBodyScope, D: Param); |
15588 | |
15589 | PushOnScopeChains(D: Param, S: FnBodyScope); |
15590 | } |
15591 | } |
15592 | |
15593 | // C++ [module.import/6] external definitions are not permitted in header |
15594 | // units. Deleted and Defaulted functions are implicitly inline (but the |
15595 | // inline state is not set at this point, so check the BodyKind explicitly). |
15596 | // FIXME: Consider an alternate location for the test where the inlined() |
15597 | // state is complete. |
15598 | if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() && |
15599 | !FD->isInvalidDecl() && !FD->isInlined() && |
15600 | BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default && |
15601 | FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() && |
15602 | !FD->isTemplateInstantiation()) { |
15603 | assert(FD->isThisDeclarationADefinition()); |
15604 | Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit); |
15605 | FD->setInvalidDecl(); |
15606 | } |
15607 | |
15608 | // Ensure that the function's exception specification is instantiated. |
15609 | if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) |
15610 | ResolveExceptionSpec(Loc: D->getLocation(), FPT); |
15611 | |
15612 | // dllimport cannot be applied to non-inline function definitions. |
15613 | if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && |
15614 | !FD->isTemplateInstantiation()) { |
15615 | assert(!FD->hasAttr<DLLExportAttr>()); |
15616 | Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition); |
15617 | FD->setInvalidDecl(); |
15618 | return D; |
15619 | } |
15620 | |
15621 | // Some function attributes (like OptimizeNoneAttr) need actions before |
15622 | // parsing body started. |
15623 | applyFunctionAttributesBeforeParsingBody(FD: D); |
15624 | |
15625 | // We want to attach documentation to original Decl (which might be |
15626 | // a function template). |
15627 | ActOnDocumentableDecl(D); |
15628 | if (getCurLexicalContext()->isObjCContainer() && |
15629 | getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && |
15630 | getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) |
15631 | Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container); |
15632 | |
15633 | return D; |
15634 | } |
15635 | |
15636 | void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) { |
15637 | if (!FD || FD->isInvalidDecl()) |
15638 | return; |
15639 | if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD)) |
15640 | FD = TD->getTemplatedDecl(); |
15641 | if (FD && FD->hasAttr<OptimizeNoneAttr>()) { |
15642 | FPOptionsOverride FPO; |
15643 | FPO.setDisallowOptimizations(); |
15644 | CurFPFeatures.applyChanges(FPO); |
15645 | FpPragmaStack.CurrentValue = |
15646 | CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts)); |
15647 | } |
15648 | } |
15649 | |
15650 | void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { |
15651 | ReturnStmt **Returns = Scope->Returns.data(); |
15652 | |
15653 | for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { |
15654 | if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { |
15655 | if (!NRVOCandidate->isNRVOVariable()) |
15656 | Returns[I]->setNRVOCandidate(nullptr); |
15657 | } |
15658 | } |
15659 | } |
15660 | |
15661 | bool Sema::canDelayFunctionBody(const Declarator &D) { |
15662 | // We can't delay parsing the body of a constexpr function template (yet). |
15663 | if (D.getDeclSpec().hasConstexprSpecifier()) |
15664 | return false; |
15665 | |
15666 | // We can't delay parsing the body of a function template with a deduced |
15667 | // return type (yet). |
15668 | if (D.getDeclSpec().hasAutoTypeSpec()) { |
15669 | // If the placeholder introduces a non-deduced trailing return type, |
15670 | // we can still delay parsing it. |
15671 | if (D.getNumTypeObjects()) { |
15672 | const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1); |
15673 | if (Outer.Kind == DeclaratorChunk::Function && |
15674 | Outer.Fun.hasTrailingReturnType()) { |
15675 | QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType()); |
15676 | return Ty.isNull() || !Ty->isUndeducedType(); |
15677 | } |
15678 | } |
15679 | return false; |
15680 | } |
15681 | |
15682 | return true; |
15683 | } |
15684 | |
15685 | bool Sema::canSkipFunctionBody(Decl *D) { |
15686 | // We cannot skip the body of a function (or function template) which is |
15687 | // constexpr, since we may need to evaluate its body in order to parse the |
15688 | // rest of the file. |
15689 | // We cannot skip the body of a function with an undeduced return type, |
15690 | // because any callers of that function need to know the type. |
15691 | if (const FunctionDecl *FD = D->getAsFunction()) { |
15692 | if (FD->isConstexpr()) |
15693 | return false; |
15694 | // We can't simply call Type::isUndeducedType here, because inside template |
15695 | // auto can be deduced to a dependent type, which is not considered |
15696 | // "undeduced". |
15697 | if (FD->getReturnType()->getContainedDeducedType()) |
15698 | return false; |
15699 | } |
15700 | return Consumer.shouldSkipFunctionBody(D); |
15701 | } |
15702 | |
15703 | Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { |
15704 | if (!Decl) |
15705 | return nullptr; |
15706 | if (FunctionDecl *FD = Decl->getAsFunction()) |
15707 | FD->setHasSkippedBody(); |
15708 | else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl)) |
15709 | MD->setHasSkippedBody(); |
15710 | return Decl; |
15711 | } |
15712 | |
15713 | Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { |
15714 | return ActOnFinishFunctionBody(Decl: D, Body: BodyArg, /*IsInstantiation=*/false); |
15715 | } |
15716 | |
15717 | /// RAII object that pops an ExpressionEvaluationContext when exiting a function |
15718 | /// body. |
15719 | class ExitFunctionBodyRAII { |
15720 | public: |
15721 | ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} |
15722 | ~ExitFunctionBodyRAII() { |
15723 | if (!IsLambda) |
15724 | S.PopExpressionEvaluationContext(); |
15725 | } |
15726 | |
15727 | private: |
15728 | Sema &S; |
15729 | bool IsLambda = false; |
15730 | }; |
15731 | |
15732 | static void diagnoseImplicitlyRetainedSelf(Sema &S) { |
15733 | llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; |
15734 | |
15735 | auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { |
15736 | if (EscapeInfo.count(Val: BD)) |
15737 | return EscapeInfo[BD]; |
15738 | |
15739 | bool R = false; |
15740 | const BlockDecl *CurBD = BD; |
15741 | |
15742 | do { |
15743 | R = !CurBD->doesNotEscape(); |
15744 | if (R) |
15745 | break; |
15746 | CurBD = CurBD->getParent()->getInnermostBlockDecl(); |
15747 | } while (CurBD); |
15748 | |
15749 | return EscapeInfo[BD] = R; |
15750 | }; |
15751 | |
15752 | // If the location where 'self' is implicitly retained is inside a escaping |
15753 | // block, emit a diagnostic. |
15754 | for (const std::pair<SourceLocation, const BlockDecl *> &P : |
15755 | S.ImplicitlyRetainedSelfLocs) |
15756 | if (IsOrNestedInEscapingBlock(P.second)) |
15757 | S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self) |
15758 | << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->" ); |
15759 | } |
15760 | |
15761 | static bool methodHasName(const FunctionDecl *FD, StringRef Name) { |
15762 | return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() && |
15763 | FD->getDeclName().isIdentifier() && FD->getName() == Name; |
15764 | } |
15765 | |
15766 | bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) { |
15767 | return methodHasName(FD, Name: "get_return_object" ); |
15768 | } |
15769 | |
15770 | bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) { |
15771 | return FD->isStatic() && |
15772 | methodHasName(FD, Name: "get_return_object_on_allocation_failure" ); |
15773 | } |
15774 | |
15775 | void Sema::CheckCoroutineWrapper(FunctionDecl *FD) { |
15776 | RecordDecl *RD = FD->getReturnType()->getAsRecordDecl(); |
15777 | if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>()) |
15778 | return; |
15779 | // Allow some_promise_type::get_return_object(). |
15780 | if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD)) |
15781 | return; |
15782 | if (!FD->hasAttr<CoroWrapperAttr>()) |
15783 | Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD; |
15784 | } |
15785 | |
15786 | Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, |
15787 | bool IsInstantiation) { |
15788 | FunctionScopeInfo *FSI = getCurFunction(); |
15789 | FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; |
15790 | |
15791 | if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) |
15792 | FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context)); |
15793 | |
15794 | sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); |
15795 | sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; |
15796 | |
15797 | // If we skip function body, we can't tell if a function is a coroutine. |
15798 | if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) { |
15799 | if (FSI->isCoroutine()) |
15800 | CheckCompletedCoroutineBody(FD, Body); |
15801 | else |
15802 | CheckCoroutineWrapper(FD); |
15803 | } |
15804 | |
15805 | { |
15806 | // Do not call PopExpressionEvaluationContext() if it is a lambda because |
15807 | // one is already popped when finishing the lambda in BuildLambdaExpr(). |
15808 | // This is meant to pop the context added in ActOnStartOfFunctionDef(). |
15809 | ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD)); |
15810 | if (FD) { |
15811 | // If this is called by Parser::ParseFunctionDefinition() after marking |
15812 | // the declaration as deleted, and if the deleted-function-body contains |
15813 | // a message (C++26), then a DefaultedOrDeletedInfo will have already been |
15814 | // added to store that message; do not overwrite it in that case. |
15815 | // |
15816 | // Since this would always set the body to 'nullptr' in that case anyway, |
15817 | // which is already done when the function decl is initially created, |
15818 | // always skipping this irrespective of whether there is a delete message |
15819 | // should not be a problem. |
15820 | if (!FD->isDeletedAsWritten()) |
15821 | FD->setBody(Body); |
15822 | FD->setWillHaveBody(false); |
15823 | CheckImmediateEscalatingFunctionDefinition(FD, FSI); |
15824 | |
15825 | if (getLangOpts().CPlusPlus14) { |
15826 | if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && |
15827 | FD->getReturnType()->isUndeducedType()) { |
15828 | // For a function with a deduced result type to return void, |
15829 | // the result type as written must be 'auto' or 'decltype(auto)', |
15830 | // possibly cv-qualified or constrained, but not ref-qualified. |
15831 | if (!FD->getReturnType()->getAs<AutoType>()) { |
15832 | Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto) |
15833 | << FD->getReturnType(); |
15834 | FD->setInvalidDecl(); |
15835 | } else { |
15836 | // Falling off the end of the function is the same as 'return;'. |
15837 | Expr *Dummy = nullptr; |
15838 | if (DeduceFunctionTypeFromReturnExpr( |
15839 | FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy, |
15840 | AT: FD->getReturnType()->getAs<AutoType>())) |
15841 | FD->setInvalidDecl(); |
15842 | } |
15843 | } |
15844 | } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) { |
15845 | // In C++11, we don't use 'auto' deduction rules for lambda call |
15846 | // operators because we don't support return type deduction. |
15847 | auto *LSI = getCurLambda(); |
15848 | if (LSI->HasImplicitReturnType) { |
15849 | deduceClosureReturnType(CSI&: *LSI); |
15850 | |
15851 | // C++11 [expr.prim.lambda]p4: |
15852 | // [...] if there are no return statements in the compound-statement |
15853 | // [the deduced type is] the type void |
15854 | QualType RetType = |
15855 | LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; |
15856 | |
15857 | // Update the return type to the deduced type. |
15858 | const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); |
15859 | FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(), |
15860 | EPI: Proto->getExtProtoInfo())); |
15861 | } |
15862 | } |
15863 | |
15864 | // If the function implicitly returns zero (like 'main') or is naked, |
15865 | // don't complain about missing return statements. |
15866 | if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) |
15867 | WP.disableCheckFallThrough(); |
15868 | |
15869 | // MSVC permits the use of pure specifier (=0) on function definition, |
15870 | // defined at class scope, warn about this non-standard construct. |
15871 | if (getLangOpts().MicrosoftExt && FD->isPureVirtual() && |
15872 | !FD->isOutOfLine()) |
15873 | Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition); |
15874 | |
15875 | if (!FD->isInvalidDecl()) { |
15876 | // Don't diagnose unused parameters of defaulted, deleted or naked |
15877 | // functions. |
15878 | if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() && |
15879 | !FD->hasAttr<NakedAttr>()) |
15880 | DiagnoseUnusedParameters(Parameters: FD->parameters()); |
15881 | DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(), |
15882 | ReturnTy: FD->getReturnType(), D: FD); |
15883 | |
15884 | // If this is a structor, we need a vtable. |
15885 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD)) |
15886 | MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent()); |
15887 | else if (CXXDestructorDecl *Destructor = |
15888 | dyn_cast<CXXDestructorDecl>(Val: FD)) |
15889 | MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent()); |
15890 | |
15891 | // Try to apply the named return value optimization. We have to check |
15892 | // if we can do this here because lambdas keep return statements around |
15893 | // to deduce an implicit return type. |
15894 | if (FD->getReturnType()->isRecordType() && |
15895 | (!getLangOpts().CPlusPlus || !FD->isDependentContext())) |
15896 | computeNRVO(Body, Scope: FSI); |
15897 | } |
15898 | |
15899 | // GNU warning -Wmissing-prototypes: |
15900 | // Warn if a global function is defined without a previous |
15901 | // prototype declaration. This warning is issued even if the |
15902 | // definition itself provides a prototype. The aim is to detect |
15903 | // global functions that fail to be declared in header files. |
15904 | const FunctionDecl *PossiblePrototype = nullptr; |
15905 | if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { |
15906 | Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD; |
15907 | |
15908 | if (PossiblePrototype) { |
15909 | // We found a declaration that is not a prototype, |
15910 | // but that could be a zero-parameter prototype |
15911 | if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { |
15912 | TypeLoc TL = TI->getTypeLoc(); |
15913 | if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) |
15914 | Diag(Loc: PossiblePrototype->getLocation(), |
15915 | DiagID: diag::note_declaration_not_a_prototype) |
15916 | << (FD->getNumParams() != 0) |
15917 | << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( |
15918 | InsertionLoc: FTL.getRParenLoc(), Code: "void" ) |
15919 | : FixItHint{}); |
15920 | } |
15921 | } else { |
15922 | // Returns true if the token beginning at this Loc is `const`. |
15923 | auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, |
15924 | const LangOptions &LangOpts) { |
15925 | std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); |
15926 | if (LocInfo.first.isInvalid()) |
15927 | return false; |
15928 | |
15929 | bool Invalid = false; |
15930 | StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid); |
15931 | if (Invalid) |
15932 | return false; |
15933 | |
15934 | if (LocInfo.second > Buffer.size()) |
15935 | return false; |
15936 | |
15937 | const char *LexStart = Buffer.data() + LocInfo.second; |
15938 | StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); |
15939 | |
15940 | return StartTok.consume_front(Prefix: "const" ) && |
15941 | (StartTok.empty() || isWhitespace(c: StartTok[0]) || |
15942 | StartTok.starts_with(Prefix: "/*" ) || StartTok.starts_with(Prefix: "//" )); |
15943 | }; |
15944 | |
15945 | auto findBeginLoc = [&]() { |
15946 | // If the return type has `const` qualifier, we want to insert |
15947 | // `static` before `const` (and not before the typename). |
15948 | if ((FD->getReturnType()->isAnyPointerType() && |
15949 | FD->getReturnType()->getPointeeType().isConstQualified()) || |
15950 | FD->getReturnType().isConstQualified()) { |
15951 | // But only do this if we can determine where the `const` is. |
15952 | |
15953 | if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), |
15954 | getLangOpts())) |
15955 | |
15956 | return FD->getBeginLoc(); |
15957 | } |
15958 | return FD->getTypeSpecStartLoc(); |
15959 | }; |
15960 | Diag(Loc: FD->getTypeSpecStartLoc(), |
15961 | DiagID: diag::note_static_for_internal_linkage) |
15962 | << /* function */ 1 |
15963 | << (FD->getStorageClass() == SC_None |
15964 | ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static " ) |
15965 | : FixItHint{}); |
15966 | } |
15967 | } |
15968 | |
15969 | // We might not have found a prototype because we didn't wish to warn on |
15970 | // the lack of a missing prototype. Try again without the checks for |
15971 | // whether we want to warn on the missing prototype. |
15972 | if (!PossiblePrototype) |
15973 | (void)FindPossiblePrototype(FD, PossiblePrototype); |
15974 | |
15975 | // If the function being defined does not have a prototype, then we may |
15976 | // need to diagnose it as changing behavior in C23 because we now know |
15977 | // whether the function accepts arguments or not. This only handles the |
15978 | // case where the definition has no prototype but does have parameters |
15979 | // and either there is no previous potential prototype, or the previous |
15980 | // potential prototype also has no actual prototype. This handles cases |
15981 | // like: |
15982 | // void f(); void f(a) int a; {} |
15983 | // void g(a) int a; {} |
15984 | // See MergeFunctionDecl() for other cases of the behavior change |
15985 | // diagnostic. See GetFullTypeForDeclarator() for handling of a function |
15986 | // type without a prototype. |
15987 | if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 && |
15988 | (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() && |
15989 | !PossiblePrototype->isImplicit()))) { |
15990 | // The function definition has parameters, so this will change behavior |
15991 | // in C23. If there is a possible prototype, it comes before the |
15992 | // function definition. |
15993 | // FIXME: The declaration may have already been diagnosed as being |
15994 | // deprecated in GetFullTypeForDeclarator() if it had no arguments, but |
15995 | // there's no way to test for the "changes behavior" condition in |
15996 | // SemaType.cpp when forming the declaration's function type. So, we do |
15997 | // this awkward dance instead. |
15998 | // |
15999 | // If we have a possible prototype and it declares a function with a |
16000 | // prototype, we don't want to diagnose it; if we have a possible |
16001 | // prototype and it has no prototype, it may have already been |
16002 | // diagnosed in SemaType.cpp as deprecated depending on whether |
16003 | // -Wstrict-prototypes is enabled. If we already warned about it being |
16004 | // deprecated, add a note that it also changes behavior. If we didn't |
16005 | // warn about it being deprecated (because the diagnostic is not |
16006 | // enabled), warn now that it is deprecated and changes behavior. |
16007 | |
16008 | // This K&R C function definition definitely changes behavior in C23, |
16009 | // so diagnose it. |
16010 | Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior) |
16011 | << /*definition*/ 1 << /* not supported in C23 */ 0; |
16012 | |
16013 | // If we have a possible prototype for the function which is a user- |
16014 | // visible declaration, we already tested that it has no prototype. |
16015 | // This will change behavior in C23. This gets a warning rather than a |
16016 | // note because it's the same behavior-changing problem as with the |
16017 | // definition. |
16018 | if (PossiblePrototype) |
16019 | Diag(Loc: PossiblePrototype->getLocation(), |
16020 | DiagID: diag::warn_non_prototype_changes_behavior) |
16021 | << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1 |
16022 | << /*definition*/ 1; |
16023 | } |
16024 | |
16025 | // Warn on CPUDispatch with an actual body. |
16026 | if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) |
16027 | if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body)) |
16028 | if (!CmpndBody->body_empty()) |
16029 | Diag(Loc: CmpndBody->body_front()->getBeginLoc(), |
16030 | DiagID: diag::warn_dispatch_body_ignored); |
16031 | |
16032 | if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) { |
16033 | const CXXMethodDecl *KeyFunction; |
16034 | if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && |
16035 | MD->isVirtual() && |
16036 | (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) && |
16037 | MD == KeyFunction->getCanonicalDecl()) { |
16038 | // Update the key-function state if necessary for this ABI. |
16039 | if (FD->isInlined() && |
16040 | !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { |
16041 | Context.setNonKeyFunction(MD); |
16042 | |
16043 | // If the newly-chosen key function is already defined, then we |
16044 | // need to mark the vtable as used retroactively. |
16045 | KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent()); |
16046 | const FunctionDecl *Definition; |
16047 | if (KeyFunction && KeyFunction->isDefined(Definition)) |
16048 | MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true); |
16049 | } else { |
16050 | // We just defined they key function; mark the vtable as used. |
16051 | MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true); |
16052 | } |
16053 | } |
16054 | } |
16055 | |
16056 | assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) && |
16057 | "Function parsing confused" ); |
16058 | } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) { |
16059 | assert(MD == getCurMethodDecl() && "Method parsing confused" ); |
16060 | MD->setBody(Body); |
16061 | if (!MD->isInvalidDecl()) { |
16062 | DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(), |
16063 | ReturnTy: MD->getReturnType(), D: MD); |
16064 | |
16065 | if (Body) |
16066 | computeNRVO(Body, Scope: FSI); |
16067 | } |
16068 | if (FSI->ObjCShouldCallSuper) { |
16069 | Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call) |
16070 | << MD->getSelector().getAsString(); |
16071 | FSI->ObjCShouldCallSuper = false; |
16072 | } |
16073 | if (FSI->ObjCWarnForNoDesignatedInitChain) { |
16074 | const ObjCMethodDecl *InitMethod = nullptr; |
16075 | bool isDesignated = |
16076 | MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod); |
16077 | assert(isDesignated && InitMethod); |
16078 | (void)isDesignated; |
16079 | |
16080 | auto superIsNSObject = [&](const ObjCMethodDecl *MD) { |
16081 | auto IFace = MD->getClassInterface(); |
16082 | if (!IFace) |
16083 | return false; |
16084 | auto SuperD = IFace->getSuperClass(); |
16085 | if (!SuperD) |
16086 | return false; |
16087 | return SuperD->getIdentifier() == |
16088 | ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject); |
16089 | }; |
16090 | // Don't issue this warning for unavailable inits or direct subclasses |
16091 | // of NSObject. |
16092 | if (!MD->isUnavailable() && !superIsNSObject(MD)) { |
16093 | Diag(Loc: MD->getLocation(), |
16094 | DiagID: diag::warn_objc_designated_init_missing_super_call); |
16095 | Diag(Loc: InitMethod->getLocation(), |
16096 | DiagID: diag::note_objc_designated_init_marked_here); |
16097 | } |
16098 | FSI->ObjCWarnForNoDesignatedInitChain = false; |
16099 | } |
16100 | if (FSI->ObjCWarnForNoInitDelegation) { |
16101 | // Don't issue this warning for unavailable inits. |
16102 | if (!MD->isUnavailable()) |
16103 | Diag(Loc: MD->getLocation(), |
16104 | DiagID: diag::warn_objc_secondary_init_missing_init_call); |
16105 | FSI->ObjCWarnForNoInitDelegation = false; |
16106 | } |
16107 | |
16108 | diagnoseImplicitlyRetainedSelf(S&: *this); |
16109 | } else { |
16110 | // Parsing the function declaration failed in some way. Pop the fake scope |
16111 | // we pushed on. |
16112 | PopFunctionScopeInfo(WP: ActivePolicy, D: dcl); |
16113 | return nullptr; |
16114 | } |
16115 | |
16116 | if (Body && FSI->HasPotentialAvailabilityViolations) |
16117 | DiagnoseUnguardedAvailabilityViolations(FD: dcl); |
16118 | |
16119 | assert(!FSI->ObjCShouldCallSuper && |
16120 | "This should only be set for ObjC methods, which should have been " |
16121 | "handled in the block above." ); |
16122 | |
16123 | // Verify and clean out per-function state. |
16124 | if (Body && (!FD || !FD->isDefaulted())) { |
16125 | // C++ constructors that have function-try-blocks can't have return |
16126 | // statements in the handlers of that block. (C++ [except.handle]p14) |
16127 | // Verify this. |
16128 | if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body)) |
16129 | DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body)); |
16130 | |
16131 | // Verify that gotos and switch cases don't jump into scopes illegally. |
16132 | if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) |
16133 | DiagnoseInvalidJumps(Body); |
16134 | |
16135 | if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) { |
16136 | if (!Destructor->getParent()->isDependentType()) |
16137 | CheckDestructor(Destructor); |
16138 | |
16139 | MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(), |
16140 | Record: Destructor->getParent()); |
16141 | } |
16142 | |
16143 | // If any errors have occurred, clear out any temporaries that may have |
16144 | // been leftover. This ensures that these temporaries won't be picked up |
16145 | // for deletion in some later function. |
16146 | if (hasUncompilableErrorOccurred() || |
16147 | hasAnyUnrecoverableErrorsInThisFunction() || |
16148 | getDiagnostics().getSuppressAllDiagnostics()) { |
16149 | DiscardCleanupsInEvaluationContext(); |
16150 | } |
16151 | if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) { |
16152 | // Since the body is valid, issue any analysis-based warnings that are |
16153 | // enabled. |
16154 | ActivePolicy = &WP; |
16155 | } |
16156 | |
16157 | if (!IsInstantiation && FD && |
16158 | (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) && |
16159 | !FD->isInvalidDecl() && |
16160 | !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose)) |
16161 | FD->setInvalidDecl(); |
16162 | |
16163 | if (FD && FD->hasAttr<NakedAttr>()) { |
16164 | for (const Stmt *S : Body->children()) { |
16165 | // Allow local register variables without initializer as they don't |
16166 | // require prologue. |
16167 | bool RegisterVariables = false; |
16168 | if (auto *DS = dyn_cast<DeclStmt>(Val: S)) { |
16169 | for (const auto *Decl : DS->decls()) { |
16170 | if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) { |
16171 | RegisterVariables = |
16172 | Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); |
16173 | if (!RegisterVariables) |
16174 | break; |
16175 | } |
16176 | } |
16177 | } |
16178 | if (RegisterVariables) |
16179 | continue; |
16180 | if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) { |
16181 | Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function); |
16182 | Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute); |
16183 | FD->setInvalidDecl(); |
16184 | break; |
16185 | } |
16186 | } |
16187 | } |
16188 | |
16189 | assert(ExprCleanupObjects.size() == |
16190 | ExprEvalContexts.back().NumCleanupObjects && |
16191 | "Leftover temporaries in function" ); |
16192 | assert(!Cleanup.exprNeedsCleanups() && |
16193 | "Unaccounted cleanups in function" ); |
16194 | assert(MaybeODRUseExprs.empty() && |
16195 | "Leftover expressions for odr-use checking" ); |
16196 | } |
16197 | } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop |
16198 | // the declaration context below. Otherwise, we're unable to transform |
16199 | // 'this' expressions when transforming immediate context functions. |
16200 | |
16201 | if (!IsInstantiation) |
16202 | PopDeclContext(); |
16203 | |
16204 | PopFunctionScopeInfo(WP: ActivePolicy, D: dcl); |
16205 | // If any errors have occurred, clear out any temporaries that may have |
16206 | // been leftover. This ensures that these temporaries won't be picked up for |
16207 | // deletion in some later function. |
16208 | if (hasUncompilableErrorOccurred()) { |
16209 | DiscardCleanupsInEvaluationContext(); |
16210 | } |
16211 | |
16212 | if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice || |
16213 | !LangOpts.OMPTargetTriples.empty())) || |
16214 | LangOpts.CUDA || LangOpts.SYCLIsDevice)) { |
16215 | auto ES = getEmissionStatus(Decl: FD); |
16216 | if (ES == Sema::FunctionEmissionStatus::Emitted || |
16217 | ES == Sema::FunctionEmissionStatus::Unknown) |
16218 | DeclsToCheckForDeferredDiags.insert(X: FD); |
16219 | } |
16220 | |
16221 | if (FD && !FD->isDeleted()) |
16222 | checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD); |
16223 | |
16224 | return dcl; |
16225 | } |
16226 | |
16227 | /// When we finish delayed parsing of an attribute, we must attach it to the |
16228 | /// relevant Decl. |
16229 | void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, |
16230 | ParsedAttributes &Attrs) { |
16231 | // Always attach attributes to the underlying decl. |
16232 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) |
16233 | D = TD->getTemplatedDecl(); |
16234 | ProcessDeclAttributeList(S, D, AttrList: Attrs); |
16235 | ProcessAPINotes(D); |
16236 | |
16237 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D)) |
16238 | if (Method->isStatic()) |
16239 | checkThisInStaticMemberFunctionAttributes(Method); |
16240 | } |
16241 | |
16242 | NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, |
16243 | IdentifierInfo &II, Scope *S) { |
16244 | // It is not valid to implicitly define a function in C23. |
16245 | assert(LangOpts.implicitFunctionsAllowed() && |
16246 | "Implicit function declarations aren't allowed in this language mode" ); |
16247 | |
16248 | // Find the scope in which the identifier is injected and the corresponding |
16249 | // DeclContext. |
16250 | // FIXME: C89 does not say what happens if there is no enclosing block scope. |
16251 | // In that case, we inject the declaration into the translation unit scope |
16252 | // instead. |
16253 | Scope *BlockScope = S; |
16254 | while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) |
16255 | BlockScope = BlockScope->getParent(); |
16256 | |
16257 | // Loop until we find a DeclContext that is either a function/method or the |
16258 | // translation unit, which are the only two valid places to implicitly define |
16259 | // a function. This avoids accidentally defining the function within a tag |
16260 | // declaration, for example. |
16261 | Scope *ContextScope = BlockScope; |
16262 | while (!ContextScope->getEntity() || |
16263 | (!ContextScope->getEntity()->isFunctionOrMethod() && |
16264 | !ContextScope->getEntity()->isTranslationUnit())) |
16265 | ContextScope = ContextScope->getParent(); |
16266 | ContextRAII SavedContext(*this, ContextScope->getEntity()); |
16267 | |
16268 | // Before we produce a declaration for an implicitly defined |
16269 | // function, see whether there was a locally-scoped declaration of |
16270 | // this name as a function or variable. If so, use that |
16271 | // (non-visible) declaration, and complain about it. |
16272 | NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II); |
16273 | if (ExternCPrev) { |
16274 | // We still need to inject the function into the enclosing block scope so |
16275 | // that later (non-call) uses can see it. |
16276 | PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false); |
16277 | |
16278 | // C89 footnote 38: |
16279 | // If in fact it is not defined as having type "function returning int", |
16280 | // the behavior is undefined. |
16281 | if (!isa<FunctionDecl>(Val: ExternCPrev) || |
16282 | !Context.typesAreCompatible( |
16283 | T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(), |
16284 | T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) { |
16285 | Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration) |
16286 | << ExternCPrev << !getLangOpts().C99; |
16287 | Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration); |
16288 | return ExternCPrev; |
16289 | } |
16290 | } |
16291 | |
16292 | // Extension in C99 (defaults to error). Legal in C89, but warn about it. |
16293 | unsigned diag_id; |
16294 | if (II.getName().starts_with(Prefix: "__builtin_" )) |
16295 | diag_id = diag::warn_builtin_unknown; |
16296 | // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. |
16297 | else if (getLangOpts().C99) |
16298 | diag_id = diag::ext_implicit_function_decl_c99; |
16299 | else |
16300 | diag_id = diag::warn_implicit_function_decl; |
16301 | |
16302 | TypoCorrection Corrected; |
16303 | // Because typo correction is expensive, only do it if the implicit |
16304 | // function declaration is going to be treated as an error. |
16305 | // |
16306 | // Perform the correction before issuing the main diagnostic, as some |
16307 | // consumers use typo-correction callbacks to enhance the main diagnostic. |
16308 | if (S && !ExternCPrev && |
16309 | (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) { |
16310 | DeclFilterCCC<FunctionDecl> CCC{}; |
16311 | Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName, |
16312 | S, SS: nullptr, CCC, Mode: CTK_NonError); |
16313 | } |
16314 | |
16315 | Diag(Loc, DiagID: diag_id) << &II; |
16316 | if (Corrected) { |
16317 | // If the correction is going to suggest an implicitly defined function, |
16318 | // skip the correction as not being a particularly good idea. |
16319 | bool Diagnose = true; |
16320 | if (const auto *D = Corrected.getCorrectionDecl()) |
16321 | Diagnose = !D->isImplicit(); |
16322 | if (Diagnose) |
16323 | diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion), |
16324 | /*ErrorRecovery*/ false); |
16325 | } |
16326 | |
16327 | // If we found a prior declaration of this function, don't bother building |
16328 | // another one. We've already pushed that one into scope, so there's nothing |
16329 | // more to do. |
16330 | if (ExternCPrev) |
16331 | return ExternCPrev; |
16332 | |
16333 | // Set a Declarator for the implicit definition: int foo(); |
16334 | const char *Dummy; |
16335 | AttributeFactory attrFactory; |
16336 | DeclSpec DS(attrFactory); |
16337 | unsigned DiagID; |
16338 | bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID, |
16339 | Policy: Context.getPrintingPolicy()); |
16340 | (void)Error; // Silence warning. |
16341 | assert(!Error && "Error setting up implicit decl!" ); |
16342 | SourceLocation NoLoc; |
16343 | Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block); |
16344 | D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false, |
16345 | /*IsAmbiguous=*/false, |
16346 | /*LParenLoc=*/NoLoc, |
16347 | /*Params=*/nullptr, |
16348 | /*NumParams=*/0, |
16349 | /*EllipsisLoc=*/NoLoc, |
16350 | /*RParenLoc=*/NoLoc, |
16351 | /*RefQualifierIsLvalueRef=*/true, |
16352 | /*RefQualifierLoc=*/NoLoc, |
16353 | /*MutableLoc=*/NoLoc, ESpecType: EST_None, |
16354 | /*ESpecRange=*/SourceRange(), |
16355 | /*Exceptions=*/nullptr, |
16356 | /*ExceptionRanges=*/nullptr, |
16357 | /*NumExceptions=*/0, |
16358 | /*NoexceptExpr=*/nullptr, |
16359 | /*ExceptionSpecTokens=*/nullptr, |
16360 | /*DeclsInPrototype=*/std::nullopt, |
16361 | LocalRangeBegin: Loc, LocalRangeEnd: Loc, TheDeclarator&: D), |
16362 | attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation()); |
16363 | D.SetIdentifier(Id: &II, IdLoc: Loc); |
16364 | |
16365 | // Insert this function into the enclosing block scope. |
16366 | FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D)); |
16367 | FD->setImplicit(); |
16368 | |
16369 | AddKnownFunctionAttributes(FD); |
16370 | |
16371 | return FD; |
16372 | } |
16373 | |
16374 | void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( |
16375 | FunctionDecl *FD) { |
16376 | if (FD->isInvalidDecl()) |
16377 | return; |
16378 | |
16379 | if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && |
16380 | FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) |
16381 | return; |
16382 | |
16383 | std::optional<unsigned> AlignmentParam; |
16384 | bool IsNothrow = false; |
16385 | if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow)) |
16386 | return; |
16387 | |
16388 | // C++2a [basic.stc.dynamic.allocation]p4: |
16389 | // An allocation function that has a non-throwing exception specification |
16390 | // indicates failure by returning a null pointer value. Any other allocation |
16391 | // function never returns a null pointer value and indicates failure only by |
16392 | // throwing an exception [...] |
16393 | // |
16394 | // However, -fcheck-new invalidates this possible assumption, so don't add |
16395 | // NonNull when that is enabled. |
16396 | if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() && |
16397 | !getLangOpts().CheckNew) |
16398 | FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation())); |
16399 | |
16400 | // C++2a [basic.stc.dynamic.allocation]p2: |
16401 | // An allocation function attempts to allocate the requested amount of |
16402 | // storage. [...] If the request succeeds, the value returned by a |
16403 | // replaceable allocation function is a [...] pointer value p0 different |
16404 | // from any previously returned value p1 [...] |
16405 | // |
16406 | // However, this particular information is being added in codegen, |
16407 | // because there is an opt-out switch for it (-fno-assume-sane-operator-new) |
16408 | |
16409 | // C++2a [basic.stc.dynamic.allocation]p2: |
16410 | // An allocation function attempts to allocate the requested amount of |
16411 | // storage. If it is successful, it returns the address of the start of a |
16412 | // block of storage whose length in bytes is at least as large as the |
16413 | // requested size. |
16414 | if (!FD->hasAttr<AllocSizeAttr>()) { |
16415 | FD->addAttr(A: AllocSizeAttr::CreateImplicit( |
16416 | Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD), |
16417 | /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation())); |
16418 | } |
16419 | |
16420 | // C++2a [basic.stc.dynamic.allocation]p3: |
16421 | // For an allocation function [...], the pointer returned on a successful |
16422 | // call shall represent the address of storage that is aligned as follows: |
16423 | // (3.1) If the allocation function takes an argument of type |
16424 | // std​::​align_Âval_Ât, the storage will have the alignment |
16425 | // specified by the value of this argument. |
16426 | if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) { |
16427 | FD->addAttr(A: AllocAlignAttr::CreateImplicit( |
16428 | Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation())); |
16429 | } |
16430 | |
16431 | // FIXME: |
16432 | // C++2a [basic.stc.dynamic.allocation]p3: |
16433 | // For an allocation function [...], the pointer returned on a successful |
16434 | // call shall represent the address of storage that is aligned as follows: |
16435 | // (3.2) Otherwise, if the allocation function is named operator new[], |
16436 | // the storage is aligned for any object that does not have |
16437 | // new-extended alignment ([basic.align]) and is no larger than the |
16438 | // requested size. |
16439 | // (3.3) Otherwise, the storage is aligned for any object that does not |
16440 | // have new-extended alignment and is of the requested size. |
16441 | } |
16442 | |
16443 | void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { |
16444 | if (FD->isInvalidDecl()) |
16445 | return; |
16446 | |
16447 | // If this is a built-in function, map its builtin attributes to |
16448 | // actual attributes. |
16449 | if (unsigned BuiltinID = FD->getBuiltinID()) { |
16450 | // Handle printf-formatting attributes. |
16451 | unsigned FormatIdx; |
16452 | bool HasVAListArg; |
16453 | if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) { |
16454 | if (!FD->hasAttr<FormatAttr>()) { |
16455 | const char *fmt = "printf" ; |
16456 | unsigned int NumParams = FD->getNumParams(); |
16457 | if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) |
16458 | FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType()) |
16459 | fmt = "NSString" ; |
16460 | FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context, |
16461 | Type: &Context.Idents.get(Name: fmt), |
16462 | FormatIdx: FormatIdx+1, |
16463 | FirstArg: HasVAListArg ? 0 : FormatIdx+2, |
16464 | Range: FD->getLocation())); |
16465 | } |
16466 | } |
16467 | if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx, |
16468 | HasVAListArg)) { |
16469 | if (!FD->hasAttr<FormatAttr>()) |
16470 | FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context, |
16471 | Type: &Context.Idents.get(Name: "scanf" ), |
16472 | FormatIdx: FormatIdx+1, |
16473 | FirstArg: HasVAListArg ? 0 : FormatIdx+2, |
16474 | Range: FD->getLocation())); |
16475 | } |
16476 | |
16477 | // Handle automatically recognized callbacks. |
16478 | SmallVector<int, 4> Encoding; |
16479 | if (!FD->hasAttr<CallbackAttr>() && |
16480 | Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding)) |
16481 | FD->addAttr(A: CallbackAttr::CreateImplicit( |
16482 | Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation())); |
16483 | |
16484 | // Mark const if we don't care about errno and/or floating point exceptions |
16485 | // that are the only thing preventing the function from being const. This |
16486 | // allows IRgen to use LLVM intrinsics for such functions. |
16487 | bool NoExceptions = |
16488 | getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore; |
16489 | bool ConstWithoutErrnoAndExceptions = |
16490 | Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID); |
16491 | bool ConstWithoutExceptions = |
16492 | Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID); |
16493 | if (!FD->hasAttr<ConstAttr>() && |
16494 | (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) && |
16495 | (!ConstWithoutErrnoAndExceptions || |
16496 | (!getLangOpts().MathErrno && NoExceptions)) && |
16497 | (!ConstWithoutExceptions || NoExceptions)) |
16498 | FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation())); |
16499 | |
16500 | // We make "fma" on GNU or Windows const because we know it does not set |
16501 | // errno in those environments even though it could set errno based on the |
16502 | // C standard. |
16503 | const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); |
16504 | if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && |
16505 | !FD->hasAttr<ConstAttr>()) { |
16506 | switch (BuiltinID) { |
16507 | case Builtin::BI__builtin_fma: |
16508 | case Builtin::BI__builtin_fmaf: |
16509 | case Builtin::BI__builtin_fmal: |
16510 | case Builtin::BIfma: |
16511 | case Builtin::BIfmaf: |
16512 | case Builtin::BIfmal: |
16513 | FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation())); |
16514 | break; |
16515 | default: |
16516 | break; |
16517 | } |
16518 | } |
16519 | |
16520 | if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) && |
16521 | !FD->hasAttr<ReturnsTwiceAttr>()) |
16522 | FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context, |
16523 | Range: FD->getLocation())); |
16524 | if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>()) |
16525 | FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation())); |
16526 | if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>()) |
16527 | FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation())); |
16528 | if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>()) |
16529 | FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation())); |
16530 | if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) && |
16531 | !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { |
16532 | // Add the appropriate attribute, depending on the CUDA compilation mode |
16533 | // and which target the builtin belongs to. For example, during host |
16534 | // compilation, aux builtins are __device__, while the rest are __host__. |
16535 | if (getLangOpts().CUDAIsDevice != |
16536 | Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID)) |
16537 | FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation())); |
16538 | else |
16539 | FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation())); |
16540 | } |
16541 | |
16542 | // Add known guaranteed alignment for allocation functions. |
16543 | switch (BuiltinID) { |
16544 | case Builtin::BImemalign: |
16545 | case Builtin::BIaligned_alloc: |
16546 | if (!FD->hasAttr<AllocAlignAttr>()) |
16547 | FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD), |
16548 | Range: FD->getLocation())); |
16549 | break; |
16550 | default: |
16551 | break; |
16552 | } |
16553 | |
16554 | // Add allocsize attribute for allocation functions. |
16555 | switch (BuiltinID) { |
16556 | case Builtin::BIcalloc: |
16557 | FD->addAttr(A: AllocSizeAttr::CreateImplicit( |
16558 | Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation())); |
16559 | break; |
16560 | case Builtin::BImemalign: |
16561 | case Builtin::BIaligned_alloc: |
16562 | case Builtin::BIrealloc: |
16563 | FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD), |
16564 | NumElemsParam: ParamIdx(), Range: FD->getLocation())); |
16565 | break; |
16566 | case Builtin::BImalloc: |
16567 | FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), |
16568 | NumElemsParam: ParamIdx(), Range: FD->getLocation())); |
16569 | break; |
16570 | default: |
16571 | break; |
16572 | } |
16573 | |
16574 | // Add lifetime attribute to std::move, std::fowrard et al. |
16575 | switch (BuiltinID) { |
16576 | case Builtin::BIaddressof: |
16577 | case Builtin::BI__addressof: |
16578 | case Builtin::BI__builtin_addressof: |
16579 | case Builtin::BIas_const: |
16580 | case Builtin::BIforward: |
16581 | case Builtin::BIforward_like: |
16582 | case Builtin::BImove: |
16583 | case Builtin::BImove_if_noexcept: |
16584 | if (ParmVarDecl *P = FD->getParamDecl(i: 0u); |
16585 | !P->hasAttr<LifetimeBoundAttr>()) |
16586 | P->addAttr( |
16587 | A: LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation())); |
16588 | break; |
16589 | default: |
16590 | break; |
16591 | } |
16592 | } |
16593 | |
16594 | AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); |
16595 | |
16596 | // If C++ exceptions are enabled but we are told extern "C" functions cannot |
16597 | // throw, add an implicit nothrow attribute to any extern "C" function we come |
16598 | // across. |
16599 | if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && |
16600 | FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { |
16601 | const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); |
16602 | if (!FPT || FPT->getExceptionSpecType() == EST_None) |
16603 | FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation())); |
16604 | } |
16605 | |
16606 | IdentifierInfo *Name = FD->getIdentifier(); |
16607 | if (!Name) |
16608 | return; |
16609 | if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) || |
16610 | (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) && |
16611 | cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() == |
16612 | LinkageSpecLanguageIDs::C)) { |
16613 | // Okay: this could be a libc/libm/Objective-C function we know |
16614 | // about. |
16615 | } else |
16616 | return; |
16617 | |
16618 | if (Name->isStr(Str: "asprintf" ) || Name->isStr(Str: "vasprintf" )) { |
16619 | // FIXME: asprintf and vasprintf aren't C99 functions. Should they be |
16620 | // target-specific builtins, perhaps? |
16621 | if (!FD->hasAttr<FormatAttr>()) |
16622 | FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context, |
16623 | Type: &Context.Idents.get(Name: "printf" ), FormatIdx: 2, |
16624 | FirstArg: Name->isStr(Str: "vasprintf" ) ? 0 : 3, |
16625 | Range: FD->getLocation())); |
16626 | } |
16627 | |
16628 | if (Name->isStr(Str: "__CFStringMakeConstantString" )) { |
16629 | // We already have a __builtin___CFStringMakeConstantString, |
16630 | // but builds that use -fno-constant-cfstrings don't go through that. |
16631 | if (!FD->hasAttr<FormatArgAttr>()) |
16632 | FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD), |
16633 | Range: FD->getLocation())); |
16634 | } |
16635 | } |
16636 | |
16637 | TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, |
16638 | TypeSourceInfo *TInfo) { |
16639 | assert(D.getIdentifier() && "Wrong callback for declspec without declarator" ); |
16640 | assert(!T.isNull() && "GetTypeForDeclarator() returned null type" ); |
16641 | |
16642 | if (!TInfo) { |
16643 | assert(D.isInvalidType() && "no declarator info for valid type" ); |
16644 | TInfo = Context.getTrivialTypeSourceInfo(T); |
16645 | } |
16646 | |
16647 | // Scope manipulation handled by caller. |
16648 | TypedefDecl *NewTD = |
16649 | TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(), |
16650 | IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo); |
16651 | |
16652 | // Bail out immediately if we have an invalid declaration. |
16653 | if (D.isInvalidType()) { |
16654 | NewTD->setInvalidDecl(); |
16655 | return NewTD; |
16656 | } |
16657 | |
16658 | if (D.getDeclSpec().isModulePrivateSpecified()) { |
16659 | if (CurContext->isFunctionOrMethod()) |
16660 | Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local) |
16661 | << 2 << NewTD |
16662 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) |
16663 | << FixItHint::CreateRemoval( |
16664 | RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc()); |
16665 | else |
16666 | NewTD->setModulePrivate(); |
16667 | } |
16668 | |
16669 | // C++ [dcl.typedef]p8: |
16670 | // If the typedef declaration defines an unnamed class (or |
16671 | // enum), the first typedef-name declared by the declaration |
16672 | // to be that class type (or enum type) is used to denote the |
16673 | // class type (or enum type) for linkage purposes only. |
16674 | // We need to check whether the type was declared in the declaration. |
16675 | switch (D.getDeclSpec().getTypeSpecType()) { |
16676 | case TST_enum: |
16677 | case TST_struct: |
16678 | case TST_interface: |
16679 | case TST_union: |
16680 | case TST_class: { |
16681 | TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl()); |
16682 | setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD); |
16683 | break; |
16684 | } |
16685 | |
16686 | default: |
16687 | break; |
16688 | } |
16689 | |
16690 | return NewTD; |
16691 | } |
16692 | |
16693 | bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { |
16694 | SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); |
16695 | QualType T = TI->getType(); |
16696 | |
16697 | if (T->isDependentType()) |
16698 | return false; |
16699 | |
16700 | // This doesn't use 'isIntegralType' despite the error message mentioning |
16701 | // integral type because isIntegralType would also allow enum types in C. |
16702 | if (const BuiltinType *BT = T->getAs<BuiltinType>()) |
16703 | if (BT->isInteger()) |
16704 | return false; |
16705 | |
16706 | return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying) |
16707 | << T << T->isBitIntType(); |
16708 | } |
16709 | |
16710 | bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, |
16711 | QualType EnumUnderlyingTy, bool IsFixed, |
16712 | const EnumDecl *Prev) { |
16713 | if (IsScoped != Prev->isScoped()) { |
16714 | Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch) |
16715 | << Prev->isScoped(); |
16716 | Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration); |
16717 | return true; |
16718 | } |
16719 | |
16720 | if (IsFixed && Prev->isFixed()) { |
16721 | if (!EnumUnderlyingTy->isDependentType() && |
16722 | !Prev->getIntegerType()->isDependentType() && |
16723 | !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy, |
16724 | T2: Prev->getIntegerType())) { |
16725 | // TODO: Highlight the underlying type of the redeclaration. |
16726 | Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch) |
16727 | << EnumUnderlyingTy << Prev->getIntegerType(); |
16728 | Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration) |
16729 | << Prev->getIntegerTypeRange(); |
16730 | return true; |
16731 | } |
16732 | } else if (IsFixed != Prev->isFixed()) { |
16733 | Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch) |
16734 | << Prev->isFixed(); |
16735 | Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration); |
16736 | return true; |
16737 | } |
16738 | |
16739 | return false; |
16740 | } |
16741 | |
16742 | /// Get diagnostic %select index for tag kind for |
16743 | /// redeclaration diagnostic message. |
16744 | /// WARNING: Indexes apply to particular diagnostics only! |
16745 | /// |
16746 | /// \returns diagnostic %select index. |
16747 | static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { |
16748 | switch (Tag) { |
16749 | case TagTypeKind::Struct: |
16750 | return 0; |
16751 | case TagTypeKind::Interface: |
16752 | return 1; |
16753 | case TagTypeKind::Class: |
16754 | return 2; |
16755 | default: llvm_unreachable("Invalid tag kind for redecl diagnostic!" ); |
16756 | } |
16757 | } |
16758 | |
16759 | /// Determine if tag kind is a class-key compatible with |
16760 | /// class for redeclaration (class, struct, or __interface). |
16761 | /// |
16762 | /// \returns true iff the tag kind is compatible. |
16763 | static bool isClassCompatTagKind(TagTypeKind Tag) |
16764 | { |
16765 | return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class || |
16766 | Tag == TagTypeKind::Interface; |
16767 | } |
16768 | |
16769 | Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, |
16770 | TagTypeKind TTK) { |
16771 | if (isa<TypedefDecl>(Val: PrevDecl)) |
16772 | return NTK_Typedef; |
16773 | else if (isa<TypeAliasDecl>(Val: PrevDecl)) |
16774 | return NTK_TypeAlias; |
16775 | else if (isa<ClassTemplateDecl>(Val: PrevDecl)) |
16776 | return NTK_Template; |
16777 | else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl)) |
16778 | return NTK_TypeAliasTemplate; |
16779 | else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl)) |
16780 | return NTK_TemplateTemplateArgument; |
16781 | switch (TTK) { |
16782 | case TagTypeKind::Struct: |
16783 | case TagTypeKind::Interface: |
16784 | case TagTypeKind::Class: |
16785 | return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; |
16786 | case TagTypeKind::Union: |
16787 | return NTK_NonUnion; |
16788 | case TagTypeKind::Enum: |
16789 | return NTK_NonEnum; |
16790 | } |
16791 | llvm_unreachable("invalid TTK" ); |
16792 | } |
16793 | |
16794 | bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, |
16795 | TagTypeKind NewTag, bool isDefinition, |
16796 | SourceLocation NewTagLoc, |
16797 | const IdentifierInfo *Name) { |
16798 | // C++ [dcl.type.elab]p3: |
16799 | // The class-key or enum keyword present in the |
16800 | // elaborated-type-specifier shall agree in kind with the |
16801 | // declaration to which the name in the elaborated-type-specifier |
16802 | // refers. This rule also applies to the form of |
16803 | // elaborated-type-specifier that declares a class-name or |
16804 | // friend class since it can be construed as referring to the |
16805 | // definition of the class. Thus, in any |
16806 | // elaborated-type-specifier, the enum keyword shall be used to |
16807 | // refer to an enumeration (7.2), the union class-key shall be |
16808 | // used to refer to a union (clause 9), and either the class or |
16809 | // struct class-key shall be used to refer to a class (clause 9) |
16810 | // declared using the class or struct class-key. |
16811 | TagTypeKind OldTag = Previous->getTagKind(); |
16812 | if (OldTag != NewTag && |
16813 | !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag))) |
16814 | return false; |
16815 | |
16816 | // Tags are compatible, but we might still want to warn on mismatched tags. |
16817 | // Non-class tags can't be mismatched at this point. |
16818 | if (!isClassCompatTagKind(Tag: NewTag)) |
16819 | return true; |
16820 | |
16821 | // Declarations for which -Wmismatched-tags is disabled are entirely ignored |
16822 | // by our warning analysis. We don't want to warn about mismatches with (eg) |
16823 | // declarations in system headers that are designed to be specialized, but if |
16824 | // a user asks us to warn, we should warn if their code contains mismatched |
16825 | // declarations. |
16826 | auto IsIgnoredLoc = [&](SourceLocation Loc) { |
16827 | return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch, |
16828 | Loc); |
16829 | }; |
16830 | if (IsIgnoredLoc(NewTagLoc)) |
16831 | return true; |
16832 | |
16833 | auto IsIgnored = [&](const TagDecl *Tag) { |
16834 | return IsIgnoredLoc(Tag->getLocation()); |
16835 | }; |
16836 | while (IsIgnored(Previous)) { |
16837 | Previous = Previous->getPreviousDecl(); |
16838 | if (!Previous) |
16839 | return true; |
16840 | OldTag = Previous->getTagKind(); |
16841 | } |
16842 | |
16843 | bool isTemplate = false; |
16844 | if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous)) |
16845 | isTemplate = Record->getDescribedClassTemplate(); |
16846 | |
16847 | if (inTemplateInstantiation()) { |
16848 | if (OldTag != NewTag) { |
16849 | // In a template instantiation, do not offer fix-its for tag mismatches |
16850 | // since they usually mess up the template instead of fixing the problem. |
16851 | Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch) |
16852 | << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name |
16853 | << getRedeclDiagFromTagKind(Tag: OldTag); |
16854 | // FIXME: Note previous location? |
16855 | } |
16856 | return true; |
16857 | } |
16858 | |
16859 | if (isDefinition) { |
16860 | // On definitions, check all previous tags and issue a fix-it for each |
16861 | // one that doesn't match the current tag. |
16862 | if (Previous->getDefinition()) { |
16863 | // Don't suggest fix-its for redefinitions. |
16864 | return true; |
16865 | } |
16866 | |
16867 | bool previousMismatch = false; |
16868 | for (const TagDecl *I : Previous->redecls()) { |
16869 | if (I->getTagKind() != NewTag) { |
16870 | // Ignore previous declarations for which the warning was disabled. |
16871 | if (IsIgnored(I)) |
16872 | continue; |
16873 | |
16874 | if (!previousMismatch) { |
16875 | previousMismatch = true; |
16876 | Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch) |
16877 | << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name |
16878 | << getRedeclDiagFromTagKind(Tag: I->getTagKind()); |
16879 | } |
16880 | Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion) |
16881 | << getRedeclDiagFromTagKind(Tag: NewTag) |
16882 | << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(), |
16883 | Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag)); |
16884 | } |
16885 | } |
16886 | return true; |
16887 | } |
16888 | |
16889 | // Identify the prevailing tag kind: this is the kind of the definition (if |
16890 | // there is a non-ignored definition), or otherwise the kind of the prior |
16891 | // (non-ignored) declaration. |
16892 | const TagDecl *PrevDef = Previous->getDefinition(); |
16893 | if (PrevDef && IsIgnored(PrevDef)) |
16894 | PrevDef = nullptr; |
16895 | const TagDecl *Redecl = PrevDef ? PrevDef : Previous; |
16896 | if (Redecl->getTagKind() != NewTag) { |
16897 | Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch) |
16898 | << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name |
16899 | << getRedeclDiagFromTagKind(Tag: OldTag); |
16900 | Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use); |
16901 | |
16902 | // If there is a previous definition, suggest a fix-it. |
16903 | if (PrevDef) { |
16904 | Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion) |
16905 | << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind()) |
16906 | << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc), |
16907 | Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind())); |
16908 | } |
16909 | } |
16910 | |
16911 | return true; |
16912 | } |
16913 | |
16914 | /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name |
16915 | /// from an outer enclosing namespace or file scope inside a friend declaration. |
16916 | /// This should provide the commented out code in the following snippet: |
16917 | /// namespace N { |
16918 | /// struct X; |
16919 | /// namespace M { |
16920 | /// struct Y { friend struct /*N::*/ X; }; |
16921 | /// } |
16922 | /// } |
16923 | static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, |
16924 | SourceLocation NameLoc) { |
16925 | // While the decl is in a namespace, do repeated lookup of that name and see |
16926 | // if we get the same namespace back. If we do not, continue until |
16927 | // translation unit scope, at which point we have a fully qualified NNS. |
16928 | SmallVector<IdentifierInfo *, 4> Namespaces; |
16929 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); |
16930 | for (; !DC->isTranslationUnit(); DC = DC->getParent()) { |
16931 | // This tag should be declared in a namespace, which can only be enclosed by |
16932 | // other namespaces. Bail if there's an anonymous namespace in the chain. |
16933 | NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC); |
16934 | if (!Namespace || Namespace->isAnonymousNamespace()) |
16935 | return FixItHint(); |
16936 | IdentifierInfo *II = Namespace->getIdentifier(); |
16937 | Namespaces.push_back(Elt: II); |
16938 | NamedDecl *Lookup = SemaRef.LookupSingleName( |
16939 | S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName); |
16940 | if (Lookup == Namespace) |
16941 | break; |
16942 | } |
16943 | |
16944 | // Once we have all the namespaces, reverse them to go outermost first, and |
16945 | // build an NNS. |
16946 | SmallString<64> Insertion; |
16947 | llvm::raw_svector_ostream OS(Insertion); |
16948 | if (DC->isTranslationUnit()) |
16949 | OS << "::" ; |
16950 | std::reverse(first: Namespaces.begin(), last: Namespaces.end()); |
16951 | for (auto *II : Namespaces) |
16952 | OS << II->getName() << "::" ; |
16953 | return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion); |
16954 | } |
16955 | |
16956 | /// Determine whether a tag originally declared in context \p OldDC can |
16957 | /// be redeclared with an unqualified name in \p NewDC (assuming name lookup |
16958 | /// found a declaration in \p OldDC as a previous decl, perhaps through a |
16959 | /// using-declaration). |
16960 | static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, |
16961 | DeclContext *NewDC) { |
16962 | OldDC = OldDC->getRedeclContext(); |
16963 | NewDC = NewDC->getRedeclContext(); |
16964 | |
16965 | if (OldDC->Equals(DC: NewDC)) |
16966 | return true; |
16967 | |
16968 | // In MSVC mode, we allow a redeclaration if the contexts are related (either |
16969 | // encloses the other). |
16970 | if (S.getLangOpts().MSVCCompat && |
16971 | (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC))) |
16972 | return true; |
16973 | |
16974 | return false; |
16975 | } |
16976 | |
16977 | DeclResult |
16978 | Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, |
16979 | CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, |
16980 | const ParsedAttributesView &Attrs, AccessSpecifier AS, |
16981 | SourceLocation ModulePrivateLoc, |
16982 | MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, |
16983 | bool &IsDependent, SourceLocation ScopedEnumKWLoc, |
16984 | bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, |
16985 | bool IsTypeSpecifier, bool IsTemplateParamOrArg, |
16986 | OffsetOfKind OOK, SkipBodyInfo *SkipBody) { |
16987 | // If this is not a definition, it must have a name. |
16988 | IdentifierInfo *OrigName = Name; |
16989 | assert((Name != nullptr || TUK == TagUseKind::Definition) && |
16990 | "Nameless record must be a definition!" ); |
16991 | assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference); |
16992 | |
16993 | OwnedDecl = false; |
16994 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec); |
16995 | bool ScopedEnum = ScopedEnumKWLoc.isValid(); |
16996 | |
16997 | // FIXME: Check member specializations more carefully. |
16998 | bool isMemberSpecialization = false; |
16999 | bool Invalid = false; |
17000 | |
17001 | // We only need to do this matching if we have template parameters |
17002 | // or a scope specifier, which also conveniently avoids this work |
17003 | // for non-C++ cases. |
17004 | if (TemplateParameterLists.size() > 0 || |
17005 | (SS.isNotEmpty() && TUK != TagUseKind::Reference)) { |
17006 | TemplateParameterList *TemplateParams = |
17007 | MatchTemplateParametersToScopeSpecifier( |
17008 | DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists, |
17009 | IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid); |
17010 | |
17011 | // C++23 [dcl.type.elab] p2: |
17012 | // If an elaborated-type-specifier is the sole constituent of a |
17013 | // declaration, the declaration is ill-formed unless it is an explicit |
17014 | // specialization, an explicit instantiation or it has one of the |
17015 | // following forms: [...] |
17016 | // C++23 [dcl.enum] p1: |
17017 | // If the enum-head-name of an opaque-enum-declaration contains a |
17018 | // nested-name-specifier, the declaration shall be an explicit |
17019 | // specialization. |
17020 | // |
17021 | // FIXME: Class template partial specializations can be forward declared |
17022 | // per CWG2213, but the resolution failed to allow qualified forward |
17023 | // declarations. This is almost certainly unintentional, so we allow them. |
17024 | if (TUK == TagUseKind::Declaration && SS.isNotEmpty() && |
17025 | !isMemberSpecialization) |
17026 | Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier) |
17027 | << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange(); |
17028 | |
17029 | if (TemplateParams) { |
17030 | if (Kind == TagTypeKind::Enum) { |
17031 | Diag(Loc: KWLoc, DiagID: diag::err_enum_template); |
17032 | return true; |
17033 | } |
17034 | |
17035 | if (TemplateParams->size() > 0) { |
17036 | // This is a declaration or definition of a class template (which may |
17037 | // be a member of another template). |
17038 | |
17039 | if (Invalid) |
17040 | return true; |
17041 | |
17042 | OwnedDecl = false; |
17043 | DeclResult Result = CheckClassTemplate( |
17044 | S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams, |
17045 | AS, ModulePrivateLoc, |
17046 | /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1, |
17047 | OuterTemplateParamLists: TemplateParameterLists.data(), SkipBody); |
17048 | return Result.get(); |
17049 | } else { |
17050 | // The "template<>" header is extraneous. |
17051 | Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams) |
17052 | << TypeWithKeyword::getTagTypeKindName(Kind) << Name; |
17053 | isMemberSpecialization = true; |
17054 | } |
17055 | } |
17056 | |
17057 | if (!TemplateParameterLists.empty() && isMemberSpecialization && |
17058 | CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back())) |
17059 | return true; |
17060 | } |
17061 | |
17062 | if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) { |
17063 | // C++23 [dcl.type.elab]p4: |
17064 | // If an elaborated-type-specifier appears with the friend specifier as |
17065 | // an entire member-declaration, the member-declaration shall have one |
17066 | // of the following forms: |
17067 | // friend class-key nested-name-specifier(opt) identifier ; |
17068 | // friend class-key simple-template-id ; |
17069 | // friend class-key nested-name-specifier template(opt) |
17070 | // simple-template-id ; |
17071 | // |
17072 | // Since enum is not a class-key, so declarations like "friend enum E;" |
17073 | // are ill-formed. Although CWG2363 reaffirms that such declarations are |
17074 | // invalid, most implementations accept so we issue a pedantic warning. |
17075 | Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval( |
17076 | RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc); |
17077 | assert(ScopedEnum || !ScopedEnumUsesClassTag); |
17078 | Diag(Loc: KWLoc, DiagID: diag::note_enum_friend) |
17079 | << (ScopedEnum + ScopedEnumUsesClassTag); |
17080 | } |
17081 | |
17082 | // Figure out the underlying type if this a enum declaration. We need to do |
17083 | // this early, because it's needed to detect if this is an incompatible |
17084 | // redeclaration. |
17085 | llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; |
17086 | bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; |
17087 | |
17088 | if (Kind == TagTypeKind::Enum) { |
17089 | if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { |
17090 | // No underlying type explicitly specified, or we failed to parse the |
17091 | // type, default to int. |
17092 | EnumUnderlying = Context.IntTy.getTypePtr(); |
17093 | } else if (UnderlyingType.get()) { |
17094 | // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an |
17095 | // integral type; any cv-qualification is ignored. |
17096 | TypeSourceInfo *TI = nullptr; |
17097 | GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI); |
17098 | EnumUnderlying = TI; |
17099 | |
17100 | if (CheckEnumUnderlyingType(TI)) |
17101 | // Recover by falling back to int. |
17102 | EnumUnderlying = Context.IntTy.getTypePtr(); |
17103 | |
17104 | if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI, |
17105 | UPPC: UPPC_FixedUnderlyingType)) |
17106 | EnumUnderlying = Context.IntTy.getTypePtr(); |
17107 | |
17108 | } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { |
17109 | // For MSVC ABI compatibility, unfixed enums must use an underlying type |
17110 | // of 'int'. However, if this is an unfixed forward declaration, don't set |
17111 | // the underlying type unless the user enables -fms-compatibility. This |
17112 | // makes unfixed forward declared enums incomplete and is more conforming. |
17113 | if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat) |
17114 | EnumUnderlying = Context.IntTy.getTypePtr(); |
17115 | } |
17116 | } |
17117 | |
17118 | DeclContext *SearchDC = CurContext; |
17119 | DeclContext *DC = CurContext; |
17120 | bool isStdBadAlloc = false; |
17121 | bool isStdAlignValT = false; |
17122 | |
17123 | RedeclarationKind Redecl = forRedeclarationInCurContext(); |
17124 | if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) |
17125 | Redecl = RedeclarationKind::NotForRedeclaration; |
17126 | |
17127 | /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C |
17128 | /// implemented asks for structural equivalence checking, the returned decl |
17129 | /// here is passed back to the parser, allowing the tag body to be parsed. |
17130 | auto createTagFromNewDecl = [&]() -> TagDecl * { |
17131 | assert(!getLangOpts().CPlusPlus && "not meant for C++ usage" ); |
17132 | // If there is an identifier, use the location of the identifier as the |
17133 | // location of the decl, otherwise use the location of the struct/union |
17134 | // keyword. |
17135 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; |
17136 | TagDecl *New = nullptr; |
17137 | |
17138 | if (Kind == TagTypeKind::Enum) { |
17139 | New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr, |
17140 | IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed); |
17141 | // If this is an undefined enum, bail. |
17142 | if (TUK != TagUseKind::Definition && !Invalid) |
17143 | return nullptr; |
17144 | if (EnumUnderlying) { |
17145 | EnumDecl *ED = cast<EnumDecl>(Val: New); |
17146 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) |
17147 | ED->setIntegerTypeSourceInfo(TI); |
17148 | else |
17149 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); |
17150 | QualType EnumTy = ED->getIntegerType(); |
17151 | ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy) |
17152 | ? Context.getPromotedIntegerType(PromotableType: EnumTy) |
17153 | : EnumTy); |
17154 | } |
17155 | } else { // struct/union |
17156 | New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, |
17157 | PrevDecl: nullptr); |
17158 | } |
17159 | |
17160 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) { |
17161 | // Add alignment attributes if necessary; these attributes are checked |
17162 | // when the ASTContext lays out the structure. |
17163 | // |
17164 | // It is important for implementing the correct semantics that this |
17165 | // happen here (in ActOnTag). The #pragma pack stack is |
17166 | // maintained as a result of parser callbacks which can occur at |
17167 | // many points during the parsing of a struct declaration (because |
17168 | // the #pragma tokens are effectively skipped over during the |
17169 | // parsing of the struct). |
17170 | if (TUK == TagUseKind::Definition && |
17171 | (!SkipBody || !SkipBody->ShouldSkip)) { |
17172 | AddAlignmentAttributesForRecord(RD); |
17173 | AddMsStructLayoutForRecord(RD); |
17174 | } |
17175 | } |
17176 | New->setLexicalDeclContext(CurContext); |
17177 | return New; |
17178 | }; |
17179 | |
17180 | LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); |
17181 | if (Name && SS.isNotEmpty()) { |
17182 | // We have a nested-name tag ('struct foo::bar'). |
17183 | |
17184 | // Check for invalid 'foo::'. |
17185 | if (SS.isInvalid()) { |
17186 | Name = nullptr; |
17187 | goto CreateNewDecl; |
17188 | } |
17189 | |
17190 | // If this is a friend or a reference to a class in a dependent |
17191 | // context, don't try to make a decl for it. |
17192 | if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) { |
17193 | DC = computeDeclContext(SS, EnteringContext: false); |
17194 | if (!DC) { |
17195 | IsDependent = true; |
17196 | return true; |
17197 | } |
17198 | } else { |
17199 | DC = computeDeclContext(SS, EnteringContext: true); |
17200 | if (!DC) { |
17201 | Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec) |
17202 | << SS.getRange(); |
17203 | return true; |
17204 | } |
17205 | } |
17206 | |
17207 | if (RequireCompleteDeclContext(SS, DC)) |
17208 | return true; |
17209 | |
17210 | SearchDC = DC; |
17211 | // Look-up name inside 'foo::'. |
17212 | LookupQualifiedName(R&: Previous, LookupCtx: DC); |
17213 | |
17214 | if (Previous.isAmbiguous()) |
17215 | return true; |
17216 | |
17217 | if (Previous.empty()) { |
17218 | // Name lookup did not find anything. However, if the |
17219 | // nested-name-specifier refers to the current instantiation, |
17220 | // and that current instantiation has any dependent base |
17221 | // classes, we might find something at instantiation time: treat |
17222 | // this as a dependent elaborated-type-specifier. |
17223 | // But this only makes any sense for reference-like lookups. |
17224 | if (Previous.wasNotFoundInCurrentInstantiation() && |
17225 | (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) { |
17226 | IsDependent = true; |
17227 | return true; |
17228 | } |
17229 | |
17230 | // A tag 'foo::bar' must already exist. |
17231 | Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope) |
17232 | << llvm::to_underlying(E: Kind) << Name << DC << SS.getRange(); |
17233 | Name = nullptr; |
17234 | Invalid = true; |
17235 | goto CreateNewDecl; |
17236 | } |
17237 | } else if (Name) { |
17238 | // C++14 [class.mem]p14: |
17239 | // If T is the name of a class, then each of the following shall have a |
17240 | // name different from T: |
17241 | // -- every member of class T that is itself a type |
17242 | if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend && |
17243 | DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc))) |
17244 | return true; |
17245 | |
17246 | // If this is a named struct, check to see if there was a previous forward |
17247 | // declaration or definition. |
17248 | // FIXME: We're looking into outer scopes here, even when we |
17249 | // shouldn't be. Doing so can result in ambiguities that we |
17250 | // shouldn't be diagnosing. |
17251 | LookupName(R&: Previous, S); |
17252 | |
17253 | // When declaring or defining a tag, ignore ambiguities introduced |
17254 | // by types using'ed into this scope. |
17255 | if (Previous.isAmbiguous() && |
17256 | (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) { |
17257 | LookupResult::Filter F = Previous.makeFilter(); |
17258 | while (F.hasNext()) { |
17259 | NamedDecl *ND = F.next(); |
17260 | if (!ND->getDeclContext()->getRedeclContext()->Equals( |
17261 | DC: SearchDC->getRedeclContext())) |
17262 | F.erase(); |
17263 | } |
17264 | F.done(); |
17265 | } |
17266 | |
17267 | // C++11 [namespace.memdef]p3: |
17268 | // If the name in a friend declaration is neither qualified nor |
17269 | // a template-id and the declaration is a function or an |
17270 | // elaborated-type-specifier, the lookup to determine whether |
17271 | // the entity has been previously declared shall not consider |
17272 | // any scopes outside the innermost enclosing namespace. |
17273 | // |
17274 | // MSVC doesn't implement the above rule for types, so a friend tag |
17275 | // declaration may be a redeclaration of a type declared in an enclosing |
17276 | // scope. They do implement this rule for friend functions. |
17277 | // |
17278 | // Does it matter that this should be by scope instead of by |
17279 | // semantic context? |
17280 | if (!Previous.empty() && TUK == TagUseKind::Friend) { |
17281 | DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); |
17282 | LookupResult::Filter F = Previous.makeFilter(); |
17283 | bool FriendSawTagOutsideEnclosingNamespace = false; |
17284 | while (F.hasNext()) { |
17285 | NamedDecl *ND = F.next(); |
17286 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); |
17287 | if (DC->isFileContext() && |
17288 | !EnclosingNS->Encloses(DC: ND->getDeclContext())) { |
17289 | if (getLangOpts().MSVCCompat) |
17290 | FriendSawTagOutsideEnclosingNamespace = true; |
17291 | else |
17292 | F.erase(); |
17293 | } |
17294 | } |
17295 | F.done(); |
17296 | |
17297 | // Diagnose this MSVC extension in the easy case where lookup would have |
17298 | // unambiguously found something outside the enclosing namespace. |
17299 | if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { |
17300 | NamedDecl *ND = Previous.getFoundDecl(); |
17301 | Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace) |
17302 | << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc); |
17303 | } |
17304 | } |
17305 | |
17306 | // Note: there used to be some attempt at recovery here. |
17307 | if (Previous.isAmbiguous()) |
17308 | return true; |
17309 | |
17310 | if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) { |
17311 | // FIXME: This makes sure that we ignore the contexts associated |
17312 | // with C structs, unions, and enums when looking for a matching |
17313 | // tag declaration or definition. See the similar lookup tweak |
17314 | // in Sema::LookupName; is there a better way to deal with this? |
17315 | while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC)) |
17316 | SearchDC = SearchDC->getParent(); |
17317 | } else if (getLangOpts().CPlusPlus) { |
17318 | // Inside ObjCContainer want to keep it as a lexical decl context but go |
17319 | // past it (most often to TranslationUnit) to find the semantic decl |
17320 | // context. |
17321 | while (isa<ObjCContainerDecl>(Val: SearchDC)) |
17322 | SearchDC = SearchDC->getParent(); |
17323 | } |
17324 | } else if (getLangOpts().CPlusPlus) { |
17325 | // Don't use ObjCContainerDecl as the semantic decl context for anonymous |
17326 | // TagDecl the same way as we skip it for named TagDecl. |
17327 | while (isa<ObjCContainerDecl>(Val: SearchDC)) |
17328 | SearchDC = SearchDC->getParent(); |
17329 | } |
17330 | |
17331 | if (Previous.isSingleResult() && |
17332 | Previous.getFoundDecl()->isTemplateParameter()) { |
17333 | // Maybe we will complain about the shadowed template parameter. |
17334 | DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl()); |
17335 | // Just pretend that we didn't see the previous declaration. |
17336 | Previous.clear(); |
17337 | } |
17338 | |
17339 | if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && |
17340 | DC->Equals(DC: getStdNamespace())) { |
17341 | if (Name->isStr(Str: "bad_alloc" )) { |
17342 | // This is a declaration of or a reference to "std::bad_alloc". |
17343 | isStdBadAlloc = true; |
17344 | |
17345 | // If std::bad_alloc has been implicitly declared (but made invisible to |
17346 | // name lookup), fill in this implicit declaration as the previous |
17347 | // declaration, so that the declarations get chained appropriately. |
17348 | if (Previous.empty() && StdBadAlloc) |
17349 | Previous.addDecl(D: getStdBadAlloc()); |
17350 | } else if (Name->isStr(Str: "align_val_t" )) { |
17351 | isStdAlignValT = true; |
17352 | if (Previous.empty() && StdAlignValT) |
17353 | Previous.addDecl(D: getStdAlignValT()); |
17354 | } |
17355 | } |
17356 | |
17357 | // If we didn't find a previous declaration, and this is a reference |
17358 | // (or friend reference), move to the correct scope. In C++, we |
17359 | // also need to do a redeclaration lookup there, just in case |
17360 | // there's a shadow friend decl. |
17361 | if (Name && Previous.empty() && |
17362 | (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend || |
17363 | IsTemplateParamOrArg)) { |
17364 | if (Invalid) goto CreateNewDecl; |
17365 | assert(SS.isEmpty()); |
17366 | |
17367 | if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) { |
17368 | // C++ [basic.scope.pdecl]p5: |
17369 | // -- for an elaborated-type-specifier of the form |
17370 | // |
17371 | // class-key identifier |
17372 | // |
17373 | // if the elaborated-type-specifier is used in the |
17374 | // decl-specifier-seq or parameter-declaration-clause of a |
17375 | // function defined in namespace scope, the identifier is |
17376 | // declared as a class-name in the namespace that contains |
17377 | // the declaration; otherwise, except as a friend |
17378 | // declaration, the identifier is declared in the smallest |
17379 | // non-class, non-function-prototype scope that contains the |
17380 | // declaration. |
17381 | // |
17382 | // C99 6.7.2.3p8 has a similar (but not identical!) provision for |
17383 | // C structs and unions. |
17384 | // |
17385 | // It is an error in C++ to declare (rather than define) an enum |
17386 | // type, including via an elaborated type specifier. We'll |
17387 | // diagnose that later; for now, declare the enum in the same |
17388 | // scope as we would have picked for any other tag type. |
17389 | // |
17390 | // GNU C also supports this behavior as part of its incomplete |
17391 | // enum types extension, while GNU C++ does not. |
17392 | // |
17393 | // Find the context where we'll be declaring the tag. |
17394 | // FIXME: We would like to maintain the current DeclContext as the |
17395 | // lexical context, |
17396 | SearchDC = getTagInjectionContext(DC: SearchDC); |
17397 | |
17398 | // Find the scope where we'll be declaring the tag. |
17399 | S = getTagInjectionScope(S, LangOpts: getLangOpts()); |
17400 | } else { |
17401 | assert(TUK == TagUseKind::Friend); |
17402 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC); |
17403 | |
17404 | // C++ [namespace.memdef]p3: |
17405 | // If a friend declaration in a non-local class first declares a |
17406 | // class or function, the friend class or function is a member of |
17407 | // the innermost enclosing namespace. |
17408 | SearchDC = RD->isLocalClass() ? RD->isLocalClass() |
17409 | : SearchDC->getEnclosingNamespaceContext(); |
17410 | } |
17411 | |
17412 | // In C++, we need to do a redeclaration lookup to properly |
17413 | // diagnose some problems. |
17414 | // FIXME: redeclaration lookup is also used (with and without C++) to find a |
17415 | // hidden declaration so that we don't get ambiguity errors when using a |
17416 | // type declared by an elaborated-type-specifier. In C that is not correct |
17417 | // and we should instead merge compatible types found by lookup. |
17418 | if (getLangOpts().CPlusPlus) { |
17419 | // FIXME: This can perform qualified lookups into function contexts, |
17420 | // which are meaningless. |
17421 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); |
17422 | LookupQualifiedName(R&: Previous, LookupCtx: SearchDC); |
17423 | } else { |
17424 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); |
17425 | LookupName(R&: Previous, S); |
17426 | } |
17427 | } |
17428 | |
17429 | // If we have a known previous declaration to use, then use it. |
17430 | if (Previous.empty() && SkipBody && SkipBody->Previous) |
17431 | Previous.addDecl(D: SkipBody->Previous); |
17432 | |
17433 | if (!Previous.empty()) { |
17434 | NamedDecl *PrevDecl = Previous.getFoundDecl(); |
17435 | NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); |
17436 | |
17437 | // It's okay to have a tag decl in the same scope as a typedef |
17438 | // which hides a tag decl in the same scope. Finding this |
17439 | // with a redeclaration lookup can only actually happen in C++. |
17440 | // |
17441 | // This is also okay for elaborated-type-specifiers, which is |
17442 | // technically forbidden by the current standard but which is |
17443 | // okay according to the likely resolution of an open issue; |
17444 | // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 |
17445 | if (getLangOpts().CPlusPlus) { |
17446 | if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) { |
17447 | if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { |
17448 | TagDecl *Tag = TT->getDecl(); |
17449 | if (Tag->getDeclName() == Name && |
17450 | Tag->getDeclContext()->getRedeclContext() |
17451 | ->Equals(DC: TD->getDeclContext()->getRedeclContext())) { |
17452 | PrevDecl = Tag; |
17453 | Previous.clear(); |
17454 | Previous.addDecl(D: Tag); |
17455 | Previous.resolveKind(); |
17456 | } |
17457 | } |
17458 | } |
17459 | } |
17460 | |
17461 | // If this is a redeclaration of a using shadow declaration, it must |
17462 | // declare a tag in the same context. In MSVC mode, we allow a |
17463 | // redefinition if either context is within the other. |
17464 | if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) { |
17465 | auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl); |
17466 | if (SS.isEmpty() && TUK != TagUseKind::Reference && |
17467 | TUK != TagUseKind::Friend && |
17468 | isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) && |
17469 | !(OldTag && isAcceptableTagRedeclContext( |
17470 | S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) { |
17471 | Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse); |
17472 | Diag(Loc: Shadow->getTargetDecl()->getLocation(), |
17473 | DiagID: diag::note_using_decl_target); |
17474 | Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) |
17475 | << 0; |
17476 | // Recover by ignoring the old declaration. |
17477 | Previous.clear(); |
17478 | goto CreateNewDecl; |
17479 | } |
17480 | } |
17481 | |
17482 | if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) { |
17483 | // If this is a use of a previous tag, or if the tag is already declared |
17484 | // in the same scope (so that the definition/declaration completes or |
17485 | // rementions the tag), reuse the decl. |
17486 | if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend || |
17487 | isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S, |
17488 | AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) { |
17489 | // Make sure that this wasn't declared as an enum and now used as a |
17490 | // struct or something similar. |
17491 | if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind, |
17492 | isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc, |
17493 | Name)) { |
17494 | bool SafeToContinue = |
17495 | (PrevTagDecl->getTagKind() != TagTypeKind::Enum && |
17496 | Kind != TagTypeKind::Enum); |
17497 | if (SafeToContinue) |
17498 | Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) |
17499 | << Name |
17500 | << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc), |
17501 | Code: PrevTagDecl->getKindName()); |
17502 | else |
17503 | Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name; |
17504 | Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use); |
17505 | |
17506 | if (SafeToContinue) |
17507 | Kind = PrevTagDecl->getTagKind(); |
17508 | else { |
17509 | // Recover by making this an anonymous redefinition. |
17510 | Name = nullptr; |
17511 | Previous.clear(); |
17512 | Invalid = true; |
17513 | } |
17514 | } |
17515 | |
17516 | if (Kind == TagTypeKind::Enum && |
17517 | PrevTagDecl->getTagKind() == TagTypeKind::Enum) { |
17518 | const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl); |
17519 | if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) |
17520 | return PrevTagDecl; |
17521 | |
17522 | QualType EnumUnderlyingTy; |
17523 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) |
17524 | EnumUnderlyingTy = TI->getType().getUnqualifiedType(); |
17525 | else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) |
17526 | EnumUnderlyingTy = QualType(T, 0); |
17527 | |
17528 | // All conflicts with previous declarations are recovered by |
17529 | // returning the previous declaration, unless this is a definition, |
17530 | // in which case we want the caller to bail out. |
17531 | if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc, |
17532 | IsScoped: ScopedEnum, EnumUnderlyingTy, |
17533 | IsFixed, Prev: PrevEnum)) |
17534 | return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr; |
17535 | } |
17536 | |
17537 | // C++11 [class.mem]p1: |
17538 | // A member shall not be declared twice in the member-specification, |
17539 | // except that a nested class or member class template can be declared |
17540 | // and then later defined. |
17541 | if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() && |
17542 | S->isDeclScope(D: PrevDecl)) { |
17543 | Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared); |
17544 | Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration); |
17545 | } |
17546 | |
17547 | if (!Invalid) { |
17548 | // If this is a use, just return the declaration we found, unless |
17549 | // we have attributes. |
17550 | if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) { |
17551 | if (!Attrs.empty()) { |
17552 | // FIXME: Diagnose these attributes. For now, we create a new |
17553 | // declaration to hold them. |
17554 | } else if (TUK == TagUseKind::Reference && |
17555 | (PrevTagDecl->getFriendObjectKind() == |
17556 | Decl::FOK_Undeclared || |
17557 | PrevDecl->getOwningModule() != getCurrentModule()) && |
17558 | SS.isEmpty()) { |
17559 | // This declaration is a reference to an existing entity, but |
17560 | // has different visibility from that entity: it either makes |
17561 | // a friend visible or it makes a type visible in a new module. |
17562 | // In either case, create a new declaration. We only do this if |
17563 | // the declaration would have meant the same thing if no prior |
17564 | // declaration were found, that is, if it was found in the same |
17565 | // scope where we would have injected a declaration. |
17566 | if (!getTagInjectionContext(DC: CurContext)->getRedeclContext() |
17567 | ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext())) |
17568 | return PrevTagDecl; |
17569 | // This is in the injected scope, create a new declaration in |
17570 | // that scope. |
17571 | S = getTagInjectionScope(S, LangOpts: getLangOpts()); |
17572 | } else { |
17573 | return PrevTagDecl; |
17574 | } |
17575 | } |
17576 | |
17577 | // Diagnose attempts to redefine a tag. |
17578 | if (TUK == TagUseKind::Definition) { |
17579 | if (NamedDecl *Def = PrevTagDecl->getDefinition()) { |
17580 | // If we're defining a specialization and the previous definition |
17581 | // is from an implicit instantiation, don't emit an error |
17582 | // here; we'll catch this in the general case below. |
17583 | bool IsExplicitSpecializationAfterInstantiation = false; |
17584 | if (isMemberSpecialization) { |
17585 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def)) |
17586 | IsExplicitSpecializationAfterInstantiation = |
17587 | RD->getTemplateSpecializationKind() != |
17588 | TSK_ExplicitSpecialization; |
17589 | else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def)) |
17590 | IsExplicitSpecializationAfterInstantiation = |
17591 | ED->getTemplateSpecializationKind() != |
17592 | TSK_ExplicitSpecialization; |
17593 | } |
17594 | |
17595 | // Note that clang allows ODR-like semantics for ObjC/C, i.e., do |
17596 | // not keep more that one definition around (merge them). However, |
17597 | // ensure the decl passes the structural compatibility check in |
17598 | // C11 6.2.7/1 (or 6.1.2.6/1 in C89). |
17599 | NamedDecl *Hidden = nullptr; |
17600 | if (SkipBody && !hasVisibleDefinition(D: Def, Suggested: &Hidden)) { |
17601 | // There is a definition of this tag, but it is not visible. We |
17602 | // explicitly make use of C++'s one definition rule here, and |
17603 | // assume that this definition is identical to the hidden one |
17604 | // we already have. Make the existing definition visible and |
17605 | // use it in place of this one. |
17606 | if (!getLangOpts().CPlusPlus) { |
17607 | // Postpone making the old definition visible until after we |
17608 | // complete parsing the new one and do the structural |
17609 | // comparison. |
17610 | SkipBody->CheckSameAsPrevious = true; |
17611 | SkipBody->New = createTagFromNewDecl(); |
17612 | SkipBody->Previous = Def; |
17613 | return Def; |
17614 | } else { |
17615 | SkipBody->ShouldSkip = true; |
17616 | SkipBody->Previous = Def; |
17617 | makeMergedDefinitionVisible(ND: Hidden); |
17618 | // Carry on and handle it like a normal definition. We'll |
17619 | // skip starting the definition later. |
17620 | } |
17621 | } else if (!IsExplicitSpecializationAfterInstantiation) { |
17622 | // A redeclaration in function prototype scope in C isn't |
17623 | // visible elsewhere, so merely issue a warning. |
17624 | if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) |
17625 | Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list) << Name; |
17626 | else |
17627 | Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name; |
17628 | notePreviousDefinition(Old: Def, |
17629 | New: NameLoc.isValid() ? NameLoc : KWLoc); |
17630 | // If this is a redefinition, recover by making this |
17631 | // struct be anonymous, which will make any later |
17632 | // references get the previous definition. |
17633 | Name = nullptr; |
17634 | Previous.clear(); |
17635 | Invalid = true; |
17636 | } |
17637 | } else { |
17638 | // If the type is currently being defined, complain |
17639 | // about a nested redefinition. |
17640 | auto *TD = Context.getTagDeclType(Decl: PrevTagDecl)->getAsTagDecl(); |
17641 | if (TD->isBeingDefined()) { |
17642 | Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name; |
17643 | Diag(Loc: PrevTagDecl->getLocation(), |
17644 | DiagID: diag::note_previous_definition); |
17645 | Name = nullptr; |
17646 | Previous.clear(); |
17647 | Invalid = true; |
17648 | } |
17649 | } |
17650 | |
17651 | // Okay, this is definition of a previously declared or referenced |
17652 | // tag. We're going to create a new Decl for it. |
17653 | } |
17654 | |
17655 | // Okay, we're going to make a redeclaration. If this is some kind |
17656 | // of reference, make sure we build the redeclaration in the same DC |
17657 | // as the original, and ignore the current access specifier. |
17658 | if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) { |
17659 | SearchDC = PrevTagDecl->getDeclContext(); |
17660 | AS = AS_none; |
17661 | } |
17662 | } |
17663 | // If we get here we have (another) forward declaration or we |
17664 | // have a definition. Just create a new decl. |
17665 | |
17666 | } else { |
17667 | // If we get here, this is a definition of a new tag type in a nested |
17668 | // scope, e.g. "struct foo; void bar() { struct foo; }", just create a |
17669 | // new decl/type. We set PrevDecl to NULL so that the entities |
17670 | // have distinct types. |
17671 | Previous.clear(); |
17672 | } |
17673 | // If we get here, we're going to create a new Decl. If PrevDecl |
17674 | // is non-NULL, it's a definition of the tag declared by |
17675 | // PrevDecl. If it's NULL, we have a new definition. |
17676 | |
17677 | // Otherwise, PrevDecl is not a tag, but was found with tag |
17678 | // lookup. This is only actually possible in C++, where a few |
17679 | // things like templates still live in the tag namespace. |
17680 | } else { |
17681 | // Use a better diagnostic if an elaborated-type-specifier |
17682 | // found the wrong kind of type on the first |
17683 | // (non-redeclaration) lookup. |
17684 | if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) && |
17685 | !Previous.isForRedeclaration()) { |
17686 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind); |
17687 | Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag) |
17688 | << PrevDecl << NTK << llvm::to_underlying(E: Kind); |
17689 | Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at); |
17690 | Invalid = true; |
17691 | |
17692 | // Otherwise, only diagnose if the declaration is in scope. |
17693 | } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S, |
17694 | AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) { |
17695 | // do nothing |
17696 | |
17697 | // Diagnose implicit declarations introduced by elaborated types. |
17698 | } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) { |
17699 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind); |
17700 | Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK; |
17701 | Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl; |
17702 | Invalid = true; |
17703 | |
17704 | // Otherwise it's a declaration. Call out a particularly common |
17705 | // case here. |
17706 | } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) { |
17707 | unsigned Kind = 0; |
17708 | if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1; |
17709 | Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef) |
17710 | << Name << Kind << TND->getUnderlyingType(); |
17711 | Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl; |
17712 | Invalid = true; |
17713 | |
17714 | // Otherwise, diagnose. |
17715 | } else { |
17716 | // The tag name clashes with something else in the target scope, |
17717 | // issue an error and recover by making this tag be anonymous. |
17718 | Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name; |
17719 | notePreviousDefinition(Old: PrevDecl, New: NameLoc); |
17720 | Name = nullptr; |
17721 | Invalid = true; |
17722 | } |
17723 | |
17724 | // The existing declaration isn't relevant to us; we're in a |
17725 | // new scope, so clear out the previous declaration. |
17726 | Previous.clear(); |
17727 | } |
17728 | } |
17729 | |
17730 | CreateNewDecl: |
17731 | |
17732 | TagDecl *PrevDecl = nullptr; |
17733 | if (Previous.isSingleResult()) |
17734 | PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl()); |
17735 | |
17736 | // If there is an identifier, use the location of the identifier as the |
17737 | // location of the decl, otherwise use the location of the struct/union |
17738 | // keyword. |
17739 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; |
17740 | |
17741 | // Otherwise, create a new declaration. If there is a previous |
17742 | // declaration of the same entity, the two will be linked via |
17743 | // PrevDecl. |
17744 | TagDecl *New; |
17745 | |
17746 | if (Kind == TagTypeKind::Enum) { |
17747 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: |
17748 | // enum X { A, B, C } D; D should chain to X. |
17749 | New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, |
17750 | PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum, |
17751 | IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed); |
17752 | |
17753 | if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) |
17754 | StdAlignValT = cast<EnumDecl>(Val: New); |
17755 | |
17756 | // If this is an undefined enum, warn. |
17757 | if (TUK != TagUseKind::Definition && !Invalid) { |
17758 | TagDecl *Def; |
17759 | if (IsFixed && cast<EnumDecl>(Val: New)->isFixed()) { |
17760 | // C++0x: 7.2p2: opaque-enum-declaration. |
17761 | // Conflicts are diagnosed above. Do nothing. |
17762 | } |
17763 | else if (PrevDecl && (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) { |
17764 | Diag(Loc, DiagID: diag::ext_forward_ref_enum_def) |
17765 | << New; |
17766 | Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition); |
17767 | } else { |
17768 | unsigned DiagID = diag::ext_forward_ref_enum; |
17769 | if (getLangOpts().MSVCCompat) |
17770 | DiagID = diag::ext_ms_forward_ref_enum; |
17771 | else if (getLangOpts().CPlusPlus) |
17772 | DiagID = diag::err_forward_ref_enum; |
17773 | Diag(Loc, DiagID); |
17774 | } |
17775 | } |
17776 | |
17777 | if (EnumUnderlying) { |
17778 | EnumDecl *ED = cast<EnumDecl>(Val: New); |
17779 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) |
17780 | ED->setIntegerTypeSourceInfo(TI); |
17781 | else |
17782 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); |
17783 | QualType EnumTy = ED->getIntegerType(); |
17784 | ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy) |
17785 | ? Context.getPromotedIntegerType(PromotableType: EnumTy) |
17786 | : EnumTy); |
17787 | assert(ED->isComplete() && "enum with type should be complete" ); |
17788 | } |
17789 | } else { |
17790 | // struct/union/class |
17791 | |
17792 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: |
17793 | // struct X { int A; } D; D should chain to X. |
17794 | if (getLangOpts().CPlusPlus) { |
17795 | // FIXME: Look for a way to use RecordDecl for simple structs. |
17796 | New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, |
17797 | PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl)); |
17798 | |
17799 | if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) |
17800 | StdBadAlloc = cast<CXXRecordDecl>(Val: New); |
17801 | } else |
17802 | New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, |
17803 | PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl)); |
17804 | } |
17805 | |
17806 | // Only C23 and later allow defining new types in 'offsetof()'. |
17807 | if (OOK != OOK_Outside && TUK == TagUseKind::Definition && |
17808 | !getLangOpts().CPlusPlus && !getLangOpts().C23) |
17809 | Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof) |
17810 | << (OOK == OOK_Macro) << New->getSourceRange(); |
17811 | |
17812 | // C++11 [dcl.type]p3: |
17813 | // A type-specifier-seq shall not define a class or enumeration [...]. |
17814 | if (!Invalid && getLangOpts().CPlusPlus && |
17815 | (IsTypeSpecifier || IsTemplateParamOrArg) && |
17816 | TUK == TagUseKind::Definition) { |
17817 | Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier) |
17818 | << Context.getTagDeclType(Decl: New); |
17819 | Invalid = true; |
17820 | } |
17821 | |
17822 | if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition && |
17823 | DC->getDeclKind() == Decl::Enum) { |
17824 | Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum) |
17825 | << Context.getTagDeclType(Decl: New); |
17826 | Invalid = true; |
17827 | } |
17828 | |
17829 | // Maybe add qualifier info. |
17830 | if (SS.isNotEmpty()) { |
17831 | if (SS.isSet()) { |
17832 | // If this is either a declaration or a definition, check the |
17833 | // nested-name-specifier against the current context. |
17834 | if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) && |
17835 | diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc, |
17836 | /*TemplateId=*/nullptr, |
17837 | IsMemberSpecialization: isMemberSpecialization)) |
17838 | Invalid = true; |
17839 | |
17840 | New->setQualifierInfo(SS.getWithLocInContext(Context)); |
17841 | if (TemplateParameterLists.size() > 0) { |
17842 | New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists); |
17843 | } |
17844 | } |
17845 | else |
17846 | Invalid = true; |
17847 | } |
17848 | |
17849 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) { |
17850 | // Add alignment attributes if necessary; these attributes are checked when |
17851 | // the ASTContext lays out the structure. |
17852 | // |
17853 | // It is important for implementing the correct semantics that this |
17854 | // happen here (in ActOnTag). The #pragma pack stack is |
17855 | // maintained as a result of parser callbacks which can occur at |
17856 | // many points during the parsing of a struct declaration (because |
17857 | // the #pragma tokens are effectively skipped over during the |
17858 | // parsing of the struct). |
17859 | if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) { |
17860 | AddAlignmentAttributesForRecord(RD); |
17861 | AddMsStructLayoutForRecord(RD); |
17862 | } |
17863 | } |
17864 | |
17865 | if (ModulePrivateLoc.isValid()) { |
17866 | if (isMemberSpecialization) |
17867 | Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization) |
17868 | << 2 |
17869 | << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc); |
17870 | // __module_private__ does not apply to local classes. However, we only |
17871 | // diagnose this as an error when the declaration specifiers are |
17872 | // freestanding. Here, we just ignore the __module_private__. |
17873 | else if (!SearchDC->isFunctionOrMethod()) |
17874 | New->setModulePrivate(); |
17875 | } |
17876 | |
17877 | // If this is a specialization of a member class (of a class template), |
17878 | // check the specialization. |
17879 | if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous)) |
17880 | Invalid = true; |
17881 | |
17882 | // If we're declaring or defining a tag in function prototype scope in C, |
17883 | // note that this type can only be used within the function and add it to |
17884 | // the list of decls to inject into the function definition scope. |
17885 | if ((Name || Kind == TagTypeKind::Enum) && |
17886 | getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { |
17887 | if (getLangOpts().CPlusPlus) { |
17888 | // C++ [dcl.fct]p6: |
17889 | // Types shall not be defined in return or parameter types. |
17890 | if (TUK == TagUseKind::Definition && !IsTypeSpecifier) { |
17891 | Diag(Loc, DiagID: diag::err_type_defined_in_param_type) |
17892 | << Name; |
17893 | Invalid = true; |
17894 | } |
17895 | } else if (!PrevDecl) { |
17896 | Diag(Loc, DiagID: diag::warn_decl_in_param_list) << Context.getTagDeclType(Decl: New); |
17897 | } |
17898 | } |
17899 | |
17900 | if (Invalid) |
17901 | New->setInvalidDecl(); |
17902 | |
17903 | // Set the lexical context. If the tag has a C++ scope specifier, the |
17904 | // lexical context will be different from the semantic context. |
17905 | New->setLexicalDeclContext(CurContext); |
17906 | |
17907 | // Mark this as a friend decl if applicable. |
17908 | // In Microsoft mode, a friend declaration also acts as a forward |
17909 | // declaration so we always pass true to setObjectOfFriendDecl to make |
17910 | // the tag name visible. |
17911 | if (TUK == TagUseKind::Friend) |
17912 | New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); |
17913 | |
17914 | // Set the access specifier. |
17915 | if (!Invalid && SearchDC->isRecord()) |
17916 | SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS); |
17917 | |
17918 | if (PrevDecl) |
17919 | CheckRedeclarationInModule(New, Old: PrevDecl); |
17920 | |
17921 | if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) |
17922 | New->startDefinition(); |
17923 | |
17924 | ProcessDeclAttributeList(S, D: New, AttrList: Attrs); |
17925 | AddPragmaAttributes(S, D: New); |
17926 | |
17927 | // If this has an identifier, add it to the scope stack. |
17928 | if (TUK == TagUseKind::Friend) { |
17929 | // We might be replacing an existing declaration in the lookup tables; |
17930 | // if so, borrow its access specifier. |
17931 | if (PrevDecl) |
17932 | New->setAccess(PrevDecl->getAccess()); |
17933 | |
17934 | DeclContext *DC = New->getDeclContext()->getRedeclContext(); |
17935 | DC->makeDeclVisibleInContext(D: New); |
17936 | if (Name) // can be null along some error paths |
17937 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) |
17938 | PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false); |
17939 | } else if (Name) { |
17940 | S = getNonFieldDeclScope(S); |
17941 | PushOnScopeChains(D: New, S, AddToContext: true); |
17942 | } else { |
17943 | CurContext->addDecl(D: New); |
17944 | } |
17945 | |
17946 | // If this is the C FILE type, notify the AST context. |
17947 | if (IdentifierInfo *II = New->getIdentifier()) |
17948 | if (!New->isInvalidDecl() && |
17949 | New->getDeclContext()->getRedeclContext()->isTranslationUnit() && |
17950 | II->isStr(Str: "FILE" )) |
17951 | Context.setFILEDecl(New); |
17952 | |
17953 | if (PrevDecl) |
17954 | mergeDeclAttributes(New, Old: PrevDecl); |
17955 | |
17956 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) { |
17957 | inferGslOwnerPointerAttribute(Record: CXXRD); |
17958 | inferNullableClassAttribute(CRD: CXXRD); |
17959 | } |
17960 | |
17961 | // If there's a #pragma GCC visibility in scope, set the visibility of this |
17962 | // record. |
17963 | AddPushedVisibilityAttribute(RD: New); |
17964 | |
17965 | if (isMemberSpecialization && !New->isInvalidDecl()) |
17966 | CompleteMemberSpecialization(Member: New, Previous); |
17967 | |
17968 | OwnedDecl = true; |
17969 | // In C++, don't return an invalid declaration. We can't recover well from |
17970 | // the cases where we make the type anonymous. |
17971 | if (Invalid && getLangOpts().CPlusPlus) { |
17972 | if (New->isBeingDefined()) |
17973 | if (auto RD = dyn_cast<RecordDecl>(Val: New)) |
17974 | RD->completeDefinition(); |
17975 | return true; |
17976 | } else if (SkipBody && SkipBody->ShouldSkip) { |
17977 | return SkipBody->Previous; |
17978 | } else { |
17979 | return New; |
17980 | } |
17981 | } |
17982 | |
17983 | void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { |
17984 | AdjustDeclIfTemplate(Decl&: TagD); |
17985 | TagDecl *Tag = cast<TagDecl>(Val: TagD); |
17986 | |
17987 | // Enter the tag context. |
17988 | PushDeclContext(S, DC: Tag); |
17989 | |
17990 | ActOnDocumentableDecl(D: TagD); |
17991 | |
17992 | // If there's a #pragma GCC visibility in scope, set the visibility of this |
17993 | // record. |
17994 | AddPushedVisibilityAttribute(RD: Tag); |
17995 | } |
17996 | |
17997 | bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) { |
17998 | if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New)) |
17999 | return false; |
18000 | |
18001 | // Make the previous decl visible. |
18002 | makeMergedDefinitionVisible(ND: SkipBody.Previous); |
18003 | return true; |
18004 | } |
18005 | |
18006 | void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, |
18007 | SourceLocation FinalLoc, |
18008 | bool IsFinalSpelledSealed, |
18009 | bool IsAbstract, |
18010 | SourceLocation LBraceLoc) { |
18011 | AdjustDeclIfTemplate(Decl&: TagD); |
18012 | CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD); |
18013 | |
18014 | FieldCollector->StartClass(); |
18015 | |
18016 | if (!Record->getIdentifier()) |
18017 | return; |
18018 | |
18019 | if (IsAbstract) |
18020 | Record->markAbstract(); |
18021 | |
18022 | if (FinalLoc.isValid()) { |
18023 | Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc, |
18024 | S: IsFinalSpelledSealed |
18025 | ? FinalAttr::Keyword_sealed |
18026 | : FinalAttr::Keyword_final)); |
18027 | } |
18028 | // C++ [class]p2: |
18029 | // [...] The class-name is also inserted into the scope of the |
18030 | // class itself; this is known as the injected-class-name. For |
18031 | // purposes of access checking, the injected-class-name is treated |
18032 | // as if it were a public member name. |
18033 | CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( |
18034 | C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(), |
18035 | IdLoc: Record->getLocation(), Id: Record->getIdentifier(), |
18036 | /*PrevDecl=*/nullptr, |
18037 | /*DelayTypeCreation=*/true); |
18038 | Context.getTypeDeclType(Decl: InjectedClassName, PrevDecl: Record); |
18039 | InjectedClassName->setImplicit(); |
18040 | InjectedClassName->setAccess(AS_public); |
18041 | if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) |
18042 | InjectedClassName->setDescribedClassTemplate(Template); |
18043 | PushOnScopeChains(D: InjectedClassName, S); |
18044 | assert(InjectedClassName->isInjectedClassName() && |
18045 | "Broken injected-class-name" ); |
18046 | } |
18047 | |
18048 | void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, |
18049 | SourceRange BraceRange) { |
18050 | AdjustDeclIfTemplate(Decl&: TagD); |
18051 | TagDecl *Tag = cast<TagDecl>(Val: TagD); |
18052 | Tag->setBraceRange(BraceRange); |
18053 | |
18054 | // Make sure we "complete" the definition even it is invalid. |
18055 | if (Tag->isBeingDefined()) { |
18056 | assert(Tag->isInvalidDecl() && "We should already have completed it" ); |
18057 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag)) |
18058 | RD->completeDefinition(); |
18059 | } |
18060 | |
18061 | if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) { |
18062 | FieldCollector->FinishClass(); |
18063 | if (RD->hasAttr<SYCLSpecialClassAttr>()) { |
18064 | auto *Def = RD->getDefinition(); |
18065 | assert(Def && "The record is expected to have a completed definition" ); |
18066 | unsigned NumInitMethods = 0; |
18067 | for (auto *Method : Def->methods()) { |
18068 | if (!Method->getIdentifier()) |
18069 | continue; |
18070 | if (Method->getName() == "__init" ) |
18071 | NumInitMethods++; |
18072 | } |
18073 | if (NumInitMethods > 1 || !Def->hasInitMethod()) |
18074 | Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method); |
18075 | } |
18076 | |
18077 | // If we're defining a dynamic class in a module interface unit, we always |
18078 | // need to produce the vtable for it, even if the vtable is not used in the |
18079 | // current TU. |
18080 | // |
18081 | // The case where the current class is not dynamic is handled in |
18082 | // MarkVTableUsed. |
18083 | if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition()) |
18084 | MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true); |
18085 | } |
18086 | |
18087 | // Exit this scope of this tag's definition. |
18088 | PopDeclContext(); |
18089 | |
18090 | if (getCurLexicalContext()->isObjCContainer() && |
18091 | Tag->getDeclContext()->isFileContext()) |
18092 | Tag->setTopLevelDeclInObjCContainer(); |
18093 | |
18094 | // Notify the consumer that we've defined a tag. |
18095 | if (!Tag->isInvalidDecl()) |
18096 | Consumer.HandleTagDeclDefinition(D: Tag); |
18097 | |
18098 | // Clangs implementation of #pragma align(packed) differs in bitfield layout |
18099 | // from XLs and instead matches the XL #pragma pack(1) behavior. |
18100 | if (Context.getTargetInfo().getTriple().isOSAIX() && |
18101 | AlignPackStack.hasValue()) { |
18102 | AlignPackInfo APInfo = AlignPackStack.CurrentValue; |
18103 | // Only diagnose #pragma align(packed). |
18104 | if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) |
18105 | return; |
18106 | const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag); |
18107 | if (!RD) |
18108 | return; |
18109 | // Only warn if there is at least 1 bitfield member. |
18110 | if (llvm::any_of(Range: RD->fields(), |
18111 | P: [](const FieldDecl *FD) { return FD->isBitField(); })) |
18112 | Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible); |
18113 | } |
18114 | } |
18115 | |
18116 | void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { |
18117 | AdjustDeclIfTemplate(Decl&: TagD); |
18118 | TagDecl *Tag = cast<TagDecl>(Val: TagD); |
18119 | Tag->setInvalidDecl(); |
18120 | |
18121 | // Make sure we "complete" the definition even it is invalid. |
18122 | if (Tag->isBeingDefined()) { |
18123 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag)) |
18124 | RD->completeDefinition(); |
18125 | } |
18126 | |
18127 | // We're undoing ActOnTagStartDefinition here, not |
18128 | // ActOnStartCXXMemberDeclarations, so we don't have to mess with |
18129 | // the FieldCollector. |
18130 | |
18131 | PopDeclContext(); |
18132 | } |
18133 | |
18134 | // Note that FieldName may be null for anonymous bitfields. |
18135 | ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, |
18136 | const IdentifierInfo *FieldName, |
18137 | QualType FieldTy, bool IsMsStruct, |
18138 | Expr *BitWidth) { |
18139 | assert(BitWidth); |
18140 | if (BitWidth->containsErrors()) |
18141 | return ExprError(); |
18142 | |
18143 | // C99 6.7.2.1p4 - verify the field type. |
18144 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. |
18145 | if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { |
18146 | // Handle incomplete and sizeless types with a specific error. |
18147 | if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy, |
18148 | DiagID: diag::err_field_incomplete_or_sizeless)) |
18149 | return ExprError(); |
18150 | if (FieldName) |
18151 | return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield) |
18152 | << FieldName << FieldTy << BitWidth->getSourceRange(); |
18153 | return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield) |
18154 | << FieldTy << BitWidth->getSourceRange(); |
18155 | } else if (DiagnoseUnexpandedParameterPack(E: const_cast<Expr *>(BitWidth), |
18156 | UPPC: UPPC_BitFieldWidth)) |
18157 | return ExprError(); |
18158 | |
18159 | // If the bit-width is type- or value-dependent, don't try to check |
18160 | // it now. |
18161 | if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) |
18162 | return BitWidth; |
18163 | |
18164 | llvm::APSInt Value; |
18165 | ExprResult ICE = VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFold); |
18166 | if (ICE.isInvalid()) |
18167 | return ICE; |
18168 | BitWidth = ICE.get(); |
18169 | |
18170 | // Zero-width bitfield is ok for anonymous field. |
18171 | if (Value == 0 && FieldName) |
18172 | return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width) |
18173 | << FieldName << BitWidth->getSourceRange(); |
18174 | |
18175 | if (Value.isSigned() && Value.isNegative()) { |
18176 | if (FieldName) |
18177 | return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width) |
18178 | << FieldName << toString(I: Value, Radix: 10); |
18179 | return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width) |
18180 | << toString(I: Value, Radix: 10); |
18181 | } |
18182 | |
18183 | // The size of the bit-field must not exceed our maximum permitted object |
18184 | // size. |
18185 | if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { |
18186 | return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide) |
18187 | << !FieldName << FieldName << toString(I: Value, Radix: 10); |
18188 | } |
18189 | |
18190 | if (!FieldTy->isDependentType()) { |
18191 | uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy); |
18192 | uint64_t TypeWidth = Context.getIntWidth(T: FieldTy); |
18193 | bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth); |
18194 | |
18195 | // Over-wide bitfields are an error in C or when using the MSVC bitfield |
18196 | // ABI. |
18197 | bool CStdConstraintViolation = |
18198 | BitfieldIsOverwide && !getLangOpts().CPlusPlus; |
18199 | bool MSBitfieldViolation = |
18200 | Value.ugt(RHS: TypeStorageSize) && |
18201 | (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); |
18202 | if (CStdConstraintViolation || MSBitfieldViolation) { |
18203 | unsigned DiagWidth = |
18204 | CStdConstraintViolation ? TypeWidth : TypeStorageSize; |
18205 | return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width) |
18206 | << (bool)FieldName << FieldName << toString(I: Value, Radix: 10) |
18207 | << !CStdConstraintViolation << DiagWidth; |
18208 | } |
18209 | |
18210 | // Warn on types where the user might conceivably expect to get all |
18211 | // specified bits as value bits: that's all integral types other than |
18212 | // 'bool'. |
18213 | if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { |
18214 | Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width) |
18215 | << FieldName << toString(I: Value, Radix: 10) |
18216 | << (unsigned)TypeWidth; |
18217 | } |
18218 | } |
18219 | |
18220 | return BitWidth; |
18221 | } |
18222 | |
18223 | Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, |
18224 | Declarator &D, Expr *BitfieldWidth) { |
18225 | FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart, |
18226 | D, BitfieldWidth, |
18227 | /*InitStyle=*/ICIS_NoInit, AS: AS_public); |
18228 | return Res; |
18229 | } |
18230 | |
18231 | FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, |
18232 | SourceLocation DeclStart, |
18233 | Declarator &D, Expr *BitWidth, |
18234 | InClassInitStyle InitStyle, |
18235 | AccessSpecifier AS) { |
18236 | if (D.isDecompositionDeclarator()) { |
18237 | const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); |
18238 | Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context) |
18239 | << Decomp.getSourceRange(); |
18240 | return nullptr; |
18241 | } |
18242 | |
18243 | const IdentifierInfo *II = D.getIdentifier(); |
18244 | SourceLocation Loc = DeclStart; |
18245 | if (II) Loc = D.getIdentifierLoc(); |
18246 | |
18247 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D); |
18248 | QualType T = TInfo->getType(); |
18249 | if (getLangOpts().CPlusPlus) { |
18250 | CheckExtraCXXDefaultArguments(D); |
18251 | |
18252 | if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo, |
18253 | UPPC: UPPC_DataMemberType)) { |
18254 | D.setInvalidType(); |
18255 | T = Context.IntTy; |
18256 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc); |
18257 | } |
18258 | } |
18259 | |
18260 | DiagnoseFunctionSpecifiers(DS: D.getDeclSpec()); |
18261 | |
18262 | if (D.getDeclSpec().isInlineSpecified()) |
18263 | Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function) |
18264 | << getLangOpts().CPlusPlus17; |
18265 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) |
18266 | Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(), |
18267 | DiagID: diag::err_invalid_thread) |
18268 | << DeclSpec::getSpecifierName(S: TSCS); |
18269 | |
18270 | // Check to see if this name was declared as a member previously |
18271 | NamedDecl *PrevDecl = nullptr; |
18272 | LookupResult Previous(*this, II, Loc, LookupMemberName, |
18273 | RedeclarationKind::ForVisibleRedeclaration); |
18274 | LookupName(R&: Previous, S); |
18275 | switch (Previous.getResultKind()) { |
18276 | case LookupResult::Found: |
18277 | case LookupResult::FoundUnresolvedValue: |
18278 | PrevDecl = Previous.getAsSingle<NamedDecl>(); |
18279 | break; |
18280 | |
18281 | case LookupResult::FoundOverloaded: |
18282 | PrevDecl = Previous.getRepresentativeDecl(); |
18283 | break; |
18284 | |
18285 | case LookupResult::NotFound: |
18286 | case LookupResult::NotFoundInCurrentInstantiation: |
18287 | case LookupResult::Ambiguous: |
18288 | break; |
18289 | } |
18290 | Previous.suppressDiagnostics(); |
18291 | |
18292 | if (PrevDecl && PrevDecl->isTemplateParameter()) { |
18293 | // Maybe we will complain about the shadowed template parameter. |
18294 | DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl); |
18295 | // Just pretend that we didn't see the previous declaration. |
18296 | PrevDecl = nullptr; |
18297 | } |
18298 | |
18299 | if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S)) |
18300 | PrevDecl = nullptr; |
18301 | |
18302 | bool Mutable |
18303 | = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); |
18304 | SourceLocation TSSL = D.getBeginLoc(); |
18305 | FieldDecl *NewFD |
18306 | = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle, |
18307 | TSSL, AS, PrevDecl, D: &D); |
18308 | |
18309 | if (NewFD->isInvalidDecl()) |
18310 | Record->setInvalidDecl(); |
18311 | |
18312 | if (D.getDeclSpec().isModulePrivateSpecified()) |
18313 | NewFD->setModulePrivate(); |
18314 | |
18315 | if (NewFD->isInvalidDecl() && PrevDecl) { |
18316 | // Don't introduce NewFD into scope; there's already something |
18317 | // with the same name in the same scope. |
18318 | } else if (II) { |
18319 | PushOnScopeChains(D: NewFD, S); |
18320 | } else |
18321 | Record->addDecl(D: NewFD); |
18322 | |
18323 | return NewFD; |
18324 | } |
18325 | |
18326 | FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, |
18327 | TypeSourceInfo *TInfo, |
18328 | RecordDecl *Record, SourceLocation Loc, |
18329 | bool Mutable, Expr *BitWidth, |
18330 | InClassInitStyle InitStyle, |
18331 | SourceLocation TSSL, |
18332 | AccessSpecifier AS, NamedDecl *PrevDecl, |
18333 | Declarator *D) { |
18334 | const IdentifierInfo *II = Name.getAsIdentifierInfo(); |
18335 | bool InvalidDecl = false; |
18336 | if (D) InvalidDecl = D->isInvalidType(); |
18337 | |
18338 | // If we receive a broken type, recover by assuming 'int' and |
18339 | // marking this declaration as invalid. |
18340 | if (T.isNull() || T->containsErrors()) { |
18341 | InvalidDecl = true; |
18342 | T = Context.IntTy; |
18343 | } |
18344 | |
18345 | QualType EltTy = Context.getBaseElementType(QT: T); |
18346 | if (!EltTy->isDependentType() && !EltTy->containsErrors()) { |
18347 | if (RequireCompleteSizedType(Loc, T: EltTy, |
18348 | DiagID: diag::err_field_incomplete_or_sizeless)) { |
18349 | // Fields of incomplete type force their record to be invalid. |
18350 | Record->setInvalidDecl(); |
18351 | InvalidDecl = true; |
18352 | } else { |
18353 | NamedDecl *Def; |
18354 | EltTy->isIncompleteType(Def: &Def); |
18355 | if (Def && Def->isInvalidDecl()) { |
18356 | Record->setInvalidDecl(); |
18357 | InvalidDecl = true; |
18358 | } |
18359 | } |
18360 | } |
18361 | |
18362 | // TR 18037 does not allow fields to be declared with address space |
18363 | if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || |
18364 | T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { |
18365 | Diag(Loc, DiagID: diag::err_field_with_address_space); |
18366 | Record->setInvalidDecl(); |
18367 | InvalidDecl = true; |
18368 | } |
18369 | |
18370 | if (LangOpts.OpenCL) { |
18371 | // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be |
18372 | // used as structure or union field: image, sampler, event or block types. |
18373 | if (T->isEventT() || T->isImageType() || T->isSamplerT() || |
18374 | T->isBlockPointerType()) { |
18375 | Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T; |
18376 | Record->setInvalidDecl(); |
18377 | InvalidDecl = true; |
18378 | } |
18379 | // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension |
18380 | // is enabled. |
18381 | if (BitWidth && !getOpenCLOptions().isAvailableOption( |
18382 | Ext: "__cl_clang_bitfields" , LO: LangOpts)) { |
18383 | Diag(Loc, DiagID: diag::err_opencl_bitfields); |
18384 | InvalidDecl = true; |
18385 | } |
18386 | } |
18387 | |
18388 | // Anonymous bit-fields cannot be cv-qualified (CWG 2229). |
18389 | if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && |
18390 | T.hasQualifiers()) { |
18391 | InvalidDecl = true; |
18392 | Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers); |
18393 | } |
18394 | |
18395 | // C99 6.7.2.1p8: A member of a structure or union may have any type other |
18396 | // than a variably modified type. |
18397 | if (!InvalidDecl && T->isVariablyModifiedType()) { |
18398 | if (!tryToFixVariablyModifiedVarType( |
18399 | TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size)) |
18400 | InvalidDecl = true; |
18401 | } |
18402 | |
18403 | // Fields can not have abstract class types |
18404 | if (!InvalidDecl && RequireNonAbstractType(Loc, T, |
18405 | DiagID: diag::err_abstract_type_in_decl, |
18406 | Args: AbstractFieldType)) |
18407 | InvalidDecl = true; |
18408 | |
18409 | if (InvalidDecl) |
18410 | BitWidth = nullptr; |
18411 | // If this is declared as a bit-field, check the bit-field. |
18412 | if (BitWidth) { |
18413 | BitWidth = |
18414 | VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get(); |
18415 | if (!BitWidth) { |
18416 | InvalidDecl = true; |
18417 | BitWidth = nullptr; |
18418 | } |
18419 | } |
18420 | |
18421 | // Check that 'mutable' is consistent with the type of the declaration. |
18422 | if (!InvalidDecl && Mutable) { |
18423 | unsigned DiagID = 0; |
18424 | if (T->isReferenceType()) |
18425 | DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference |
18426 | : diag::err_mutable_reference; |
18427 | else if (T.isConstQualified()) |
18428 | DiagID = diag::err_mutable_const; |
18429 | |
18430 | if (DiagID) { |
18431 | SourceLocation ErrLoc = Loc; |
18432 | if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) |
18433 | ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); |
18434 | Diag(Loc: ErrLoc, DiagID); |
18435 | if (DiagID != diag::ext_mutable_reference) { |
18436 | Mutable = false; |
18437 | InvalidDecl = true; |
18438 | } |
18439 | } |
18440 | } |
18441 | |
18442 | // C++11 [class.union]p8 (DR1460): |
18443 | // At most one variant member of a union may have a |
18444 | // brace-or-equal-initializer. |
18445 | if (InitStyle != ICIS_NoInit) |
18446 | checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc); |
18447 | |
18448 | FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo, |
18449 | BW: BitWidth, Mutable, InitStyle); |
18450 | if (InvalidDecl) |
18451 | NewFD->setInvalidDecl(); |
18452 | |
18453 | if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) && |
18454 | !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) { |
18455 | Diag(Loc, DiagID: diag::err_duplicate_member) << II; |
18456 | Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration); |
18457 | NewFD->setInvalidDecl(); |
18458 | } |
18459 | |
18460 | if (!InvalidDecl && getLangOpts().CPlusPlus) { |
18461 | if (Record->isUnion()) { |
18462 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { |
18463 | CXXRecordDecl* RDecl = cast<CXXRecordDecl>(Val: RT->getDecl()); |
18464 | if (RDecl->getDefinition()) { |
18465 | // C++ [class.union]p1: An object of a class with a non-trivial |
18466 | // constructor, a non-trivial copy constructor, a non-trivial |
18467 | // destructor, or a non-trivial copy assignment operator |
18468 | // cannot be a member of a union, nor can an array of such |
18469 | // objects. |
18470 | if (CheckNontrivialField(FD: NewFD)) |
18471 | NewFD->setInvalidDecl(); |
18472 | } |
18473 | } |
18474 | |
18475 | // C++ [class.union]p1: If a union contains a member of reference type, |
18476 | // the program is ill-formed, except when compiling with MSVC extensions |
18477 | // enabled. |
18478 | if (EltTy->isReferenceType()) { |
18479 | Diag(Loc: NewFD->getLocation(), DiagID: getLangOpts().MicrosoftExt ? |
18480 | diag::ext_union_member_of_reference_type : |
18481 | diag::err_union_member_of_reference_type) |
18482 | << NewFD->getDeclName() << EltTy; |
18483 | if (!getLangOpts().MicrosoftExt) |
18484 | NewFD->setInvalidDecl(); |
18485 | } |
18486 | } |
18487 | } |
18488 | |
18489 | // FIXME: We need to pass in the attributes given an AST |
18490 | // representation, not a parser representation. |
18491 | if (D) { |
18492 | // FIXME: The current scope is almost... but not entirely... correct here. |
18493 | ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D); |
18494 | |
18495 | if (NewFD->hasAttrs()) |
18496 | CheckAlignasUnderalignment(D: NewFD); |
18497 | } |
18498 | |
18499 | // In auto-retain/release, infer strong retension for fields of |
18500 | // retainable type. |
18501 | if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD)) |
18502 | NewFD->setInvalidDecl(); |
18503 | |
18504 | if (T.isObjCGCWeak()) |
18505 | Diag(Loc, DiagID: diag::warn_attribute_weak_on_field); |
18506 | |
18507 | // PPC MMA non-pointer types are not allowed as field types. |
18508 | if (Context.getTargetInfo().getTriple().isPPC64() && |
18509 | PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation())) |
18510 | NewFD->setInvalidDecl(); |
18511 | |
18512 | NewFD->setAccess(AS); |
18513 | return NewFD; |
18514 | } |
18515 | |
18516 | bool Sema::CheckNontrivialField(FieldDecl *FD) { |
18517 | assert(FD); |
18518 | assert(getLangOpts().CPlusPlus && "valid check only for C++" ); |
18519 | |
18520 | if (FD->isInvalidDecl() || FD->getType()->isDependentType()) |
18521 | return false; |
18522 | |
18523 | QualType EltTy = Context.getBaseElementType(QT: FD->getType()); |
18524 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { |
18525 | CXXRecordDecl *RDecl = cast<CXXRecordDecl>(Val: RT->getDecl()); |
18526 | if (RDecl->getDefinition()) { |
18527 | // We check for copy constructors before constructors |
18528 | // because otherwise we'll never get complaints about |
18529 | // copy constructors. |
18530 | |
18531 | CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid; |
18532 | // We're required to check for any non-trivial constructors. Since the |
18533 | // implicit default constructor is suppressed if there are any |
18534 | // user-declared constructors, we just need to check that there is a |
18535 | // trivial default constructor and a trivial copy constructor. (We don't |
18536 | // worry about move constructors here, since this is a C++98 check.) |
18537 | if (RDecl->hasNonTrivialCopyConstructor()) |
18538 | member = CXXSpecialMemberKind::CopyConstructor; |
18539 | else if (!RDecl->hasTrivialDefaultConstructor()) |
18540 | member = CXXSpecialMemberKind::DefaultConstructor; |
18541 | else if (RDecl->hasNonTrivialCopyAssignment()) |
18542 | member = CXXSpecialMemberKind::CopyAssignment; |
18543 | else if (RDecl->hasNonTrivialDestructor()) |
18544 | member = CXXSpecialMemberKind::Destructor; |
18545 | |
18546 | if (member != CXXSpecialMemberKind::Invalid) { |
18547 | if (!getLangOpts().CPlusPlus11 && |
18548 | getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { |
18549 | // Objective-C++ ARC: it is an error to have a non-trivial field of |
18550 | // a union. However, system headers in Objective-C programs |
18551 | // occasionally have Objective-C lifetime objects within unions, |
18552 | // and rather than cause the program to fail, we make those |
18553 | // members unavailable. |
18554 | SourceLocation Loc = FD->getLocation(); |
18555 | if (getSourceManager().isInSystemHeader(Loc)) { |
18556 | if (!FD->hasAttr<UnavailableAttr>()) |
18557 | FD->addAttr(A: UnavailableAttr::CreateImplicit(Ctx&: Context, Message: "" , |
18558 | ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc)); |
18559 | return false; |
18560 | } |
18561 | } |
18562 | |
18563 | Diag( |
18564 | Loc: FD->getLocation(), |
18565 | DiagID: getLangOpts().CPlusPlus11 |
18566 | ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member |
18567 | : diag::err_illegal_union_or_anon_struct_member) |
18568 | << FD->getParent()->isUnion() << FD->getDeclName() |
18569 | << llvm::to_underlying(E: member); |
18570 | DiagnoseNontrivial(Record: RDecl, CSM: member); |
18571 | return !getLangOpts().CPlusPlus11; |
18572 | } |
18573 | } |
18574 | } |
18575 | |
18576 | return false; |
18577 | } |
18578 | |
18579 | void Sema::ActOnLastBitfield(SourceLocation DeclLoc, |
18580 | SmallVectorImpl<Decl *> &AllIvarDecls) { |
18581 | if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) |
18582 | return; |
18583 | |
18584 | Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; |
18585 | ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl); |
18586 | |
18587 | if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Ctx: Context)) |
18588 | return; |
18589 | ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext); |
18590 | if (!ID) { |
18591 | if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) { |
18592 | if (!CD->IsClassExtension()) |
18593 | return; |
18594 | } |
18595 | // No need to add this to end of @implementation. |
18596 | else |
18597 | return; |
18598 | } |
18599 | // All conditions are met. Add a new bitfield to the tail end of ivars. |
18600 | llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0); |
18601 | Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc); |
18602 | |
18603 | Ivar = ObjCIvarDecl::Create(C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), |
18604 | StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr, |
18605 | T: Context.CharTy, |
18606 | TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, |
18607 | Loc: DeclLoc), |
18608 | ac: ObjCIvarDecl::Private, BW, |
18609 | synthesized: true); |
18610 | AllIvarDecls.push_back(Elt: Ivar); |
18611 | } |
18612 | |
18613 | /// [class.dtor]p4: |
18614 | /// At the end of the definition of a class, overload resolution is |
18615 | /// performed among the prospective destructors declared in that class with |
18616 | /// an empty argument list to select the destructor for the class, also |
18617 | /// known as the selected destructor. |
18618 | /// |
18619 | /// We do the overload resolution here, then mark the selected constructor in the AST. |
18620 | /// Later CXXRecordDecl::getDestructor() will return the selected constructor. |
18621 | static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) { |
18622 | if (!Record->hasUserDeclaredDestructor()) { |
18623 | return; |
18624 | } |
18625 | |
18626 | SourceLocation Loc = Record->getLocation(); |
18627 | OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal); |
18628 | |
18629 | for (auto *Decl : Record->decls()) { |
18630 | if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) { |
18631 | if (DD->isInvalidDecl()) |
18632 | continue; |
18633 | S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {}, |
18634 | CandidateSet&: OCS); |
18635 | assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected." ); |
18636 | } |
18637 | } |
18638 | |
18639 | if (OCS.empty()) { |
18640 | return; |
18641 | } |
18642 | OverloadCandidateSet::iterator Best; |
18643 | unsigned Msg = 0; |
18644 | OverloadCandidateDisplayKind DisplayKind; |
18645 | |
18646 | switch (OCS.BestViableFunction(S, Loc, Best)) { |
18647 | case OR_Success: |
18648 | case OR_Deleted: |
18649 | Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function)); |
18650 | break; |
18651 | |
18652 | case OR_Ambiguous: |
18653 | Msg = diag::err_ambiguous_destructor; |
18654 | DisplayKind = OCD_AmbiguousCandidates; |
18655 | break; |
18656 | |
18657 | case OR_No_Viable_Function: |
18658 | Msg = diag::err_no_viable_destructor; |
18659 | DisplayKind = OCD_AllCandidates; |
18660 | break; |
18661 | } |
18662 | |
18663 | if (Msg) { |
18664 | // OpenCL have got their own thing going with destructors. It's slightly broken, |
18665 | // but we allow it. |
18666 | if (!S.LangOpts.OpenCL) { |
18667 | PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record; |
18668 | OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {}); |
18669 | Record->setInvalidDecl(); |
18670 | } |
18671 | // It's a bit hacky: At this point we've raised an error but we want the |
18672 | // rest of the compiler to continue somehow working. However almost |
18673 | // everything we'll try to do with the class will depend on there being a |
18674 | // destructor. So let's pretend the first one is selected and hope for the |
18675 | // best. |
18676 | Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function)); |
18677 | } |
18678 | } |
18679 | |
18680 | /// [class.mem.special]p5 |
18681 | /// Two special member functions are of the same kind if: |
18682 | /// - they are both default constructors, |
18683 | /// - they are both copy or move constructors with the same first parameter |
18684 | /// type, or |
18685 | /// - they are both copy or move assignment operators with the same first |
18686 | /// parameter type and the same cv-qualifiers and ref-qualifier, if any. |
18687 | static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, |
18688 | CXXMethodDecl *M1, |
18689 | CXXMethodDecl *M2, |
18690 | CXXSpecialMemberKind CSM) { |
18691 | // We don't want to compare templates to non-templates: See |
18692 | // https://github.com/llvm/llvm-project/issues/59206 |
18693 | if (CSM == CXXSpecialMemberKind::DefaultConstructor) |
18694 | return bool(M1->getDescribedFunctionTemplate()) == |
18695 | bool(M2->getDescribedFunctionTemplate()); |
18696 | // FIXME: better resolve CWG |
18697 | // https://cplusplus.github.io/CWG/issues/2787.html |
18698 | if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(), |
18699 | T2: M2->getNonObjectParameter(I: 0)->getType())) |
18700 | return false; |
18701 | if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(), |
18702 | T2: M2->getFunctionObjectParameterReferenceType())) |
18703 | return false; |
18704 | |
18705 | return true; |
18706 | } |
18707 | |
18708 | /// [class.mem.special]p6: |
18709 | /// An eligible special member function is a special member function for which: |
18710 | /// - the function is not deleted, |
18711 | /// - the associated constraints, if any, are satisfied, and |
18712 | /// - no special member function of the same kind whose associated constraints |
18713 | /// [CWG2595], if any, are satisfied is more constrained. |
18714 | static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, |
18715 | ArrayRef<CXXMethodDecl *> Methods, |
18716 | CXXSpecialMemberKind CSM) { |
18717 | SmallVector<bool, 4> SatisfactionStatus; |
18718 | |
18719 | for (CXXMethodDecl *Method : Methods) { |
18720 | const Expr *Constraints = Method->getTrailingRequiresClause(); |
18721 | if (!Constraints) |
18722 | SatisfactionStatus.push_back(Elt: true); |
18723 | else { |
18724 | ConstraintSatisfaction Satisfaction; |
18725 | if (S.CheckFunctionConstraints(FD: Method, Satisfaction)) |
18726 | SatisfactionStatus.push_back(Elt: false); |
18727 | else |
18728 | SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied); |
18729 | } |
18730 | } |
18731 | |
18732 | for (size_t i = 0; i < Methods.size(); i++) { |
18733 | if (!SatisfactionStatus[i]) |
18734 | continue; |
18735 | CXXMethodDecl *Method = Methods[i]; |
18736 | CXXMethodDecl *OrigMethod = Method; |
18737 | if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction()) |
18738 | OrigMethod = cast<CXXMethodDecl>(Val: MF); |
18739 | |
18740 | const Expr *Constraints = OrigMethod->getTrailingRequiresClause(); |
18741 | bool AnotherMethodIsMoreConstrained = false; |
18742 | for (size_t j = 0; j < Methods.size(); j++) { |
18743 | if (i == j || !SatisfactionStatus[j]) |
18744 | continue; |
18745 | CXXMethodDecl *OtherMethod = Methods[j]; |
18746 | if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction()) |
18747 | OtherMethod = cast<CXXMethodDecl>(Val: MF); |
18748 | |
18749 | if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod, |
18750 | CSM)) |
18751 | continue; |
18752 | |
18753 | const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause(); |
18754 | if (!OtherConstraints) |
18755 | continue; |
18756 | if (!Constraints) { |
18757 | AnotherMethodIsMoreConstrained = true; |
18758 | break; |
18759 | } |
18760 | if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {OtherConstraints}, D2: OrigMethod, |
18761 | AC2: {Constraints}, |
18762 | Result&: AnotherMethodIsMoreConstrained)) { |
18763 | // There was an error with the constraints comparison. Exit the loop |
18764 | // and don't consider this function eligible. |
18765 | AnotherMethodIsMoreConstrained = true; |
18766 | } |
18767 | if (AnotherMethodIsMoreConstrained) |
18768 | break; |
18769 | } |
18770 | // FIXME: Do not consider deleted methods as eligible after implementing |
18771 | // DR1734 and DR1496. |
18772 | if (!AnotherMethodIsMoreConstrained) { |
18773 | Method->setIneligibleOrNotSelected(false); |
18774 | Record->addedEligibleSpecialMemberFunction(MD: Method, |
18775 | SMKind: 1 << llvm::to_underlying(E: CSM)); |
18776 | } |
18777 | } |
18778 | } |
18779 | |
18780 | static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, |
18781 | CXXRecordDecl *Record) { |
18782 | SmallVector<CXXMethodDecl *, 4> DefaultConstructors; |
18783 | SmallVector<CXXMethodDecl *, 4> CopyConstructors; |
18784 | SmallVector<CXXMethodDecl *, 4> MoveConstructors; |
18785 | SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators; |
18786 | SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators; |
18787 | |
18788 | for (auto *Decl : Record->decls()) { |
18789 | auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl); |
18790 | if (!MD) { |
18791 | auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl); |
18792 | if (FTD) |
18793 | MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl()); |
18794 | } |
18795 | if (!MD) |
18796 | continue; |
18797 | if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) { |
18798 | if (CD->isInvalidDecl()) |
18799 | continue; |
18800 | if (CD->isDefaultConstructor()) |
18801 | DefaultConstructors.push_back(Elt: MD); |
18802 | else if (CD->isCopyConstructor()) |
18803 | CopyConstructors.push_back(Elt: MD); |
18804 | else if (CD->isMoveConstructor()) |
18805 | MoveConstructors.push_back(Elt: MD); |
18806 | } else if (MD->isCopyAssignmentOperator()) { |
18807 | CopyAssignmentOperators.push_back(Elt: MD); |
18808 | } else if (MD->isMoveAssignmentOperator()) { |
18809 | MoveAssignmentOperators.push_back(Elt: MD); |
18810 | } |
18811 | } |
18812 | |
18813 | SetEligibleMethods(S, Record, Methods: DefaultConstructors, |
18814 | CSM: CXXSpecialMemberKind::DefaultConstructor); |
18815 | SetEligibleMethods(S, Record, Methods: CopyConstructors, |
18816 | CSM: CXXSpecialMemberKind::CopyConstructor); |
18817 | SetEligibleMethods(S, Record, Methods: MoveConstructors, |
18818 | CSM: CXXSpecialMemberKind::MoveConstructor); |
18819 | SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators, |
18820 | CSM: CXXSpecialMemberKind::CopyAssignment); |
18821 | SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators, |
18822 | CSM: CXXSpecialMemberKind::MoveAssignment); |
18823 | } |
18824 | |
18825 | void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, |
18826 | ArrayRef<Decl *> Fields, SourceLocation LBrac, |
18827 | SourceLocation RBrac, |
18828 | const ParsedAttributesView &Attrs) { |
18829 | assert(EnclosingDecl && "missing record or interface decl" ); |
18830 | |
18831 | // If this is an Objective-C @implementation or category and we have |
18832 | // new fields here we should reset the layout of the interface since |
18833 | // it will now change. |
18834 | if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) { |
18835 | ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl); |
18836 | switch (DC->getKind()) { |
18837 | default: break; |
18838 | case Decl::ObjCCategory: |
18839 | Context.ResetObjCLayout(CD: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface()); |
18840 | break; |
18841 | case Decl::ObjCImplementation: |
18842 | Context. |
18843 | ResetObjCLayout(CD: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface()); |
18844 | break; |
18845 | } |
18846 | } |
18847 | |
18848 | RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl); |
18849 | CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl); |
18850 | |
18851 | // Start counting up the number of named members; make sure to include |
18852 | // members of anonymous structs and unions in the total. |
18853 | unsigned NumNamedMembers = 0; |
18854 | if (Record) { |
18855 | for (const auto *I : Record->decls()) { |
18856 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I)) |
18857 | if (IFD->getDeclName()) |
18858 | ++NumNamedMembers; |
18859 | } |
18860 | } |
18861 | |
18862 | // Verify that all the fields are okay. |
18863 | SmallVector<FieldDecl*, 32> RecFields; |
18864 | |
18865 | for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); |
18866 | i != end; ++i) { |
18867 | FieldDecl *FD = cast<FieldDecl>(Val: *i); |
18868 | |
18869 | // Get the type for the field. |
18870 | const Type *FDTy = FD->getType().getTypePtr(); |
18871 | |
18872 | if (!FD->isAnonymousStructOrUnion()) { |
18873 | // Remember all fields written by the user. |
18874 | RecFields.push_back(Elt: FD); |
18875 | } |
18876 | |
18877 | // If the field is already invalid for some reason, don't emit more |
18878 | // diagnostics about it. |
18879 | if (FD->isInvalidDecl()) { |
18880 | EnclosingDecl->setInvalidDecl(); |
18881 | continue; |
18882 | } |
18883 | |
18884 | // C99 6.7.2.1p2: |
18885 | // A structure or union shall not contain a member with |
18886 | // incomplete or function type (hence, a structure shall not |
18887 | // contain an instance of itself, but may contain a pointer to |
18888 | // an instance of itself), except that the last member of a |
18889 | // structure with more than one named member may have incomplete |
18890 | // array type; such a structure (and any union containing, |
18891 | // possibly recursively, a member that is such a structure) |
18892 | // shall not be a member of a structure or an element of an |
18893 | // array. |
18894 | bool IsLastField = (i + 1 == Fields.end()); |
18895 | if (FDTy->isFunctionType()) { |
18896 | // Field declared as a function. |
18897 | Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function) |
18898 | << FD->getDeclName(); |
18899 | FD->setInvalidDecl(); |
18900 | EnclosingDecl->setInvalidDecl(); |
18901 | continue; |
18902 | } else if (FDTy->isIncompleteArrayType() && |
18903 | (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) { |
18904 | if (Record) { |
18905 | // Flexible array member. |
18906 | // Microsoft and g++ is more permissive regarding flexible array. |
18907 | // It will accept flexible array in union and also |
18908 | // as the sole element of a struct/class. |
18909 | unsigned DiagID = 0; |
18910 | if (!Record->isUnion() && !IsLastField) { |
18911 | Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end) |
18912 | << FD->getDeclName() << FD->getType() |
18913 | << llvm::to_underlying(E: Record->getTagKind()); |
18914 | Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration); |
18915 | FD->setInvalidDecl(); |
18916 | EnclosingDecl->setInvalidDecl(); |
18917 | continue; |
18918 | } else if (Record->isUnion()) |
18919 | DiagID = getLangOpts().MicrosoftExt |
18920 | ? diag::ext_flexible_array_union_ms |
18921 | : diag::ext_flexible_array_union_gnu; |
18922 | else if (NumNamedMembers < 1) |
18923 | DiagID = getLangOpts().MicrosoftExt |
18924 | ? diag::ext_flexible_array_empty_aggregate_ms |
18925 | : diag::ext_flexible_array_empty_aggregate_gnu; |
18926 | |
18927 | if (DiagID) |
18928 | Diag(Loc: FD->getLocation(), DiagID) |
18929 | << FD->getDeclName() << llvm::to_underlying(E: Record->getTagKind()); |
18930 | // While the layout of types that contain virtual bases is not specified |
18931 | // by the C++ standard, both the Itanium and Microsoft C++ ABIs place |
18932 | // virtual bases after the derived members. This would make a flexible |
18933 | // array member declared at the end of an object not adjacent to the end |
18934 | // of the type. |
18935 | if (CXXRecord && CXXRecord->getNumVBases() != 0) |
18936 | Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base) |
18937 | << FD->getDeclName() << llvm::to_underlying(E: Record->getTagKind()); |
18938 | if (!getLangOpts().C99) |
18939 | Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member) |
18940 | << FD->getDeclName() << llvm::to_underlying(E: Record->getTagKind()); |
18941 | |
18942 | // If the element type has a non-trivial destructor, we would not |
18943 | // implicitly destroy the elements, so disallow it for now. |
18944 | // |
18945 | // FIXME: GCC allows this. We should probably either implicitly delete |
18946 | // the destructor of the containing class, or just allow this. |
18947 | QualType BaseElem = Context.getBaseElementType(QT: FD->getType()); |
18948 | if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { |
18949 | Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor) |
18950 | << FD->getDeclName() << FD->getType(); |
18951 | FD->setInvalidDecl(); |
18952 | EnclosingDecl->setInvalidDecl(); |
18953 | continue; |
18954 | } |
18955 | // Okay, we have a legal flexible array member at the end of the struct. |
18956 | Record->setHasFlexibleArrayMember(true); |
18957 | } else { |
18958 | // In ObjCContainerDecl ivars with incomplete array type are accepted, |
18959 | // unless they are followed by another ivar. That check is done |
18960 | // elsewhere, after synthesized ivars are known. |
18961 | } |
18962 | } else if (!FDTy->isDependentType() && |
18963 | RequireCompleteSizedType( |
18964 | Loc: FD->getLocation(), T: FD->getType(), |
18965 | DiagID: diag::err_field_incomplete_or_sizeless)) { |
18966 | // Incomplete type |
18967 | FD->setInvalidDecl(); |
18968 | EnclosingDecl->setInvalidDecl(); |
18969 | continue; |
18970 | } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { |
18971 | if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { |
18972 | // A type which contains a flexible array member is considered to be a |
18973 | // flexible array member. |
18974 | Record->setHasFlexibleArrayMember(true); |
18975 | if (!Record->isUnion()) { |
18976 | // If this is a struct/class and this is not the last element, reject |
18977 | // it. Note that GCC supports variable sized arrays in the middle of |
18978 | // structures. |
18979 | if (!IsLastField) |
18980 | Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct) |
18981 | << FD->getDeclName() << FD->getType(); |
18982 | else { |
18983 | // We support flexible arrays at the end of structs in |
18984 | // other structs as an extension. |
18985 | Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct) |
18986 | << FD->getDeclName(); |
18987 | } |
18988 | } |
18989 | } |
18990 | if (isa<ObjCContainerDecl>(Val: EnclosingDecl) && |
18991 | RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(), |
18992 | DiagID: diag::err_abstract_type_in_decl, |
18993 | Args: AbstractIvarType)) { |
18994 | // Ivars can not have abstract class types |
18995 | FD->setInvalidDecl(); |
18996 | } |
18997 | if (Record && FDTTy->getDecl()->hasObjectMember()) |
18998 | Record->setHasObjectMember(true); |
18999 | if (Record && FDTTy->getDecl()->hasVolatileMember()) |
19000 | Record->setHasVolatileMember(true); |
19001 | } else if (FDTy->isObjCObjectType()) { |
19002 | /// A field cannot be an Objective-c object |
19003 | Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object) |
19004 | << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*" ); |
19005 | QualType T = Context.getObjCObjectPointerType(OIT: FD->getType()); |
19006 | FD->setType(T); |
19007 | } else if (Record && Record->isUnion() && |
19008 | FD->getType().hasNonTrivialObjCLifetime() && |
19009 | getSourceManager().isInSystemHeader(Loc: FD->getLocation()) && |
19010 | !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && |
19011 | (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || |
19012 | !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) { |
19013 | // For backward compatibility, fields of C unions declared in system |
19014 | // headers that have non-trivial ObjC ownership qualifications are marked |
19015 | // as unavailable unless the qualifier is explicit and __strong. This can |
19016 | // break ABI compatibility between programs compiled with ARC and MRR, but |
19017 | // is a better option than rejecting programs using those unions under |
19018 | // ARC. |
19019 | FD->addAttr(A: UnavailableAttr::CreateImplicit( |
19020 | Ctx&: Context, Message: "" , ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, |
19021 | Range: FD->getLocation())); |
19022 | } else if (getLangOpts().ObjC && |
19023 | getLangOpts().getGC() != LangOptions::NonGC && Record && |
19024 | !Record->hasObjectMember()) { |
19025 | if (FD->getType()->isObjCObjectPointerType() || |
19026 | FD->getType().isObjCGCStrong()) |
19027 | Record->setHasObjectMember(true); |
19028 | else if (Context.getAsArrayType(T: FD->getType())) { |
19029 | QualType BaseType = Context.getBaseElementType(QT: FD->getType()); |
19030 | if (BaseType->isRecordType() && |
19031 | BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) |
19032 | Record->setHasObjectMember(true); |
19033 | else if (BaseType->isObjCObjectPointerType() || |
19034 | BaseType.isObjCGCStrong()) |
19035 | Record->setHasObjectMember(true); |
19036 | } |
19037 | } |
19038 | |
19039 | if (Record && !getLangOpts().CPlusPlus && |
19040 | !shouldIgnoreForRecordTriviality(FD)) { |
19041 | QualType FT = FD->getType(); |
19042 | if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { |
19043 | Record->setNonTrivialToPrimitiveDefaultInitialize(true); |
19044 | if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || |
19045 | Record->isUnion()) |
19046 | Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); |
19047 | } |
19048 | QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); |
19049 | if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { |
19050 | Record->setNonTrivialToPrimitiveCopy(true); |
19051 | if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) |
19052 | Record->setHasNonTrivialToPrimitiveCopyCUnion(true); |
19053 | } |
19054 | if (FT.isDestructedType()) { |
19055 | Record->setNonTrivialToPrimitiveDestroy(true); |
19056 | Record->setParamDestroyedInCallee(true); |
19057 | if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) |
19058 | Record->setHasNonTrivialToPrimitiveDestructCUnion(true); |
19059 | } |
19060 | |
19061 | if (const auto *RT = FT->getAs<RecordType>()) { |
19062 | if (RT->getDecl()->getArgPassingRestrictions() == |
19063 | RecordArgPassingKind::CanNeverPassInRegs) |
19064 | Record->setArgPassingRestrictions( |
19065 | RecordArgPassingKind::CanNeverPassInRegs); |
19066 | } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) |
19067 | Record->setArgPassingRestrictions( |
19068 | RecordArgPassingKind::CanNeverPassInRegs); |
19069 | } |
19070 | |
19071 | if (Record && FD->getType().isVolatileQualified()) |
19072 | Record->setHasVolatileMember(true); |
19073 | // Keep track of the number of named members. |
19074 | if (FD->getIdentifier()) |
19075 | ++NumNamedMembers; |
19076 | } |
19077 | |
19078 | // Okay, we successfully defined 'Record'. |
19079 | if (Record) { |
19080 | bool Completed = false; |
19081 | if (S) { |
19082 | Scope *Parent = S->getParent(); |
19083 | if (Parent && Parent->isTypeAliasScope() && |
19084 | Parent->isTemplateParamScope()) |
19085 | Record->setInvalidDecl(); |
19086 | } |
19087 | |
19088 | if (CXXRecord) { |
19089 | if (!CXXRecord->isInvalidDecl()) { |
19090 | // Set access bits correctly on the directly-declared conversions. |
19091 | for (CXXRecordDecl::conversion_iterator |
19092 | I = CXXRecord->conversion_begin(), |
19093 | E = CXXRecord->conversion_end(); I != E; ++I) |
19094 | I.setAccess((*I)->getAccess()); |
19095 | } |
19096 | |
19097 | // Add any implicitly-declared members to this class. |
19098 | AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord); |
19099 | |
19100 | if (!CXXRecord->isDependentType()) { |
19101 | if (!CXXRecord->isInvalidDecl()) { |
19102 | // If we have virtual base classes, we may end up finding multiple |
19103 | // final overriders for a given virtual function. Check for this |
19104 | // problem now. |
19105 | if (CXXRecord->getNumVBases()) { |
19106 | CXXFinalOverriderMap FinalOverriders; |
19107 | CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders); |
19108 | |
19109 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), |
19110 | MEnd = FinalOverriders.end(); |
19111 | M != MEnd; ++M) { |
19112 | for (OverridingMethods::iterator SO = M->second.begin(), |
19113 | SOEnd = M->second.end(); |
19114 | SO != SOEnd; ++SO) { |
19115 | assert(SO->second.size() > 0 && |
19116 | "Virtual function without overriding functions?" ); |
19117 | if (SO->second.size() == 1) |
19118 | continue; |
19119 | |
19120 | // C++ [class.virtual]p2: |
19121 | // In a derived class, if a virtual member function of a base |
19122 | // class subobject has more than one final overrider the |
19123 | // program is ill-formed. |
19124 | Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders) |
19125 | << (const NamedDecl *)M->first << Record; |
19126 | Diag(Loc: M->first->getLocation(), |
19127 | DiagID: diag::note_overridden_virtual_function); |
19128 | for (OverridingMethods::overriding_iterator |
19129 | OM = SO->second.begin(), |
19130 | OMEnd = SO->second.end(); |
19131 | OM != OMEnd; ++OM) |
19132 | Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider) |
19133 | << (const NamedDecl *)M->first << OM->Method->getParent(); |
19134 | |
19135 | Record->setInvalidDecl(); |
19136 | } |
19137 | } |
19138 | CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders); |
19139 | Completed = true; |
19140 | } |
19141 | } |
19142 | ComputeSelectedDestructor(S&: *this, Record: CXXRecord); |
19143 | ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord); |
19144 | } |
19145 | } |
19146 | |
19147 | if (!Completed) |
19148 | Record->completeDefinition(); |
19149 | |
19150 | // Handle attributes before checking the layout. |
19151 | ProcessDeclAttributeList(S, D: Record, AttrList: Attrs); |
19152 | |
19153 | // Check to see if a FieldDecl is a pointer to a function. |
19154 | auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) { |
19155 | const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D); |
19156 | if (!FD) { |
19157 | // Check whether this is a forward declaration that was inserted by |
19158 | // Clang. This happens when a non-forward declared / defined type is |
19159 | // used, e.g.: |
19160 | // |
19161 | // struct foo { |
19162 | // struct bar *(*f)(); |
19163 | // struct bar *(*g)(); |
19164 | // }; |
19165 | // |
19166 | // "struct bar" shows up in the decl AST as a "RecordDecl" with an |
19167 | // incomplete definition. |
19168 | if (const auto *TD = dyn_cast<TagDecl>(Val: D)) |
19169 | return !TD->isCompleteDefinition(); |
19170 | return false; |
19171 | } |
19172 | QualType FieldType = FD->getType().getDesugaredType(Context); |
19173 | if (isa<PointerType>(Val: FieldType)) { |
19174 | QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType(); |
19175 | return PointeeType.getDesugaredType(Context)->isFunctionType(); |
19176 | } |
19177 | return false; |
19178 | }; |
19179 | |
19180 | // Maybe randomize the record's decls. We automatically randomize a record |
19181 | // of function pointers, unless it has the "no_randomize_layout" attribute. |
19182 | if (!getLangOpts().CPlusPlus && |
19183 | (Record->hasAttr<RandomizeLayoutAttr>() || |
19184 | (!Record->hasAttr<NoRandomizeLayoutAttr>() && |
19185 | llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl))) && |
19186 | !Record->isUnion() && !getLangOpts().RandstructSeed.empty() && |
19187 | !Record->isRandomized()) { |
19188 | SmallVector<Decl *, 32> NewDeclOrdering; |
19189 | if (randstruct::randomizeStructureLayout(Context, RD: Record, |
19190 | FinalOrdering&: NewDeclOrdering)) |
19191 | Record->reorderDecls(Decls: NewDeclOrdering); |
19192 | } |
19193 | |
19194 | // We may have deferred checking for a deleted destructor. Check now. |
19195 | if (CXXRecord) { |
19196 | auto *Dtor = CXXRecord->getDestructor(); |
19197 | if (Dtor && Dtor->isImplicit() && |
19198 | ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) { |
19199 | CXXRecord->setImplicitDestructorIsDeleted(); |
19200 | SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation()); |
19201 | } |
19202 | } |
19203 | |
19204 | if (Record->hasAttrs()) { |
19205 | CheckAlignasUnderalignment(D: Record); |
19206 | |
19207 | if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) |
19208 | checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record), |
19209 | Range: IA->getRange(), BestCase: IA->getBestCase(), |
19210 | SemanticSpelling: IA->getInheritanceModel()); |
19211 | } |
19212 | |
19213 | // Check if the structure/union declaration is a type that can have zero |
19214 | // size in C. For C this is a language extension, for C++ it may cause |
19215 | // compatibility problems. |
19216 | bool CheckForZeroSize; |
19217 | if (!getLangOpts().CPlusPlus) { |
19218 | CheckForZeroSize = true; |
19219 | } else { |
19220 | // For C++ filter out types that cannot be referenced in C code. |
19221 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record); |
19222 | CheckForZeroSize = |
19223 | CXXRecord->getLexicalDeclContext()->isExternCContext() && |
19224 | !CXXRecord->isDependentType() && !inTemplateInstantiation() && |
19225 | CXXRecord->isCLike(); |
19226 | } |
19227 | if (CheckForZeroSize) { |
19228 | bool ZeroSize = true; |
19229 | bool IsEmpty = true; |
19230 | unsigned NonBitFields = 0; |
19231 | for (RecordDecl::field_iterator I = Record->field_begin(), |
19232 | E = Record->field_end(); |
19233 | (NonBitFields == 0 || ZeroSize) && I != E; ++I) { |
19234 | IsEmpty = false; |
19235 | if (I->isUnnamedBitField()) { |
19236 | if (!I->isZeroLengthBitField(Ctx: Context)) |
19237 | ZeroSize = false; |
19238 | } else { |
19239 | ++NonBitFields; |
19240 | QualType FieldType = I->getType(); |
19241 | if (FieldType->isIncompleteType() || |
19242 | !Context.getTypeSizeInChars(T: FieldType).isZero()) |
19243 | ZeroSize = false; |
19244 | } |
19245 | } |
19246 | |
19247 | // Empty structs are an extension in C (C99 6.7.2.1p7). They are |
19248 | // allowed in C++, but warn if its declaration is inside |
19249 | // extern "C" block. |
19250 | if (ZeroSize) { |
19251 | Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ? |
19252 | diag::warn_zero_size_struct_union_in_extern_c : |
19253 | diag::warn_zero_size_struct_union_compat) |
19254 | << IsEmpty << Record->isUnion() << (NonBitFields > 1); |
19255 | } |
19256 | |
19257 | // Structs without named members are extension in C (C99 6.7.2.1p7), |
19258 | // but are accepted by GCC. |
19259 | if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { |
19260 | Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union : |
19261 | diag::ext_no_named_members_in_struct_union) |
19262 | << Record->isUnion(); |
19263 | } |
19264 | } |
19265 | } else { |
19266 | ObjCIvarDecl **ClsFields = |
19267 | reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); |
19268 | if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) { |
19269 | ID->setEndOfDefinitionLoc(RBrac); |
19270 | // Add ivar's to class's DeclContext. |
19271 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { |
19272 | ClsFields[i]->setLexicalDeclContext(ID); |
19273 | ID->addDecl(D: ClsFields[i]); |
19274 | } |
19275 | // Must enforce the rule that ivars in the base classes may not be |
19276 | // duplicates. |
19277 | if (ID->getSuperClass()) |
19278 | ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass()); |
19279 | } else if (ObjCImplementationDecl *IMPDecl = |
19280 | dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) { |
19281 | assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl" ); |
19282 | for (unsigned I = 0, N = RecFields.size(); I != N; ++I) |
19283 | // Ivar declared in @implementation never belongs to the implementation. |
19284 | // Only it is in implementation's lexical context. |
19285 | ClsFields[I]->setLexicalDeclContext(IMPDecl); |
19286 | ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(), |
19287 | Loc: RBrac); |
19288 | IMPDecl->setIvarLBraceLoc(LBrac); |
19289 | IMPDecl->setIvarRBraceLoc(RBrac); |
19290 | } else if (ObjCCategoryDecl *CDecl = |
19291 | dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) { |
19292 | // case of ivars in class extension; all other cases have been |
19293 | // reported as errors elsewhere. |
19294 | // FIXME. Class extension does not have a LocEnd field. |
19295 | // CDecl->setLocEnd(RBrac); |
19296 | // Add ivar's to class extension's DeclContext. |
19297 | // Diagnose redeclaration of private ivars. |
19298 | ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); |
19299 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { |
19300 | if (IDecl) { |
19301 | if (const ObjCIvarDecl *ClsIvar = |
19302 | IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) { |
19303 | Diag(Loc: ClsFields[i]->getLocation(), |
19304 | DiagID: diag::err_duplicate_ivar_declaration); |
19305 | Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition); |
19306 | continue; |
19307 | } |
19308 | for (const auto *Ext : IDecl->known_extensions()) { |
19309 | if (const ObjCIvarDecl *ClsExtIvar |
19310 | = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) { |
19311 | Diag(Loc: ClsFields[i]->getLocation(), |
19312 | DiagID: diag::err_duplicate_ivar_declaration); |
19313 | Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition); |
19314 | continue; |
19315 | } |
19316 | } |
19317 | } |
19318 | ClsFields[i]->setLexicalDeclContext(CDecl); |
19319 | CDecl->addDecl(D: ClsFields[i]); |
19320 | } |
19321 | CDecl->setIvarLBraceLoc(LBrac); |
19322 | CDecl->setIvarRBraceLoc(RBrac); |
19323 | } |
19324 | } |
19325 | ProcessAPINotes(D: Record); |
19326 | } |
19327 | |
19328 | /// Determine whether the given integral value is representable within |
19329 | /// the given type T. |
19330 | static bool isRepresentableIntegerValue(ASTContext &Context, |
19331 | llvm::APSInt &Value, |
19332 | QualType T) { |
19333 | assert((T->isIntegralType(Context) || T->isEnumeralType()) && |
19334 | "Integral type required!" ); |
19335 | unsigned BitWidth = Context.getIntWidth(T); |
19336 | |
19337 | if (Value.isUnsigned() || Value.isNonNegative()) { |
19338 | if (T->isSignedIntegerOrEnumerationType()) |
19339 | --BitWidth; |
19340 | return Value.getActiveBits() <= BitWidth; |
19341 | } |
19342 | return Value.getSignificantBits() <= BitWidth; |
19343 | } |
19344 | |
19345 | // Given an integral type, return the next larger integral type |
19346 | // (or a NULL type of no such type exists). |
19347 | static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { |
19348 | // FIXME: Int128/UInt128 support, which also needs to be introduced into |
19349 | // enum checking below. |
19350 | assert((T->isIntegralType(Context) || |
19351 | T->isEnumeralType()) && "Integral type required!" ); |
19352 | const unsigned NumTypes = 4; |
19353 | QualType SignedIntegralTypes[NumTypes] = { |
19354 | Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy |
19355 | }; |
19356 | QualType UnsignedIntegralTypes[NumTypes] = { |
19357 | Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, |
19358 | Context.UnsignedLongLongTy |
19359 | }; |
19360 | |
19361 | unsigned BitWidth = Context.getTypeSize(T); |
19362 | QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes |
19363 | : UnsignedIntegralTypes; |
19364 | for (unsigned I = 0; I != NumTypes; ++I) |
19365 | if (Context.getTypeSize(T: Types[I]) > BitWidth) |
19366 | return Types[I]; |
19367 | |
19368 | return QualType(); |
19369 | } |
19370 | |
19371 | EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, |
19372 | EnumConstantDecl *LastEnumConst, |
19373 | SourceLocation IdLoc, |
19374 | IdentifierInfo *Id, |
19375 | Expr *Val) { |
19376 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); |
19377 | llvm::APSInt EnumVal(IntWidth); |
19378 | QualType EltTy; |
19379 | |
19380 | if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue)) |
19381 | Val = nullptr; |
19382 | |
19383 | if (Val) |
19384 | Val = DefaultLvalueConversion(E: Val).get(); |
19385 | |
19386 | if (Val) { |
19387 | if (Enum->isDependentType() || Val->isTypeDependent() || |
19388 | Val->containsErrors()) |
19389 | EltTy = Context.DependentTy; |
19390 | else { |
19391 | // FIXME: We don't allow folding in C++11 mode for an enum with a fixed |
19392 | // underlying type, but do allow it in all other contexts. |
19393 | if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { |
19394 | // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the |
19395 | // constant-expression in the enumerator-definition shall be a converted |
19396 | // constant expression of the underlying type. |
19397 | EltTy = Enum->getIntegerType(); |
19398 | ExprResult Converted = |
19399 | CheckConvertedConstantExpression(From: Val, T: EltTy, Value&: EnumVal, |
19400 | CCE: CCEK_Enumerator); |
19401 | if (Converted.isInvalid()) |
19402 | Val = nullptr; |
19403 | else |
19404 | Val = Converted.get(); |
19405 | } else if (!Val->isValueDependent() && |
19406 | !(Val = |
19407 | VerifyIntegerConstantExpression(E: Val, Result: &EnumVal, CanFold: AllowFold) |
19408 | .get())) { |
19409 | // C99 6.7.2.2p2: Make sure we have an integer constant expression. |
19410 | } else { |
19411 | if (Enum->isComplete()) { |
19412 | EltTy = Enum->getIntegerType(); |
19413 | |
19414 | // In Obj-C and Microsoft mode, require the enumeration value to be |
19415 | // representable in the underlying type of the enumeration. In C++11, |
19416 | // we perform a non-narrowing conversion as part of converted constant |
19417 | // expression checking. |
19418 | if (!isRepresentableIntegerValue(Context, Value&: EnumVal, T: EltTy)) { |
19419 | if (Context.getTargetInfo() |
19420 | .getTriple() |
19421 | .isWindowsMSVCEnvironment()) { |
19422 | Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy; |
19423 | } else { |
19424 | Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy; |
19425 | } |
19426 | } |
19427 | |
19428 | // Cast to the underlying type. |
19429 | Val = ImpCastExprToType(E: Val, Type: EltTy, |
19430 | CK: EltTy->isBooleanType() ? CK_IntegralToBoolean |
19431 | : CK_IntegralCast) |
19432 | .get(); |
19433 | } else if (getLangOpts().CPlusPlus) { |
19434 | // C++11 [dcl.enum]p5: |
19435 | // If the underlying type is not fixed, the type of each enumerator |
19436 | // is the type of its initializing value: |
19437 | // - If an initializer is specified for an enumerator, the |
19438 | // initializing value has the same type as the expression. |
19439 | EltTy = Val->getType(); |
19440 | } else { |
19441 | // C99 6.7.2.2p2: |
19442 | // The expression that defines the value of an enumeration constant |
19443 | // shall be an integer constant expression that has a value |
19444 | // representable as an int. |
19445 | |
19446 | // Complain if the value is not representable in an int. |
19447 | if (!isRepresentableIntegerValue(Context, Value&: EnumVal, T: Context.IntTy)) |
19448 | Diag(Loc: IdLoc, DiagID: diag::ext_enum_value_not_int) |
19449 | << toString(I: EnumVal, Radix: 10) << Val->getSourceRange() |
19450 | << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); |
19451 | else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) { |
19452 | // Force the type of the expression to 'int'. |
19453 | Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get(); |
19454 | } |
19455 | EltTy = Val->getType(); |
19456 | } |
19457 | } |
19458 | } |
19459 | } |
19460 | |
19461 | if (!Val) { |
19462 | if (Enum->isDependentType()) |
19463 | EltTy = Context.DependentTy; |
19464 | else if (!LastEnumConst) { |
19465 | // C++0x [dcl.enum]p5: |
19466 | // If the underlying type is not fixed, the type of each enumerator |
19467 | // is the type of its initializing value: |
19468 | // - If no initializer is specified for the first enumerator, the |
19469 | // initializing value has an unspecified integral type. |
19470 | // |
19471 | // GCC uses 'int' for its unspecified integral type, as does |
19472 | // C99 6.7.2.2p3. |
19473 | if (Enum->isFixed()) { |
19474 | EltTy = Enum->getIntegerType(); |
19475 | } |
19476 | else { |
19477 | EltTy = Context.IntTy; |
19478 | } |
19479 | } else { |
19480 | // Assign the last value + 1. |
19481 | EnumVal = LastEnumConst->getInitVal(); |
19482 | ++EnumVal; |
19483 | EltTy = LastEnumConst->getType(); |
19484 | |
19485 | // Check for overflow on increment. |
19486 | if (EnumVal < LastEnumConst->getInitVal()) { |
19487 | // C++0x [dcl.enum]p5: |
19488 | // If the underlying type is not fixed, the type of each enumerator |
19489 | // is the type of its initializing value: |
19490 | // |
19491 | // - Otherwise the type of the initializing value is the same as |
19492 | // the type of the initializing value of the preceding enumerator |
19493 | // unless the incremented value is not representable in that type, |
19494 | // in which case the type is an unspecified integral type |
19495 | // sufficient to contain the incremented value. If no such type |
19496 | // exists, the program is ill-formed. |
19497 | QualType T = getNextLargerIntegralType(Context, T: EltTy); |
19498 | if (T.isNull() || Enum->isFixed()) { |
19499 | // There is no integral type larger enough to represent this |
19500 | // value. Complain, then allow the value to wrap around. |
19501 | EnumVal = LastEnumConst->getInitVal(); |
19502 | EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2); |
19503 | ++EnumVal; |
19504 | if (Enum->isFixed()) |
19505 | // When the underlying type is fixed, this is ill-formed. |
19506 | Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped) |
19507 | << toString(I: EnumVal, Radix: 10) |
19508 | << EltTy; |
19509 | else |
19510 | Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large) |
19511 | << toString(I: EnumVal, Radix: 10); |
19512 | } else { |
19513 | EltTy = T; |
19514 | } |
19515 | |
19516 | // Retrieve the last enumerator's value, extent that type to the |
19517 | // type that is supposed to be large enough to represent the incremented |
19518 | // value, then increment. |
19519 | EnumVal = LastEnumConst->getInitVal(); |
19520 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); |
19521 | EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy)); |
19522 | ++EnumVal; |
19523 | |
19524 | // If we're not in C++, diagnose the overflow of enumerator values, |
19525 | // which in C99 means that the enumerator value is not representable in |
19526 | // an int (C99 6.7.2.2p2). However, we support GCC's extension that |
19527 | // permits enumerator values that are representable in some larger |
19528 | // integral type. |
19529 | if (!getLangOpts().CPlusPlus && !T.isNull()) |
19530 | Diag(Loc: IdLoc, DiagID: diag::warn_enum_value_overflow); |
19531 | } else if (!getLangOpts().CPlusPlus && |
19532 | !EltTy->isDependentType() && |
19533 | !isRepresentableIntegerValue(Context, Value&: EnumVal, T: EltTy)) { |
19534 | // Enforce C99 6.7.2.2p2 even when we compute the next value. |
19535 | Diag(Loc: IdLoc, DiagID: diag::ext_enum_value_not_int) |
19536 | << toString(I: EnumVal, Radix: 10) << 1; |
19537 | } |
19538 | } |
19539 | } |
19540 | |
19541 | if (!EltTy->isDependentType()) { |
19542 | // Make the enumerator value match the signedness and size of the |
19543 | // enumerator's type. |
19544 | EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy)); |
19545 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); |
19546 | } |
19547 | |
19548 | return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy, |
19549 | E: Val, V: EnumVal); |
19550 | } |
19551 | |
19552 | SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, |
19553 | SourceLocation IILoc) { |
19554 | if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || |
19555 | !getLangOpts().CPlusPlus) |
19556 | return SkipBodyInfo(); |
19557 | |
19558 | // We have an anonymous enum definition. Look up the first enumerator to |
19559 | // determine if we should merge the definition with an existing one and |
19560 | // skip the body. |
19561 | NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName, |
19562 | Redecl: forRedeclarationInCurContext()); |
19563 | auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl); |
19564 | if (!PrevECD) |
19565 | return SkipBodyInfo(); |
19566 | |
19567 | EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext()); |
19568 | NamedDecl *Hidden; |
19569 | if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) { |
19570 | SkipBodyInfo Skip; |
19571 | Skip.Previous = Hidden; |
19572 | return Skip; |
19573 | } |
19574 | |
19575 | return SkipBodyInfo(); |
19576 | } |
19577 | |
19578 | Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, |
19579 | SourceLocation IdLoc, IdentifierInfo *Id, |
19580 | const ParsedAttributesView &Attrs, |
19581 | SourceLocation EqualLoc, Expr *Val) { |
19582 | EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl); |
19583 | EnumConstantDecl *LastEnumConst = |
19584 | cast_or_null<EnumConstantDecl>(Val: lastEnumConst); |
19585 | |
19586 | // The scope passed in may not be a decl scope. Zip up the scope tree until |
19587 | // we find one that is. |
19588 | S = getNonFieldDeclScope(S); |
19589 | |
19590 | // Verify that there isn't already something declared with this name in this |
19591 | // scope. |
19592 | LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, |
19593 | RedeclarationKind::ForVisibleRedeclaration); |
19594 | LookupName(R, S); |
19595 | NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); |
19596 | |
19597 | if (PrevDecl && PrevDecl->isTemplateParameter()) { |
19598 | // Maybe we will complain about the shadowed template parameter. |
19599 | DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl); |
19600 | // Just pretend that we didn't see the previous declaration. |
19601 | PrevDecl = nullptr; |
19602 | } |
19603 | |
19604 | // C++ [class.mem]p15: |
19605 | // If T is the name of a class, then each of the following shall have a name |
19606 | // different from T: |
19607 | // - every enumerator of every member of class T that is an unscoped |
19608 | // enumerated type |
19609 | if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) |
19610 | DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(), |
19611 | NameInfo: DeclarationNameInfo(Id, IdLoc)); |
19612 | |
19613 | EnumConstantDecl *New = |
19614 | CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val); |
19615 | if (!New) |
19616 | return nullptr; |
19617 | |
19618 | if (PrevDecl) { |
19619 | if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) { |
19620 | // Check for other kinds of shadowing not already handled. |
19621 | CheckShadow(D: New, ShadowedDecl: PrevDecl, R); |
19622 | } |
19623 | |
19624 | // When in C++, we may get a TagDecl with the same name; in this case the |
19625 | // enum constant will 'hide' the tag. |
19626 | assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && |
19627 | "Received TagDecl when not in C++!" ); |
19628 | if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) { |
19629 | if (isa<EnumConstantDecl>(Val: PrevDecl)) |
19630 | Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id; |
19631 | else |
19632 | Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id; |
19633 | notePreviousDefinition(Old: PrevDecl, New: IdLoc); |
19634 | return nullptr; |
19635 | } |
19636 | } |
19637 | |
19638 | // Process attributes. |
19639 | ProcessDeclAttributeList(S, D: New, AttrList: Attrs); |
19640 | AddPragmaAttributes(S, D: New); |
19641 | ProcessAPINotes(D: New); |
19642 | |
19643 | // Register this decl in the current scope stack. |
19644 | New->setAccess(TheEnumDecl->getAccess()); |
19645 | PushOnScopeChains(D: New, S); |
19646 | |
19647 | ActOnDocumentableDecl(D: New); |
19648 | |
19649 | return New; |
19650 | } |
19651 | |
19652 | // Returns true when the enum initial expression does not trigger the |
19653 | // duplicate enum warning. A few common cases are exempted as follows: |
19654 | // Element2 = Element1 |
19655 | // Element2 = Element1 + 1 |
19656 | // Element2 = Element1 - 1 |
19657 | // Where Element2 and Element1 are from the same enum. |
19658 | static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { |
19659 | Expr *InitExpr = ECD->getInitExpr(); |
19660 | if (!InitExpr) |
19661 | return true; |
19662 | InitExpr = InitExpr->IgnoreImpCasts(); |
19663 | |
19664 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) { |
19665 | if (!BO->isAdditiveOp()) |
19666 | return true; |
19667 | IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS()); |
19668 | if (!IL) |
19669 | return true; |
19670 | if (IL->getValue() != 1) |
19671 | return true; |
19672 | |
19673 | InitExpr = BO->getLHS(); |
19674 | } |
19675 | |
19676 | // This checks if the elements are from the same enum. |
19677 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr); |
19678 | if (!DRE) |
19679 | return true; |
19680 | |
19681 | EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl()); |
19682 | if (!EnumConstant) |
19683 | return true; |
19684 | |
19685 | if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) != |
19686 | Enum) |
19687 | return true; |
19688 | |
19689 | return false; |
19690 | } |
19691 | |
19692 | // Emits a warning when an element is implicitly set a value that |
19693 | // a previous element has already been set to. |
19694 | static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, |
19695 | EnumDecl *Enum, QualType EnumType) { |
19696 | // Avoid anonymous enums |
19697 | if (!Enum->getIdentifier()) |
19698 | return; |
19699 | |
19700 | // Only check for small enums. |
19701 | if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) |
19702 | return; |
19703 | |
19704 | if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation())) |
19705 | return; |
19706 | |
19707 | typedef SmallVector<EnumConstantDecl *, 3> ECDVector; |
19708 | typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; |
19709 | |
19710 | typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; |
19711 | |
19712 | // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. |
19713 | typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; |
19714 | |
19715 | // Use int64_t as a key to avoid needing special handling for map keys. |
19716 | auto EnumConstantToKey = [](const EnumConstantDecl *D) { |
19717 | llvm::APSInt Val = D->getInitVal(); |
19718 | return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); |
19719 | }; |
19720 | |
19721 | DuplicatesVector DupVector; |
19722 | ValueToVectorMap EnumMap; |
19723 | |
19724 | // Populate the EnumMap with all values represented by enum constants without |
19725 | // an initializer. |
19726 | for (auto *Element : Elements) { |
19727 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element); |
19728 | |
19729 | // Null EnumConstantDecl means a previous diagnostic has been emitted for |
19730 | // this constant. Skip this enum since it may be ill-formed. |
19731 | if (!ECD) { |
19732 | return; |
19733 | } |
19734 | |
19735 | // Constants with initializers are handled in the next loop. |
19736 | if (ECD->getInitExpr()) |
19737 | continue; |
19738 | |
19739 | // Duplicate values are handled in the next loop. |
19740 | EnumMap.insert(x: {EnumConstantToKey(ECD), ECD}); |
19741 | } |
19742 | |
19743 | if (EnumMap.size() == 0) |
19744 | return; |
19745 | |
19746 | // Create vectors for any values that has duplicates. |
19747 | for (auto *Element : Elements) { |
19748 | // The last loop returned if any constant was null. |
19749 | EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element); |
19750 | if (!ValidDuplicateEnum(ECD, Enum)) |
19751 | continue; |
19752 | |
19753 | auto Iter = EnumMap.find(x: EnumConstantToKey(ECD)); |
19754 | if (Iter == EnumMap.end()) |
19755 | continue; |
19756 | |
19757 | DeclOrVector& Entry = Iter->second; |
19758 | if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { |
19759 | // Ensure constants are different. |
19760 | if (D == ECD) |
19761 | continue; |
19762 | |
19763 | // Create new vector and push values onto it. |
19764 | auto Vec = std::make_unique<ECDVector>(); |
19765 | Vec->push_back(Elt: D); |
19766 | Vec->push_back(Elt: ECD); |
19767 | |
19768 | // Update entry to point to the duplicates vector. |
19769 | Entry = Vec.get(); |
19770 | |
19771 | // Store the vector somewhere we can consult later for quick emission of |
19772 | // diagnostics. |
19773 | DupVector.emplace_back(Args: std::move(Vec)); |
19774 | continue; |
19775 | } |
19776 | |
19777 | ECDVector *Vec = Entry.get<ECDVector*>(); |
19778 | // Make sure constants are not added more than once. |
19779 | if (*Vec->begin() == ECD) |
19780 | continue; |
19781 | |
19782 | Vec->push_back(Elt: ECD); |
19783 | } |
19784 | |
19785 | // Emit diagnostics. |
19786 | for (const auto &Vec : DupVector) { |
19787 | assert(Vec->size() > 1 && "ECDVector should have at least 2 elements." ); |
19788 | |
19789 | // Emit warning for one enum constant. |
19790 | auto *FirstECD = Vec->front(); |
19791 | S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values) |
19792 | << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10) |
19793 | << FirstECD->getSourceRange(); |
19794 | |
19795 | // Emit one note for each of the remaining enum constants with |
19796 | // the same value. |
19797 | for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec)) |
19798 | S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element) |
19799 | << ECD << toString(I: ECD->getInitVal(), Radix: 10) |
19800 | << ECD->getSourceRange(); |
19801 | } |
19802 | } |
19803 | |
19804 | bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, |
19805 | bool AllowMask) const { |
19806 | assert(ED->isClosedFlag() && "looking for value in non-flag or open enum" ); |
19807 | assert(ED->isCompleteDefinition() && "expected enum definition" ); |
19808 | |
19809 | auto R = FlagBitsCache.insert(KV: std::make_pair(x&: ED, y: llvm::APInt())); |
19810 | llvm::APInt &FlagBits = R.first->second; |
19811 | |
19812 | if (R.second) { |
19813 | for (auto *E : ED->enumerators()) { |
19814 | const auto &EVal = E->getInitVal(); |
19815 | // Only single-bit enumerators introduce new flag values. |
19816 | if (EVal.isPowerOf2()) |
19817 | FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal; |
19818 | } |
19819 | } |
19820 | |
19821 | // A value is in a flag enum if either its bits are a subset of the enum's |
19822 | // flag bits (the first condition) or we are allowing masks and the same is |
19823 | // true of its complement (the second condition). When masks are allowed, we |
19824 | // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. |
19825 | // |
19826 | // While it's true that any value could be used as a mask, the assumption is |
19827 | // that a mask will have all of the insignificant bits set. Anything else is |
19828 | // likely a logic error. |
19829 | llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth()); |
19830 | return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); |
19831 | } |
19832 | |
19833 | void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, |
19834 | Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, |
19835 | const ParsedAttributesView &Attrs) { |
19836 | EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX); |
19837 | QualType EnumType = Context.getTypeDeclType(Decl: Enum); |
19838 | |
19839 | ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs); |
19840 | ProcessAPINotes(D: Enum); |
19841 | |
19842 | if (Enum->isDependentType()) { |
19843 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { |
19844 | EnumConstantDecl *ECD = |
19845 | cast_or_null<EnumConstantDecl>(Val: Elements[i]); |
19846 | if (!ECD) continue; |
19847 | |
19848 | ECD->setType(EnumType); |
19849 | } |
19850 | |
19851 | Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0); |
19852 | return; |
19853 | } |
19854 | |
19855 | // TODO: If the result value doesn't fit in an int, it must be a long or long |
19856 | // long value. ISO C does not support this, but GCC does as an extension, |
19857 | // emit a warning. |
19858 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); |
19859 | unsigned CharWidth = Context.getTargetInfo().getCharWidth(); |
19860 | unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); |
19861 | |
19862 | // Verify that all the values are okay, compute the size of the values, and |
19863 | // reverse the list. |
19864 | unsigned NumNegativeBits = 0; |
19865 | unsigned NumPositiveBits = 0; |
19866 | |
19867 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { |
19868 | EnumConstantDecl *ECD = |
19869 | cast_or_null<EnumConstantDecl>(Val: Elements[i]); |
19870 | if (!ECD) continue; // Already issued a diagnostic. |
19871 | |
19872 | const llvm::APSInt &InitVal = ECD->getInitVal(); |
19873 | |
19874 | // Keep track of the size of positive and negative values. |
19875 | if (InitVal.isUnsigned() || InitVal.isNonNegative()) { |
19876 | // If the enumerator is zero that should still be counted as a positive |
19877 | // bit since we need a bit to store the value zero. |
19878 | unsigned ActiveBits = InitVal.getActiveBits(); |
19879 | NumPositiveBits = std::max(l: {NumPositiveBits, ActiveBits, 1u}); |
19880 | } else { |
19881 | NumNegativeBits = |
19882 | std::max(a: NumNegativeBits, b: (unsigned)InitVal.getSignificantBits()); |
19883 | } |
19884 | } |
19885 | |
19886 | // If we have an empty set of enumerators we still need one bit. |
19887 | // From [dcl.enum]p8 |
19888 | // If the enumerator-list is empty, the values of the enumeration are as if |
19889 | // the enumeration had a single enumerator with value 0 |
19890 | if (!NumPositiveBits && !NumNegativeBits) |
19891 | NumPositiveBits = 1; |
19892 | |
19893 | // Figure out the type that should be used for this enum. |
19894 | QualType BestType; |
19895 | unsigned BestWidth; |
19896 | |
19897 | // C++0x N3000 [conv.prom]p3: |
19898 | // An rvalue of an unscoped enumeration type whose underlying |
19899 | // type is not fixed can be converted to an rvalue of the first |
19900 | // of the following types that can represent all the values of |
19901 | // the enumeration: int, unsigned int, long int, unsigned long |
19902 | // int, long long int, or unsigned long long int. |
19903 | // C99 6.4.4.3p2: |
19904 | // An identifier declared as an enumeration constant has type int. |
19905 | // The C99 rule is modified by a gcc extension |
19906 | QualType BestPromotionType; |
19907 | |
19908 | bool Packed = Enum->hasAttr<PackedAttr>(); |
19909 | // -fshort-enums is the equivalent to specifying the packed attribute on all |
19910 | // enum definitions. |
19911 | if (LangOpts.ShortEnums) |
19912 | Packed = true; |
19913 | |
19914 | // If the enum already has a type because it is fixed or dictated by the |
19915 | // target, promote that type instead of analyzing the enumerators. |
19916 | if (Enum->isComplete()) { |
19917 | BestType = Enum->getIntegerType(); |
19918 | if (Context.isPromotableIntegerType(T: BestType)) |
19919 | BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType); |
19920 | else |
19921 | BestPromotionType = BestType; |
19922 | |
19923 | BestWidth = Context.getIntWidth(T: BestType); |
19924 | } |
19925 | else if (NumNegativeBits) { |
19926 | // If there is a negative value, figure out the smallest integer type (of |
19927 | // int/long/longlong) that fits. |
19928 | // If it's packed, check also if it fits a char or a short. |
19929 | if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { |
19930 | BestType = Context.SignedCharTy; |
19931 | BestWidth = CharWidth; |
19932 | } else if (Packed && NumNegativeBits <= ShortWidth && |
19933 | NumPositiveBits < ShortWidth) { |
19934 | BestType = Context.ShortTy; |
19935 | BestWidth = ShortWidth; |
19936 | } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { |
19937 | BestType = Context.IntTy; |
19938 | BestWidth = IntWidth; |
19939 | } else { |
19940 | BestWidth = Context.getTargetInfo().getLongWidth(); |
19941 | |
19942 | if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { |
19943 | BestType = Context.LongTy; |
19944 | } else { |
19945 | BestWidth = Context.getTargetInfo().getLongLongWidth(); |
19946 | |
19947 | if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) |
19948 | Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large); |
19949 | BestType = Context.LongLongTy; |
19950 | } |
19951 | } |
19952 | BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); |
19953 | } else { |
19954 | // If there is no negative value, figure out the smallest type that fits |
19955 | // all of the enumerator values. |
19956 | // If it's packed, check also if it fits a char or a short. |
19957 | if (Packed && NumPositiveBits <= CharWidth) { |
19958 | BestType = Context.UnsignedCharTy; |
19959 | BestPromotionType = Context.IntTy; |
19960 | BestWidth = CharWidth; |
19961 | } else if (Packed && NumPositiveBits <= ShortWidth) { |
19962 | BestType = Context.UnsignedShortTy; |
19963 | BestPromotionType = Context.IntTy; |
19964 | BestWidth = ShortWidth; |
19965 | } else if (NumPositiveBits <= IntWidth) { |
19966 | BestType = Context.UnsignedIntTy; |
19967 | BestWidth = IntWidth; |
19968 | BestPromotionType |
19969 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) |
19970 | ? Context.UnsignedIntTy : Context.IntTy; |
19971 | } else if (NumPositiveBits <= |
19972 | (BestWidth = Context.getTargetInfo().getLongWidth())) { |
19973 | BestType = Context.UnsignedLongTy; |
19974 | BestPromotionType |
19975 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) |
19976 | ? Context.UnsignedLongTy : Context.LongTy; |
19977 | } else { |
19978 | BestWidth = Context.getTargetInfo().getLongLongWidth(); |
19979 | if (NumPositiveBits > BestWidth) { |
19980 | // This can happen with bit-precise integer types, but those are not |
19981 | // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12. |
19982 | // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within |
19983 | // a 128-bit integer, we should consider doing the same. |
19984 | Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large); |
19985 | } |
19986 | BestType = Context.UnsignedLongLongTy; |
19987 | BestPromotionType |
19988 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) |
19989 | ? Context.UnsignedLongLongTy : Context.LongLongTy; |
19990 | } |
19991 | } |
19992 | |
19993 | // Loop over all of the enumerator constants, changing their types to match |
19994 | // the type of the enum if needed. |
19995 | for (auto *D : Elements) { |
19996 | auto *ECD = cast_or_null<EnumConstantDecl>(Val: D); |
19997 | if (!ECD) continue; // Already issued a diagnostic. |
19998 | |
19999 | // Standard C says the enumerators have int type, but we allow, as an |
20000 | // extension, the enumerators to be larger than int size. If each |
20001 | // enumerator value fits in an int, type it as an int, otherwise type it the |
20002 | // same as the enumerator decl itself. This means that in "enum { X = 1U }" |
20003 | // that X has type 'int', not 'unsigned'. |
20004 | |
20005 | // Determine whether the value fits into an int. |
20006 | llvm::APSInt InitVal = ECD->getInitVal(); |
20007 | |
20008 | // If it fits into an integer type, force it. Otherwise force it to match |
20009 | // the enum decl type. |
20010 | QualType NewTy; |
20011 | unsigned NewWidth; |
20012 | bool NewSign; |
20013 | if (!getLangOpts().CPlusPlus && |
20014 | !Enum->isFixed() && |
20015 | isRepresentableIntegerValue(Context, Value&: InitVal, T: Context.IntTy)) { |
20016 | NewTy = Context.IntTy; |
20017 | NewWidth = IntWidth; |
20018 | NewSign = true; |
20019 | } else if (ECD->getType() == BestType) { |
20020 | // Already the right type! |
20021 | if (getLangOpts().CPlusPlus) |
20022 | // C++ [dcl.enum]p4: Following the closing brace of an |
20023 | // enum-specifier, each enumerator has the type of its |
20024 | // enumeration. |
20025 | ECD->setType(EnumType); |
20026 | continue; |
20027 | } else { |
20028 | NewTy = BestType; |
20029 | NewWidth = BestWidth; |
20030 | NewSign = BestType->isSignedIntegerOrEnumerationType(); |
20031 | } |
20032 | |
20033 | // Adjust the APSInt value. |
20034 | InitVal = InitVal.extOrTrunc(width: NewWidth); |
20035 | InitVal.setIsSigned(NewSign); |
20036 | ECD->setInitVal(C: Context, V: InitVal); |
20037 | |
20038 | // Adjust the Expr initializer and type. |
20039 | if (ECD->getInitExpr() && |
20040 | !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType())) |
20041 | ECD->setInitExpr(ImplicitCastExpr::Create( |
20042 | Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(), |
20043 | /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride())); |
20044 | if (getLangOpts().CPlusPlus) |
20045 | // C++ [dcl.enum]p4: Following the closing brace of an |
20046 | // enum-specifier, each enumerator has the type of its |
20047 | // enumeration. |
20048 | ECD->setType(EnumType); |
20049 | else |
20050 | ECD->setType(NewTy); |
20051 | } |
20052 | |
20053 | Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType, |
20054 | NumPositiveBits, NumNegativeBits); |
20055 | |
20056 | CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType); |
20057 | |
20058 | if (Enum->isClosedFlag()) { |
20059 | for (Decl *D : Elements) { |
20060 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D); |
20061 | if (!ECD) continue; // Already issued a diagnostic. |
20062 | |
20063 | llvm::APSInt InitVal = ECD->getInitVal(); |
20064 | if (InitVal != 0 && !InitVal.isPowerOf2() && |
20065 | !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true)) |
20066 | Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range) |
20067 | << ECD << Enum; |
20068 | } |
20069 | } |
20070 | |
20071 | // Now that the enum type is defined, ensure it's not been underaligned. |
20072 | if (Enum->hasAttrs()) |
20073 | CheckAlignasUnderalignment(D: Enum); |
20074 | } |
20075 | |
20076 | Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, |
20077 | SourceLocation StartLoc, |
20078 | SourceLocation EndLoc) { |
20079 | StringLiteral *AsmString = cast<StringLiteral>(Val: expr); |
20080 | |
20081 | FileScopeAsmDecl *New = FileScopeAsmDecl::Create(C&: Context, DC: CurContext, |
20082 | Str: AsmString, AsmLoc: StartLoc, |
20083 | RParenLoc: EndLoc); |
20084 | CurContext->addDecl(D: New); |
20085 | return New; |
20086 | } |
20087 | |
20088 | TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) { |
20089 | auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr); |
20090 | CurContext->addDecl(D: New); |
20091 | PushDeclContext(S, DC: New); |
20092 | PushFunctionScope(); |
20093 | PushCompoundScope(IsStmtExpr: false); |
20094 | return New; |
20095 | } |
20096 | |
20097 | void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) { |
20098 | D->setStmt(Statement); |
20099 | PopCompoundScope(); |
20100 | PopFunctionScopeInfo(); |
20101 | PopDeclContext(); |
20102 | } |
20103 | |
20104 | void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, |
20105 | IdentifierInfo* AliasName, |
20106 | SourceLocation PragmaLoc, |
20107 | SourceLocation NameLoc, |
20108 | SourceLocation AliasNameLoc) { |
20109 | NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, |
20110 | NameKind: LookupOrdinaryName); |
20111 | AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), |
20112 | AttributeCommonInfo::Form::Pragma()); |
20113 | AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( |
20114 | Ctx&: Context, Label: AliasName->getName(), /*IsLiteralLabel=*/true, CommonInfo: Info); |
20115 | |
20116 | // If a declaration that: |
20117 | // 1) declares a function or a variable |
20118 | // 2) has external linkage |
20119 | // already exists, add a label attribute to it. |
20120 | if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) { |
20121 | if (isDeclExternC(D: PrevDecl)) |
20122 | PrevDecl->addAttr(A: Attr); |
20123 | else |
20124 | Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied) |
20125 | << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl; |
20126 | // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers. |
20127 | } else |
20128 | (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr)); |
20129 | } |
20130 | |
20131 | void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, |
20132 | SourceLocation PragmaLoc, |
20133 | SourceLocation NameLoc) { |
20134 | Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName); |
20135 | |
20136 | if (PrevDecl) { |
20137 | PrevDecl->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc)); |
20138 | } else { |
20139 | (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc)); |
20140 | } |
20141 | } |
20142 | |
20143 | void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, |
20144 | IdentifierInfo* AliasName, |
20145 | SourceLocation PragmaLoc, |
20146 | SourceLocation NameLoc, |
20147 | SourceLocation AliasNameLoc) { |
20148 | Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc, |
20149 | NameKind: LookupOrdinaryName); |
20150 | WeakInfo W = WeakInfo(Name, NameLoc); |
20151 | |
20152 | if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) { |
20153 | if (!PrevDecl->hasAttr<AliasAttr>()) |
20154 | if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl)) |
20155 | DeclApplyPragmaWeak(S: TUScope, ND, W); |
20156 | } else { |
20157 | (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W); |
20158 | } |
20159 | } |
20160 | |
20161 | Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD, |
20162 | bool Final) { |
20163 | assert(FD && "Expected non-null FunctionDecl" ); |
20164 | |
20165 | // SYCL functions can be template, so we check if they have appropriate |
20166 | // attribute prior to checking if it is a template. |
20167 | if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) |
20168 | return FunctionEmissionStatus::Emitted; |
20169 | |
20170 | // Templates are emitted when they're instantiated. |
20171 | if (FD->isDependentContext()) |
20172 | return FunctionEmissionStatus::TemplateDiscarded; |
20173 | |
20174 | // Check whether this function is an externally visible definition. |
20175 | auto IsEmittedForExternalSymbol = [this, FD]() { |
20176 | // We have to check the GVA linkage of the function's *definition* -- if we |
20177 | // only have a declaration, we don't know whether or not the function will |
20178 | // be emitted, because (say) the definition could include "inline". |
20179 | const FunctionDecl *Def = FD->getDefinition(); |
20180 | |
20181 | return Def && !isDiscardableGVALinkage( |
20182 | L: getASTContext().GetGVALinkageForFunction(FD: Def)); |
20183 | }; |
20184 | |
20185 | if (LangOpts.OpenMPIsTargetDevice) { |
20186 | // In OpenMP device mode we will not emit host only functions, or functions |
20187 | // we don't need due to their linkage. |
20188 | std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = |
20189 | OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl()); |
20190 | // DevTy may be changed later by |
20191 | // #pragma omp declare target to(*) device_type(*). |
20192 | // Therefore DevTy having no value does not imply host. The emission status |
20193 | // will be checked again at the end of compilation unit with Final = true. |
20194 | if (DevTy) |
20195 | if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) |
20196 | return FunctionEmissionStatus::OMPDiscarded; |
20197 | // If we have an explicit value for the device type, or we are in a target |
20198 | // declare context, we need to emit all extern and used symbols. |
20199 | if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy) |
20200 | if (IsEmittedForExternalSymbol()) |
20201 | return FunctionEmissionStatus::Emitted; |
20202 | // Device mode only emits what it must, if it wasn't tagged yet and needed, |
20203 | // we'll omit it. |
20204 | if (Final) |
20205 | return FunctionEmissionStatus::OMPDiscarded; |
20206 | } else if (LangOpts.OpenMP > 45) { |
20207 | // In OpenMP host compilation prior to 5.0 everything was an emitted host |
20208 | // function. In 5.0, no_host was introduced which might cause a function to |
20209 | // be omitted. |
20210 | std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = |
20211 | OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl()); |
20212 | if (DevTy) |
20213 | if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) |
20214 | return FunctionEmissionStatus::OMPDiscarded; |
20215 | } |
20216 | |
20217 | if (Final && LangOpts.OpenMP && !LangOpts.CUDA) |
20218 | return FunctionEmissionStatus::Emitted; |
20219 | |
20220 | if (LangOpts.CUDA) { |
20221 | // When compiling for device, host functions are never emitted. Similarly, |
20222 | // when compiling for host, device and global functions are never emitted. |
20223 | // (Technically, we do emit a host-side stub for global functions, but this |
20224 | // doesn't count for our purposes here.) |
20225 | CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD); |
20226 | if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host) |
20227 | return FunctionEmissionStatus::CUDADiscarded; |
20228 | if (!LangOpts.CUDAIsDevice && |
20229 | (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global)) |
20230 | return FunctionEmissionStatus::CUDADiscarded; |
20231 | |
20232 | if (IsEmittedForExternalSymbol()) |
20233 | return FunctionEmissionStatus::Emitted; |
20234 | } |
20235 | |
20236 | // Otherwise, the function is known-emitted if it's in our set of |
20237 | // known-emitted functions. |
20238 | return FunctionEmissionStatus::Unknown; |
20239 | } |
20240 | |
20241 | bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { |
20242 | // Host-side references to a __global__ function refer to the stub, so the |
20243 | // function itself is never emitted and therefore should not be marked. |
20244 | // If we have host fn calls kernel fn calls host+device, the HD function |
20245 | // does not get instantiated on the host. We model this by omitting at the |
20246 | // call to the kernel from the callgraph. This ensures that, when compiling |
20247 | // for host, only HD functions actually called from the host get marked as |
20248 | // known-emitted. |
20249 | return LangOpts.CUDA && !LangOpts.CUDAIsDevice && |
20250 | CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global; |
20251 | } |
20252 | |
20253 | void Sema::diagnoseFunctionEffectMergeConflicts( |
20254 | const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, |
20255 | SourceLocation OldLoc) { |
20256 | for (const FunctionEffectSet::Conflict &Conflict : Errs) { |
20257 | Diag(Loc: NewLoc, DiagID: diag::warn_conflicting_func_effects) |
20258 | << Conflict.Kept.description() << Conflict.Rejected.description(); |
20259 | Diag(Loc: OldLoc, DiagID: diag::note_previous_declaration); |
20260 | } |
20261 | } |
20262 | |
20263 | bool Sema::diagnoseConflictingFunctionEffect( |
20264 | const FunctionEffectsRef &FX, const FunctionEffectWithCondition &NewEC, |
20265 | SourceLocation NewAttrLoc) { |
20266 | // If the new effect has a condition, we can't detect conflicts until the |
20267 | // condition is resolved. |
20268 | if (NewEC.Cond.getCondition() != nullptr) |
20269 | return false; |
20270 | |
20271 | // Diagnose the new attribute as incompatible with a previous one. |
20272 | auto Incompatible = [&](const FunctionEffectWithCondition &PrevEC) { |
20273 | Diag(Loc: NewAttrLoc, DiagID: diag::err_attributes_are_not_compatible) |
20274 | << ("'" + NewEC.description() + "'" ) |
20275 | << ("'" + PrevEC.description() + "'" ) << false; |
20276 | // We don't necessarily have the location of the previous attribute, |
20277 | // so no note. |
20278 | return true; |
20279 | }; |
20280 | |
20281 | // Compare against previous attributes. |
20282 | FunctionEffect::Kind NewKind = NewEC.Effect.kind(); |
20283 | |
20284 | for (const FunctionEffectWithCondition &PrevEC : FX) { |
20285 | // Again, can't check yet when the effect is conditional. |
20286 | if (PrevEC.Cond.getCondition() != nullptr) |
20287 | continue; |
20288 | |
20289 | FunctionEffect::Kind PrevKind = PrevEC.Effect.kind(); |
20290 | // Note that we allow PrevKind == NewKind; it's redundant and ignored. |
20291 | |
20292 | if (PrevEC.Effect.oppositeKind() == NewKind) |
20293 | return Incompatible(PrevEC); |
20294 | |
20295 | // A new allocating is incompatible with a previous nonblocking. |
20296 | if (PrevKind == FunctionEffect::Kind::NonBlocking && |
20297 | NewKind == FunctionEffect::Kind::Allocating) |
20298 | return Incompatible(PrevEC); |
20299 | |
20300 | // A new nonblocking is incompatible with a previous allocating. |
20301 | if (PrevKind == FunctionEffect::Kind::Allocating && |
20302 | NewKind == FunctionEffect::Kind::NonBlocking) |
20303 | return Incompatible(PrevEC); |
20304 | } |
20305 | |
20306 | return false; |
20307 | } |
20308 | |