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/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/Randstruct.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/HLSLRuntime.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
36 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
37 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
38 #include "clang/Sema/CXXFieldCollector.h"
39 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/DelayedDiagnostic.h"
41 #include "clang/Sema/Initialization.h"
42 #include "clang/Sema/Lookup.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/ADT/SmallString.h"
49 #include "llvm/ADT/Triple.h"
50 #include <algorithm>
51 #include <cstring>
52 #include <functional>
53 #include <optional>
54 #include <unordered_map>
55
56 using namespace clang;
57 using namespace sema;
58
ConvertDeclToDeclGroup(Decl * Ptr,Decl * OwnedType)59 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
60 if (OwnedType) {
61 Decl *Group[2] = { OwnedType, Ptr };
62 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
63 }
64
65 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
66 }
67
68 namespace {
69
70 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
71 public:
TypeNameValidatorCCC(bool AllowInvalid,bool WantClass=false,bool AllowTemplates=false,bool AllowNonTemplates=true)72 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
73 bool AllowTemplates = false,
74 bool AllowNonTemplates = true)
75 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
76 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
77 WantExpressionKeywords = false;
78 WantCXXNamedCasts = false;
79 WantRemainingKeywords = false;
80 }
81
ValidateCandidate(const TypoCorrection & candidate)82 bool ValidateCandidate(const TypoCorrection &candidate) override {
83 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
84 if (!AllowInvalidDecl && ND->isInvalidDecl())
85 return false;
86
87 if (getAsTypeTemplateDecl(ND))
88 return AllowTemplates;
89
90 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
91 if (!IsType)
92 return false;
93
94 if (AllowNonTemplates)
95 return true;
96
97 // An injected-class-name of a class template (specialization) is valid
98 // as a template or as a non-template.
99 if (AllowTemplates) {
100 auto *RD = dyn_cast<CXXRecordDecl>(ND);
101 if (!RD || !RD->isInjectedClassName())
102 return false;
103 RD = cast<CXXRecordDecl>(RD->getDeclContext());
104 return RD->getDescribedClassTemplate() ||
105 isa<ClassTemplateSpecializationDecl>(RD);
106 }
107
108 return false;
109 }
110
111 return !WantClassName && candidate.isKeyword();
112 }
113
clone()114 std::unique_ptr<CorrectionCandidateCallback> clone() override {
115 return std::make_unique<TypeNameValidatorCCC>(*this);
116 }
117
118 private:
119 bool AllowInvalidDecl;
120 bool WantClassName;
121 bool AllowTemplates;
122 bool AllowNonTemplates;
123 };
124
125 } // end anonymous namespace
126
127 /// Determine whether the token kind starts a simple-type-specifier.
isSimpleTypeSpecifier(tok::TokenKind Kind) const128 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
129 switch (Kind) {
130 // FIXME: Take into account the current language when deciding whether a
131 // token kind is a valid type specifier
132 case tok::kw_short:
133 case tok::kw_long:
134 case tok::kw___int64:
135 case tok::kw___int128:
136 case tok::kw_signed:
137 case tok::kw_unsigned:
138 case tok::kw_void:
139 case tok::kw_char:
140 case tok::kw_int:
141 case tok::kw_half:
142 case tok::kw_float:
143 case tok::kw_double:
144 case tok::kw___bf16:
145 case tok::kw__Float16:
146 case tok::kw___float128:
147 case tok::kw___ibm128:
148 case tok::kw_wchar_t:
149 case tok::kw_bool:
150 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
151 #include "clang/Basic/TransformTypeTraits.def"
152 case tok::kw___auto_type:
153 return true;
154
155 case tok::annot_typename:
156 case tok::kw_char16_t:
157 case tok::kw_char32_t:
158 case tok::kw_typeof:
159 case tok::annot_decltype:
160 case tok::kw_decltype:
161 return getLangOpts().CPlusPlus;
162
163 case tok::kw_char8_t:
164 return getLangOpts().Char8;
165
166 default:
167 break;
168 }
169
170 return false;
171 }
172
173 namespace {
174 enum class UnqualifiedTypeNameLookupResult {
175 NotFound,
176 FoundNonType,
177 FoundType
178 };
179 } // end anonymous namespace
180
181 /// Tries to perform unqualified lookup of the type decls in bases for
182 /// dependent class.
183 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
184 /// type decl, \a FoundType if only type decls are found.
185 static UnqualifiedTypeNameLookupResult
lookupUnqualifiedTypeNameInBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc,const CXXRecordDecl * RD)186 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
187 SourceLocation NameLoc,
188 const CXXRecordDecl *RD) {
189 if (!RD->hasDefinition())
190 return UnqualifiedTypeNameLookupResult::NotFound;
191 // Look for type decls in base classes.
192 UnqualifiedTypeNameLookupResult FoundTypeDecl =
193 UnqualifiedTypeNameLookupResult::NotFound;
194 for (const auto &Base : RD->bases()) {
195 const CXXRecordDecl *BaseRD = nullptr;
196 if (auto *BaseTT = Base.getType()->getAs<TagType>())
197 BaseRD = BaseTT->getAsCXXRecordDecl();
198 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
199 // Look for type decls in dependent base classes that have known primary
200 // templates.
201 if (!TST || !TST->isDependentType())
202 continue;
203 auto *TD = TST->getTemplateName().getAsTemplateDecl();
204 if (!TD)
205 continue;
206 if (auto *BasePrimaryTemplate =
207 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
208 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = BasePrimaryTemplate;
210 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
211 if (const ClassTemplatePartialSpecializationDecl *PS =
212 CTD->findPartialSpecialization(Base.getType()))
213 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
214 BaseRD = PS;
215 }
216 }
217 }
218 if (BaseRD) {
219 for (NamedDecl *ND : BaseRD->lookup(&II)) {
220 if (!isa<TypeDecl>(ND))
221 return UnqualifiedTypeNameLookupResult::FoundNonType;
222 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
223 }
224 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
225 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
226 case UnqualifiedTypeNameLookupResult::FoundNonType:
227 return UnqualifiedTypeNameLookupResult::FoundNonType;
228 case UnqualifiedTypeNameLookupResult::FoundType:
229 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
230 break;
231 case UnqualifiedTypeNameLookupResult::NotFound:
232 break;
233 }
234 }
235 }
236 }
237
238 return FoundTypeDecl;
239 }
240
recoverFromTypeInKnownDependentBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc)241 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
242 const IdentifierInfo &II,
243 SourceLocation NameLoc) {
244 // Lookup in the parent class template context, if any.
245 const CXXRecordDecl *RD = nullptr;
246 UnqualifiedTypeNameLookupResult FoundTypeDecl =
247 UnqualifiedTypeNameLookupResult::NotFound;
248 for (DeclContext *DC = S.CurContext;
249 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
250 DC = DC->getParent()) {
251 // Look for type decls in dependent base classes that have known primary
252 // templates.
253 RD = dyn_cast<CXXRecordDecl>(DC);
254 if (RD && RD->getDescribedClassTemplate())
255 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
256 }
257 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
258 return nullptr;
259
260 // We found some types in dependent base classes. Recover as if the user
261 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
262 // lookup during template instantiation.
263 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
264
265 ASTContext &Context = S.Context;
266 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
267 cast<Type>(Context.getRecordType(RD)));
268 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
269
270 CXXScopeSpec SS;
271 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
272
273 TypeLocBuilder Builder;
274 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
275 DepTL.setNameLoc(NameLoc);
276 DepTL.setElaboratedKeywordLoc(SourceLocation());
277 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
278 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
279 }
280
281 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
buildNamedType(Sema & S,const CXXScopeSpec * SS,QualType T,SourceLocation NameLoc,bool WantNontrivialTypeSourceInfo=true)282 static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
283 SourceLocation NameLoc,
284 bool WantNontrivialTypeSourceInfo = true) {
285 switch (T->getTypeClass()) {
286 case Type::DeducedTemplateSpecialization:
287 case Type::Enum:
288 case Type::InjectedClassName:
289 case Type::Record:
290 case Type::Typedef:
291 case Type::UnresolvedUsing:
292 case Type::Using:
293 break;
294 // These can never be qualified so an ElaboratedType node
295 // would carry no additional meaning.
296 case Type::ObjCInterface:
297 case Type::ObjCTypeParam:
298 case Type::TemplateTypeParm:
299 return ParsedType::make(T);
300 default:
301 llvm_unreachable("Unexpected Type Class");
302 }
303
304 if (!SS || SS->isEmpty())
305 return ParsedType::make(
306 S.Context.getElaboratedType(ETK_None, nullptr, T, nullptr));
307
308 QualType ElTy = S.getElaboratedType(ETK_None, *SS, T);
309 if (!WantNontrivialTypeSourceInfo)
310 return ParsedType::make(ElTy);
311
312 TypeLocBuilder Builder;
313 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
314 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
315 ElabTL.setElaboratedKeywordLoc(SourceLocation());
316 ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
317 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
318 }
319
320 /// If the identifier refers to a type name within this scope,
321 /// return the declaration of that type.
322 ///
323 /// This routine performs ordinary name lookup of the identifier II
324 /// within the given scope, with optional C++ scope specifier SS, to
325 /// determine whether the name refers to a type. If so, returns an
326 /// opaque pointer (actually a QualType) corresponding to that
327 /// type. Otherwise, returns NULL.
getTypeName(const IdentifierInfo & II,SourceLocation NameLoc,Scope * S,CXXScopeSpec * SS,bool isClassName,bool HasTrailingDot,ParsedType ObjectTypePtr,bool IsCtorOrDtorName,bool WantNontrivialTypeSourceInfo,bool IsClassTemplateDeductionContext,ImplicitTypenameContext AllowImplicitTypename,IdentifierInfo ** CorrectedII)328 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
329 Scope *S, CXXScopeSpec *SS, bool isClassName,
330 bool HasTrailingDot, ParsedType ObjectTypePtr,
331 bool IsCtorOrDtorName,
332 bool WantNontrivialTypeSourceInfo,
333 bool IsClassTemplateDeductionContext,
334 ImplicitTypenameContext AllowImplicitTypename,
335 IdentifierInfo **CorrectedII) {
336 // FIXME: Consider allowing this outside C++1z mode as an extension.
337 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
338 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
339 !isClassName && !HasTrailingDot;
340
341 // Determine where we will perform name lookup.
342 DeclContext *LookupCtx = nullptr;
343 if (ObjectTypePtr) {
344 QualType ObjectType = ObjectTypePtr.get();
345 if (ObjectType->isRecordType())
346 LookupCtx = computeDeclContext(ObjectType);
347 } else if (SS && SS->isNotEmpty()) {
348 LookupCtx = computeDeclContext(*SS, false);
349
350 if (!LookupCtx) {
351 if (isDependentScopeSpecifier(*SS)) {
352 // C++ [temp.res]p3:
353 // A qualified-id that refers to a type and in which the
354 // nested-name-specifier depends on a template-parameter (14.6.2)
355 // shall be prefixed by the keyword typename to indicate that the
356 // qualified-id denotes a type, forming an
357 // elaborated-type-specifier (7.1.5.3).
358 //
359 // We therefore do not perform any name lookup if the result would
360 // refer to a member of an unknown specialization.
361 // In C++2a, in several contexts a 'typename' is not required. Also
362 // allow this as an extension.
363 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
364 !isClassName && !IsCtorOrDtorName)
365 return nullptr;
366 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
367 if (IsImplicitTypename) {
368 SourceLocation QualifiedLoc = SS->getRange().getBegin();
369 if (getLangOpts().CPlusPlus20)
370 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
371 else
372 Diag(QualifiedLoc, diag::ext_implicit_typename)
373 << SS->getScopeRep() << II.getName()
374 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
375 }
376
377 // We know from the grammar that this name refers to a type,
378 // so build a dependent node to describe the type.
379 if (WantNontrivialTypeSourceInfo)
380 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
381 (ImplicitTypenameContext)IsImplicitTypename)
382 .get();
383
384 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
385 QualType T =
386 CheckTypenameType(IsImplicitTypename ? ETK_Typename : ETK_None,
387 SourceLocation(), QualifierLoc, II, NameLoc);
388 return ParsedType::make(T);
389 }
390
391 return nullptr;
392 }
393
394 if (!LookupCtx->isDependentContext() &&
395 RequireCompleteDeclContext(*SS, LookupCtx))
396 return nullptr;
397 }
398
399 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
400 // lookup for class-names.
401 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
402 LookupOrdinaryName;
403 LookupResult Result(*this, &II, NameLoc, Kind);
404 if (LookupCtx) {
405 // Perform "qualified" name lookup into the declaration context we
406 // computed, which is either the type of the base of a member access
407 // expression or the declaration context associated with a prior
408 // nested-name-specifier.
409 LookupQualifiedName(Result, LookupCtx);
410
411 if (ObjectTypePtr && Result.empty()) {
412 // C++ [basic.lookup.classref]p3:
413 // If the unqualified-id is ~type-name, the type-name is looked up
414 // in the context of the entire postfix-expression. If the type T of
415 // the object expression is of a class type C, the type-name is also
416 // looked up in the scope of class C. At least one of the lookups shall
417 // find a name that refers to (possibly cv-qualified) T.
418 LookupName(Result, S);
419 }
420 } else {
421 // Perform unqualified name lookup.
422 LookupName(Result, S);
423
424 // For unqualified lookup in a class template in MSVC mode, look into
425 // dependent base classes where the primary class template is known.
426 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
427 if (ParsedType TypeInBase =
428 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
429 return TypeInBase;
430 }
431 }
432
433 NamedDecl *IIDecl = nullptr;
434 UsingShadowDecl *FoundUsingShadow = nullptr;
435 switch (Result.getResultKind()) {
436 case LookupResult::NotFound:
437 case LookupResult::NotFoundInCurrentInstantiation:
438 if (CorrectedII) {
439 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
440 AllowDeducedTemplate);
441 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
442 S, SS, CCC, CTK_ErrorRecovery);
443 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
444 TemplateTy Template;
445 bool MemberOfUnknownSpecialization;
446 UnqualifiedId TemplateName;
447 TemplateName.setIdentifier(NewII, NameLoc);
448 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
449 CXXScopeSpec NewSS, *NewSSPtr = SS;
450 if (SS && NNS) {
451 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
452 NewSSPtr = &NewSS;
453 }
454 if (Correction && (NNS || NewII != &II) &&
455 // Ignore a correction to a template type as the to-be-corrected
456 // identifier is not a template (typo correction for template names
457 // is handled elsewhere).
458 !(getLangOpts().CPlusPlus && NewSSPtr &&
459 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
460 Template, MemberOfUnknownSpecialization))) {
461 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
462 isClassName, HasTrailingDot, ObjectTypePtr,
463 IsCtorOrDtorName,
464 WantNontrivialTypeSourceInfo,
465 IsClassTemplateDeductionContext);
466 if (Ty) {
467 diagnoseTypo(Correction,
468 PDiag(diag::err_unknown_type_or_class_name_suggest)
469 << Result.getLookupName() << isClassName);
470 if (SS && NNS)
471 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
472 *CorrectedII = NewII;
473 return Ty;
474 }
475 }
476 }
477 // If typo correction failed or was not performed, fall through
478 [[fallthrough]];
479 case LookupResult::FoundOverloaded:
480 case LookupResult::FoundUnresolvedValue:
481 Result.suppressDiagnostics();
482 return nullptr;
483
484 case LookupResult::Ambiguous:
485 // Recover from type-hiding ambiguities by hiding the type. We'll
486 // do the lookup again when looking for an object, and we can
487 // diagnose the error then. If we don't do this, then the error
488 // about hiding the type will be immediately followed by an error
489 // that only makes sense if the identifier was treated like a type.
490 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
491 Result.suppressDiagnostics();
492 return nullptr;
493 }
494
495 // Look to see if we have a type anywhere in the list of results.
496 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
497 Res != ResEnd; ++Res) {
498 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
499 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
500 RealRes) ||
501 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
502 if (!IIDecl ||
503 // Make the selection of the recovery decl deterministic.
504 RealRes->getLocation() < IIDecl->getLocation()) {
505 IIDecl = RealRes;
506 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
507 }
508 }
509 }
510
511 if (!IIDecl) {
512 // None of the entities we found is a type, so there is no way
513 // to even assume that the result is a type. In this case, don't
514 // complain about the ambiguity. The parser will either try to
515 // perform this lookup again (e.g., as an object name), which
516 // will produce the ambiguity, or will complain that it expected
517 // a type name.
518 Result.suppressDiagnostics();
519 return nullptr;
520 }
521
522 // We found a type within the ambiguous lookup; diagnose the
523 // ambiguity and then return that type. This might be the right
524 // answer, or it might not be, but it suppresses any attempt to
525 // perform the name lookup again.
526 break;
527
528 case LookupResult::Found:
529 IIDecl = Result.getFoundDecl();
530 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
531 break;
532 }
533
534 assert(IIDecl && "Didn't find decl");
535
536 QualType T;
537 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
538 // C++ [class.qual]p2: A lookup that would find the injected-class-name
539 // instead names the constructors of the class, except when naming a class.
540 // This is ill-formed when we're not actually forming a ctor or dtor name.
541 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
542 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
543 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
544 FoundRD->isInjectedClassName() &&
545 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
546 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
547 << &II << /*Type*/1;
548
549 DiagnoseUseOfDecl(IIDecl, NameLoc);
550
551 T = Context.getTypeDeclType(TD);
552 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
553 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
554 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
555 if (!HasTrailingDot)
556 T = Context.getObjCInterfaceType(IDecl);
557 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
558 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
559 (void)DiagnoseUseOfDecl(UD, NameLoc);
560 // Recover with 'int'
561 return ParsedType::make(Context.IntTy);
562 } else if (AllowDeducedTemplate) {
563 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
564 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
565 TemplateName Template =
566 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
567 T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
568 false);
569 // Don't wrap in a further UsingType.
570 FoundUsingShadow = nullptr;
571 }
572 }
573
574 if (T.isNull()) {
575 // If it's not plausibly a type, suppress diagnostics.
576 Result.suppressDiagnostics();
577 return nullptr;
578 }
579
580 if (FoundUsingShadow)
581 T = Context.getUsingType(FoundUsingShadow, T);
582
583 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
584 }
585
586 // Builds a fake NNS for the given decl context.
587 static NestedNameSpecifier *
synthesizeCurrentNestedNameSpecifier(ASTContext & Context,DeclContext * DC)588 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
589 for (;; DC = DC->getLookupParent()) {
590 DC = DC->getPrimaryContext();
591 auto *ND = dyn_cast<NamespaceDecl>(DC);
592 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
593 return NestedNameSpecifier::Create(Context, nullptr, ND);
594 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
595 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
596 RD->getTypeForDecl());
597 else if (isa<TranslationUnitDecl>(DC))
598 return NestedNameSpecifier::GlobalSpecifier(Context);
599 }
600 llvm_unreachable("something isn't in TU scope?");
601 }
602
603 /// Find the parent class with dependent bases of the innermost enclosing method
604 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
605 /// up allowing unqualified dependent type names at class-level, which MSVC
606 /// correctly rejects.
607 static const CXXRecordDecl *
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext * DC)608 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
609 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
610 DC = DC->getPrimaryContext();
611 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
612 if (MD->getParent()->hasAnyDependentBases())
613 return MD->getParent();
614 }
615 return nullptr;
616 }
617
ActOnMSVCUnknownTypeName(const IdentifierInfo & II,SourceLocation NameLoc,bool IsTemplateTypeArg)618 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
619 SourceLocation NameLoc,
620 bool IsTemplateTypeArg) {
621 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
622
623 NestedNameSpecifier *NNS = nullptr;
624 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
625 // If we weren't able to parse a default template argument, delay lookup
626 // until instantiation time by making a non-dependent DependentTypeName. We
627 // pretend we saw a NestedNameSpecifier referring to the current scope, and
628 // lookup is retried.
629 // FIXME: This hurts our diagnostic quality, since we get errors like "no
630 // type named 'Foo' in 'current_namespace'" when the user didn't write any
631 // name specifiers.
632 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
633 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
634 } else if (const CXXRecordDecl *RD =
635 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
636 // Build a DependentNameType that will perform lookup into RD at
637 // instantiation time.
638 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
639 RD->getTypeForDecl());
640
641 // Diagnose that this identifier was undeclared, and retry the lookup during
642 // template instantiation.
643 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
644 << RD;
645 } else {
646 // This is not a situation that we should recover from.
647 return ParsedType();
648 }
649
650 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
651
652 // Build type location information. We synthesized the qualifier, so we have
653 // to build a fake NestedNameSpecifierLoc.
654 NestedNameSpecifierLocBuilder NNSLocBuilder;
655 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
656 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
657
658 TypeLocBuilder Builder;
659 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
660 DepTL.setNameLoc(NameLoc);
661 DepTL.setElaboratedKeywordLoc(SourceLocation());
662 DepTL.setQualifierLoc(QualifierLoc);
663 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
664 }
665
666 /// isTagName() - This method is called *for error recovery purposes only*
667 /// to determine if the specified name is a valid tag name ("struct foo"). If
668 /// so, this returns the TST for the tag corresponding to it (TST_enum,
669 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
670 /// cases in C where the user forgot to specify the tag.
isTagName(IdentifierInfo & II,Scope * S)671 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
672 // Do a tag name lookup in this scope.
673 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
674 LookupName(R, S, false);
675 R.suppressDiagnostics();
676 if (R.getResultKind() == LookupResult::Found)
677 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
678 switch (TD->getTagKind()) {
679 case TTK_Struct: return DeclSpec::TST_struct;
680 case TTK_Interface: return DeclSpec::TST_interface;
681 case TTK_Union: return DeclSpec::TST_union;
682 case TTK_Class: return DeclSpec::TST_class;
683 case TTK_Enum: return DeclSpec::TST_enum;
684 }
685 }
686
687 return DeclSpec::TST_unspecified;
688 }
689
690 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
691 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
692 /// then downgrade the missing typename error to a warning.
693 /// This is needed for MSVC compatibility; Example:
694 /// @code
695 /// template<class T> class A {
696 /// public:
697 /// typedef int TYPE;
698 /// };
699 /// template<class T> class B : public A<T> {
700 /// public:
701 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
702 /// };
703 /// @endcode
isMicrosoftMissingTypename(const CXXScopeSpec * SS,Scope * S)704 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
705 if (CurContext->isRecord()) {
706 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
707 return true;
708
709 const Type *Ty = SS->getScopeRep()->getAsType();
710
711 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
712 for (const auto &Base : RD->bases())
713 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
714 return true;
715 return S->isFunctionPrototypeScope();
716 }
717 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
718 }
719
DiagnoseUnknownTypeName(IdentifierInfo * & II,SourceLocation IILoc,Scope * S,CXXScopeSpec * SS,ParsedType & SuggestedType,bool IsTemplateName)720 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
721 SourceLocation IILoc,
722 Scope *S,
723 CXXScopeSpec *SS,
724 ParsedType &SuggestedType,
725 bool IsTemplateName) {
726 // Don't report typename errors for editor placeholders.
727 if (II->isEditorPlaceholder())
728 return;
729 // We don't have anything to suggest (yet).
730 SuggestedType = nullptr;
731
732 // There may have been a typo in the name of the type. Look up typo
733 // results, in case we have something that we can suggest.
734 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
735 /*AllowTemplates=*/IsTemplateName,
736 /*AllowNonTemplates=*/!IsTemplateName);
737 if (TypoCorrection Corrected =
738 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
739 CCC, CTK_ErrorRecovery)) {
740 // FIXME: Support error recovery for the template-name case.
741 bool CanRecover = !IsTemplateName;
742 if (Corrected.isKeyword()) {
743 // We corrected to a keyword.
744 diagnoseTypo(Corrected,
745 PDiag(IsTemplateName ? diag::err_no_template_suggest
746 : diag::err_unknown_typename_suggest)
747 << II);
748 II = Corrected.getCorrectionAsIdentifierInfo();
749 } else {
750 // We found a similarly-named type or interface; suggest that.
751 if (!SS || !SS->isSet()) {
752 diagnoseTypo(Corrected,
753 PDiag(IsTemplateName ? diag::err_no_template_suggest
754 : diag::err_unknown_typename_suggest)
755 << II, CanRecover);
756 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
757 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
758 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
759 II->getName().equals(CorrectedStr);
760 diagnoseTypo(Corrected,
761 PDiag(IsTemplateName
762 ? diag::err_no_member_template_suggest
763 : diag::err_unknown_nested_typename_suggest)
764 << II << DC << DroppedSpecifier << SS->getRange(),
765 CanRecover);
766 } else {
767 llvm_unreachable("could not have corrected a typo here");
768 }
769
770 if (!CanRecover)
771 return;
772
773 CXXScopeSpec tmpSS;
774 if (Corrected.getCorrectionSpecifier())
775 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
776 SourceRange(IILoc));
777 // FIXME: Support class template argument deduction here.
778 SuggestedType =
779 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
780 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
781 /*IsCtorOrDtorName=*/false,
782 /*WantNontrivialTypeSourceInfo=*/true);
783 }
784 return;
785 }
786
787 if (getLangOpts().CPlusPlus && !IsTemplateName) {
788 // See if II is a class template that the user forgot to pass arguments to.
789 UnqualifiedId Name;
790 Name.setIdentifier(II, IILoc);
791 CXXScopeSpec EmptySS;
792 TemplateTy TemplateResult;
793 bool MemberOfUnknownSpecialization;
794 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
795 Name, nullptr, true, TemplateResult,
796 MemberOfUnknownSpecialization) == TNK_Type_template) {
797 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
798 return;
799 }
800 }
801
802 // FIXME: Should we move the logic that tries to recover from a missing tag
803 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
804
805 if (!SS || (!SS->isSet() && !SS->isInvalid()))
806 Diag(IILoc, IsTemplateName ? diag::err_no_template
807 : diag::err_unknown_typename)
808 << II;
809 else if (DeclContext *DC = computeDeclContext(*SS, false))
810 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
811 : diag::err_typename_nested_not_found)
812 << II << DC << SS->getRange();
813 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
814 SuggestedType =
815 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
816 } else if (isDependentScopeSpecifier(*SS)) {
817 unsigned DiagID = diag::err_typename_missing;
818 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
819 DiagID = diag::ext_typename_missing;
820
821 Diag(SS->getRange().getBegin(), DiagID)
822 << SS->getScopeRep() << II->getName()
823 << SourceRange(SS->getRange().getBegin(), IILoc)
824 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
825 SuggestedType = ActOnTypenameType(S, SourceLocation(),
826 *SS, *II, IILoc).get();
827 } else {
828 assert(SS && SS->isInvalid() &&
829 "Invalid scope specifier has already been diagnosed");
830 }
831 }
832
833 /// Determine whether the given result set contains either a type name
834 /// or
isResultTypeOrTemplate(LookupResult & R,const Token & NextToken)835 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
836 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
837 NextToken.is(tok::less);
838
839 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
840 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
841 return true;
842
843 if (CheckTemplate && isa<TemplateDecl>(*I))
844 return true;
845 }
846
847 return false;
848 }
849
isTagTypeWithMissingTag(Sema & SemaRef,LookupResult & Result,Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc)850 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
851 Scope *S, CXXScopeSpec &SS,
852 IdentifierInfo *&Name,
853 SourceLocation NameLoc) {
854 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
855 SemaRef.LookupParsedName(R, S, &SS);
856 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
857 StringRef FixItTagName;
858 switch (Tag->getTagKind()) {
859 case TTK_Class:
860 FixItTagName = "class ";
861 break;
862
863 case TTK_Enum:
864 FixItTagName = "enum ";
865 break;
866
867 case TTK_Struct:
868 FixItTagName = "struct ";
869 break;
870
871 case TTK_Interface:
872 FixItTagName = "__interface ";
873 break;
874
875 case TTK_Union:
876 FixItTagName = "union ";
877 break;
878 }
879
880 StringRef TagName = FixItTagName.drop_back();
881 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
882 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
883 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
884
885 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
886 I != IEnd; ++I)
887 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
888 << Name << TagName;
889
890 // Replace lookup results with just the tag decl.
891 Result.clear(Sema::LookupTagName);
892 SemaRef.LookupParsedName(Result, S, &SS);
893 return true;
894 }
895
896 return false;
897 }
898
ClassifyName(Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc,const Token & NextToken,CorrectionCandidateCallback * CCC)899 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
900 IdentifierInfo *&Name,
901 SourceLocation NameLoc,
902 const Token &NextToken,
903 CorrectionCandidateCallback *CCC) {
904 DeclarationNameInfo NameInfo(Name, NameLoc);
905 ObjCMethodDecl *CurMethod = getCurMethodDecl();
906
907 assert(NextToken.isNot(tok::coloncolon) &&
908 "parse nested name specifiers before calling ClassifyName");
909 if (getLangOpts().CPlusPlus && SS.isSet() &&
910 isCurrentClassName(*Name, S, &SS)) {
911 // Per [class.qual]p2, this names the constructors of SS, not the
912 // injected-class-name. We don't have a classification for that.
913 // There's not much point caching this result, since the parser
914 // will reject it later.
915 return NameClassification::Unknown();
916 }
917
918 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
919 LookupParsedName(Result, S, &SS, !CurMethod);
920
921 if (SS.isInvalid())
922 return NameClassification::Error();
923
924 // For unqualified lookup in a class template in MSVC mode, look into
925 // dependent base classes where the primary class template is known.
926 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
927 if (ParsedType TypeInBase =
928 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
929 return TypeInBase;
930 }
931
932 // Perform lookup for Objective-C instance variables (including automatically
933 // synthesized instance variables), if we're in an Objective-C method.
934 // FIXME: This lookup really, really needs to be folded in to the normal
935 // unqualified lookup mechanism.
936 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
937 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
938 if (Ivar.isInvalid())
939 return NameClassification::Error();
940 if (Ivar.isUsable())
941 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
942
943 // We defer builtin creation until after ivar lookup inside ObjC methods.
944 if (Result.empty())
945 LookupBuiltin(Result);
946 }
947
948 bool SecondTry = false;
949 bool IsFilteredTemplateName = false;
950
951 Corrected:
952 switch (Result.getResultKind()) {
953 case LookupResult::NotFound:
954 // If an unqualified-id is followed by a '(', then we have a function
955 // call.
956 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
957 // In C++, this is an ADL-only call.
958 // FIXME: Reference?
959 if (getLangOpts().CPlusPlus)
960 return NameClassification::UndeclaredNonType();
961
962 // C90 6.3.2.2:
963 // If the expression that precedes the parenthesized argument list in a
964 // function call consists solely of an identifier, and if no
965 // declaration is visible for this identifier, the identifier is
966 // implicitly declared exactly as if, in the innermost block containing
967 // the function call, the declaration
968 //
969 // extern int identifier ();
970 //
971 // appeared.
972 //
973 // We also allow this in C99 as an extension. However, this is not
974 // allowed in all language modes as functions without prototypes may not
975 // be supported.
976 if (getLangOpts().implicitFunctionsAllowed()) {
977 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
978 return NameClassification::NonType(D);
979 }
980 }
981
982 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
983 // In C++20 onwards, this could be an ADL-only call to a function
984 // template, and we're required to assume that this is a template name.
985 //
986 // FIXME: Find a way to still do typo correction in this case.
987 TemplateName Template =
988 Context.getAssumedTemplateName(NameInfo.getName());
989 return NameClassification::UndeclaredTemplate(Template);
990 }
991
992 // In C, we first see whether there is a tag type by the same name, in
993 // which case it's likely that the user just forgot to write "enum",
994 // "struct", or "union".
995 if (!getLangOpts().CPlusPlus && !SecondTry &&
996 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
997 break;
998 }
999
1000 // Perform typo correction to determine if there is another name that is
1001 // close to this name.
1002 if (!SecondTry && CCC) {
1003 SecondTry = true;
1004 if (TypoCorrection Corrected =
1005 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1006 &SS, *CCC, CTK_ErrorRecovery)) {
1007 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1008 unsigned QualifiedDiag = diag::err_no_member_suggest;
1009
1010 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1011 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1012 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1013 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1014 UnqualifiedDiag = diag::err_no_template_suggest;
1015 QualifiedDiag = diag::err_no_member_template_suggest;
1016 } else if (UnderlyingFirstDecl &&
1017 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1018 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1019 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1020 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1021 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1022 }
1023
1024 if (SS.isEmpty()) {
1025 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1026 } else {// FIXME: is this even reachable? Test it.
1027 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1028 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1029 Name->getName().equals(CorrectedStr);
1030 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1031 << Name << computeDeclContext(SS, false)
1032 << DroppedSpecifier << SS.getRange());
1033 }
1034
1035 // Update the name, so that the caller has the new name.
1036 Name = Corrected.getCorrectionAsIdentifierInfo();
1037
1038 // Typo correction corrected to a keyword.
1039 if (Corrected.isKeyword())
1040 return Name;
1041
1042 // Also update the LookupResult...
1043 // FIXME: This should probably go away at some point
1044 Result.clear();
1045 Result.setLookupName(Corrected.getCorrection());
1046 if (FirstDecl)
1047 Result.addDecl(FirstDecl);
1048
1049 // If we found an Objective-C instance variable, let
1050 // LookupInObjCMethod build the appropriate expression to
1051 // reference the ivar.
1052 // FIXME: This is a gross hack.
1053 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1054 DeclResult R =
1055 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1056 if (R.isInvalid())
1057 return NameClassification::Error();
1058 if (R.isUsable())
1059 return NameClassification::NonType(Ivar);
1060 }
1061
1062 goto Corrected;
1063 }
1064 }
1065
1066 // We failed to correct; just fall through and let the parser deal with it.
1067 Result.suppressDiagnostics();
1068 return NameClassification::Unknown();
1069
1070 case LookupResult::NotFoundInCurrentInstantiation: {
1071 // We performed name lookup into the current instantiation, and there were
1072 // dependent bases, so we treat this result the same way as any other
1073 // dependent nested-name-specifier.
1074
1075 // C++ [temp.res]p2:
1076 // A name used in a template declaration or definition and that is
1077 // dependent on a template-parameter is assumed not to name a type
1078 // unless the applicable name lookup finds a type name or the name is
1079 // qualified by the keyword typename.
1080 //
1081 // FIXME: If the next token is '<', we might want to ask the parser to
1082 // perform some heroics to see if we actually have a
1083 // template-argument-list, which would indicate a missing 'template'
1084 // keyword here.
1085 return NameClassification::DependentNonType();
1086 }
1087
1088 case LookupResult::Found:
1089 case LookupResult::FoundOverloaded:
1090 case LookupResult::FoundUnresolvedValue:
1091 break;
1092
1093 case LookupResult::Ambiguous:
1094 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1095 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1096 /*AllowDependent=*/false)) {
1097 // C++ [temp.local]p3:
1098 // A lookup that finds an injected-class-name (10.2) can result in an
1099 // ambiguity in certain cases (for example, if it is found in more than
1100 // one base class). If all of the injected-class-names that are found
1101 // refer to specializations of the same class template, and if the name
1102 // is followed by a template-argument-list, the reference refers to the
1103 // class template itself and not a specialization thereof, and is not
1104 // ambiguous.
1105 //
1106 // This filtering can make an ambiguous result into an unambiguous one,
1107 // so try again after filtering out template names.
1108 FilterAcceptableTemplateNames(Result);
1109 if (!Result.isAmbiguous()) {
1110 IsFilteredTemplateName = true;
1111 break;
1112 }
1113 }
1114
1115 // Diagnose the ambiguity and return an error.
1116 return NameClassification::Error();
1117 }
1118
1119 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1120 (IsFilteredTemplateName ||
1121 hasAnyAcceptableTemplateNames(
1122 Result, /*AllowFunctionTemplates=*/true,
1123 /*AllowDependent=*/false,
1124 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1125 getLangOpts().CPlusPlus20))) {
1126 // C++ [temp.names]p3:
1127 // After name lookup (3.4) finds that a name is a template-name or that
1128 // an operator-function-id or a literal- operator-id refers to a set of
1129 // overloaded functions any member of which is a function template if
1130 // this is followed by a <, the < is always taken as the delimiter of a
1131 // template-argument-list and never as the less-than operator.
1132 // C++2a [temp.names]p2:
1133 // A name is also considered to refer to a template if it is an
1134 // unqualified-id followed by a < and name lookup finds either one
1135 // or more functions or finds nothing.
1136 if (!IsFilteredTemplateName)
1137 FilterAcceptableTemplateNames(Result);
1138
1139 bool IsFunctionTemplate;
1140 bool IsVarTemplate;
1141 TemplateName Template;
1142 if (Result.end() - Result.begin() > 1) {
1143 IsFunctionTemplate = true;
1144 Template = Context.getOverloadedTemplateName(Result.begin(),
1145 Result.end());
1146 } else if (!Result.empty()) {
1147 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1148 *Result.begin(), /*AllowFunctionTemplates=*/true,
1149 /*AllowDependent=*/false));
1150 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1151 IsVarTemplate = isa<VarTemplateDecl>(TD);
1152
1153 UsingShadowDecl *FoundUsingShadow =
1154 dyn_cast<UsingShadowDecl>(*Result.begin());
1155 assert(!FoundUsingShadow ||
1156 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1157 Template =
1158 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1159 if (SS.isNotEmpty())
1160 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1161 /*TemplateKeyword=*/false,
1162 Template);
1163 } else {
1164 // All results were non-template functions. This is a function template
1165 // name.
1166 IsFunctionTemplate = true;
1167 Template = Context.getAssumedTemplateName(NameInfo.getName());
1168 }
1169
1170 if (IsFunctionTemplate) {
1171 // Function templates always go through overload resolution, at which
1172 // point we'll perform the various checks (e.g., accessibility) we need
1173 // to based on which function we selected.
1174 Result.suppressDiagnostics();
1175
1176 return NameClassification::FunctionTemplate(Template);
1177 }
1178
1179 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1180 : NameClassification::TypeTemplate(Template);
1181 }
1182
1183 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1184 QualType T = Context.getTypeDeclType(Type);
1185 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1186 T = Context.getUsingType(USD, T);
1187 return buildNamedType(*this, &SS, T, NameLoc);
1188 };
1189
1190 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1191 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1192 DiagnoseUseOfDecl(Type, NameLoc);
1193 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1194 return BuildTypeFor(Type, *Result.begin());
1195 }
1196
1197 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1198 if (!Class) {
1199 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1200 if (ObjCCompatibleAliasDecl *Alias =
1201 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1202 Class = Alias->getClassInterface();
1203 }
1204
1205 if (Class) {
1206 DiagnoseUseOfDecl(Class, NameLoc);
1207
1208 if (NextToken.is(tok::period)) {
1209 // Interface. <something> is parsed as a property reference expression.
1210 // Just return "unknown" as a fall-through for now.
1211 Result.suppressDiagnostics();
1212 return NameClassification::Unknown();
1213 }
1214
1215 QualType T = Context.getObjCInterfaceType(Class);
1216 return ParsedType::make(T);
1217 }
1218
1219 if (isa<ConceptDecl>(FirstDecl))
1220 return NameClassification::Concept(
1221 TemplateName(cast<TemplateDecl>(FirstDecl)));
1222
1223 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1224 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1225 return NameClassification::Error();
1226 }
1227
1228 // We can have a type template here if we're classifying a template argument.
1229 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1230 !isa<VarTemplateDecl>(FirstDecl))
1231 return NameClassification::TypeTemplate(
1232 TemplateName(cast<TemplateDecl>(FirstDecl)));
1233
1234 // Check for a tag type hidden by a non-type decl in a few cases where it
1235 // seems likely a type is wanted instead of the non-type that was found.
1236 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1237 if ((NextToken.is(tok::identifier) ||
1238 (NextIsOp &&
1239 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1240 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1241 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1242 DiagnoseUseOfDecl(Type, NameLoc);
1243 return BuildTypeFor(Type, *Result.begin());
1244 }
1245
1246 // If we already know which single declaration is referenced, just annotate
1247 // that declaration directly. Defer resolving even non-overloaded class
1248 // member accesses, as we need to defer certain access checks until we know
1249 // the context.
1250 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1251 if (Result.isSingleResult() && !ADL &&
1252 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1253 return NameClassification::NonType(Result.getRepresentativeDecl());
1254
1255 // Otherwise, this is an overload set that we will need to resolve later.
1256 Result.suppressDiagnostics();
1257 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1258 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1259 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1260 Result.begin(), Result.end()));
1261 }
1262
1263 ExprResult
ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo * Name,SourceLocation NameLoc)1264 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1265 SourceLocation NameLoc) {
1266 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1267 CXXScopeSpec SS;
1268 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1269 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1270 }
1271
1272 ExprResult
ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,bool IsAddressOfOperand)1273 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1274 IdentifierInfo *Name,
1275 SourceLocation NameLoc,
1276 bool IsAddressOfOperand) {
1277 DeclarationNameInfo NameInfo(Name, NameLoc);
1278 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1279 NameInfo, IsAddressOfOperand,
1280 /*TemplateArgs=*/nullptr);
1281 }
1282
ActOnNameClassifiedAsNonType(Scope * S,const CXXScopeSpec & SS,NamedDecl * Found,SourceLocation NameLoc,const Token & NextToken)1283 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1284 NamedDecl *Found,
1285 SourceLocation NameLoc,
1286 const Token &NextToken) {
1287 if (getCurMethodDecl() && SS.isEmpty())
1288 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1289 return BuildIvarRefExpr(S, NameLoc, Ivar);
1290
1291 // Reconstruct the lookup result.
1292 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1293 Result.addDecl(Found);
1294 Result.resolveKind();
1295
1296 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1297 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1298 }
1299
ActOnNameClassifiedAsOverloadSet(Scope * S,Expr * E)1300 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1301 // For an implicit class member access, transform the result into a member
1302 // access expression if necessary.
1303 auto *ULE = cast<UnresolvedLookupExpr>(E);
1304 if ((*ULE->decls_begin())->isCXXClassMember()) {
1305 CXXScopeSpec SS;
1306 SS.Adopt(ULE->getQualifierLoc());
1307
1308 // Reconstruct the lookup result.
1309 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1310 LookupOrdinaryName);
1311 Result.setNamingClass(ULE->getNamingClass());
1312 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1313 Result.addDecl(*I, I.getAccess());
1314 Result.resolveKind();
1315 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1316 nullptr, S);
1317 }
1318
1319 // Otherwise, this is already in the form we needed, and no further checks
1320 // are necessary.
1321 return ULE;
1322 }
1323
1324 Sema::TemplateNameKindForDiagnostics
getTemplateNameKindForDiagnostics(TemplateName Name)1325 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1326 auto *TD = Name.getAsTemplateDecl();
1327 if (!TD)
1328 return TemplateNameKindForDiagnostics::DependentTemplate;
1329 if (isa<ClassTemplateDecl>(TD))
1330 return TemplateNameKindForDiagnostics::ClassTemplate;
1331 if (isa<FunctionTemplateDecl>(TD))
1332 return TemplateNameKindForDiagnostics::FunctionTemplate;
1333 if (isa<VarTemplateDecl>(TD))
1334 return TemplateNameKindForDiagnostics::VarTemplate;
1335 if (isa<TypeAliasTemplateDecl>(TD))
1336 return TemplateNameKindForDiagnostics::AliasTemplate;
1337 if (isa<TemplateTemplateParmDecl>(TD))
1338 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1339 if (isa<ConceptDecl>(TD))
1340 return TemplateNameKindForDiagnostics::Concept;
1341 return TemplateNameKindForDiagnostics::DependentTemplate;
1342 }
1343
PushDeclContext(Scope * S,DeclContext * DC)1344 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1345 assert(DC->getLexicalParent() == CurContext &&
1346 "The next DeclContext should be lexically contained in the current one.");
1347 CurContext = DC;
1348 S->setEntity(DC);
1349 }
1350
PopDeclContext()1351 void Sema::PopDeclContext() {
1352 assert(CurContext && "DeclContext imbalance!");
1353
1354 CurContext = CurContext->getLexicalParent();
1355 assert(CurContext && "Popped translation unit!");
1356 }
1357
ActOnTagStartSkippedDefinition(Scope * S,Decl * D)1358 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1359 Decl *D) {
1360 // Unlike PushDeclContext, the context to which we return is not necessarily
1361 // the containing DC of TD, because the new context will be some pre-existing
1362 // TagDecl definition instead of a fresh one.
1363 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1364 CurContext = cast<TagDecl>(D)->getDefinition();
1365 assert(CurContext && "skipping definition of undefined tag");
1366 // Start lookups from the parent of the current context; we don't want to look
1367 // into the pre-existing complete definition.
1368 S->setEntity(CurContext->getLookupParent());
1369 return Result;
1370 }
1371
ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)1372 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1373 CurContext = static_cast<decltype(CurContext)>(Context);
1374 }
1375
1376 /// EnterDeclaratorContext - Used when we must lookup names in the context
1377 /// of a declarator's nested name specifier.
1378 ///
EnterDeclaratorContext(Scope * S,DeclContext * DC)1379 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1380 // C++0x [basic.lookup.unqual]p13:
1381 // A name used in the definition of a static data member of class
1382 // X (after the qualified-id of the static member) is looked up as
1383 // if the name was used in a member function of X.
1384 // C++0x [basic.lookup.unqual]p14:
1385 // If a variable member of a namespace is defined outside of the
1386 // scope of its namespace then any name used in the definition of
1387 // the variable member (after the declarator-id) is looked up as
1388 // if the definition of the variable member occurred in its
1389 // namespace.
1390 // Both of these imply that we should push a scope whose context
1391 // is the semantic context of the declaration. We can't use
1392 // PushDeclContext here because that context is not necessarily
1393 // lexically contained in the current context. Fortunately,
1394 // the containing scope should have the appropriate information.
1395
1396 assert(!S->getEntity() && "scope already has entity");
1397
1398 #ifndef NDEBUG
1399 Scope *Ancestor = S->getParent();
1400 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1401 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1402 #endif
1403
1404 CurContext = DC;
1405 S->setEntity(DC);
1406
1407 if (S->getParent()->isTemplateParamScope()) {
1408 // Also set the corresponding entities for all immediately-enclosing
1409 // template parameter scopes.
1410 EnterTemplatedContext(S->getParent(), DC);
1411 }
1412 }
1413
ExitDeclaratorContext(Scope * S)1414 void Sema::ExitDeclaratorContext(Scope *S) {
1415 assert(S->getEntity() == CurContext && "Context imbalance!");
1416
1417 // Switch back to the lexical context. The safety of this is
1418 // enforced by an assert in EnterDeclaratorContext.
1419 Scope *Ancestor = S->getParent();
1420 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1421 CurContext = Ancestor->getEntity();
1422
1423 // We don't need to do anything with the scope, which is going to
1424 // disappear.
1425 }
1426
EnterTemplatedContext(Scope * S,DeclContext * DC)1427 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1428 assert(S->isTemplateParamScope() &&
1429 "expected to be initializing a template parameter scope");
1430
1431 // C++20 [temp.local]p7:
1432 // In the definition of a member of a class template that appears outside
1433 // of the class template definition, the name of a member of the class
1434 // template hides the name of a template-parameter of any enclosing class
1435 // templates (but not a template-parameter of the member if the member is a
1436 // class or function template).
1437 // C++20 [temp.local]p9:
1438 // In the definition of a class template or in the definition of a member
1439 // of such a template that appears outside of the template definition, for
1440 // each non-dependent base class (13.8.2.1), if the name of the base class
1441 // or the name of a member of the base class is the same as the name of a
1442 // template-parameter, the base class name or member name hides the
1443 // template-parameter name (6.4.10).
1444 //
1445 // This means that a template parameter scope should be searched immediately
1446 // after searching the DeclContext for which it is a template parameter
1447 // scope. For example, for
1448 // template<typename T> template<typename U> template<typename V>
1449 // void N::A<T>::B<U>::f(...)
1450 // we search V then B<U> (and base classes) then U then A<T> (and base
1451 // classes) then T then N then ::.
1452 unsigned ScopeDepth = getTemplateDepth(S);
1453 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1454 DeclContext *SearchDCAfterScope = DC;
1455 for (; DC; DC = DC->getLookupParent()) {
1456 if (const TemplateParameterList *TPL =
1457 cast<Decl>(DC)->getDescribedTemplateParams()) {
1458 unsigned DCDepth = TPL->getDepth() + 1;
1459 if (DCDepth > ScopeDepth)
1460 continue;
1461 if (ScopeDepth == DCDepth)
1462 SearchDCAfterScope = DC = DC->getLookupParent();
1463 break;
1464 }
1465 }
1466 S->setLookupEntity(SearchDCAfterScope);
1467 }
1468 }
1469
ActOnReenterFunctionContext(Scope * S,Decl * D)1470 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1471 // We assume that the caller has already called
1472 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1473 FunctionDecl *FD = D->getAsFunction();
1474 if (!FD)
1475 return;
1476
1477 // Same implementation as PushDeclContext, but enters the context
1478 // from the lexical parent, rather than the top-level class.
1479 assert(CurContext == FD->getLexicalParent() &&
1480 "The next DeclContext should be lexically contained in the current one.");
1481 CurContext = FD;
1482 S->setEntity(CurContext);
1483
1484 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1485 ParmVarDecl *Param = FD->getParamDecl(P);
1486 // If the parameter has an identifier, then add it to the scope
1487 if (Param->getIdentifier()) {
1488 S->AddDecl(Param);
1489 IdResolver.AddDecl(Param);
1490 }
1491 }
1492 }
1493
ActOnExitFunctionContext()1494 void Sema::ActOnExitFunctionContext() {
1495 // Same implementation as PopDeclContext, but returns to the lexical parent,
1496 // rather than the top-level class.
1497 assert(CurContext && "DeclContext imbalance!");
1498 CurContext = CurContext->getLexicalParent();
1499 assert(CurContext && "Popped translation unit!");
1500 }
1501
1502 /// Determine whether overloading is allowed for a new function
1503 /// declaration considering prior declarations of the same name.
1504 ///
1505 /// This routine determines whether overloading is possible, not
1506 /// whether a new declaration actually overloads a previous one.
1507 /// It will return true in C++ (where overloads are alway permitted)
1508 /// or, as a C extension, when either the new declaration or a
1509 /// previous one is declared with the 'overloadable' attribute.
AllowOverloadingOfFunction(const LookupResult & Previous,ASTContext & Context,const FunctionDecl * New)1510 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1511 ASTContext &Context,
1512 const FunctionDecl *New) {
1513 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1514 return true;
1515
1516 // Multiversion function declarations are not overloads in the
1517 // usual sense of that term, but lookup will report that an
1518 // overload set was found if more than one multiversion function
1519 // declaration is present for the same name. It is therefore
1520 // inadequate to assume that some prior declaration(s) had
1521 // the overloadable attribute; checking is required. Since one
1522 // declaration is permitted to omit the attribute, it is necessary
1523 // to check at least two; hence the 'any_of' check below. Note that
1524 // the overloadable attribute is implicitly added to declarations
1525 // that were required to have it but did not.
1526 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1527 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1528 return ND->hasAttr<OverloadableAttr>();
1529 });
1530 } else if (Previous.getResultKind() == LookupResult::Found)
1531 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1532
1533 return false;
1534 }
1535
1536 /// Add this decl to the scope shadowed decl chains.
PushOnScopeChains(NamedDecl * D,Scope * S,bool AddToContext)1537 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1538 // Move up the scope chain until we find the nearest enclosing
1539 // non-transparent context. The declaration will be introduced into this
1540 // scope.
1541 while (S->getEntity() && S->getEntity()->isTransparentContext())
1542 S = S->getParent();
1543
1544 // Add scoped declarations into their context, so that they can be
1545 // found later. Declarations without a context won't be inserted
1546 // into any context.
1547 if (AddToContext)
1548 CurContext->addDecl(D);
1549
1550 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1551 // are function-local declarations.
1552 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1553 return;
1554
1555 // Template instantiations should also not be pushed into scope.
1556 if (isa<FunctionDecl>(D) &&
1557 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1558 return;
1559
1560 // If this replaces anything in the current scope,
1561 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1562 IEnd = IdResolver.end();
1563 for (; I != IEnd; ++I) {
1564 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1565 S->RemoveDecl(*I);
1566 IdResolver.RemoveDecl(*I);
1567
1568 // Should only need to replace one decl.
1569 break;
1570 }
1571 }
1572
1573 S->AddDecl(D);
1574
1575 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1576 // Implicitly-generated labels may end up getting generated in an order that
1577 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1578 // the label at the appropriate place in the identifier chain.
1579 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1580 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1581 if (IDC == CurContext) {
1582 if (!S->isDeclScope(*I))
1583 continue;
1584 } else if (IDC->Encloses(CurContext))
1585 break;
1586 }
1587
1588 IdResolver.InsertDeclAfter(I, D);
1589 } else {
1590 IdResolver.AddDecl(D);
1591 }
1592 warnOnReservedIdentifier(D);
1593 }
1594
isDeclInScope(NamedDecl * D,DeclContext * Ctx,Scope * S,bool AllowInlineNamespace)1595 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1596 bool AllowInlineNamespace) {
1597 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1598 }
1599
getScopeForDeclContext(Scope * S,DeclContext * DC)1600 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1601 DeclContext *TargetDC = DC->getPrimaryContext();
1602 do {
1603 if (DeclContext *ScopeDC = S->getEntity())
1604 if (ScopeDC->getPrimaryContext() == TargetDC)
1605 return S;
1606 } while ((S = S->getParent()));
1607
1608 return nullptr;
1609 }
1610
1611 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1612 DeclContext*,
1613 ASTContext&);
1614
1615 /// Filters out lookup results that don't fall within the given scope
1616 /// as determined by isDeclInScope.
FilterLookupForScope(LookupResult & R,DeclContext * Ctx,Scope * S,bool ConsiderLinkage,bool AllowInlineNamespace)1617 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1618 bool ConsiderLinkage,
1619 bool AllowInlineNamespace) {
1620 LookupResult::Filter F = R.makeFilter();
1621 while (F.hasNext()) {
1622 NamedDecl *D = F.next();
1623
1624 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1625 continue;
1626
1627 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1628 continue;
1629
1630 F.erase();
1631 }
1632
1633 F.done();
1634 }
1635
1636 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1637 /// have compatible owning modules.
CheckRedeclarationModuleOwnership(NamedDecl * New,NamedDecl * Old)1638 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1639 // [module.interface]p7:
1640 // A declaration is attached to a module as follows:
1641 // - If the declaration is a non-dependent friend declaration that nominates a
1642 // function with a declarator-id that is a qualified-id or template-id or that
1643 // nominates a class other than with an elaborated-type-specifier with neither
1644 // a nested-name-specifier nor a simple-template-id, it is attached to the
1645 // module to which the friend is attached ([basic.link]).
1646 if (New->getFriendObjectKind() &&
1647 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1648 New->setLocalOwningModule(Old->getOwningModule());
1649 makeMergedDefinitionVisible(New);
1650 return false;
1651 }
1652
1653 Module *NewM = New->getOwningModule();
1654 Module *OldM = Old->getOwningModule();
1655
1656 if (NewM && NewM->isPrivateModule())
1657 NewM = NewM->Parent;
1658 if (OldM && OldM->isPrivateModule())
1659 OldM = OldM->Parent;
1660
1661 if (NewM == OldM)
1662 return false;
1663
1664 // Partitions are part of the module, but a partition could import another
1665 // module, so verify that the PMIs agree.
1666 if (NewM && OldM &&
1667 (NewM->isModulePartition() || OldM->isModulePartition()) &&
1668 NewM->getPrimaryModuleInterfaceName() ==
1669 OldM->getPrimaryModuleInterfaceName())
1670 return false;
1671
1672 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1673 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1674 if (NewIsModuleInterface || OldIsModuleInterface) {
1675 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1676 // if a declaration of D [...] appears in the purview of a module, all
1677 // other such declarations shall appear in the purview of the same module
1678 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1679 << New
1680 << NewIsModuleInterface
1681 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1682 << OldIsModuleInterface
1683 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1684 Diag(Old->getLocation(), diag::note_previous_declaration);
1685 New->setInvalidDecl();
1686 return true;
1687 }
1688
1689 return false;
1690 }
1691
1692 // [module.interface]p6:
1693 // A redeclaration of an entity X is implicitly exported if X was introduced by
1694 // an exported declaration; otherwise it shall not be exported.
CheckRedeclarationExported(NamedDecl * New,NamedDecl * Old)1695 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1696 // [module.interface]p1:
1697 // An export-declaration shall inhabit a namespace scope.
1698 //
1699 // So it is meaningless to talk about redeclaration which is not at namespace
1700 // scope.
1701 if (!New->getLexicalDeclContext()
1702 ->getNonTransparentContext()
1703 ->isFileContext() ||
1704 !Old->getLexicalDeclContext()
1705 ->getNonTransparentContext()
1706 ->isFileContext())
1707 return false;
1708
1709 bool IsNewExported = New->isInExportDeclContext();
1710 bool IsOldExported = Old->isInExportDeclContext();
1711
1712 // It should be irrevelant if both of them are not exported.
1713 if (!IsNewExported && !IsOldExported)
1714 return false;
1715
1716 if (IsOldExported)
1717 return false;
1718
1719 assert(IsNewExported);
1720
1721 auto Lk = Old->getFormalLinkage();
1722 int S = 0;
1723 if (Lk == Linkage::InternalLinkage)
1724 S = 1;
1725 else if (Lk == Linkage::ModuleLinkage)
1726 S = 2;
1727 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1728 Diag(Old->getLocation(), diag::note_previous_declaration);
1729 return true;
1730 }
1731
1732 // A wrapper function for checking the semantic restrictions of
1733 // a redeclaration within a module.
CheckRedeclarationInModule(NamedDecl * New,NamedDecl * Old)1734 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1735 if (CheckRedeclarationModuleOwnership(New, Old))
1736 return true;
1737
1738 if (CheckRedeclarationExported(New, Old))
1739 return true;
1740
1741 return false;
1742 }
1743
1744 // Check the redefinition in C++20 Modules.
1745 //
1746 // [basic.def.odr]p14:
1747 // For any definable item D with definitions in multiple translation units,
1748 // - if D is a non-inline non-templated function or variable, or
1749 // - if the definitions in different translation units do not satisfy the
1750 // following requirements,
1751 // the program is ill-formed; a diagnostic is required only if the definable
1752 // item is attached to a named module and a prior definition is reachable at
1753 // the point where a later definition occurs.
1754 // - Each such definition shall not be attached to a named module
1755 // ([module.unit]).
1756 // - Each such definition shall consist of the same sequence of tokens, ...
1757 // ...
1758 //
1759 // Return true if the redefinition is not allowed. Return false otherwise.
IsRedefinitionInModule(const NamedDecl * New,const NamedDecl * Old) const1760 bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1761 const NamedDecl *Old) const {
1762 assert(getASTContext().isSameEntity(New, Old) &&
1763 "New and Old are not the same definition, we should diagnostic it "
1764 "immediately instead of checking it.");
1765 assert(const_cast<Sema *>(this)->isReachable(New) &&
1766 const_cast<Sema *>(this)->isReachable(Old) &&
1767 "We shouldn't see unreachable definitions here.");
1768
1769 Module *NewM = New->getOwningModule();
1770 Module *OldM = Old->getOwningModule();
1771
1772 // We only checks for named modules here. The header like modules is skipped.
1773 // FIXME: This is not right if we import the header like modules in the module
1774 // purview.
1775 //
1776 // For example, assuming "header.h" provides definition for `D`.
1777 // ```C++
1778 // //--- M.cppm
1779 // export module M;
1780 // import "header.h"; // or #include "header.h" but import it by clang modules
1781 // actually.
1782 //
1783 // //--- Use.cpp
1784 // import M;
1785 // import "header.h"; // or uses clang modules.
1786 // ```
1787 //
1788 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1789 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1790 // reject it. But the current implementation couldn't detect the case since we
1791 // don't record the information about the importee modules.
1792 //
1793 // But this might not be painful in practice. Since the design of C++20 Named
1794 // Modules suggests us to use headers in global module fragment instead of
1795 // module purview.
1796 if (NewM && NewM->isHeaderLikeModule())
1797 NewM = nullptr;
1798 if (OldM && OldM->isHeaderLikeModule())
1799 OldM = nullptr;
1800
1801 if (!NewM && !OldM)
1802 return true;
1803
1804 // [basic.def.odr]p14.3
1805 // Each such definition shall not be attached to a named module
1806 // ([module.unit]).
1807 if ((NewM && NewM->isModulePurview()) || (OldM && OldM->isModulePurview()))
1808 return true;
1809
1810 // Then New and Old lives in the same TU if their share one same module unit.
1811 if (NewM)
1812 NewM = NewM->getTopLevelModule();
1813 if (OldM)
1814 OldM = OldM->getTopLevelModule();
1815 return OldM == NewM;
1816 }
1817
isUsingDecl(NamedDecl * D)1818 static bool isUsingDecl(NamedDecl *D) {
1819 return isa<UsingShadowDecl>(D) ||
1820 isa<UnresolvedUsingTypenameDecl>(D) ||
1821 isa<UnresolvedUsingValueDecl>(D);
1822 }
1823
1824 /// Removes using shadow declarations from the lookup results.
RemoveUsingDecls(LookupResult & R)1825 static void RemoveUsingDecls(LookupResult &R) {
1826 LookupResult::Filter F = R.makeFilter();
1827 while (F.hasNext())
1828 if (isUsingDecl(F.next()))
1829 F.erase();
1830
1831 F.done();
1832 }
1833
1834 /// Check for this common pattern:
1835 /// @code
1836 /// class S {
1837 /// S(const S&); // DO NOT IMPLEMENT
1838 /// void operator=(const S&); // DO NOT IMPLEMENT
1839 /// };
1840 /// @endcode
IsDisallowedCopyOrAssign(const CXXMethodDecl * D)1841 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1842 // FIXME: Should check for private access too but access is set after we get
1843 // the decl here.
1844 if (D->doesThisDeclarationHaveABody())
1845 return false;
1846
1847 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1848 return CD->isCopyConstructor();
1849 return D->isCopyAssignmentOperator();
1850 }
1851
1852 // We need this to handle
1853 //
1854 // typedef struct {
1855 // void *foo() { return 0; }
1856 // } A;
1857 //
1858 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1859 // for example. If 'A', foo will have external linkage. If we have '*A',
1860 // foo will have no linkage. Since we can't know until we get to the end
1861 // of the typedef, this function finds out if D might have non-external linkage.
1862 // Callers should verify at the end of the TU if it D has external linkage or
1863 // not.
mightHaveNonExternalLinkage(const DeclaratorDecl * D)1864 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1865 const DeclContext *DC = D->getDeclContext();
1866 while (!DC->isTranslationUnit()) {
1867 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1868 if (!RD->hasNameForLinkage())
1869 return true;
1870 }
1871 DC = DC->getParent();
1872 }
1873
1874 return !D->isExternallyVisible();
1875 }
1876
1877 // FIXME: This needs to be refactored; some other isInMainFile users want
1878 // these semantics.
isMainFileLoc(const Sema & S,SourceLocation Loc)1879 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1880 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1881 return false;
1882 return S.SourceMgr.isInMainFile(Loc);
1883 }
1884
ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl * D) const1885 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1886 assert(D);
1887
1888 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1889 return false;
1890
1891 // Ignore all entities declared within templates, and out-of-line definitions
1892 // of members of class templates.
1893 if (D->getDeclContext()->isDependentContext() ||
1894 D->getLexicalDeclContext()->isDependentContext())
1895 return false;
1896
1897 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1898 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1899 return false;
1900 // A non-out-of-line declaration of a member specialization was implicitly
1901 // instantiated; it's the out-of-line declaration that we're interested in.
1902 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1903 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1904 return false;
1905
1906 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1907 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1908 return false;
1909 } else {
1910 // 'static inline' functions are defined in headers; don't warn.
1911 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1912 return false;
1913 }
1914
1915 if (FD->doesThisDeclarationHaveABody() &&
1916 Context.DeclMustBeEmitted(FD))
1917 return false;
1918 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1919 // Constants and utility variables are defined in headers with internal
1920 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1921 // like "inline".)
1922 if (!isMainFileLoc(*this, VD->getLocation()))
1923 return false;
1924
1925 if (Context.DeclMustBeEmitted(VD))
1926 return false;
1927
1928 if (VD->isStaticDataMember() &&
1929 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1930 return false;
1931 if (VD->isStaticDataMember() &&
1932 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1933 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1934 return false;
1935
1936 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1937 return false;
1938 } else {
1939 return false;
1940 }
1941
1942 // Only warn for unused decls internal to the translation unit.
1943 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1944 // for inline functions defined in the main source file, for instance.
1945 return mightHaveNonExternalLinkage(D);
1946 }
1947
MarkUnusedFileScopedDecl(const DeclaratorDecl * D)1948 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1949 if (!D)
1950 return;
1951
1952 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1953 const FunctionDecl *First = FD->getFirstDecl();
1954 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1955 return; // First should already be in the vector.
1956 }
1957
1958 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1959 const VarDecl *First = VD->getFirstDecl();
1960 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1961 return; // First should already be in the vector.
1962 }
1963
1964 if (ShouldWarnIfUnusedFileScopedDecl(D))
1965 UnusedFileScopedDecls.push_back(D);
1966 }
1967
ShouldDiagnoseUnusedDecl(const NamedDecl * D)1968 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1969 if (D->isInvalidDecl())
1970 return false;
1971
1972 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1973 // For a decomposition declaration, warn if none of the bindings are
1974 // referenced, instead of if the variable itself is referenced (which
1975 // it is, by the bindings' expressions).
1976 for (auto *BD : DD->bindings())
1977 if (BD->isReferenced())
1978 return false;
1979 } else if (!D->getDeclName()) {
1980 return false;
1981 } else if (D->isReferenced() || D->isUsed()) {
1982 return false;
1983 }
1984
1985 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1986 return false;
1987
1988 if (isa<LabelDecl>(D))
1989 return true;
1990
1991 // Except for labels, we only care about unused decls that are local to
1992 // functions.
1993 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1994 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1995 // For dependent types, the diagnostic is deferred.
1996 WithinFunction =
1997 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1998 if (!WithinFunction)
1999 return false;
2000
2001 if (isa<TypedefNameDecl>(D))
2002 return true;
2003
2004 // White-list anything that isn't a local variable.
2005 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2006 return false;
2007
2008 // Types of valid local variables should be complete, so this should succeed.
2009 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2010
2011 const Expr *Init = VD->getInit();
2012 if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
2013 Init = Cleanups->getSubExpr();
2014
2015 const auto *Ty = VD->getType().getTypePtr();
2016
2017 // Only look at the outermost level of typedef.
2018 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2019 // Allow anything marked with __attribute__((unused)).
2020 if (TT->getDecl()->hasAttr<UnusedAttr>())
2021 return false;
2022 }
2023
2024 // Warn for reference variables whose initializtion performs lifetime
2025 // extension.
2026 if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
2027 if (MTE->getExtendingDecl()) {
2028 Ty = VD->getType().getNonReferenceType().getTypePtr();
2029 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2030 }
2031 }
2032
2033 // If we failed to complete the type for some reason, or if the type is
2034 // dependent, don't diagnose the variable.
2035 if (Ty->isIncompleteType() || Ty->isDependentType())
2036 return false;
2037
2038 // Look at the element type to ensure that the warning behaviour is
2039 // consistent for both scalars and arrays.
2040 Ty = Ty->getBaseElementTypeUnsafe();
2041
2042 if (const TagType *TT = Ty->getAs<TagType>()) {
2043 const TagDecl *Tag = TT->getDecl();
2044 if (Tag->hasAttr<UnusedAttr>())
2045 return false;
2046
2047 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2048 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2049 return false;
2050
2051 if (Init) {
2052 const CXXConstructExpr *Construct =
2053 dyn_cast<CXXConstructExpr>(Init);
2054 if (Construct && !Construct->isElidable()) {
2055 CXXConstructorDecl *CD = Construct->getConstructor();
2056 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2057 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2058 return false;
2059 }
2060
2061 // Suppress the warning if we don't know how this is constructed, and
2062 // it could possibly be non-trivial constructor.
2063 if (Init->isTypeDependent()) {
2064 for (const CXXConstructorDecl *Ctor : RD->ctors())
2065 if (!Ctor->isTrivial())
2066 return false;
2067 }
2068
2069 // Suppress the warning if the constructor is unresolved because
2070 // its arguments are dependent.
2071 if (isa<CXXUnresolvedConstructExpr>(Init))
2072 return false;
2073 }
2074 }
2075 }
2076
2077 // TODO: __attribute__((unused)) templates?
2078 }
2079
2080 return true;
2081 }
2082
GenerateFixForUnusedDecl(const NamedDecl * D,ASTContext & Ctx,FixItHint & Hint)2083 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2084 FixItHint &Hint) {
2085 if (isa<LabelDecl>(D)) {
2086 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2087 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2088 true);
2089 if (AfterColon.isInvalid())
2090 return;
2091 Hint = FixItHint::CreateRemoval(
2092 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2093 }
2094 }
2095
DiagnoseUnusedNestedTypedefs(const RecordDecl * D)2096 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2097 DiagnoseUnusedNestedTypedefs(
2098 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2099 }
2100
DiagnoseUnusedNestedTypedefs(const RecordDecl * D,DiagReceiverTy DiagReceiver)2101 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2102 DiagReceiverTy DiagReceiver) {
2103 if (D->getTypeForDecl()->isDependentType())
2104 return;
2105
2106 for (auto *TmpD : D->decls()) {
2107 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2108 DiagnoseUnusedDecl(T, DiagReceiver);
2109 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2110 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2111 }
2112 }
2113
DiagnoseUnusedDecl(const NamedDecl * D)2114 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2115 DiagnoseUnusedDecl(
2116 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2117 }
2118
2119 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2120 /// unless they are marked attr(unused).
DiagnoseUnusedDecl(const NamedDecl * D,DiagReceiverTy DiagReceiver)2121 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2122 if (!ShouldDiagnoseUnusedDecl(D))
2123 return;
2124
2125 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2126 // typedefs can be referenced later on, so the diagnostics are emitted
2127 // at end-of-translation-unit.
2128 UnusedLocalTypedefNameCandidates.insert(TD);
2129 return;
2130 }
2131
2132 FixItHint Hint;
2133 GenerateFixForUnusedDecl(D, Context, Hint);
2134
2135 unsigned DiagID;
2136 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2137 DiagID = diag::warn_unused_exception_param;
2138 else if (isa<LabelDecl>(D))
2139 DiagID = diag::warn_unused_label;
2140 else
2141 DiagID = diag::warn_unused_variable;
2142
2143 DiagReceiver(D->getLocation(), PDiag(DiagID) << D << Hint);
2144 }
2145
DiagnoseUnusedButSetDecl(const VarDecl * VD,DiagReceiverTy DiagReceiver)2146 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2147 DiagReceiverTy DiagReceiver) {
2148 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2149 // it's not really unused.
2150 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2151 VD->hasAttr<CleanupAttr>())
2152 return;
2153
2154 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2155
2156 if (Ty->isReferenceType() || Ty->isDependentType())
2157 return;
2158
2159 if (const TagType *TT = Ty->getAs<TagType>()) {
2160 const TagDecl *Tag = TT->getDecl();
2161 if (Tag->hasAttr<UnusedAttr>())
2162 return;
2163 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2164 // mimic gcc's behavior.
2165 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2166 if (!RD->hasAttr<WarnUnusedAttr>())
2167 return;
2168 }
2169 }
2170
2171 // Don't warn about __block Objective-C pointer variables, as they might
2172 // be assigned in the block but not used elsewhere for the purpose of lifetime
2173 // extension.
2174 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2175 return;
2176
2177 // Don't warn about Objective-C pointer variables with precise lifetime
2178 // semantics; they can be used to ensure ARC releases the object at a known
2179 // time, which may mean assignment but no other references.
2180 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2181 return;
2182
2183 auto iter = RefsMinusAssignments.find(VD);
2184 if (iter == RefsMinusAssignments.end())
2185 return;
2186
2187 assert(iter->getSecond() >= 0 &&
2188 "Found a negative number of references to a VarDecl");
2189 if (iter->getSecond() != 0)
2190 return;
2191 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2192 : diag::warn_unused_but_set_variable;
2193 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2194 }
2195
CheckPoppedLabel(LabelDecl * L,Sema & S,Sema::DiagReceiverTy DiagReceiver)2196 static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2197 Sema::DiagReceiverTy DiagReceiver) {
2198 // Verify that we have no forward references left. If so, there was a goto
2199 // or address of a label taken, but no definition of it. Label fwd
2200 // definitions are indicated with a null substmt which is also not a resolved
2201 // MS inline assembly label name.
2202 bool Diagnose = false;
2203 if (L->isMSAsmLabel())
2204 Diagnose = !L->isResolvedMSAsmLabel();
2205 else
2206 Diagnose = L->getStmt() == nullptr;
2207 if (Diagnose)
2208 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2209 << L);
2210 }
2211
ActOnPopScope(SourceLocation Loc,Scope * S)2212 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2213 S->applyNRVO();
2214
2215 if (S->decl_empty()) return;
2216 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2217 "Scope shouldn't contain decls!");
2218
2219 /// We visit the decls in non-deterministic order, but we want diagnostics
2220 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2221 /// and sort the diagnostics before emitting them, after we visited all decls.
2222 struct LocAndDiag {
2223 SourceLocation Loc;
2224 std::optional<SourceLocation> PreviousDeclLoc;
2225 PartialDiagnostic PD;
2226 };
2227 SmallVector<LocAndDiag, 16> DeclDiags;
2228 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2229 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2230 };
2231 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2232 SourceLocation PreviousDeclLoc,
2233 PartialDiagnostic PD) {
2234 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2235 };
2236
2237 for (auto *TmpD : S->decls()) {
2238 assert(TmpD && "This decl didn't get pushed??");
2239
2240 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2241 NamedDecl *D = cast<NamedDecl>(TmpD);
2242
2243 // Diagnose unused variables in this scope.
2244 if (!S->hasUnrecoverableErrorOccurred()) {
2245 DiagnoseUnusedDecl(D, addDiag);
2246 if (const auto *RD = dyn_cast<RecordDecl>(D))
2247 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2248 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2249 DiagnoseUnusedButSetDecl(VD, addDiag);
2250 RefsMinusAssignments.erase(VD);
2251 }
2252 }
2253
2254 if (!D->getDeclName()) continue;
2255
2256 // If this was a forward reference to a label, verify it was defined.
2257 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2258 CheckPoppedLabel(LD, *this, addDiag);
2259
2260 // Remove this name from our lexical scope, and warn on it if we haven't
2261 // already.
2262 IdResolver.RemoveDecl(D);
2263 auto ShadowI = ShadowingDecls.find(D);
2264 if (ShadowI != ShadowingDecls.end()) {
2265 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2266 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2267 PDiag(diag::warn_ctor_parm_shadows_field)
2268 << D << FD << FD->getParent());
2269 }
2270 ShadowingDecls.erase(ShadowI);
2271 }
2272 }
2273
2274 llvm::sort(DeclDiags,
2275 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2276 // The particular order for diagnostics is not important, as long
2277 // as the order is deterministic. Using the raw location is going
2278 // to generally be in source order unless there are macro
2279 // expansions involved.
2280 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2281 });
2282 for (const LocAndDiag &D : DeclDiags) {
2283 Diag(D.Loc, D.PD);
2284 if (D.PreviousDeclLoc)
2285 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2286 }
2287 }
2288
2289 /// Look for an Objective-C class in the translation unit.
2290 ///
2291 /// \param Id The name of the Objective-C class we're looking for. If
2292 /// typo-correction fixes this name, the Id will be updated
2293 /// to the fixed name.
2294 ///
2295 /// \param IdLoc The location of the name in the translation unit.
2296 ///
2297 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2298 /// if there is no class with the given name.
2299 ///
2300 /// \returns The declaration of the named Objective-C class, or NULL if the
2301 /// class could not be found.
getObjCInterfaceDecl(IdentifierInfo * & Id,SourceLocation IdLoc,bool DoTypoCorrection)2302 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2303 SourceLocation IdLoc,
2304 bool DoTypoCorrection) {
2305 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2306 // creation from this context.
2307 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2308
2309 if (!IDecl && DoTypoCorrection) {
2310 // Perform typo correction at the given location, but only if we
2311 // find an Objective-C class name.
2312 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2313 if (TypoCorrection C =
2314 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2315 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2316 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2317 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2318 Id = IDecl->getIdentifier();
2319 }
2320 }
2321 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2322 // This routine must always return a class definition, if any.
2323 if (Def && Def->getDefinition())
2324 Def = Def->getDefinition();
2325 return Def;
2326 }
2327
2328 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2329 /// from S, where a non-field would be declared. This routine copes
2330 /// with the difference between C and C++ scoping rules in structs and
2331 /// unions. For example, the following code is well-formed in C but
2332 /// ill-formed in C++:
2333 /// @code
2334 /// struct S6 {
2335 /// enum { BAR } e;
2336 /// };
2337 ///
2338 /// void test_S6() {
2339 /// struct S6 a;
2340 /// a.e = BAR;
2341 /// }
2342 /// @endcode
2343 /// For the declaration of BAR, this routine will return a different
2344 /// scope. The scope S will be the scope of the unnamed enumeration
2345 /// within S6. In C++, this routine will return the scope associated
2346 /// with S6, because the enumeration's scope is a transparent
2347 /// context but structures can contain non-field names. In C, this
2348 /// routine will return the translation unit scope, since the
2349 /// enumeration's scope is a transparent context and structures cannot
2350 /// contain non-field names.
getNonFieldDeclScope(Scope * S)2351 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2352 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2353 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2354 (S->isClassScope() && !getLangOpts().CPlusPlus))
2355 S = S->getParent();
2356 return S;
2357 }
2358
getHeaderName(Builtin::Context & BuiltinInfo,unsigned ID,ASTContext::GetBuiltinTypeError Error)2359 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2360 ASTContext::GetBuiltinTypeError Error) {
2361 switch (Error) {
2362 case ASTContext::GE_None:
2363 return "";
2364 case ASTContext::GE_Missing_type:
2365 return BuiltinInfo.getHeaderName(ID);
2366 case ASTContext::GE_Missing_stdio:
2367 return "stdio.h";
2368 case ASTContext::GE_Missing_setjmp:
2369 return "setjmp.h";
2370 case ASTContext::GE_Missing_ucontext:
2371 return "ucontext.h";
2372 }
2373 llvm_unreachable("unhandled error kind");
2374 }
2375
CreateBuiltin(IdentifierInfo * II,QualType Type,unsigned ID,SourceLocation Loc)2376 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2377 unsigned ID, SourceLocation Loc) {
2378 DeclContext *Parent = Context.getTranslationUnitDecl();
2379
2380 if (getLangOpts().CPlusPlus) {
2381 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2382 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2383 CLinkageDecl->setImplicit();
2384 Parent->addDecl(CLinkageDecl);
2385 Parent = CLinkageDecl;
2386 }
2387
2388 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2389 /*TInfo=*/nullptr, SC_Extern,
2390 getCurFPFeatures().isFPConstrained(),
2391 false, Type->isFunctionProtoType());
2392 New->setImplicit();
2393 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2394
2395 // Create Decl objects for each parameter, adding them to the
2396 // FunctionDecl.
2397 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2398 SmallVector<ParmVarDecl *, 16> Params;
2399 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2400 ParmVarDecl *parm = ParmVarDecl::Create(
2401 Context, New, SourceLocation(), SourceLocation(), nullptr,
2402 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2403 parm->setScopeInfo(0, i);
2404 Params.push_back(parm);
2405 }
2406 New->setParams(Params);
2407 }
2408
2409 AddKnownFunctionAttributes(New);
2410 return New;
2411 }
2412
2413 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2414 /// file scope. lazily create a decl for it. ForRedeclaration is true
2415 /// if we're creating this built-in in anticipation of redeclaring the
2416 /// built-in.
LazilyCreateBuiltin(IdentifierInfo * II,unsigned ID,Scope * S,bool ForRedeclaration,SourceLocation Loc)2417 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2418 Scope *S, bool ForRedeclaration,
2419 SourceLocation Loc) {
2420 LookupNecessaryTypesForBuiltin(S, ID);
2421
2422 ASTContext::GetBuiltinTypeError Error;
2423 QualType R = Context.GetBuiltinType(ID, Error);
2424 if (Error) {
2425 if (!ForRedeclaration)
2426 return nullptr;
2427
2428 // If we have a builtin without an associated type we should not emit a
2429 // warning when we were not able to find a type for it.
2430 if (Error == ASTContext::GE_Missing_type ||
2431 Context.BuiltinInfo.allowTypeMismatch(ID))
2432 return nullptr;
2433
2434 // If we could not find a type for setjmp it is because the jmp_buf type was
2435 // not defined prior to the setjmp declaration.
2436 if (Error == ASTContext::GE_Missing_setjmp) {
2437 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2438 << Context.BuiltinInfo.getName(ID);
2439 return nullptr;
2440 }
2441
2442 // Generally, we emit a warning that the declaration requires the
2443 // appropriate header.
2444 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2445 << getHeaderName(Context.BuiltinInfo, ID, Error)
2446 << Context.BuiltinInfo.getName(ID);
2447 return nullptr;
2448 }
2449
2450 if (!ForRedeclaration &&
2451 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2452 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2453 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2454 : diag::ext_implicit_lib_function_decl)
2455 << Context.BuiltinInfo.getName(ID) << R;
2456 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2457 Diag(Loc, diag::note_include_header_or_declare)
2458 << Header << Context.BuiltinInfo.getName(ID);
2459 }
2460
2461 if (R.isNull())
2462 return nullptr;
2463
2464 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2465 RegisterLocallyScopedExternCDecl(New, S);
2466
2467 // TUScope is the translation-unit scope to insert this function into.
2468 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2469 // relate Scopes to DeclContexts, and probably eliminate CurContext
2470 // entirely, but we're not there yet.
2471 DeclContext *SavedContext = CurContext;
2472 CurContext = New->getDeclContext();
2473 PushOnScopeChains(New, TUScope);
2474 CurContext = SavedContext;
2475 return New;
2476 }
2477
2478 /// Typedef declarations don't have linkage, but they still denote the same
2479 /// entity if their types are the same.
2480 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2481 /// isSameEntity.
filterNonConflictingPreviousTypedefDecls(Sema & S,TypedefNameDecl * Decl,LookupResult & Previous)2482 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2483 TypedefNameDecl *Decl,
2484 LookupResult &Previous) {
2485 // This is only interesting when modules are enabled.
2486 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2487 return;
2488
2489 // Empty sets are uninteresting.
2490 if (Previous.empty())
2491 return;
2492
2493 LookupResult::Filter Filter = Previous.makeFilter();
2494 while (Filter.hasNext()) {
2495 NamedDecl *Old = Filter.next();
2496
2497 // Non-hidden declarations are never ignored.
2498 if (S.isVisible(Old))
2499 continue;
2500
2501 // Declarations of the same entity are not ignored, even if they have
2502 // different linkages.
2503 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2504 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2505 Decl->getUnderlyingType()))
2506 continue;
2507
2508 // If both declarations give a tag declaration a typedef name for linkage
2509 // purposes, then they declare the same entity.
2510 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2511 Decl->getAnonDeclWithTypedefName())
2512 continue;
2513 }
2514
2515 Filter.erase();
2516 }
2517
2518 Filter.done();
2519 }
2520
isIncompatibleTypedef(TypeDecl * Old,TypedefNameDecl * New)2521 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2522 QualType OldType;
2523 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2524 OldType = OldTypedef->getUnderlyingType();
2525 else
2526 OldType = Context.getTypeDeclType(Old);
2527 QualType NewType = New->getUnderlyingType();
2528
2529 if (NewType->isVariablyModifiedType()) {
2530 // Must not redefine a typedef with a variably-modified type.
2531 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2532 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2533 << Kind << NewType;
2534 if (Old->getLocation().isValid())
2535 notePreviousDefinition(Old, New->getLocation());
2536 New->setInvalidDecl();
2537 return true;
2538 }
2539
2540 if (OldType != NewType &&
2541 !OldType->isDependentType() &&
2542 !NewType->isDependentType() &&
2543 !Context.hasSameType(OldType, NewType)) {
2544 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2545 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2546 << Kind << NewType << OldType;
2547 if (Old->getLocation().isValid())
2548 notePreviousDefinition(Old, New->getLocation());
2549 New->setInvalidDecl();
2550 return true;
2551 }
2552 return false;
2553 }
2554
2555 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2556 /// same name and scope as a previous declaration 'Old'. Figure out
2557 /// how to resolve this situation, merging decls or emitting
2558 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2559 ///
MergeTypedefNameDecl(Scope * S,TypedefNameDecl * New,LookupResult & OldDecls)2560 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2561 LookupResult &OldDecls) {
2562 // If the new decl is known invalid already, don't bother doing any
2563 // merging checks.
2564 if (New->isInvalidDecl()) return;
2565
2566 // Allow multiple definitions for ObjC built-in typedefs.
2567 // FIXME: Verify the underlying types are equivalent!
2568 if (getLangOpts().ObjC) {
2569 const IdentifierInfo *TypeID = New->getIdentifier();
2570 switch (TypeID->getLength()) {
2571 default: break;
2572 case 2:
2573 {
2574 if (!TypeID->isStr("id"))
2575 break;
2576 QualType T = New->getUnderlyingType();
2577 if (!T->isPointerType())
2578 break;
2579 if (!T->isVoidPointerType()) {
2580 QualType PT = T->castAs<PointerType>()->getPointeeType();
2581 if (!PT->isStructureType())
2582 break;
2583 }
2584 Context.setObjCIdRedefinitionType(T);
2585 // Install the built-in type for 'id', ignoring the current definition.
2586 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2587 return;
2588 }
2589 case 5:
2590 if (!TypeID->isStr("Class"))
2591 break;
2592 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2593 // Install the built-in type for 'Class', ignoring the current definition.
2594 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2595 return;
2596 case 3:
2597 if (!TypeID->isStr("SEL"))
2598 break;
2599 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2600 // Install the built-in type for 'SEL', ignoring the current definition.
2601 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2602 return;
2603 }
2604 // Fall through - the typedef name was not a builtin type.
2605 }
2606
2607 // Verify the old decl was also a type.
2608 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2609 if (!Old) {
2610 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2611 << New->getDeclName();
2612
2613 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2614 if (OldD->getLocation().isValid())
2615 notePreviousDefinition(OldD, New->getLocation());
2616
2617 return New->setInvalidDecl();
2618 }
2619
2620 // If the old declaration is invalid, just give up here.
2621 if (Old->isInvalidDecl())
2622 return New->setInvalidDecl();
2623
2624 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2625 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2626 auto *NewTag = New->getAnonDeclWithTypedefName();
2627 NamedDecl *Hidden = nullptr;
2628 if (OldTag && NewTag &&
2629 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2630 !hasVisibleDefinition(OldTag, &Hidden)) {
2631 // There is a definition of this tag, but it is not visible. Use it
2632 // instead of our tag.
2633 New->setTypeForDecl(OldTD->getTypeForDecl());
2634 if (OldTD->isModed())
2635 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2636 OldTD->getUnderlyingType());
2637 else
2638 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2639
2640 // Make the old tag definition visible.
2641 makeMergedDefinitionVisible(Hidden);
2642
2643 // If this was an unscoped enumeration, yank all of its enumerators
2644 // out of the scope.
2645 if (isa<EnumDecl>(NewTag)) {
2646 Scope *EnumScope = getNonFieldDeclScope(S);
2647 for (auto *D : NewTag->decls()) {
2648 auto *ED = cast<EnumConstantDecl>(D);
2649 assert(EnumScope->isDeclScope(ED));
2650 EnumScope->RemoveDecl(ED);
2651 IdResolver.RemoveDecl(ED);
2652 ED->getLexicalDeclContext()->removeDecl(ED);
2653 }
2654 }
2655 }
2656 }
2657
2658 // If the typedef types are not identical, reject them in all languages and
2659 // with any extensions enabled.
2660 if (isIncompatibleTypedef(Old, New))
2661 return;
2662
2663 // The types match. Link up the redeclaration chain and merge attributes if
2664 // the old declaration was a typedef.
2665 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2666 New->setPreviousDecl(Typedef);
2667 mergeDeclAttributes(New, Old);
2668 }
2669
2670 if (getLangOpts().MicrosoftExt)
2671 return;
2672
2673 if (getLangOpts().CPlusPlus) {
2674 // C++ [dcl.typedef]p2:
2675 // In a given non-class scope, a typedef specifier can be used to
2676 // redefine the name of any type declared in that scope to refer
2677 // to the type to which it already refers.
2678 if (!isa<CXXRecordDecl>(CurContext))
2679 return;
2680
2681 // C++0x [dcl.typedef]p4:
2682 // In a given class scope, a typedef specifier can be used to redefine
2683 // any class-name declared in that scope that is not also a typedef-name
2684 // to refer to the type to which it already refers.
2685 //
2686 // This wording came in via DR424, which was a correction to the
2687 // wording in DR56, which accidentally banned code like:
2688 //
2689 // struct S {
2690 // typedef struct A { } A;
2691 // };
2692 //
2693 // in the C++03 standard. We implement the C++0x semantics, which
2694 // allow the above but disallow
2695 //
2696 // struct S {
2697 // typedef int I;
2698 // typedef int I;
2699 // };
2700 //
2701 // since that was the intent of DR56.
2702 if (!isa<TypedefNameDecl>(Old))
2703 return;
2704
2705 Diag(New->getLocation(), diag::err_redefinition)
2706 << New->getDeclName();
2707 notePreviousDefinition(Old, New->getLocation());
2708 return New->setInvalidDecl();
2709 }
2710
2711 // Modules always permit redefinition of typedefs, as does C11.
2712 if (getLangOpts().Modules || getLangOpts().C11)
2713 return;
2714
2715 // If we have a redefinition of a typedef in C, emit a warning. This warning
2716 // is normally mapped to an error, but can be controlled with
2717 // -Wtypedef-redefinition. If either the original or the redefinition is
2718 // in a system header, don't emit this for compatibility with GCC.
2719 if (getDiagnostics().getSuppressSystemWarnings() &&
2720 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2721 (Old->isImplicit() ||
2722 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2723 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2724 return;
2725
2726 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2727 << New->getDeclName();
2728 notePreviousDefinition(Old, New->getLocation());
2729 }
2730
2731 /// DeclhasAttr - returns true if decl Declaration already has the target
2732 /// attribute.
DeclHasAttr(const Decl * D,const Attr * A)2733 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2734 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2735 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2736 for (const auto *i : D->attrs())
2737 if (i->getKind() == A->getKind()) {
2738 if (Ann) {
2739 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2740 return true;
2741 continue;
2742 }
2743 // FIXME: Don't hardcode this check
2744 if (OA && isa<OwnershipAttr>(i))
2745 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2746 return true;
2747 }
2748
2749 return false;
2750 }
2751
isAttributeTargetADefinition(Decl * D)2752 static bool isAttributeTargetADefinition(Decl *D) {
2753 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2754 return VD->isThisDeclarationADefinition();
2755 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2756 return TD->isCompleteDefinition() || TD->isBeingDefined();
2757 return true;
2758 }
2759
2760 /// Merge alignment attributes from \p Old to \p New, taking into account the
2761 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2762 ///
2763 /// \return \c true if any attributes were added to \p New.
mergeAlignedAttrs(Sema & S,NamedDecl * New,Decl * Old)2764 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2765 // Look for alignas attributes on Old, and pick out whichever attribute
2766 // specifies the strictest alignment requirement.
2767 AlignedAttr *OldAlignasAttr = nullptr;
2768 AlignedAttr *OldStrictestAlignAttr = nullptr;
2769 unsigned OldAlign = 0;
2770 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2771 // FIXME: We have no way of representing inherited dependent alignments
2772 // in a case like:
2773 // template<int A, int B> struct alignas(A) X;
2774 // template<int A, int B> struct alignas(B) X {};
2775 // For now, we just ignore any alignas attributes which are not on the
2776 // definition in such a case.
2777 if (I->isAlignmentDependent())
2778 return false;
2779
2780 if (I->isAlignas())
2781 OldAlignasAttr = I;
2782
2783 unsigned Align = I->getAlignment(S.Context);
2784 if (Align > OldAlign) {
2785 OldAlign = Align;
2786 OldStrictestAlignAttr = I;
2787 }
2788 }
2789
2790 // Look for alignas attributes on New.
2791 AlignedAttr *NewAlignasAttr = nullptr;
2792 unsigned NewAlign = 0;
2793 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2794 if (I->isAlignmentDependent())
2795 return false;
2796
2797 if (I->isAlignas())
2798 NewAlignasAttr = I;
2799
2800 unsigned Align = I->getAlignment(S.Context);
2801 if (Align > NewAlign)
2802 NewAlign = Align;
2803 }
2804
2805 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2806 // Both declarations have 'alignas' attributes. We require them to match.
2807 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2808 // fall short. (If two declarations both have alignas, they must both match
2809 // every definition, and so must match each other if there is a definition.)
2810
2811 // If either declaration only contains 'alignas(0)' specifiers, then it
2812 // specifies the natural alignment for the type.
2813 if (OldAlign == 0 || NewAlign == 0) {
2814 QualType Ty;
2815 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2816 Ty = VD->getType();
2817 else
2818 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2819
2820 if (OldAlign == 0)
2821 OldAlign = S.Context.getTypeAlign(Ty);
2822 if (NewAlign == 0)
2823 NewAlign = S.Context.getTypeAlign(Ty);
2824 }
2825
2826 if (OldAlign != NewAlign) {
2827 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2828 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2829 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2830 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2831 }
2832 }
2833
2834 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2835 // C++11 [dcl.align]p6:
2836 // if any declaration of an entity has an alignment-specifier,
2837 // every defining declaration of that entity shall specify an
2838 // equivalent alignment.
2839 // C11 6.7.5/7:
2840 // If the definition of an object does not have an alignment
2841 // specifier, any other declaration of that object shall also
2842 // have no alignment specifier.
2843 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2844 << OldAlignasAttr;
2845 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2846 << OldAlignasAttr;
2847 }
2848
2849 bool AnyAdded = false;
2850
2851 // Ensure we have an attribute representing the strictest alignment.
2852 if (OldAlign > NewAlign) {
2853 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2854 Clone->setInherited(true);
2855 New->addAttr(Clone);
2856 AnyAdded = true;
2857 }
2858
2859 // Ensure we have an alignas attribute if the old declaration had one.
2860 if (OldAlignasAttr && !NewAlignasAttr &&
2861 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2862 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2863 Clone->setInherited(true);
2864 New->addAttr(Clone);
2865 AnyAdded = true;
2866 }
2867
2868 return AnyAdded;
2869 }
2870
2871 #define WANT_DECL_MERGE_LOGIC
2872 #include "clang/Sema/AttrParsedAttrImpl.inc"
2873 #undef WANT_DECL_MERGE_LOGIC
2874
mergeDeclAttribute(Sema & S,NamedDecl * D,const InheritableAttr * Attr,Sema::AvailabilityMergeKind AMK)2875 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2876 const InheritableAttr *Attr,
2877 Sema::AvailabilityMergeKind AMK) {
2878 // Diagnose any mutual exclusions between the attribute that we want to add
2879 // and attributes that already exist on the declaration.
2880 if (!DiagnoseMutualExclusions(S, D, Attr))
2881 return false;
2882
2883 // This function copies an attribute Attr from a previous declaration to the
2884 // new declaration D if the new declaration doesn't itself have that attribute
2885 // yet or if that attribute allows duplicates.
2886 // If you're adding a new attribute that requires logic different from
2887 // "use explicit attribute on decl if present, else use attribute from
2888 // previous decl", for example if the attribute needs to be consistent
2889 // between redeclarations, you need to call a custom merge function here.
2890 InheritableAttr *NewAttr = nullptr;
2891 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2892 NewAttr = S.mergeAvailabilityAttr(
2893 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2894 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2895 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2896 AA->getPriority());
2897 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2898 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2899 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2900 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2901 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2902 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2903 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2904 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2905 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2906 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2907 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2908 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2909 FA->getFirstArg());
2910 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2911 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2912 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2913 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2914 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2915 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2916 IA->getInheritanceModel());
2917 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2918 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2919 &S.Context.Idents.get(AA->getSpelling()));
2920 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2921 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2922 isa<CUDAGlobalAttr>(Attr))) {
2923 // CUDA target attributes are part of function signature for
2924 // overloading purposes and must not be merged.
2925 return false;
2926 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2927 NewAttr = S.mergeMinSizeAttr(D, *MA);
2928 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2929 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2930 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2931 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2932 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2933 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2934 else if (isa<AlignedAttr>(Attr))
2935 // AlignedAttrs are handled separately, because we need to handle all
2936 // such attributes on a declaration at the same time.
2937 NewAttr = nullptr;
2938 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2939 (AMK == Sema::AMK_Override ||
2940 AMK == Sema::AMK_ProtocolImplementation ||
2941 AMK == Sema::AMK_OptionalProtocolImplementation))
2942 NewAttr = nullptr;
2943 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2944 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2945 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2946 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2947 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2948 NewAttr = S.mergeImportNameAttr(D, *INA);
2949 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2950 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2951 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2952 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2953 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2954 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2955 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2956 NewAttr =
2957 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2958 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2959 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2960 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2961 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2962
2963 if (NewAttr) {
2964 NewAttr->setInherited(true);
2965 D->addAttr(NewAttr);
2966 if (isa<MSInheritanceAttr>(NewAttr))
2967 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2968 return true;
2969 }
2970
2971 return false;
2972 }
2973
getDefinition(const Decl * D)2974 static const NamedDecl *getDefinition(const Decl *D) {
2975 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2976 return TD->getDefinition();
2977 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2978 const VarDecl *Def = VD->getDefinition();
2979 if (Def)
2980 return Def;
2981 return VD->getActingDefinition();
2982 }
2983 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2984 const FunctionDecl *Def = nullptr;
2985 if (FD->isDefined(Def, true))
2986 return Def;
2987 }
2988 return nullptr;
2989 }
2990
hasAttribute(const Decl * D,attr::Kind Kind)2991 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2992 for (const auto *Attribute : D->attrs())
2993 if (Attribute->getKind() == Kind)
2994 return true;
2995 return false;
2996 }
2997
2998 /// checkNewAttributesAfterDef - If we already have a definition, check that
2999 /// there are no new attributes in this declaration.
checkNewAttributesAfterDef(Sema & S,Decl * New,const Decl * Old)3000 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3001 if (!New->hasAttrs())
3002 return;
3003
3004 const NamedDecl *Def = getDefinition(Old);
3005 if (!Def || Def == New)
3006 return;
3007
3008 AttrVec &NewAttributes = New->getAttrs();
3009 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3010 const Attr *NewAttribute = NewAttributes[I];
3011
3012 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3013 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3014 Sema::SkipBodyInfo SkipBody;
3015 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3016
3017 // If we're skipping this definition, drop the "alias" attribute.
3018 if (SkipBody.ShouldSkip) {
3019 NewAttributes.erase(NewAttributes.begin() + I);
3020 --E;
3021 continue;
3022 }
3023 } else {
3024 VarDecl *VD = cast<VarDecl>(New);
3025 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3026 VarDecl::TentativeDefinition
3027 ? diag::err_alias_after_tentative
3028 : diag::err_redefinition;
3029 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3030 if (Diag == diag::err_redefinition)
3031 S.notePreviousDefinition(Def, VD->getLocation());
3032 else
3033 S.Diag(Def->getLocation(), diag::note_previous_definition);
3034 VD->setInvalidDecl();
3035 }
3036 ++I;
3037 continue;
3038 }
3039
3040 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3041 // Tentative definitions are only interesting for the alias check above.
3042 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3043 ++I;
3044 continue;
3045 }
3046 }
3047
3048 if (hasAttribute(Def, NewAttribute->getKind())) {
3049 ++I;
3050 continue; // regular attr merging will take care of validating this.
3051 }
3052
3053 if (isa<C11NoReturnAttr>(NewAttribute)) {
3054 // C's _Noreturn is allowed to be added to a function after it is defined.
3055 ++I;
3056 continue;
3057 } else if (isa<UuidAttr>(NewAttribute)) {
3058 // msvc will allow a subsequent definition to add an uuid to a class
3059 ++I;
3060 continue;
3061 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3062 if (AA->isAlignas()) {
3063 // C++11 [dcl.align]p6:
3064 // if any declaration of an entity has an alignment-specifier,
3065 // every defining declaration of that entity shall specify an
3066 // equivalent alignment.
3067 // C11 6.7.5/7:
3068 // If the definition of an object does not have an alignment
3069 // specifier, any other declaration of that object shall also
3070 // have no alignment specifier.
3071 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3072 << AA;
3073 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3074 << AA;
3075 NewAttributes.erase(NewAttributes.begin() + I);
3076 --E;
3077 continue;
3078 }
3079 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3080 // If there is a C definition followed by a redeclaration with this
3081 // attribute then there are two different definitions. In C++, prefer the
3082 // standard diagnostics.
3083 if (!S.getLangOpts().CPlusPlus) {
3084 S.Diag(NewAttribute->getLocation(),
3085 diag::err_loader_uninitialized_redeclaration);
3086 S.Diag(Def->getLocation(), diag::note_previous_definition);
3087 NewAttributes.erase(NewAttributes.begin() + I);
3088 --E;
3089 continue;
3090 }
3091 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3092 cast<VarDecl>(New)->isInline() &&
3093 !cast<VarDecl>(New)->isInlineSpecified()) {
3094 // Don't warn about applying selectany to implicitly inline variables.
3095 // Older compilers and language modes would require the use of selectany
3096 // to make such variables inline, and it would have no effect if we
3097 // honored it.
3098 ++I;
3099 continue;
3100 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3101 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3102 // declarations after definitions.
3103 ++I;
3104 continue;
3105 }
3106
3107 S.Diag(NewAttribute->getLocation(),
3108 diag::warn_attribute_precede_definition);
3109 S.Diag(Def->getLocation(), diag::note_previous_definition);
3110 NewAttributes.erase(NewAttributes.begin() + I);
3111 --E;
3112 }
3113 }
3114
diagnoseMissingConstinit(Sema & S,const VarDecl * InitDecl,const ConstInitAttr * CIAttr,bool AttrBeforeInit)3115 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3116 const ConstInitAttr *CIAttr,
3117 bool AttrBeforeInit) {
3118 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3119
3120 // Figure out a good way to write this specifier on the old declaration.
3121 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3122 // enough of the attribute list spelling information to extract that without
3123 // heroics.
3124 std::string SuitableSpelling;
3125 if (S.getLangOpts().CPlusPlus20)
3126 SuitableSpelling = std::string(
3127 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3128 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3129 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3130 InsertLoc, {tok::l_square, tok::l_square,
3131 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3132 S.PP.getIdentifierInfo("require_constant_initialization"),
3133 tok::r_square, tok::r_square}));
3134 if (SuitableSpelling.empty())
3135 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3136 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3137 S.PP.getIdentifierInfo("require_constant_initialization"),
3138 tok::r_paren, tok::r_paren}));
3139 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3140 SuitableSpelling = "constinit";
3141 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3142 SuitableSpelling = "[[clang::require_constant_initialization]]";
3143 if (SuitableSpelling.empty())
3144 SuitableSpelling = "__attribute__((require_constant_initialization))";
3145 SuitableSpelling += " ";
3146
3147 if (AttrBeforeInit) {
3148 // extern constinit int a;
3149 // int a = 0; // error (missing 'constinit'), accepted as extension
3150 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3151 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3152 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3153 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3154 } else {
3155 // int a = 0;
3156 // constinit extern int a; // error (missing 'constinit')
3157 S.Diag(CIAttr->getLocation(),
3158 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3159 : diag::warn_require_const_init_added_too_late)
3160 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3161 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3162 << CIAttr->isConstinit()
3163 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3164 }
3165 }
3166
3167 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
mergeDeclAttributes(NamedDecl * New,Decl * Old,AvailabilityMergeKind AMK)3168 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3169 AvailabilityMergeKind AMK) {
3170 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3171 UsedAttr *NewAttr = OldAttr->clone(Context);
3172 NewAttr->setInherited(true);
3173 New->addAttr(NewAttr);
3174 }
3175 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3176 RetainAttr *NewAttr = OldAttr->clone(Context);
3177 NewAttr->setInherited(true);
3178 New->addAttr(NewAttr);
3179 }
3180
3181 if (!Old->hasAttrs() && !New->hasAttrs())
3182 return;
3183
3184 // [dcl.constinit]p1:
3185 // If the [constinit] specifier is applied to any declaration of a
3186 // variable, it shall be applied to the initializing declaration.
3187 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3188 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3189 if (bool(OldConstInit) != bool(NewConstInit)) {
3190 const auto *OldVD = cast<VarDecl>(Old);
3191 auto *NewVD = cast<VarDecl>(New);
3192
3193 // Find the initializing declaration. Note that we might not have linked
3194 // the new declaration into the redeclaration chain yet.
3195 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3196 if (!InitDecl &&
3197 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3198 InitDecl = NewVD;
3199
3200 if (InitDecl == NewVD) {
3201 // This is the initializing declaration. If it would inherit 'constinit',
3202 // that's ill-formed. (Note that we do not apply this to the attribute
3203 // form).
3204 if (OldConstInit && OldConstInit->isConstinit())
3205 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3206 /*AttrBeforeInit=*/true);
3207 } else if (NewConstInit) {
3208 // This is the first time we've been told that this declaration should
3209 // have a constant initializer. If we already saw the initializing
3210 // declaration, this is too late.
3211 if (InitDecl && InitDecl != NewVD) {
3212 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3213 /*AttrBeforeInit=*/false);
3214 NewVD->dropAttr<ConstInitAttr>();
3215 }
3216 }
3217 }
3218
3219 // Attributes declared post-definition are currently ignored.
3220 checkNewAttributesAfterDef(*this, New, Old);
3221
3222 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3223 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3224 if (!OldA->isEquivalent(NewA)) {
3225 // This redeclaration changes __asm__ label.
3226 Diag(New->getLocation(), diag::err_different_asm_label);
3227 Diag(OldA->getLocation(), diag::note_previous_declaration);
3228 }
3229 } else if (Old->isUsed()) {
3230 // This redeclaration adds an __asm__ label to a declaration that has
3231 // already been ODR-used.
3232 Diag(New->getLocation(), diag::err_late_asm_label_name)
3233 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3234 }
3235 }
3236
3237 // Re-declaration cannot add abi_tag's.
3238 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3239 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3240 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3241 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3242 Diag(NewAbiTagAttr->getLocation(),
3243 diag::err_new_abi_tag_on_redeclaration)
3244 << NewTag;
3245 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3246 }
3247 }
3248 } else {
3249 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3250 Diag(Old->getLocation(), diag::note_previous_declaration);
3251 }
3252 }
3253
3254 // This redeclaration adds a section attribute.
3255 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3256 if (auto *VD = dyn_cast<VarDecl>(New)) {
3257 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3258 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3259 Diag(Old->getLocation(), diag::note_previous_declaration);
3260 }
3261 }
3262 }
3263
3264 // Redeclaration adds code-seg attribute.
3265 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3266 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3267 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3268 Diag(New->getLocation(), diag::warn_mismatched_section)
3269 << 0 /*codeseg*/;
3270 Diag(Old->getLocation(), diag::note_previous_declaration);
3271 }
3272
3273 if (!Old->hasAttrs())
3274 return;
3275
3276 bool foundAny = New->hasAttrs();
3277
3278 // Ensure that any moving of objects within the allocated map is done before
3279 // we process them.
3280 if (!foundAny) New->setAttrs(AttrVec());
3281
3282 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3283 // Ignore deprecated/unavailable/availability attributes if requested.
3284 AvailabilityMergeKind LocalAMK = AMK_None;
3285 if (isa<DeprecatedAttr>(I) ||
3286 isa<UnavailableAttr>(I) ||
3287 isa<AvailabilityAttr>(I)) {
3288 switch (AMK) {
3289 case AMK_None:
3290 continue;
3291
3292 case AMK_Redeclaration:
3293 case AMK_Override:
3294 case AMK_ProtocolImplementation:
3295 case AMK_OptionalProtocolImplementation:
3296 LocalAMK = AMK;
3297 break;
3298 }
3299 }
3300
3301 // Already handled.
3302 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3303 continue;
3304
3305 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3306 foundAny = true;
3307 }
3308
3309 if (mergeAlignedAttrs(*this, New, Old))
3310 foundAny = true;
3311
3312 if (!foundAny) New->dropAttrs();
3313 }
3314
3315 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3316 /// to the new one.
mergeParamDeclAttributes(ParmVarDecl * newDecl,const ParmVarDecl * oldDecl,Sema & S)3317 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3318 const ParmVarDecl *oldDecl,
3319 Sema &S) {
3320 // C++11 [dcl.attr.depend]p2:
3321 // The first declaration of a function shall specify the
3322 // carries_dependency attribute for its declarator-id if any declaration
3323 // of the function specifies the carries_dependency attribute.
3324 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3325 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3326 S.Diag(CDA->getLocation(),
3327 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3328 // Find the first declaration of the parameter.
3329 // FIXME: Should we build redeclaration chains for function parameters?
3330 const FunctionDecl *FirstFD =
3331 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3332 const ParmVarDecl *FirstVD =
3333 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3334 S.Diag(FirstVD->getLocation(),
3335 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3336 }
3337
3338 if (!oldDecl->hasAttrs())
3339 return;
3340
3341 bool foundAny = newDecl->hasAttrs();
3342
3343 // Ensure that any moving of objects within the allocated map is
3344 // done before we process them.
3345 if (!foundAny) newDecl->setAttrs(AttrVec());
3346
3347 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3348 if (!DeclHasAttr(newDecl, I)) {
3349 InheritableAttr *newAttr =
3350 cast<InheritableParamAttr>(I->clone(S.Context));
3351 newAttr->setInherited(true);
3352 newDecl->addAttr(newAttr);
3353 foundAny = true;
3354 }
3355 }
3356
3357 if (!foundAny) newDecl->dropAttrs();
3358 }
3359
EquivalentArrayTypes(QualType Old,QualType New,const ASTContext & Ctx)3360 static bool EquivalentArrayTypes(QualType Old, QualType New,
3361 const ASTContext &Ctx) {
3362
3363 auto NoSizeInfo = [&Ctx](QualType Ty) {
3364 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3365 return true;
3366 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3367 return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
3368 return false;
3369 };
3370
3371 // `type[]` is equivalent to `type *` and `type[*]`.
3372 if (NoSizeInfo(Old) && NoSizeInfo(New))
3373 return true;
3374
3375 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3376 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3377 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3378 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3379 if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
3380 (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
3381 return false;
3382 return true;
3383 }
3384
3385 // Only compare size, ignore Size modifiers and CVR.
3386 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3387 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3388 Ctx.getAsConstantArrayType(New)->getSize();
3389 }
3390
3391 // Don't try to compare dependent sized array
3392 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3393 return true;
3394 }
3395
3396 return Old == New;
3397 }
3398
mergeParamDeclTypes(ParmVarDecl * NewParam,const ParmVarDecl * OldParam,Sema & S)3399 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3400 const ParmVarDecl *OldParam,
3401 Sema &S) {
3402 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3403 if (auto Newnullability = NewParam->getType()->getNullability()) {
3404 if (*Oldnullability != *Newnullability) {
3405 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3406 << DiagNullabilityKind(
3407 *Newnullability,
3408 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3409 != 0))
3410 << DiagNullabilityKind(
3411 *Oldnullability,
3412 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3413 != 0));
3414 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3415 }
3416 } else {
3417 QualType NewT = NewParam->getType();
3418 NewT = S.Context.getAttributedType(
3419 AttributedType::getNullabilityAttrKind(*Oldnullability),
3420 NewT, NewT);
3421 NewParam->setType(NewT);
3422 }
3423 }
3424 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3425 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3426 if (OldParamDT && NewParamDT &&
3427 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3428 QualType OldParamOT = OldParamDT->getOriginalType();
3429 QualType NewParamOT = NewParamDT->getOriginalType();
3430 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3431 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3432 << NewParam << NewParamOT;
3433 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3434 << OldParamOT;
3435 }
3436 }
3437 }
3438
3439 namespace {
3440
3441 /// Used in MergeFunctionDecl to keep track of function parameters in
3442 /// C.
3443 struct GNUCompatibleParamWarning {
3444 ParmVarDecl *OldParm;
3445 ParmVarDecl *NewParm;
3446 QualType PromotedType;
3447 };
3448
3449 } // end anonymous namespace
3450
3451 // Determine whether the previous declaration was a definition, implicit
3452 // declaration, or a declaration.
3453 template <typename T>
3454 static std::pair<diag::kind, SourceLocation>
getNoteDiagForInvalidRedeclaration(const T * Old,const T * New)3455 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3456 diag::kind PrevDiag;
3457 SourceLocation OldLocation = Old->getLocation();
3458 if (Old->isThisDeclarationADefinition())
3459 PrevDiag = diag::note_previous_definition;
3460 else if (Old->isImplicit()) {
3461 PrevDiag = diag::note_previous_implicit_declaration;
3462 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3463 if (FD->getBuiltinID())
3464 PrevDiag = diag::note_previous_builtin_declaration;
3465 }
3466 if (OldLocation.isInvalid())
3467 OldLocation = New->getLocation();
3468 } else
3469 PrevDiag = diag::note_previous_declaration;
3470 return std::make_pair(PrevDiag, OldLocation);
3471 }
3472
3473 /// canRedefineFunction - checks if a function can be redefined. Currently,
3474 /// only extern inline functions can be redefined, and even then only in
3475 /// GNU89 mode.
canRedefineFunction(const FunctionDecl * FD,const LangOptions & LangOpts)3476 static bool canRedefineFunction(const FunctionDecl *FD,
3477 const LangOptions& LangOpts) {
3478 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3479 !LangOpts.CPlusPlus &&
3480 FD->isInlineSpecified() &&
3481 FD->getStorageClass() == SC_Extern);
3482 }
3483
getCallingConvAttributedType(QualType T) const3484 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3485 const AttributedType *AT = T->getAs<AttributedType>();
3486 while (AT && !AT->isCallingConv())
3487 AT = AT->getModifiedType()->getAs<AttributedType>();
3488 return AT;
3489 }
3490
3491 template <typename T>
haveIncompatibleLanguageLinkages(const T * Old,const T * New)3492 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3493 const DeclContext *DC = Old->getDeclContext();
3494 if (DC->isRecord())
3495 return false;
3496
3497 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3498 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3499 return true;
3500 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3501 return true;
3502 return false;
3503 }
3504
isExternC(T * D)3505 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
isExternC(VarTemplateDecl *)3506 static bool isExternC(VarTemplateDecl *) { return false; }
isExternC(FunctionTemplateDecl *)3507 static bool isExternC(FunctionTemplateDecl *) { return false; }
3508
3509 /// Check whether a redeclaration of an entity introduced by a
3510 /// using-declaration is valid, given that we know it's not an overload
3511 /// (nor a hidden tag declaration).
3512 template<typename ExpectedDecl>
checkUsingShadowRedecl(Sema & S,UsingShadowDecl * OldS,ExpectedDecl * New)3513 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3514 ExpectedDecl *New) {
3515 // C++11 [basic.scope.declarative]p4:
3516 // Given a set of declarations in a single declarative region, each of
3517 // which specifies the same unqualified name,
3518 // -- they shall all refer to the same entity, or all refer to functions
3519 // and function templates; or
3520 // -- exactly one declaration shall declare a class name or enumeration
3521 // name that is not a typedef name and the other declarations shall all
3522 // refer to the same variable or enumerator, or all refer to functions
3523 // and function templates; in this case the class name or enumeration
3524 // name is hidden (3.3.10).
3525
3526 // C++11 [namespace.udecl]p14:
3527 // If a function declaration in namespace scope or block scope has the
3528 // same name and the same parameter-type-list as a function introduced
3529 // by a using-declaration, and the declarations do not declare the same
3530 // function, the program is ill-formed.
3531
3532 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3533 if (Old &&
3534 !Old->getDeclContext()->getRedeclContext()->Equals(
3535 New->getDeclContext()->getRedeclContext()) &&
3536 !(isExternC(Old) && isExternC(New)))
3537 Old = nullptr;
3538
3539 if (!Old) {
3540 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3541 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3542 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3543 return true;
3544 }
3545 return false;
3546 }
3547
hasIdenticalPassObjectSizeAttrs(const FunctionDecl * A,const FunctionDecl * B)3548 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3549 const FunctionDecl *B) {
3550 assert(A->getNumParams() == B->getNumParams());
3551
3552 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3553 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3554 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3555 if (AttrA == AttrB)
3556 return true;
3557 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3558 AttrA->isDynamic() == AttrB->isDynamic();
3559 };
3560
3561 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3562 }
3563
3564 /// If necessary, adjust the semantic declaration context for a qualified
3565 /// declaration to name the correct inline namespace within the qualifier.
adjustDeclContextForDeclaratorDecl(DeclaratorDecl * NewD,DeclaratorDecl * OldD)3566 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3567 DeclaratorDecl *OldD) {
3568 // The only case where we need to update the DeclContext is when
3569 // redeclaration lookup for a qualified name finds a declaration
3570 // in an inline namespace within the context named by the qualifier:
3571 //
3572 // inline namespace N { int f(); }
3573 // int ::f(); // Sema DC needs adjusting from :: to N::.
3574 //
3575 // For unqualified declarations, the semantic context *can* change
3576 // along the redeclaration chain (for local extern declarations,
3577 // extern "C" declarations, and friend declarations in particular).
3578 if (!NewD->getQualifier())
3579 return;
3580
3581 // NewD is probably already in the right context.
3582 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3583 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3584 if (NamedDC->Equals(SemaDC))
3585 return;
3586
3587 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3588 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3589 "unexpected context for redeclaration");
3590
3591 auto *LexDC = NewD->getLexicalDeclContext();
3592 auto FixSemaDC = [=](NamedDecl *D) {
3593 if (!D)
3594 return;
3595 D->setDeclContext(SemaDC);
3596 D->setLexicalDeclContext(LexDC);
3597 };
3598
3599 FixSemaDC(NewD);
3600 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3601 FixSemaDC(FD->getDescribedFunctionTemplate());
3602 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3603 FixSemaDC(VD->getDescribedVarTemplate());
3604 }
3605
3606 /// MergeFunctionDecl - We just parsed a function 'New' from
3607 /// declarator D which has the same name and scope as a previous
3608 /// declaration 'Old'. Figure out how to resolve this situation,
3609 /// merging decls or emitting diagnostics as appropriate.
3610 ///
3611 /// In C++, New and Old must be declarations that are not
3612 /// overloaded. Use IsOverload to determine whether New and Old are
3613 /// overloaded, and to select the Old declaration that New should be
3614 /// merged with.
3615 ///
3616 /// Returns true if there was an error, false otherwise.
MergeFunctionDecl(FunctionDecl * New,NamedDecl * & OldD,Scope * S,bool MergeTypeWithOld,bool NewDeclIsDefn)3617 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3618 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3619 // Verify the old decl was also a function.
3620 FunctionDecl *Old = OldD->getAsFunction();
3621 if (!Old) {
3622 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3623 if (New->getFriendObjectKind()) {
3624 Diag(New->getLocation(), diag::err_using_decl_friend);
3625 Diag(Shadow->getTargetDecl()->getLocation(),
3626 diag::note_using_decl_target);
3627 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3628 << 0;
3629 return true;
3630 }
3631
3632 // Check whether the two declarations might declare the same function or
3633 // function template.
3634 if (FunctionTemplateDecl *NewTemplate =
3635 New->getDescribedFunctionTemplate()) {
3636 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3637 NewTemplate))
3638 return true;
3639 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3640 ->getAsFunction();
3641 } else {
3642 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3643 return true;
3644 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3645 }
3646 } else {
3647 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3648 << New->getDeclName();
3649 notePreviousDefinition(OldD, New->getLocation());
3650 return true;
3651 }
3652 }
3653
3654 // If the old declaration was found in an inline namespace and the new
3655 // declaration was qualified, update the DeclContext to match.
3656 adjustDeclContextForDeclaratorDecl(New, Old);
3657
3658 // If the old declaration is invalid, just give up here.
3659 if (Old->isInvalidDecl())
3660 return true;
3661
3662 // Disallow redeclaration of some builtins.
3663 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3664 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3665 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3666 << Old << Old->getType();
3667 return true;
3668 }
3669
3670 diag::kind PrevDiag;
3671 SourceLocation OldLocation;
3672 std::tie(PrevDiag, OldLocation) =
3673 getNoteDiagForInvalidRedeclaration(Old, New);
3674
3675 // Don't complain about this if we're in GNU89 mode and the old function
3676 // is an extern inline function.
3677 // Don't complain about specializations. They are not supposed to have
3678 // storage classes.
3679 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3680 New->getStorageClass() == SC_Static &&
3681 Old->hasExternalFormalLinkage() &&
3682 !New->getTemplateSpecializationInfo() &&
3683 !canRedefineFunction(Old, getLangOpts())) {
3684 if (getLangOpts().MicrosoftExt) {
3685 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3686 Diag(OldLocation, PrevDiag);
3687 } else {
3688 Diag(New->getLocation(), diag::err_static_non_static) << New;
3689 Diag(OldLocation, PrevDiag);
3690 return true;
3691 }
3692 }
3693
3694 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3695 if (!Old->hasAttr<InternalLinkageAttr>()) {
3696 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3697 << ILA;
3698 Diag(Old->getLocation(), diag::note_previous_declaration);
3699 New->dropAttr<InternalLinkageAttr>();
3700 }
3701
3702 if (auto *EA = New->getAttr<ErrorAttr>()) {
3703 if (!Old->hasAttr<ErrorAttr>()) {
3704 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3705 Diag(Old->getLocation(), diag::note_previous_declaration);
3706 New->dropAttr<ErrorAttr>();
3707 }
3708 }
3709
3710 if (CheckRedeclarationInModule(New, Old))
3711 return true;
3712
3713 if (!getLangOpts().CPlusPlus) {
3714 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3715 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3716 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3717 << New << OldOvl;
3718
3719 // Try our best to find a decl that actually has the overloadable
3720 // attribute for the note. In most cases (e.g. programs with only one
3721 // broken declaration/definition), this won't matter.
3722 //
3723 // FIXME: We could do this if we juggled some extra state in
3724 // OverloadableAttr, rather than just removing it.
3725 const Decl *DiagOld = Old;
3726 if (OldOvl) {
3727 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3728 const auto *A = D->getAttr<OverloadableAttr>();
3729 return A && !A->isImplicit();
3730 });
3731 // If we've implicitly added *all* of the overloadable attrs to this
3732 // chain, emitting a "previous redecl" note is pointless.
3733 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3734 }
3735
3736 if (DiagOld)
3737 Diag(DiagOld->getLocation(),
3738 diag::note_attribute_overloadable_prev_overload)
3739 << OldOvl;
3740
3741 if (OldOvl)
3742 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3743 else
3744 New->dropAttr<OverloadableAttr>();
3745 }
3746 }
3747
3748 // If a function is first declared with a calling convention, but is later
3749 // declared or defined without one, all following decls assume the calling
3750 // convention of the first.
3751 //
3752 // It's OK if a function is first declared without a calling convention,
3753 // but is later declared or defined with the default calling convention.
3754 //
3755 // To test if either decl has an explicit calling convention, we look for
3756 // AttributedType sugar nodes on the type as written. If they are missing or
3757 // were canonicalized away, we assume the calling convention was implicit.
3758 //
3759 // Note also that we DO NOT return at this point, because we still have
3760 // other tests to run.
3761 QualType OldQType = Context.getCanonicalType(Old->getType());
3762 QualType NewQType = Context.getCanonicalType(New->getType());
3763 const FunctionType *OldType = cast<FunctionType>(OldQType);
3764 const FunctionType *NewType = cast<FunctionType>(NewQType);
3765 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3766 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3767 bool RequiresAdjustment = false;
3768
3769 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3770 FunctionDecl *First = Old->getFirstDecl();
3771 const FunctionType *FT =
3772 First->getType().getCanonicalType()->castAs<FunctionType>();
3773 FunctionType::ExtInfo FI = FT->getExtInfo();
3774 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3775 if (!NewCCExplicit) {
3776 // Inherit the CC from the previous declaration if it was specified
3777 // there but not here.
3778 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3779 RequiresAdjustment = true;
3780 } else if (Old->getBuiltinID()) {
3781 // Builtin attribute isn't propagated to the new one yet at this point,
3782 // so we check if the old one is a builtin.
3783
3784 // Calling Conventions on a Builtin aren't really useful and setting a
3785 // default calling convention and cdecl'ing some builtin redeclarations is
3786 // common, so warn and ignore the calling convention on the redeclaration.
3787 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3788 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3789 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3790 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3791 RequiresAdjustment = true;
3792 } else {
3793 // Calling conventions aren't compatible, so complain.
3794 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3795 Diag(New->getLocation(), diag::err_cconv_change)
3796 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3797 << !FirstCCExplicit
3798 << (!FirstCCExplicit ? "" :
3799 FunctionType::getNameForCallConv(FI.getCC()));
3800
3801 // Put the note on the first decl, since it is the one that matters.
3802 Diag(First->getLocation(), diag::note_previous_declaration);
3803 return true;
3804 }
3805 }
3806
3807 // FIXME: diagnose the other way around?
3808 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3809 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3810 RequiresAdjustment = true;
3811 }
3812
3813 // Merge regparm attribute.
3814 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3815 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3816 if (NewTypeInfo.getHasRegParm()) {
3817 Diag(New->getLocation(), diag::err_regparm_mismatch)
3818 << NewType->getRegParmType()
3819 << OldType->getRegParmType();
3820 Diag(OldLocation, diag::note_previous_declaration);
3821 return true;
3822 }
3823
3824 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3825 RequiresAdjustment = true;
3826 }
3827
3828 // Merge ns_returns_retained attribute.
3829 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3830 if (NewTypeInfo.getProducesResult()) {
3831 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3832 << "'ns_returns_retained'";
3833 Diag(OldLocation, diag::note_previous_declaration);
3834 return true;
3835 }
3836
3837 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3838 RequiresAdjustment = true;
3839 }
3840
3841 if (OldTypeInfo.getNoCallerSavedRegs() !=
3842 NewTypeInfo.getNoCallerSavedRegs()) {
3843 if (NewTypeInfo.getNoCallerSavedRegs()) {
3844 AnyX86NoCallerSavedRegistersAttr *Attr =
3845 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3846 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3847 Diag(OldLocation, diag::note_previous_declaration);
3848 return true;
3849 }
3850
3851 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3852 RequiresAdjustment = true;
3853 }
3854
3855 if (RequiresAdjustment) {
3856 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3857 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3858 New->setType(QualType(AdjustedType, 0));
3859 NewQType = Context.getCanonicalType(New->getType());
3860 }
3861
3862 // If this redeclaration makes the function inline, we may need to add it to
3863 // UndefinedButUsed.
3864 if (!Old->isInlined() && New->isInlined() &&
3865 !New->hasAttr<GNUInlineAttr>() &&
3866 !getLangOpts().GNUInline &&
3867 Old->isUsed(false) &&
3868 !Old->isDefined() && !New->isThisDeclarationADefinition())
3869 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3870 SourceLocation()));
3871
3872 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3873 // about it.
3874 if (New->hasAttr<GNUInlineAttr>() &&
3875 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3876 UndefinedButUsed.erase(Old->getCanonicalDecl());
3877 }
3878
3879 // If pass_object_size params don't match up perfectly, this isn't a valid
3880 // redeclaration.
3881 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3882 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3883 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3884 << New->getDeclName();
3885 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3886 return true;
3887 }
3888
3889 if (getLangOpts().CPlusPlus) {
3890 // C++1z [over.load]p2
3891 // Certain function declarations cannot be overloaded:
3892 // -- Function declarations that differ only in the return type,
3893 // the exception specification, or both cannot be overloaded.
3894
3895 // Check the exception specifications match. This may recompute the type of
3896 // both Old and New if it resolved exception specifications, so grab the
3897 // types again after this. Because this updates the type, we do this before
3898 // any of the other checks below, which may update the "de facto" NewQType
3899 // but do not necessarily update the type of New.
3900 if (CheckEquivalentExceptionSpec(Old, New))
3901 return true;
3902 OldQType = Context.getCanonicalType(Old->getType());
3903 NewQType = Context.getCanonicalType(New->getType());
3904
3905 // Go back to the type source info to compare the declared return types,
3906 // per C++1y [dcl.type.auto]p13:
3907 // Redeclarations or specializations of a function or function template
3908 // with a declared return type that uses a placeholder type shall also
3909 // use that placeholder, not a deduced type.
3910 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3911 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3912 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3913 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3914 OldDeclaredReturnType)) {
3915 QualType ResQT;
3916 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3917 OldDeclaredReturnType->isObjCObjectPointerType())
3918 // FIXME: This does the wrong thing for a deduced return type.
3919 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3920 if (ResQT.isNull()) {
3921 if (New->isCXXClassMember() && New->isOutOfLine())
3922 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3923 << New << New->getReturnTypeSourceRange();
3924 else
3925 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3926 << New->getReturnTypeSourceRange();
3927 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3928 << Old->getReturnTypeSourceRange();
3929 return true;
3930 }
3931 else
3932 NewQType = ResQT;
3933 }
3934
3935 QualType OldReturnType = OldType->getReturnType();
3936 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3937 if (OldReturnType != NewReturnType) {
3938 // If this function has a deduced return type and has already been
3939 // defined, copy the deduced value from the old declaration.
3940 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3941 if (OldAT && OldAT->isDeduced()) {
3942 QualType DT = OldAT->getDeducedType();
3943 if (DT.isNull()) {
3944 New->setType(SubstAutoTypeDependent(New->getType()));
3945 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3946 } else {
3947 New->setType(SubstAutoType(New->getType(), DT));
3948 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3949 }
3950 }
3951 }
3952
3953 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3954 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3955 if (OldMethod && NewMethod) {
3956 // Preserve triviality.
3957 NewMethod->setTrivial(OldMethod->isTrivial());
3958
3959 // MSVC allows explicit template specialization at class scope:
3960 // 2 CXXMethodDecls referring to the same function will be injected.
3961 // We don't want a redeclaration error.
3962 bool IsClassScopeExplicitSpecialization =
3963 OldMethod->isFunctionTemplateSpecialization() &&
3964 NewMethod->isFunctionTemplateSpecialization();
3965 bool isFriend = NewMethod->getFriendObjectKind();
3966
3967 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3968 !IsClassScopeExplicitSpecialization) {
3969 // -- Member function declarations with the same name and the
3970 // same parameter types cannot be overloaded if any of them
3971 // is a static member function declaration.
3972 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3973 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3974 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3975 return true;
3976 }
3977
3978 // C++ [class.mem]p1:
3979 // [...] A member shall not be declared twice in the
3980 // member-specification, except that a nested class or member
3981 // class template can be declared and then later defined.
3982 if (!inTemplateInstantiation()) {
3983 unsigned NewDiag;
3984 if (isa<CXXConstructorDecl>(OldMethod))
3985 NewDiag = diag::err_constructor_redeclared;
3986 else if (isa<CXXDestructorDecl>(NewMethod))
3987 NewDiag = diag::err_destructor_redeclared;
3988 else if (isa<CXXConversionDecl>(NewMethod))
3989 NewDiag = diag::err_conv_function_redeclared;
3990 else
3991 NewDiag = diag::err_member_redeclared;
3992
3993 Diag(New->getLocation(), NewDiag);
3994 } else {
3995 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3996 << New << New->getType();
3997 }
3998 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3999 return true;
4000
4001 // Complain if this is an explicit declaration of a special
4002 // member that was initially declared implicitly.
4003 //
4004 // As an exception, it's okay to befriend such methods in order
4005 // to permit the implicit constructor/destructor/operator calls.
4006 } else if (OldMethod->isImplicit()) {
4007 if (isFriend) {
4008 NewMethod->setImplicit();
4009 } else {
4010 Diag(NewMethod->getLocation(),
4011 diag::err_definition_of_implicitly_declared_member)
4012 << New << getSpecialMember(OldMethod);
4013 return true;
4014 }
4015 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4016 Diag(NewMethod->getLocation(),
4017 diag::err_definition_of_explicitly_defaulted_member)
4018 << getSpecialMember(OldMethod);
4019 return true;
4020 }
4021 }
4022
4023 // C++11 [dcl.attr.noreturn]p1:
4024 // The first declaration of a function shall specify the noreturn
4025 // attribute if any declaration of that function specifies the noreturn
4026 // attribute.
4027 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4028 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4029 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4030 << NRA;
4031 Diag(Old->getLocation(), diag::note_previous_declaration);
4032 }
4033
4034 // C++11 [dcl.attr.depend]p2:
4035 // The first declaration of a function shall specify the
4036 // carries_dependency attribute for its declarator-id if any declaration
4037 // of the function specifies the carries_dependency attribute.
4038 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4039 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4040 Diag(CDA->getLocation(),
4041 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4042 Diag(Old->getFirstDecl()->getLocation(),
4043 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4044 }
4045
4046 // (C++98 8.3.5p3):
4047 // All declarations for a function shall agree exactly in both the
4048 // return type and the parameter-type-list.
4049 // We also want to respect all the extended bits except noreturn.
4050
4051 // noreturn should now match unless the old type info didn't have it.
4052 QualType OldQTypeForComparison = OldQType;
4053 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4054 auto *OldType = OldQType->castAs<FunctionProtoType>();
4055 const FunctionType *OldTypeForComparison
4056 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4057 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4058 assert(OldQTypeForComparison.isCanonical());
4059 }
4060
4061 if (haveIncompatibleLanguageLinkages(Old, New)) {
4062 // As a special case, retain the language linkage from previous
4063 // declarations of a friend function as an extension.
4064 //
4065 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4066 // and is useful because there's otherwise no way to specify language
4067 // linkage within class scope.
4068 //
4069 // Check cautiously as the friend object kind isn't yet complete.
4070 if (New->getFriendObjectKind() != Decl::FOK_None) {
4071 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4072 Diag(OldLocation, PrevDiag);
4073 } else {
4074 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4075 Diag(OldLocation, PrevDiag);
4076 return true;
4077 }
4078 }
4079
4080 // If the function types are compatible, merge the declarations. Ignore the
4081 // exception specifier because it was already checked above in
4082 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4083 // about incompatible types under -fms-compatibility.
4084 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4085 NewQType))
4086 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4087
4088 // If the types are imprecise (due to dependent constructs in friends or
4089 // local extern declarations), it's OK if they differ. We'll check again
4090 // during instantiation.
4091 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4092 return false;
4093
4094 // Fall through for conflicting redeclarations and redefinitions.
4095 }
4096
4097 // C: Function types need to be compatible, not identical. This handles
4098 // duplicate function decls like "void f(int); void f(enum X);" properly.
4099 if (!getLangOpts().CPlusPlus) {
4100 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4101 // type is specified by a function definition that contains a (possibly
4102 // empty) identifier list, both shall agree in the number of parameters
4103 // and the type of each parameter shall be compatible with the type that
4104 // results from the application of default argument promotions to the
4105 // type of the corresponding identifier. ...
4106 // This cannot be handled by ASTContext::typesAreCompatible() because that
4107 // doesn't know whether the function type is for a definition or not when
4108 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4109 // we need to cover here is that the number of arguments agree as the
4110 // default argument promotion rules were already checked by
4111 // ASTContext::typesAreCompatible().
4112 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4113 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4114 if (Old->hasInheritedPrototype())
4115 Old = Old->getCanonicalDecl();
4116 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4117 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4118 return true;
4119 }
4120
4121 // If we are merging two functions where only one of them has a prototype,
4122 // we may have enough information to decide to issue a diagnostic that the
4123 // function without a protoype will change behavior in C2x. This handles
4124 // cases like:
4125 // void i(); void i(int j);
4126 // void i(int j); void i();
4127 // void i(); void i(int j) {}
4128 // See ActOnFinishFunctionBody() for other cases of the behavior change
4129 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4130 // type without a prototype.
4131 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4132 !New->isImplicit() && !Old->isImplicit()) {
4133 const FunctionDecl *WithProto, *WithoutProto;
4134 if (New->hasWrittenPrototype()) {
4135 WithProto = New;
4136 WithoutProto = Old;
4137 } else {
4138 WithProto = Old;
4139 WithoutProto = New;
4140 }
4141
4142 if (WithProto->getNumParams() != 0) {
4143 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4144 // The one without the prototype will be changing behavior in C2x, so
4145 // warn about that one so long as it's a user-visible declaration.
4146 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4147 if (WithoutProto == New)
4148 IsWithoutProtoADef = NewDeclIsDefn;
4149 else
4150 IsWithProtoADef = NewDeclIsDefn;
4151 Diag(WithoutProto->getLocation(),
4152 diag::warn_non_prototype_changes_behavior)
4153 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4154 << (WithoutProto == Old) << IsWithProtoADef;
4155
4156 // The reason the one without the prototype will be changing behavior
4157 // is because of the one with the prototype, so note that so long as
4158 // it's a user-visible declaration. There is one exception to this:
4159 // when the new declaration is a definition without a prototype, the
4160 // old declaration with a prototype is not the cause of the issue,
4161 // and that does not need to be noted because the one with a
4162 // prototype will not change behavior in C2x.
4163 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4164 !IsWithoutProtoADef)
4165 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4166 }
4167 }
4168 }
4169
4170 if (Context.typesAreCompatible(OldQType, NewQType)) {
4171 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4172 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4173 const FunctionProtoType *OldProto = nullptr;
4174 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4175 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4176 // The old declaration provided a function prototype, but the
4177 // new declaration does not. Merge in the prototype.
4178 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4179 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4180 OldProto->getParamTypes(),
4181 OldProto->getExtProtoInfo());
4182 New->setType(NewQType);
4183 New->setHasInheritedPrototype();
4184
4185 // Synthesize parameters with the same types.
4186 SmallVector<ParmVarDecl *, 16> Params;
4187 for (const auto &ParamType : OldProto->param_types()) {
4188 ParmVarDecl *Param = ParmVarDecl::Create(
4189 Context, New, SourceLocation(), SourceLocation(), nullptr,
4190 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4191 Param->setScopeInfo(0, Params.size());
4192 Param->setImplicit();
4193 Params.push_back(Param);
4194 }
4195
4196 New->setParams(Params);
4197 }
4198
4199 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4200 }
4201 }
4202
4203 // Check if the function types are compatible when pointer size address
4204 // spaces are ignored.
4205 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4206 return false;
4207
4208 // GNU C permits a K&R definition to follow a prototype declaration
4209 // if the declared types of the parameters in the K&R definition
4210 // match the types in the prototype declaration, even when the
4211 // promoted types of the parameters from the K&R definition differ
4212 // from the types in the prototype. GCC then keeps the types from
4213 // the prototype.
4214 //
4215 // If a variadic prototype is followed by a non-variadic K&R definition,
4216 // the K&R definition becomes variadic. This is sort of an edge case, but
4217 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4218 // C99 6.9.1p8.
4219 if (!getLangOpts().CPlusPlus &&
4220 Old->hasPrototype() && !New->hasPrototype() &&
4221 New->getType()->getAs<FunctionProtoType>() &&
4222 Old->getNumParams() == New->getNumParams()) {
4223 SmallVector<QualType, 16> ArgTypes;
4224 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4225 const FunctionProtoType *OldProto
4226 = Old->getType()->getAs<FunctionProtoType>();
4227 const FunctionProtoType *NewProto
4228 = New->getType()->getAs<FunctionProtoType>();
4229
4230 // Determine whether this is the GNU C extension.
4231 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4232 NewProto->getReturnType());
4233 bool LooseCompatible = !MergedReturn.isNull();
4234 for (unsigned Idx = 0, End = Old->getNumParams();
4235 LooseCompatible && Idx != End; ++Idx) {
4236 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4237 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4238 if (Context.typesAreCompatible(OldParm->getType(),
4239 NewProto->getParamType(Idx))) {
4240 ArgTypes.push_back(NewParm->getType());
4241 } else if (Context.typesAreCompatible(OldParm->getType(),
4242 NewParm->getType(),
4243 /*CompareUnqualified=*/true)) {
4244 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4245 NewProto->getParamType(Idx) };
4246 Warnings.push_back(Warn);
4247 ArgTypes.push_back(NewParm->getType());
4248 } else
4249 LooseCompatible = false;
4250 }
4251
4252 if (LooseCompatible) {
4253 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4254 Diag(Warnings[Warn].NewParm->getLocation(),
4255 diag::ext_param_promoted_not_compatible_with_prototype)
4256 << Warnings[Warn].PromotedType
4257 << Warnings[Warn].OldParm->getType();
4258 if (Warnings[Warn].OldParm->getLocation().isValid())
4259 Diag(Warnings[Warn].OldParm->getLocation(),
4260 diag::note_previous_declaration);
4261 }
4262
4263 if (MergeTypeWithOld)
4264 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4265 OldProto->getExtProtoInfo()));
4266 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4267 }
4268
4269 // Fall through to diagnose conflicting types.
4270 }
4271
4272 // A function that has already been declared has been redeclared or
4273 // defined with a different type; show an appropriate diagnostic.
4274
4275 // If the previous declaration was an implicitly-generated builtin
4276 // declaration, then at the very least we should use a specialized note.
4277 unsigned BuiltinID;
4278 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4279 // If it's actually a library-defined builtin function like 'malloc'
4280 // or 'printf', just warn about the incompatible redeclaration.
4281 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4282 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4283 Diag(OldLocation, diag::note_previous_builtin_declaration)
4284 << Old << Old->getType();
4285 return false;
4286 }
4287
4288 PrevDiag = diag::note_previous_builtin_declaration;
4289 }
4290
4291 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4292 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4293 return true;
4294 }
4295
4296 /// Completes the merge of two function declarations that are
4297 /// known to be compatible.
4298 ///
4299 /// This routine handles the merging of attributes and other
4300 /// properties of function declarations from the old declaration to
4301 /// the new declaration, once we know that New is in fact a
4302 /// redeclaration of Old.
4303 ///
4304 /// \returns false
MergeCompatibleFunctionDecls(FunctionDecl * New,FunctionDecl * Old,Scope * S,bool MergeTypeWithOld)4305 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4306 Scope *S, bool MergeTypeWithOld) {
4307 // Merge the attributes
4308 mergeDeclAttributes(New, Old);
4309
4310 // Merge "pure" flag.
4311 if (Old->isPure())
4312 New->setPure();
4313
4314 // Merge "used" flag.
4315 if (Old->getMostRecentDecl()->isUsed(false))
4316 New->setIsUsed();
4317
4318 // Merge attributes from the parameters. These can mismatch with K&R
4319 // declarations.
4320 if (New->getNumParams() == Old->getNumParams())
4321 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4322 ParmVarDecl *NewParam = New->getParamDecl(i);
4323 ParmVarDecl *OldParam = Old->getParamDecl(i);
4324 mergeParamDeclAttributes(NewParam, OldParam, *this);
4325 mergeParamDeclTypes(NewParam, OldParam, *this);
4326 }
4327
4328 if (getLangOpts().CPlusPlus)
4329 return MergeCXXFunctionDecl(New, Old, S);
4330
4331 // Merge the function types so the we get the composite types for the return
4332 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4333 // was visible.
4334 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4335 if (!Merged.isNull() && MergeTypeWithOld)
4336 New->setType(Merged);
4337
4338 return false;
4339 }
4340
mergeObjCMethodDecls(ObjCMethodDecl * newMethod,ObjCMethodDecl * oldMethod)4341 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4342 ObjCMethodDecl *oldMethod) {
4343 // Merge the attributes, including deprecated/unavailable
4344 AvailabilityMergeKind MergeKind =
4345 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4346 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4347 : AMK_ProtocolImplementation)
4348 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4349 : AMK_Override;
4350
4351 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4352
4353 // Merge attributes from the parameters.
4354 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4355 oe = oldMethod->param_end();
4356 for (ObjCMethodDecl::param_iterator
4357 ni = newMethod->param_begin(), ne = newMethod->param_end();
4358 ni != ne && oi != oe; ++ni, ++oi)
4359 mergeParamDeclAttributes(*ni, *oi, *this);
4360
4361 CheckObjCMethodOverride(newMethod, oldMethod);
4362 }
4363
diagnoseVarDeclTypeMismatch(Sema & S,VarDecl * New,VarDecl * Old)4364 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4365 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4366
4367 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4368 ? diag::err_redefinition_different_type
4369 : diag::err_redeclaration_different_type)
4370 << New->getDeclName() << New->getType() << Old->getType();
4371
4372 diag::kind PrevDiag;
4373 SourceLocation OldLocation;
4374 std::tie(PrevDiag, OldLocation)
4375 = getNoteDiagForInvalidRedeclaration(Old, New);
4376 S.Diag(OldLocation, PrevDiag);
4377 New->setInvalidDecl();
4378 }
4379
4380 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4381 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
4382 /// emitting diagnostics as appropriate.
4383 ///
4384 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4385 /// to here in AddInitializerToDecl. We can't check them before the initializer
4386 /// is attached.
MergeVarDeclTypes(VarDecl * New,VarDecl * Old,bool MergeTypeWithOld)4387 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4388 bool MergeTypeWithOld) {
4389 if (New->isInvalidDecl() || Old->isInvalidDecl())
4390 return;
4391
4392 QualType MergedT;
4393 if (getLangOpts().CPlusPlus) {
4394 if (New->getType()->isUndeducedType()) {
4395 // We don't know what the new type is until the initializer is attached.
4396 return;
4397 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4398 // These could still be something that needs exception specs checked.
4399 return MergeVarDeclExceptionSpecs(New, Old);
4400 }
4401 // C++ [basic.link]p10:
4402 // [...] the types specified by all declarations referring to a given
4403 // object or function shall be identical, except that declarations for an
4404 // array object can specify array types that differ by the presence or
4405 // absence of a major array bound (8.3.4).
4406 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4407 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4408 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4409
4410 // We are merging a variable declaration New into Old. If it has an array
4411 // bound, and that bound differs from Old's bound, we should diagnose the
4412 // mismatch.
4413 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4414 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4415 PrevVD = PrevVD->getPreviousDecl()) {
4416 QualType PrevVDTy = PrevVD->getType();
4417 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4418 continue;
4419
4420 if (!Context.hasSameType(New->getType(), PrevVDTy))
4421 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4422 }
4423 }
4424
4425 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4426 if (Context.hasSameType(OldArray->getElementType(),
4427 NewArray->getElementType()))
4428 MergedT = New->getType();
4429 }
4430 // FIXME: Check visibility. New is hidden but has a complete type. If New
4431 // has no array bound, it should not inherit one from Old, if Old is not
4432 // visible.
4433 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4434 if (Context.hasSameType(OldArray->getElementType(),
4435 NewArray->getElementType()))
4436 MergedT = Old->getType();
4437 }
4438 }
4439 else if (New->getType()->isObjCObjectPointerType() &&
4440 Old->getType()->isObjCObjectPointerType()) {
4441 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4442 Old->getType());
4443 }
4444 } else {
4445 // C 6.2.7p2:
4446 // All declarations that refer to the same object or function shall have
4447 // compatible type.
4448 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4449 }
4450 if (MergedT.isNull()) {
4451 // It's OK if we couldn't merge types if either type is dependent, for a
4452 // block-scope variable. In other cases (static data members of class
4453 // templates, variable templates, ...), we require the types to be
4454 // equivalent.
4455 // FIXME: The C++ standard doesn't say anything about this.
4456 if ((New->getType()->isDependentType() ||
4457 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4458 // If the old type was dependent, we can't merge with it, so the new type
4459 // becomes dependent for now. We'll reproduce the original type when we
4460 // instantiate the TypeSourceInfo for the variable.
4461 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4462 New->setType(Context.DependentTy);
4463 return;
4464 }
4465 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4466 }
4467
4468 // Don't actually update the type on the new declaration if the old
4469 // declaration was an extern declaration in a different scope.
4470 if (MergeTypeWithOld)
4471 New->setType(MergedT);
4472 }
4473
mergeTypeWithPrevious(Sema & S,VarDecl * NewVD,VarDecl * OldVD,LookupResult & Previous)4474 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4475 LookupResult &Previous) {
4476 // C11 6.2.7p4:
4477 // For an identifier with internal or external linkage declared
4478 // in a scope in which a prior declaration of that identifier is
4479 // visible, if the prior declaration specifies internal or
4480 // external linkage, the type of the identifier at the later
4481 // declaration becomes the composite type.
4482 //
4483 // If the variable isn't visible, we do not merge with its type.
4484 if (Previous.isShadowed())
4485 return false;
4486
4487 if (S.getLangOpts().CPlusPlus) {
4488 // C++11 [dcl.array]p3:
4489 // If there is a preceding declaration of the entity in the same
4490 // scope in which the bound was specified, an omitted array bound
4491 // is taken to be the same as in that earlier declaration.
4492 return NewVD->isPreviousDeclInSameBlockScope() ||
4493 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4494 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4495 } else {
4496 // If the old declaration was function-local, don't merge with its
4497 // type unless we're in the same function.
4498 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4499 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4500 }
4501 }
4502
4503 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4504 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4505 /// situation, merging decls or emitting diagnostics as appropriate.
4506 ///
4507 /// Tentative definition rules (C99 6.9.2p2) are checked by
4508 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4509 /// definitions here, since the initializer hasn't been attached.
4510 ///
MergeVarDecl(VarDecl * New,LookupResult & Previous)4511 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4512 // If the new decl is already invalid, don't do any other checking.
4513 if (New->isInvalidDecl())
4514 return;
4515
4516 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4517 return;
4518
4519 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4520
4521 // Verify the old decl was also a variable or variable template.
4522 VarDecl *Old = nullptr;
4523 VarTemplateDecl *OldTemplate = nullptr;
4524 if (Previous.isSingleResult()) {
4525 if (NewTemplate) {
4526 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4527 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4528
4529 if (auto *Shadow =
4530 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4531 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4532 return New->setInvalidDecl();
4533 } else {
4534 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4535
4536 if (auto *Shadow =
4537 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4538 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4539 return New->setInvalidDecl();
4540 }
4541 }
4542 if (!Old) {
4543 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4544 << New->getDeclName();
4545 notePreviousDefinition(Previous.getRepresentativeDecl(),
4546 New->getLocation());
4547 return New->setInvalidDecl();
4548 }
4549
4550 // If the old declaration was found in an inline namespace and the new
4551 // declaration was qualified, update the DeclContext to match.
4552 adjustDeclContextForDeclaratorDecl(New, Old);
4553
4554 // Ensure the template parameters are compatible.
4555 if (NewTemplate &&
4556 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4557 OldTemplate->getTemplateParameters(),
4558 /*Complain=*/true, TPL_TemplateMatch))
4559 return New->setInvalidDecl();
4560
4561 // C++ [class.mem]p1:
4562 // A member shall not be declared twice in the member-specification [...]
4563 //
4564 // Here, we need only consider static data members.
4565 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4566 Diag(New->getLocation(), diag::err_duplicate_member)
4567 << New->getIdentifier();
4568 Diag(Old->getLocation(), diag::note_previous_declaration);
4569 New->setInvalidDecl();
4570 }
4571
4572 mergeDeclAttributes(New, Old);
4573 // Warn if an already-declared variable is made a weak_import in a subsequent
4574 // declaration
4575 if (New->hasAttr<WeakImportAttr>() &&
4576 Old->getStorageClass() == SC_None &&
4577 !Old->hasAttr<WeakImportAttr>()) {
4578 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4579 Diag(Old->getLocation(), diag::note_previous_declaration);
4580 // Remove weak_import attribute on new declaration.
4581 New->dropAttr<WeakImportAttr>();
4582 }
4583
4584 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4585 if (!Old->hasAttr<InternalLinkageAttr>()) {
4586 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4587 << ILA;
4588 Diag(Old->getLocation(), diag::note_previous_declaration);
4589 New->dropAttr<InternalLinkageAttr>();
4590 }
4591
4592 // Merge the types.
4593 VarDecl *MostRecent = Old->getMostRecentDecl();
4594 if (MostRecent != Old) {
4595 MergeVarDeclTypes(New, MostRecent,
4596 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4597 if (New->isInvalidDecl())
4598 return;
4599 }
4600
4601 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4602 if (New->isInvalidDecl())
4603 return;
4604
4605 diag::kind PrevDiag;
4606 SourceLocation OldLocation;
4607 std::tie(PrevDiag, OldLocation) =
4608 getNoteDiagForInvalidRedeclaration(Old, New);
4609
4610 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4611 if (New->getStorageClass() == SC_Static &&
4612 !New->isStaticDataMember() &&
4613 Old->hasExternalFormalLinkage()) {
4614 if (getLangOpts().MicrosoftExt) {
4615 Diag(New->getLocation(), diag::ext_static_non_static)
4616 << New->getDeclName();
4617 Diag(OldLocation, PrevDiag);
4618 } else {
4619 Diag(New->getLocation(), diag::err_static_non_static)
4620 << New->getDeclName();
4621 Diag(OldLocation, PrevDiag);
4622 return New->setInvalidDecl();
4623 }
4624 }
4625 // C99 6.2.2p4:
4626 // For an identifier declared with the storage-class specifier
4627 // extern in a scope in which a prior declaration of that
4628 // identifier is visible,23) if the prior declaration specifies
4629 // internal or external linkage, the linkage of the identifier at
4630 // the later declaration is the same as the linkage specified at
4631 // the prior declaration. If no prior declaration is visible, or
4632 // if the prior declaration specifies no linkage, then the
4633 // identifier has external linkage.
4634 if (New->hasExternalStorage() && Old->hasLinkage())
4635 /* Okay */;
4636 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4637 !New->isStaticDataMember() &&
4638 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4639 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4640 Diag(OldLocation, PrevDiag);
4641 return New->setInvalidDecl();
4642 }
4643
4644 // Check if extern is followed by non-extern and vice-versa.
4645 if (New->hasExternalStorage() &&
4646 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4647 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4648 Diag(OldLocation, PrevDiag);
4649 return New->setInvalidDecl();
4650 }
4651 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4652 !New->hasExternalStorage()) {
4653 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4654 Diag(OldLocation, PrevDiag);
4655 return New->setInvalidDecl();
4656 }
4657
4658 if (CheckRedeclarationInModule(New, Old))
4659 return;
4660
4661 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4662
4663 // FIXME: The test for external storage here seems wrong? We still
4664 // need to check for mismatches.
4665 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4666 // Don't complain about out-of-line definitions of static members.
4667 !(Old->getLexicalDeclContext()->isRecord() &&
4668 !New->getLexicalDeclContext()->isRecord())) {
4669 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4670 Diag(OldLocation, PrevDiag);
4671 return New->setInvalidDecl();
4672 }
4673
4674 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4675 if (VarDecl *Def = Old->getDefinition()) {
4676 // C++1z [dcl.fcn.spec]p4:
4677 // If the definition of a variable appears in a translation unit before
4678 // its first declaration as inline, the program is ill-formed.
4679 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4680 Diag(Def->getLocation(), diag::note_previous_definition);
4681 }
4682 }
4683
4684 // If this redeclaration makes the variable inline, we may need to add it to
4685 // UndefinedButUsed.
4686 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4687 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4688 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4689 SourceLocation()));
4690
4691 if (New->getTLSKind() != Old->getTLSKind()) {
4692 if (!Old->getTLSKind()) {
4693 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4694 Diag(OldLocation, PrevDiag);
4695 } else if (!New->getTLSKind()) {
4696 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4697 Diag(OldLocation, PrevDiag);
4698 } else {
4699 // Do not allow redeclaration to change the variable between requiring
4700 // static and dynamic initialization.
4701 // FIXME: GCC allows this, but uses the TLS keyword on the first
4702 // declaration to determine the kind. Do we need to be compatible here?
4703 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4704 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4705 Diag(OldLocation, PrevDiag);
4706 }
4707 }
4708
4709 // C++ doesn't have tentative definitions, so go right ahead and check here.
4710 if (getLangOpts().CPlusPlus) {
4711 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4712 Old->getCanonicalDecl()->isConstexpr()) {
4713 // This definition won't be a definition any more once it's been merged.
4714 Diag(New->getLocation(),
4715 diag::warn_deprecated_redundant_constexpr_static_def);
4716 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4717 VarDecl *Def = Old->getDefinition();
4718 if (Def && checkVarDeclRedefinition(Def, New))
4719 return;
4720 }
4721 }
4722
4723 if (haveIncompatibleLanguageLinkages(Old, New)) {
4724 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4725 Diag(OldLocation, PrevDiag);
4726 New->setInvalidDecl();
4727 return;
4728 }
4729
4730 // Merge "used" flag.
4731 if (Old->getMostRecentDecl()->isUsed(false))
4732 New->setIsUsed();
4733
4734 // Keep a chain of previous declarations.
4735 New->setPreviousDecl(Old);
4736 if (NewTemplate)
4737 NewTemplate->setPreviousDecl(OldTemplate);
4738
4739 // Inherit access appropriately.
4740 New->setAccess(Old->getAccess());
4741 if (NewTemplate)
4742 NewTemplate->setAccess(New->getAccess());
4743
4744 if (Old->isInline())
4745 New->setImplicitlyInline();
4746 }
4747
notePreviousDefinition(const NamedDecl * Old,SourceLocation New)4748 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4749 SourceManager &SrcMgr = getSourceManager();
4750 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4751 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4752 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4753 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4754 auto &HSI = PP.getHeaderSearchInfo();
4755 StringRef HdrFilename =
4756 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4757
4758 auto noteFromModuleOrInclude = [&](Module *Mod,
4759 SourceLocation IncLoc) -> bool {
4760 // Redefinition errors with modules are common with non modular mapped
4761 // headers, example: a non-modular header H in module A that also gets
4762 // included directly in a TU. Pointing twice to the same header/definition
4763 // is confusing, try to get better diagnostics when modules is on.
4764 if (IncLoc.isValid()) {
4765 if (Mod) {
4766 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4767 << HdrFilename.str() << Mod->getFullModuleName();
4768 if (!Mod->DefinitionLoc.isInvalid())
4769 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4770 << Mod->getFullModuleName();
4771 } else {
4772 Diag(IncLoc, diag::note_redefinition_include_same_file)
4773 << HdrFilename.str();
4774 }
4775 return true;
4776 }
4777
4778 return false;
4779 };
4780
4781 // Is it the same file and same offset? Provide more information on why
4782 // this leads to a redefinition error.
4783 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4784 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4785 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4786 bool EmittedDiag =
4787 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4788 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4789
4790 // If the header has no guards, emit a note suggesting one.
4791 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4792 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4793
4794 if (EmittedDiag)
4795 return;
4796 }
4797
4798 // Redefinition coming from different files or couldn't do better above.
4799 if (Old->getLocation().isValid())
4800 Diag(Old->getLocation(), diag::note_previous_definition);
4801 }
4802
4803 /// We've just determined that \p Old and \p New both appear to be definitions
4804 /// of the same variable. Either diagnose or fix the problem.
checkVarDeclRedefinition(VarDecl * Old,VarDecl * New)4805 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4806 if (!hasVisibleDefinition(Old) &&
4807 (New->getFormalLinkage() == InternalLinkage ||
4808 New->isInline() ||
4809 isa<VarTemplateSpecializationDecl>(New) ||
4810 New->getDescribedVarTemplate() ||
4811 New->getNumTemplateParameterLists() ||
4812 New->getDeclContext()->isDependentContext())) {
4813 // The previous definition is hidden, and multiple definitions are
4814 // permitted (in separate TUs). Demote this to a declaration.
4815 New->demoteThisDefinitionToDeclaration();
4816
4817 // Make the canonical definition visible.
4818 if (auto *OldTD = Old->getDescribedVarTemplate())
4819 makeMergedDefinitionVisible(OldTD);
4820 makeMergedDefinitionVisible(Old);
4821 return false;
4822 } else {
4823 Diag(New->getLocation(), diag::err_redefinition) << New;
4824 notePreviousDefinition(Old, New->getLocation());
4825 New->setInvalidDecl();
4826 return true;
4827 }
4828 }
4829
4830 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4831 /// no declarator (e.g. "struct foo;") is parsed.
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,const ParsedAttributesView & DeclAttrs,RecordDecl * & AnonRecord)4832 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4833 DeclSpec &DS,
4834 const ParsedAttributesView &DeclAttrs,
4835 RecordDecl *&AnonRecord) {
4836 return ParsedFreeStandingDeclSpec(
4837 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4838 }
4839
4840 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4841 // disambiguate entities defined in different scopes.
4842 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4843 // compatibility.
4844 // We will pick our mangling number depending on which version of MSVC is being
4845 // targeted.
getMSManglingNumber(const LangOptions & LO,Scope * S)4846 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4847 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4848 ? S->getMSCurManglingNumber()
4849 : S->getMSLastManglingNumber();
4850 }
4851
handleTagNumbering(const TagDecl * Tag,Scope * TagScope)4852 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4853 if (!Context.getLangOpts().CPlusPlus)
4854 return;
4855
4856 if (isa<CXXRecordDecl>(Tag->getParent())) {
4857 // If this tag is the direct child of a class, number it if
4858 // it is anonymous.
4859 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4860 return;
4861 MangleNumberingContext &MCtx =
4862 Context.getManglingNumberContext(Tag->getParent());
4863 Context.setManglingNumber(
4864 Tag, MCtx.getManglingNumber(
4865 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4866 return;
4867 }
4868
4869 // If this tag isn't a direct child of a class, number it if it is local.
4870 MangleNumberingContext *MCtx;
4871 Decl *ManglingContextDecl;
4872 std::tie(MCtx, ManglingContextDecl) =
4873 getCurrentMangleNumberContext(Tag->getDeclContext());
4874 if (MCtx) {
4875 Context.setManglingNumber(
4876 Tag, MCtx->getManglingNumber(
4877 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4878 }
4879 }
4880
4881 namespace {
4882 struct NonCLikeKind {
4883 enum {
4884 None,
4885 BaseClass,
4886 DefaultMemberInit,
4887 Lambda,
4888 Friend,
4889 OtherMember,
4890 Invalid,
4891 } Kind = None;
4892 SourceRange Range;
4893
operator bool__anon82674d9a1011::NonCLikeKind4894 explicit operator bool() { return Kind != None; }
4895 };
4896 }
4897
4898 /// Determine whether a class is C-like, according to the rules of C++
4899 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
getNonCLikeKindForAnonymousStruct(const CXXRecordDecl * RD)4900 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4901 if (RD->isInvalidDecl())
4902 return {NonCLikeKind::Invalid, {}};
4903
4904 // C++ [dcl.typedef]p9: [P1766R1]
4905 // An unnamed class with a typedef name for linkage purposes shall not
4906 //
4907 // -- have any base classes
4908 if (RD->getNumBases())
4909 return {NonCLikeKind::BaseClass,
4910 SourceRange(RD->bases_begin()->getBeginLoc(),
4911 RD->bases_end()[-1].getEndLoc())};
4912 bool Invalid = false;
4913 for (Decl *D : RD->decls()) {
4914 // Don't complain about things we already diagnosed.
4915 if (D->isInvalidDecl()) {
4916 Invalid = true;
4917 continue;
4918 }
4919
4920 // -- have any [...] default member initializers
4921 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4922 if (FD->hasInClassInitializer()) {
4923 auto *Init = FD->getInClassInitializer();
4924 return {NonCLikeKind::DefaultMemberInit,
4925 Init ? Init->getSourceRange() : D->getSourceRange()};
4926 }
4927 continue;
4928 }
4929
4930 // FIXME: We don't allow friend declarations. This violates the wording of
4931 // P1766, but not the intent.
4932 if (isa<FriendDecl>(D))
4933 return {NonCLikeKind::Friend, D->getSourceRange()};
4934
4935 // -- declare any members other than non-static data members, member
4936 // enumerations, or member classes,
4937 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4938 isa<EnumDecl>(D))
4939 continue;
4940 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4941 if (!MemberRD) {
4942 if (D->isImplicit())
4943 continue;
4944 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4945 }
4946
4947 // -- contain a lambda-expression,
4948 if (MemberRD->isLambda())
4949 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4950
4951 // and all member classes shall also satisfy these requirements
4952 // (recursively).
4953 if (MemberRD->isThisDeclarationADefinition()) {
4954 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4955 return Kind;
4956 }
4957 }
4958
4959 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4960 }
4961
setTagNameForLinkagePurposes(TagDecl * TagFromDeclSpec,TypedefNameDecl * NewTD)4962 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4963 TypedefNameDecl *NewTD) {
4964 if (TagFromDeclSpec->isInvalidDecl())
4965 return;
4966
4967 // Do nothing if the tag already has a name for linkage purposes.
4968 if (TagFromDeclSpec->hasNameForLinkage())
4969 return;
4970
4971 // A well-formed anonymous tag must always be a TUK_Definition.
4972 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4973
4974 // The type must match the tag exactly; no qualifiers allowed.
4975 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4976 Context.getTagDeclType(TagFromDeclSpec))) {
4977 if (getLangOpts().CPlusPlus)
4978 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4979 return;
4980 }
4981
4982 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4983 // An unnamed class with a typedef name for linkage purposes shall [be
4984 // C-like].
4985 //
4986 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4987 // shouldn't happen, but there are constructs that the language rule doesn't
4988 // disallow for which we can't reasonably avoid computing linkage early.
4989 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4990 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4991 : NonCLikeKind();
4992 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4993 if (NonCLike || ChangesLinkage) {
4994 if (NonCLike.Kind == NonCLikeKind::Invalid)
4995 return;
4996
4997 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4998 if (ChangesLinkage) {
4999 // If the linkage changes, we can't accept this as an extension.
5000 if (NonCLike.Kind == NonCLikeKind::None)
5001 DiagID = diag::err_typedef_changes_linkage;
5002 else
5003 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5004 }
5005
5006 SourceLocation FixitLoc =
5007 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5008 llvm::SmallString<40> TextToInsert;
5009 TextToInsert += ' ';
5010 TextToInsert += NewTD->getIdentifier()->getName();
5011
5012 Diag(FixitLoc, DiagID)
5013 << isa<TypeAliasDecl>(NewTD)
5014 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5015 if (NonCLike.Kind != NonCLikeKind::None) {
5016 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5017 << NonCLike.Kind - 1 << NonCLike.Range;
5018 }
5019 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5020 << NewTD << isa<TypeAliasDecl>(NewTD);
5021
5022 if (ChangesLinkage)
5023 return;
5024 }
5025
5026 // Otherwise, set this as the anon-decl typedef for the tag.
5027 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5028 }
5029
GetDiagnosticTypeSpecifierID(DeclSpec::TST T)5030 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
5031 switch (T) {
5032 case DeclSpec::TST_class:
5033 return 0;
5034 case DeclSpec::TST_struct:
5035 return 1;
5036 case DeclSpec::TST_interface:
5037 return 2;
5038 case DeclSpec::TST_union:
5039 return 3;
5040 case DeclSpec::TST_enum:
5041 return 4;
5042 default:
5043 llvm_unreachable("unexpected type specifier");
5044 }
5045 }
5046
5047 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5048 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5049 /// parameters to cope with template friend declarations.
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,const ParsedAttributesView & DeclAttrs,MultiTemplateParamsArg TemplateParams,bool IsExplicitInstantiation,RecordDecl * & AnonRecord)5050 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5051 DeclSpec &DS,
5052 const ParsedAttributesView &DeclAttrs,
5053 MultiTemplateParamsArg TemplateParams,
5054 bool IsExplicitInstantiation,
5055 RecordDecl *&AnonRecord) {
5056 Decl *TagD = nullptr;
5057 TagDecl *Tag = nullptr;
5058 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5059 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5060 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5061 DS.getTypeSpecType() == DeclSpec::TST_union ||
5062 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5063 TagD = DS.getRepAsDecl();
5064
5065 if (!TagD) // We probably had an error
5066 return nullptr;
5067
5068 // Note that the above type specs guarantee that the
5069 // type rep is a Decl, whereas in many of the others
5070 // it's a Type.
5071 if (isa<TagDecl>(TagD))
5072 Tag = cast<TagDecl>(TagD);
5073 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5074 Tag = CTD->getTemplatedDecl();
5075 }
5076
5077 if (Tag) {
5078 handleTagNumbering(Tag, S);
5079 Tag->setFreeStanding();
5080 if (Tag->isInvalidDecl())
5081 return Tag;
5082 }
5083
5084 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5085 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5086 // or incomplete types shall not be restrict-qualified."
5087 if (TypeQuals & DeclSpec::TQ_restrict)
5088 Diag(DS.getRestrictSpecLoc(),
5089 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5090 << DS.getSourceRange();
5091 }
5092
5093 if (DS.isInlineSpecified())
5094 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5095 << getLangOpts().CPlusPlus17;
5096
5097 if (DS.hasConstexprSpecifier()) {
5098 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5099 // and definitions of functions and variables.
5100 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5101 // the declaration of a function or function template
5102 if (Tag)
5103 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5104 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
5105 << static_cast<int>(DS.getConstexprSpecifier());
5106 else
5107 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5108 << static_cast<int>(DS.getConstexprSpecifier());
5109 // Don't emit warnings after this error.
5110 return TagD;
5111 }
5112
5113 DiagnoseFunctionSpecifiers(DS);
5114
5115 if (DS.isFriendSpecified()) {
5116 // If we're dealing with a decl but not a TagDecl, assume that
5117 // whatever routines created it handled the friendship aspect.
5118 if (TagD && !Tag)
5119 return nullptr;
5120 return ActOnFriendTypeDecl(S, DS, TemplateParams);
5121 }
5122
5123 const CXXScopeSpec &SS = DS.getTypeSpecScope();
5124 bool IsExplicitSpecialization =
5125 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
5126 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
5127 !IsExplicitInstantiation && !IsExplicitSpecialization &&
5128 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
5129 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5130 // nested-name-specifier unless it is an explicit instantiation
5131 // or an explicit specialization.
5132 //
5133 // FIXME: We allow class template partial specializations here too, per the
5134 // obvious intent of DR1819.
5135 //
5136 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5137 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5138 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
5139 return nullptr;
5140 }
5141
5142 // Track whether this decl-specifier declares anything.
5143 bool DeclaresAnything = true;
5144
5145 // Handle anonymous struct definitions.
5146 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5147 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5148 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5149 if (getLangOpts().CPlusPlus ||
5150 Record->getDeclContext()->isRecord()) {
5151 // If CurContext is a DeclContext that can contain statements,
5152 // RecursiveASTVisitor won't visit the decls that
5153 // BuildAnonymousStructOrUnion() will put into CurContext.
5154 // Also store them here so that they can be part of the
5155 // DeclStmt that gets created in this case.
5156 // FIXME: Also return the IndirectFieldDecls created by
5157 // BuildAnonymousStructOr union, for the same reason?
5158 if (CurContext->isFunctionOrMethod())
5159 AnonRecord = Record;
5160 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5161 Context.getPrintingPolicy());
5162 }
5163
5164 DeclaresAnything = false;
5165 }
5166 }
5167
5168 // C11 6.7.2.1p2:
5169 // A struct-declaration that does not declare an anonymous structure or
5170 // anonymous union shall contain a struct-declarator-list.
5171 //
5172 // This rule also existed in C89 and C99; the grammar for struct-declaration
5173 // did not permit a struct-declaration without a struct-declarator-list.
5174 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5175 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5176 // Check for Microsoft C extension: anonymous struct/union member.
5177 // Handle 2 kinds of anonymous struct/union:
5178 // struct STRUCT;
5179 // union UNION;
5180 // and
5181 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5182 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5183 if ((Tag && Tag->getDeclName()) ||
5184 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5185 RecordDecl *Record = nullptr;
5186 if (Tag)
5187 Record = dyn_cast<RecordDecl>(Tag);
5188 else if (const RecordType *RT =
5189 DS.getRepAsType().get()->getAsStructureType())
5190 Record = RT->getDecl();
5191 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5192 Record = UT->getDecl();
5193
5194 if (Record && getLangOpts().MicrosoftExt) {
5195 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5196 << Record->isUnion() << DS.getSourceRange();
5197 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5198 }
5199
5200 DeclaresAnything = false;
5201 }
5202 }
5203
5204 // Skip all the checks below if we have a type error.
5205 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5206 (TagD && TagD->isInvalidDecl()))
5207 return TagD;
5208
5209 if (getLangOpts().CPlusPlus &&
5210 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5211 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5212 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5213 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5214 DeclaresAnything = false;
5215
5216 if (!DS.isMissingDeclaratorOk()) {
5217 // Customize diagnostic for a typedef missing a name.
5218 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5219 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5220 << DS.getSourceRange();
5221 else
5222 DeclaresAnything = false;
5223 }
5224
5225 if (DS.isModulePrivateSpecified() &&
5226 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5227 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5228 << Tag->getTagKind()
5229 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5230
5231 ActOnDocumentableDecl(TagD);
5232
5233 // C 6.7/2:
5234 // A declaration [...] shall declare at least a declarator [...], a tag,
5235 // or the members of an enumeration.
5236 // C++ [dcl.dcl]p3:
5237 // [If there are no declarators], and except for the declaration of an
5238 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5239 // names into the program, or shall redeclare a name introduced by a
5240 // previous declaration.
5241 if (!DeclaresAnything) {
5242 // In C, we allow this as a (popular) extension / bug. Don't bother
5243 // producing further diagnostics for redundant qualifiers after this.
5244 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5245 ? diag::err_no_declarators
5246 : diag::ext_no_declarators)
5247 << DS.getSourceRange();
5248 return TagD;
5249 }
5250
5251 // C++ [dcl.stc]p1:
5252 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5253 // init-declarator-list of the declaration shall not be empty.
5254 // C++ [dcl.fct.spec]p1:
5255 // If a cv-qualifier appears in a decl-specifier-seq, the
5256 // init-declarator-list of the declaration shall not be empty.
5257 //
5258 // Spurious qualifiers here appear to be valid in C.
5259 unsigned DiagID = diag::warn_standalone_specifier;
5260 if (getLangOpts().CPlusPlus)
5261 DiagID = diag::ext_standalone_specifier;
5262
5263 // Note that a linkage-specification sets a storage class, but
5264 // 'extern "C" struct foo;' is actually valid and not theoretically
5265 // useless.
5266 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5267 if (SCS == DeclSpec::SCS_mutable)
5268 // Since mutable is not a viable storage class specifier in C, there is
5269 // no reason to treat it as an extension. Instead, diagnose as an error.
5270 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5271 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5272 Diag(DS.getStorageClassSpecLoc(), DiagID)
5273 << DeclSpec::getSpecifierName(SCS);
5274 }
5275
5276 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5277 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5278 << DeclSpec::getSpecifierName(TSCS);
5279 if (DS.getTypeQualifiers()) {
5280 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5281 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5282 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5283 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5284 // Restrict is covered above.
5285 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5286 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5287 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5288 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5289 }
5290
5291 // Warn about ignored type attributes, for example:
5292 // __attribute__((aligned)) struct A;
5293 // Attributes should be placed after tag to apply to type declaration.
5294 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5295 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5296 if (TypeSpecType == DeclSpec::TST_class ||
5297 TypeSpecType == DeclSpec::TST_struct ||
5298 TypeSpecType == DeclSpec::TST_interface ||
5299 TypeSpecType == DeclSpec::TST_union ||
5300 TypeSpecType == DeclSpec::TST_enum) {
5301 for (const ParsedAttr &AL : DS.getAttributes())
5302 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5303 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5304 for (const ParsedAttr &AL : DeclAttrs)
5305 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5306 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5307 }
5308 }
5309
5310 return TagD;
5311 }
5312
5313 /// We are trying to inject an anonymous member into the given scope;
5314 /// check if there's an existing declaration that can't be overloaded.
5315 ///
5316 /// \return true if this is a forbidden redeclaration
CheckAnonMemberRedeclaration(Sema & SemaRef,Scope * S,DeclContext * Owner,DeclarationName Name,SourceLocation NameLoc,bool IsUnion)5317 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5318 Scope *S,
5319 DeclContext *Owner,
5320 DeclarationName Name,
5321 SourceLocation NameLoc,
5322 bool IsUnion) {
5323 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5324 Sema::ForVisibleRedeclaration);
5325 if (!SemaRef.LookupName(R, S)) return false;
5326
5327 // Pick a representative declaration.
5328 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5329 assert(PrevDecl && "Expected a non-null Decl");
5330
5331 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5332 return false;
5333
5334 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5335 << IsUnion << Name;
5336 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5337
5338 return true;
5339 }
5340
5341 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5342 /// anonymous struct or union AnonRecord into the owning context Owner
5343 /// and scope S. This routine will be invoked just after we realize
5344 /// that an unnamed union or struct is actually an anonymous union or
5345 /// struct, e.g.,
5346 ///
5347 /// @code
5348 /// union {
5349 /// int i;
5350 /// float f;
5351 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5352 /// // f into the surrounding scope.x
5353 /// @endcode
5354 ///
5355 /// This routine is recursive, injecting the names of nested anonymous
5356 /// structs/unions into the owning context and scope as well.
5357 static bool
InjectAnonymousStructOrUnionMembers(Sema & SemaRef,Scope * S,DeclContext * Owner,RecordDecl * AnonRecord,AccessSpecifier AS,SmallVectorImpl<NamedDecl * > & Chaining)5358 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5359 RecordDecl *AnonRecord, AccessSpecifier AS,
5360 SmallVectorImpl<NamedDecl *> &Chaining) {
5361 bool Invalid = false;
5362
5363 // Look every FieldDecl and IndirectFieldDecl with a name.
5364 for (auto *D : AnonRecord->decls()) {
5365 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5366 cast<NamedDecl>(D)->getDeclName()) {
5367 ValueDecl *VD = cast<ValueDecl>(D);
5368 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5369 VD->getLocation(),
5370 AnonRecord->isUnion())) {
5371 // C++ [class.union]p2:
5372 // The names of the members of an anonymous union shall be
5373 // distinct from the names of any other entity in the
5374 // scope in which the anonymous union is declared.
5375 Invalid = true;
5376 } else {
5377 // C++ [class.union]p2:
5378 // For the purpose of name lookup, after the anonymous union
5379 // definition, the members of the anonymous union are
5380 // considered to have been defined in the scope in which the
5381 // anonymous union is declared.
5382 unsigned OldChainingSize = Chaining.size();
5383 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5384 Chaining.append(IF->chain_begin(), IF->chain_end());
5385 else
5386 Chaining.push_back(VD);
5387
5388 assert(Chaining.size() >= 2);
5389 NamedDecl **NamedChain =
5390 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5391 for (unsigned i = 0; i < Chaining.size(); i++)
5392 NamedChain[i] = Chaining[i];
5393
5394 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5395 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5396 VD->getType(), {NamedChain, Chaining.size()});
5397
5398 for (const auto *Attr : VD->attrs())
5399 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5400
5401 IndirectField->setAccess(AS);
5402 IndirectField->setImplicit();
5403 SemaRef.PushOnScopeChains(IndirectField, S);
5404
5405 // That includes picking up the appropriate access specifier.
5406 if (AS != AS_none) IndirectField->setAccess(AS);
5407
5408 Chaining.resize(OldChainingSize);
5409 }
5410 }
5411 }
5412
5413 return Invalid;
5414 }
5415
5416 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5417 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5418 /// illegal input values are mapped to SC_None.
5419 static StorageClass
StorageClassSpecToVarDeclStorageClass(const DeclSpec & DS)5420 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5421 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5422 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5423 "Parser allowed 'typedef' as storage class VarDecl.");
5424 switch (StorageClassSpec) {
5425 case DeclSpec::SCS_unspecified: return SC_None;
5426 case DeclSpec::SCS_extern:
5427 if (DS.isExternInLinkageSpec())
5428 return SC_None;
5429 return SC_Extern;
5430 case DeclSpec::SCS_static: return SC_Static;
5431 case DeclSpec::SCS_auto: return SC_Auto;
5432 case DeclSpec::SCS_register: return SC_Register;
5433 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5434 // Illegal SCSs map to None: error reporting is up to the caller.
5435 case DeclSpec::SCS_mutable: // Fall through.
5436 case DeclSpec::SCS_typedef: return SC_None;
5437 }
5438 llvm_unreachable("unknown storage class specifier");
5439 }
5440
findDefaultInitializer(const CXXRecordDecl * Record)5441 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5442 assert(Record->hasInClassInitializer());
5443
5444 for (const auto *I : Record->decls()) {
5445 const auto *FD = dyn_cast<FieldDecl>(I);
5446 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5447 FD = IFD->getAnonField();
5448 if (FD && FD->hasInClassInitializer())
5449 return FD->getLocation();
5450 }
5451
5452 llvm_unreachable("couldn't find in-class initializer");
5453 }
5454
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,SourceLocation DefaultInitLoc)5455 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5456 SourceLocation DefaultInitLoc) {
5457 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5458 return;
5459
5460 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5461 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5462 }
5463
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,CXXRecordDecl * AnonUnion)5464 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5465 CXXRecordDecl *AnonUnion) {
5466 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5467 return;
5468
5469 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5470 }
5471
5472 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5473 /// anonymous structure or union. Anonymous unions are a C++ feature
5474 /// (C++ [class.union]) and a C11 feature; anonymous structures
5475 /// are a C11 feature and GNU C++ extension.
BuildAnonymousStructOrUnion(Scope * S,DeclSpec & DS,AccessSpecifier AS,RecordDecl * Record,const PrintingPolicy & Policy)5476 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5477 AccessSpecifier AS,
5478 RecordDecl *Record,
5479 const PrintingPolicy &Policy) {
5480 DeclContext *Owner = Record->getDeclContext();
5481
5482 // Diagnose whether this anonymous struct/union is an extension.
5483 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5484 Diag(Record->getLocation(), diag::ext_anonymous_union);
5485 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5486 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5487 else if (!Record->isUnion() && !getLangOpts().C11)
5488 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5489
5490 // C and C++ require different kinds of checks for anonymous
5491 // structs/unions.
5492 bool Invalid = false;
5493 if (getLangOpts().CPlusPlus) {
5494 const char *PrevSpec = nullptr;
5495 if (Record->isUnion()) {
5496 // C++ [class.union]p6:
5497 // C++17 [class.union.anon]p2:
5498 // Anonymous unions declared in a named namespace or in the
5499 // global namespace shall be declared static.
5500 unsigned DiagID;
5501 DeclContext *OwnerScope = Owner->getRedeclContext();
5502 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5503 (OwnerScope->isTranslationUnit() ||
5504 (OwnerScope->isNamespace() &&
5505 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5506 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5507 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5508
5509 // Recover by adding 'static'.
5510 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5511 PrevSpec, DiagID, Policy);
5512 }
5513 // C++ [class.union]p6:
5514 // A storage class is not allowed in a declaration of an
5515 // anonymous union in a class scope.
5516 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5517 isa<RecordDecl>(Owner)) {
5518 Diag(DS.getStorageClassSpecLoc(),
5519 diag::err_anonymous_union_with_storage_spec)
5520 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5521
5522 // Recover by removing the storage specifier.
5523 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5524 SourceLocation(),
5525 PrevSpec, DiagID, Context.getPrintingPolicy());
5526 }
5527 }
5528
5529 // Ignore const/volatile/restrict qualifiers.
5530 if (DS.getTypeQualifiers()) {
5531 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5532 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5533 << Record->isUnion() << "const"
5534 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5535 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5536 Diag(DS.getVolatileSpecLoc(),
5537 diag::ext_anonymous_struct_union_qualified)
5538 << Record->isUnion() << "volatile"
5539 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5540 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5541 Diag(DS.getRestrictSpecLoc(),
5542 diag::ext_anonymous_struct_union_qualified)
5543 << Record->isUnion() << "restrict"
5544 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5545 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5546 Diag(DS.getAtomicSpecLoc(),
5547 diag::ext_anonymous_struct_union_qualified)
5548 << Record->isUnion() << "_Atomic"
5549 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5550 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5551 Diag(DS.getUnalignedSpecLoc(),
5552 diag::ext_anonymous_struct_union_qualified)
5553 << Record->isUnion() << "__unaligned"
5554 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5555
5556 DS.ClearTypeQualifiers();
5557 }
5558
5559 // C++ [class.union]p2:
5560 // The member-specification of an anonymous union shall only
5561 // define non-static data members. [Note: nested types and
5562 // functions cannot be declared within an anonymous union. ]
5563 for (auto *Mem : Record->decls()) {
5564 // Ignore invalid declarations; we already diagnosed them.
5565 if (Mem->isInvalidDecl())
5566 continue;
5567
5568 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5569 // C++ [class.union]p3:
5570 // An anonymous union shall not have private or protected
5571 // members (clause 11).
5572 assert(FD->getAccess() != AS_none);
5573 if (FD->getAccess() != AS_public) {
5574 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5575 << Record->isUnion() << (FD->getAccess() == AS_protected);
5576 Invalid = true;
5577 }
5578
5579 // C++ [class.union]p1
5580 // An object of a class with a non-trivial constructor, a non-trivial
5581 // copy constructor, a non-trivial destructor, or a non-trivial copy
5582 // assignment operator cannot be a member of a union, nor can an
5583 // array of such objects.
5584 if (CheckNontrivialField(FD))
5585 Invalid = true;
5586 } else if (Mem->isImplicit()) {
5587 // Any implicit members are fine.
5588 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5589 // This is a type that showed up in an
5590 // elaborated-type-specifier inside the anonymous struct or
5591 // union, but which actually declares a type outside of the
5592 // anonymous struct or union. It's okay.
5593 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5594 if (!MemRecord->isAnonymousStructOrUnion() &&
5595 MemRecord->getDeclName()) {
5596 // Visual C++ allows type definition in anonymous struct or union.
5597 if (getLangOpts().MicrosoftExt)
5598 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5599 << Record->isUnion();
5600 else {
5601 // This is a nested type declaration.
5602 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5603 << Record->isUnion();
5604 Invalid = true;
5605 }
5606 } else {
5607 // This is an anonymous type definition within another anonymous type.
5608 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5609 // not part of standard C++.
5610 Diag(MemRecord->getLocation(),
5611 diag::ext_anonymous_record_with_anonymous_type)
5612 << Record->isUnion();
5613 }
5614 } else if (isa<AccessSpecDecl>(Mem)) {
5615 // Any access specifier is fine.
5616 } else if (isa<StaticAssertDecl>(Mem)) {
5617 // In C++1z, static_assert declarations are also fine.
5618 } else {
5619 // We have something that isn't a non-static data
5620 // member. Complain about it.
5621 unsigned DK = diag::err_anonymous_record_bad_member;
5622 if (isa<TypeDecl>(Mem))
5623 DK = diag::err_anonymous_record_with_type;
5624 else if (isa<FunctionDecl>(Mem))
5625 DK = diag::err_anonymous_record_with_function;
5626 else if (isa<VarDecl>(Mem))
5627 DK = diag::err_anonymous_record_with_static;
5628
5629 // Visual C++ allows type definition in anonymous struct or union.
5630 if (getLangOpts().MicrosoftExt &&
5631 DK == diag::err_anonymous_record_with_type)
5632 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5633 << Record->isUnion();
5634 else {
5635 Diag(Mem->getLocation(), DK) << Record->isUnion();
5636 Invalid = true;
5637 }
5638 }
5639 }
5640
5641 // C++11 [class.union]p8 (DR1460):
5642 // At most one variant member of a union may have a
5643 // brace-or-equal-initializer.
5644 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5645 Owner->isRecord())
5646 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5647 cast<CXXRecordDecl>(Record));
5648 }
5649
5650 if (!Record->isUnion() && !Owner->isRecord()) {
5651 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5652 << getLangOpts().CPlusPlus;
5653 Invalid = true;
5654 }
5655
5656 // C++ [dcl.dcl]p3:
5657 // [If there are no declarators], and except for the declaration of an
5658 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5659 // names into the program
5660 // C++ [class.mem]p2:
5661 // each such member-declaration shall either declare at least one member
5662 // name of the class or declare at least one unnamed bit-field
5663 //
5664 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5665 if (getLangOpts().CPlusPlus && Record->field_empty())
5666 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5667
5668 // Mock up a declarator.
5669 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5670 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5671 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5672
5673 // Create a declaration for this anonymous struct/union.
5674 NamedDecl *Anon = nullptr;
5675 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5676 Anon = FieldDecl::Create(
5677 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5678 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5679 /*BitWidth=*/nullptr, /*Mutable=*/false,
5680 /*InitStyle=*/ICIS_NoInit);
5681 Anon->setAccess(AS);
5682 ProcessDeclAttributes(S, Anon, Dc);
5683
5684 if (getLangOpts().CPlusPlus)
5685 FieldCollector->Add(cast<FieldDecl>(Anon));
5686 } else {
5687 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5688 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5689 if (SCSpec == DeclSpec::SCS_mutable) {
5690 // mutable can only appear on non-static class members, so it's always
5691 // an error here
5692 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5693 Invalid = true;
5694 SC = SC_None;
5695 }
5696
5697 assert(DS.getAttributes().empty() && "No attribute expected");
5698 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5699 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5700 Context.getTypeDeclType(Record), TInfo, SC);
5701
5702 // Default-initialize the implicit variable. This initialization will be
5703 // trivial in almost all cases, except if a union member has an in-class
5704 // initializer:
5705 // union { int n = 0; };
5706 ActOnUninitializedDecl(Anon);
5707 }
5708 Anon->setImplicit();
5709
5710 // Mark this as an anonymous struct/union type.
5711 Record->setAnonymousStructOrUnion(true);
5712
5713 // Add the anonymous struct/union object to the current
5714 // context. We'll be referencing this object when we refer to one of
5715 // its members.
5716 Owner->addDecl(Anon);
5717
5718 // Inject the members of the anonymous struct/union into the owning
5719 // context and into the identifier resolver chain for name lookup
5720 // purposes.
5721 SmallVector<NamedDecl*, 2> Chain;
5722 Chain.push_back(Anon);
5723
5724 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5725 Invalid = true;
5726
5727 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5728 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5729 MangleNumberingContext *MCtx;
5730 Decl *ManglingContextDecl;
5731 std::tie(MCtx, ManglingContextDecl) =
5732 getCurrentMangleNumberContext(NewVD->getDeclContext());
5733 if (MCtx) {
5734 Context.setManglingNumber(
5735 NewVD, MCtx->getManglingNumber(
5736 NewVD, getMSManglingNumber(getLangOpts(), S)));
5737 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5738 }
5739 }
5740 }
5741
5742 if (Invalid)
5743 Anon->setInvalidDecl();
5744
5745 return Anon;
5746 }
5747
5748 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5749 /// Microsoft C anonymous structure.
5750 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5751 /// Example:
5752 ///
5753 /// struct A { int a; };
5754 /// struct B { struct A; int b; };
5755 ///
5756 /// void foo() {
5757 /// B var;
5758 /// var.a = 3;
5759 /// }
5760 ///
BuildMicrosoftCAnonymousStruct(Scope * S,DeclSpec & DS,RecordDecl * Record)5761 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5762 RecordDecl *Record) {
5763 assert(Record && "expected a record!");
5764
5765 // Mock up a declarator.
5766 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5767 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5768 assert(TInfo && "couldn't build declarator info for anonymous struct");
5769
5770 auto *ParentDecl = cast<RecordDecl>(CurContext);
5771 QualType RecTy = Context.getTypeDeclType(Record);
5772
5773 // Create a declaration for this anonymous struct.
5774 NamedDecl *Anon =
5775 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5776 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5777 /*BitWidth=*/nullptr, /*Mutable=*/false,
5778 /*InitStyle=*/ICIS_NoInit);
5779 Anon->setImplicit();
5780
5781 // Add the anonymous struct object to the current context.
5782 CurContext->addDecl(Anon);
5783
5784 // Inject the members of the anonymous struct into the current
5785 // context and into the identifier resolver chain for name lookup
5786 // purposes.
5787 SmallVector<NamedDecl*, 2> Chain;
5788 Chain.push_back(Anon);
5789
5790 RecordDecl *RecordDef = Record->getDefinition();
5791 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5792 diag::err_field_incomplete_or_sizeless) ||
5793 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5794 AS_none, Chain)) {
5795 Anon->setInvalidDecl();
5796 ParentDecl->setInvalidDecl();
5797 }
5798
5799 return Anon;
5800 }
5801
5802 /// GetNameForDeclarator - Determine the full declaration name for the
5803 /// given Declarator.
GetNameForDeclarator(Declarator & D)5804 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5805 return GetNameFromUnqualifiedId(D.getName());
5806 }
5807
5808 /// Retrieves the declaration name from a parsed unqualified-id.
5809 DeclarationNameInfo
GetNameFromUnqualifiedId(const UnqualifiedId & Name)5810 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5811 DeclarationNameInfo NameInfo;
5812 NameInfo.setLoc(Name.StartLocation);
5813
5814 switch (Name.getKind()) {
5815
5816 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5817 case UnqualifiedIdKind::IK_Identifier:
5818 NameInfo.setName(Name.Identifier);
5819 return NameInfo;
5820
5821 case UnqualifiedIdKind::IK_DeductionGuideName: {
5822 // C++ [temp.deduct.guide]p3:
5823 // The simple-template-id shall name a class template specialization.
5824 // The template-name shall be the same identifier as the template-name
5825 // of the simple-template-id.
5826 // These together intend to imply that the template-name shall name a
5827 // class template.
5828 // FIXME: template<typename T> struct X {};
5829 // template<typename T> using Y = X<T>;
5830 // Y(int) -> Y<int>;
5831 // satisfies these rules but does not name a class template.
5832 TemplateName TN = Name.TemplateName.get().get();
5833 auto *Template = TN.getAsTemplateDecl();
5834 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5835 Diag(Name.StartLocation,
5836 diag::err_deduction_guide_name_not_class_template)
5837 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5838 if (Template)
5839 Diag(Template->getLocation(), diag::note_template_decl_here);
5840 return DeclarationNameInfo();
5841 }
5842
5843 NameInfo.setName(
5844 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5845 return NameInfo;
5846 }
5847
5848 case UnqualifiedIdKind::IK_OperatorFunctionId:
5849 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5850 Name.OperatorFunctionId.Operator));
5851 NameInfo.setCXXOperatorNameRange(SourceRange(
5852 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5853 return NameInfo;
5854
5855 case UnqualifiedIdKind::IK_LiteralOperatorId:
5856 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5857 Name.Identifier));
5858 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5859 return NameInfo;
5860
5861 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5862 TypeSourceInfo *TInfo;
5863 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5864 if (Ty.isNull())
5865 return DeclarationNameInfo();
5866 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5867 Context.getCanonicalType(Ty)));
5868 NameInfo.setNamedTypeInfo(TInfo);
5869 return NameInfo;
5870 }
5871
5872 case UnqualifiedIdKind::IK_ConstructorName: {
5873 TypeSourceInfo *TInfo;
5874 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5875 if (Ty.isNull())
5876 return DeclarationNameInfo();
5877 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5878 Context.getCanonicalType(Ty)));
5879 NameInfo.setNamedTypeInfo(TInfo);
5880 return NameInfo;
5881 }
5882
5883 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5884 // In well-formed code, we can only have a constructor
5885 // template-id that refers to the current context, so go there
5886 // to find the actual type being constructed.
5887 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5888 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5889 return DeclarationNameInfo();
5890
5891 // Determine the type of the class being constructed.
5892 QualType CurClassType = Context.getTypeDeclType(CurClass);
5893
5894 // FIXME: Check two things: that the template-id names the same type as
5895 // CurClassType, and that the template-id does not occur when the name
5896 // was qualified.
5897
5898 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5899 Context.getCanonicalType(CurClassType)));
5900 // FIXME: should we retrieve TypeSourceInfo?
5901 NameInfo.setNamedTypeInfo(nullptr);
5902 return NameInfo;
5903 }
5904
5905 case UnqualifiedIdKind::IK_DestructorName: {
5906 TypeSourceInfo *TInfo;
5907 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5908 if (Ty.isNull())
5909 return DeclarationNameInfo();
5910 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5911 Context.getCanonicalType(Ty)));
5912 NameInfo.setNamedTypeInfo(TInfo);
5913 return NameInfo;
5914 }
5915
5916 case UnqualifiedIdKind::IK_TemplateId: {
5917 TemplateName TName = Name.TemplateId->Template.get();
5918 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5919 return Context.getNameForTemplate(TName, TNameLoc);
5920 }
5921
5922 } // switch (Name.getKind())
5923
5924 llvm_unreachable("Unknown name kind");
5925 }
5926
getCoreType(QualType Ty)5927 static QualType getCoreType(QualType Ty) {
5928 do {
5929 if (Ty->isPointerType() || Ty->isReferenceType())
5930 Ty = Ty->getPointeeType();
5931 else if (Ty->isArrayType())
5932 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5933 else
5934 return Ty.withoutLocalFastQualifiers();
5935 } while (true);
5936 }
5937
5938 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5939 /// and Definition have "nearly" matching parameters. This heuristic is
5940 /// used to improve diagnostics in the case where an out-of-line function
5941 /// definition doesn't match any declaration within the class or namespace.
5942 /// Also sets Params to the list of indices to the parameters that differ
5943 /// between the declaration and the definition. If hasSimilarParameters
5944 /// returns true and Params is empty, then all of the parameters match.
hasSimilarParameters(ASTContext & Context,FunctionDecl * Declaration,FunctionDecl * Definition,SmallVectorImpl<unsigned> & Params)5945 static bool hasSimilarParameters(ASTContext &Context,
5946 FunctionDecl *Declaration,
5947 FunctionDecl *Definition,
5948 SmallVectorImpl<unsigned> &Params) {
5949 Params.clear();
5950 if (Declaration->param_size() != Definition->param_size())
5951 return false;
5952 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5953 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5954 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5955
5956 // The parameter types are identical
5957 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5958 continue;
5959
5960 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5961 QualType DefParamBaseTy = getCoreType(DefParamTy);
5962 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5963 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5964
5965 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5966 (DeclTyName && DeclTyName == DefTyName))
5967 Params.push_back(Idx);
5968 else // The two parameters aren't even close
5969 return false;
5970 }
5971
5972 return true;
5973 }
5974
5975 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5976 /// declarator needs to be rebuilt in the current instantiation.
5977 /// Any bits of declarator which appear before the name are valid for
5978 /// consideration here. That's specifically the type in the decl spec
5979 /// and the base type in any member-pointer chunks.
RebuildDeclaratorInCurrentInstantiation(Sema & S,Declarator & D,DeclarationName Name)5980 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5981 DeclarationName Name) {
5982 // The types we specifically need to rebuild are:
5983 // - typenames, typeofs, and decltypes
5984 // - types which will become injected class names
5985 // Of course, we also need to rebuild any type referencing such a
5986 // type. It's safest to just say "dependent", but we call out a
5987 // few cases here.
5988
5989 DeclSpec &DS = D.getMutableDeclSpec();
5990 switch (DS.getTypeSpecType()) {
5991 case DeclSpec::TST_typename:
5992 case DeclSpec::TST_typeofType:
5993 case DeclSpec::TST_typeof_unqualType:
5994 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
5995 #include "clang/Basic/TransformTypeTraits.def"
5996 case DeclSpec::TST_atomic: {
5997 // Grab the type from the parser.
5998 TypeSourceInfo *TSI = nullptr;
5999 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6000 if (T.isNull() || !T->isInstantiationDependentType()) break;
6001
6002 // Make sure there's a type source info. This isn't really much
6003 // of a waste; most dependent types should have type source info
6004 // attached already.
6005 if (!TSI)
6006 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
6007
6008 // Rebuild the type in the current instantiation.
6009 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6010 if (!TSI) return true;
6011
6012 // Store the new type back in the decl spec.
6013 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6014 DS.UpdateTypeRep(LocType);
6015 break;
6016 }
6017
6018 case DeclSpec::TST_decltype:
6019 case DeclSpec::TST_typeof_unqualExpr:
6020 case DeclSpec::TST_typeofExpr: {
6021 Expr *E = DS.getRepAsExpr();
6022 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6023 if (Result.isInvalid()) return true;
6024 DS.UpdateExprRep(Result.get());
6025 break;
6026 }
6027
6028 default:
6029 // Nothing to do for these decl specs.
6030 break;
6031 }
6032
6033 // It doesn't matter what order we do this in.
6034 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6035 DeclaratorChunk &Chunk = D.getTypeObject(I);
6036
6037 // The only type information in the declarator which can come
6038 // before the declaration name is the base type of a member
6039 // pointer.
6040 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6041 continue;
6042
6043 // Rebuild the scope specifier in-place.
6044 CXXScopeSpec &SS = Chunk.Mem.Scope();
6045 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6046 return true;
6047 }
6048
6049 return false;
6050 }
6051
6052 /// Returns true if the declaration is declared in a system header or from a
6053 /// system macro.
isFromSystemHeader(SourceManager & SM,const Decl * D)6054 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6055 return SM.isInSystemHeader(D->getLocation()) ||
6056 SM.isInSystemMacro(D->getLocation());
6057 }
6058
warnOnReservedIdentifier(const NamedDecl * D)6059 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6060 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6061 // of system decl.
6062 if (D->getPreviousDecl() || D->isImplicit())
6063 return;
6064 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6065 if (Status != ReservedIdentifierStatus::NotReserved &&
6066 !isFromSystemHeader(Context.getSourceManager(), D)) {
6067 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6068 << D << static_cast<int>(Status);
6069 }
6070 }
6071
ActOnDeclarator(Scope * S,Declarator & D)6072 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6073 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6074
6075 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6076 // declaration only if the `bind_to_declaration` extension is set.
6077 SmallVector<FunctionDecl *, 4> Bases;
6078 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
6079 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6080 implementation_extension_bind_to_declaration))
6081 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6082 S, D, MultiTemplateParamsArg(), Bases);
6083
6084 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6085
6086 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6087 Dcl && Dcl->getDeclContext()->isFileContext())
6088 Dcl->setTopLevelDeclInObjCContainer();
6089
6090 if (!Bases.empty())
6091 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
6092
6093 return Dcl;
6094 }
6095
6096 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6097 /// If T is the name of a class, then each of the following shall have a
6098 /// name different from T:
6099 /// - every static data member of class T;
6100 /// - every member function of class T
6101 /// - every member of class T that is itself a type;
6102 /// \returns true if the declaration name violates these rules.
DiagnoseClassNameShadow(DeclContext * DC,DeclarationNameInfo NameInfo)6103 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6104 DeclarationNameInfo NameInfo) {
6105 DeclarationName Name = NameInfo.getName();
6106
6107 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6108 while (Record && Record->isAnonymousStructOrUnion())
6109 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6110 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6111 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6112 return true;
6113 }
6114
6115 return false;
6116 }
6117
6118 /// Diagnose a declaration whose declarator-id has the given
6119 /// nested-name-specifier.
6120 ///
6121 /// \param SS The nested-name-specifier of the declarator-id.
6122 ///
6123 /// \param DC The declaration context to which the nested-name-specifier
6124 /// resolves.
6125 ///
6126 /// \param Name The name of the entity being declared.
6127 ///
6128 /// \param Loc The location of the name of the entity being declared.
6129 ///
6130 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6131 /// we're declaring an explicit / partial specialization / instantiation.
6132 ///
6133 /// \returns true if we cannot safely recover from this error, false otherwise.
diagnoseQualifiedDeclaration(CXXScopeSpec & SS,DeclContext * DC,DeclarationName Name,SourceLocation Loc,bool IsTemplateId)6134 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6135 DeclarationName Name,
6136 SourceLocation Loc, bool IsTemplateId) {
6137 DeclContext *Cur = CurContext;
6138 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6139 Cur = Cur->getParent();
6140
6141 // If the user provided a superfluous scope specifier that refers back to the
6142 // class in which the entity is already declared, diagnose and ignore it.
6143 //
6144 // class X {
6145 // void X::f();
6146 // };
6147 //
6148 // Note, it was once ill-formed to give redundant qualification in all
6149 // contexts, but that rule was removed by DR482.
6150 if (Cur->Equals(DC)) {
6151 if (Cur->isRecord()) {
6152 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6153 : diag::err_member_extra_qualification)
6154 << Name << FixItHint::CreateRemoval(SS.getRange());
6155 SS.clear();
6156 } else {
6157 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6158 }
6159 return false;
6160 }
6161
6162 // Check whether the qualifying scope encloses the scope of the original
6163 // declaration. For a template-id, we perform the checks in
6164 // CheckTemplateSpecializationScope.
6165 if (!Cur->Encloses(DC) && !IsTemplateId) {
6166 if (Cur->isRecord())
6167 Diag(Loc, diag::err_member_qualification)
6168 << Name << SS.getRange();
6169 else if (isa<TranslationUnitDecl>(DC))
6170 Diag(Loc, diag::err_invalid_declarator_global_scope)
6171 << Name << SS.getRange();
6172 else if (isa<FunctionDecl>(Cur))
6173 Diag(Loc, diag::err_invalid_declarator_in_function)
6174 << Name << SS.getRange();
6175 else if (isa<BlockDecl>(Cur))
6176 Diag(Loc, diag::err_invalid_declarator_in_block)
6177 << Name << SS.getRange();
6178 else if (isa<ExportDecl>(Cur)) {
6179 if (!isa<NamespaceDecl>(DC))
6180 Diag(Loc, diag::err_export_non_namespace_scope_name)
6181 << Name << SS.getRange();
6182 else
6183 // The cases that DC is not NamespaceDecl should be handled in
6184 // CheckRedeclarationExported.
6185 return false;
6186 } else
6187 Diag(Loc, diag::err_invalid_declarator_scope)
6188 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6189
6190 return true;
6191 }
6192
6193 if (Cur->isRecord()) {
6194 // Cannot qualify members within a class.
6195 Diag(Loc, diag::err_member_qualification)
6196 << Name << SS.getRange();
6197 SS.clear();
6198
6199 // C++ constructors and destructors with incorrect scopes can break
6200 // our AST invariants by having the wrong underlying types. If
6201 // that's the case, then drop this declaration entirely.
6202 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6203 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6204 !Context.hasSameType(Name.getCXXNameType(),
6205 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6206 return true;
6207
6208 return false;
6209 }
6210
6211 // C++11 [dcl.meaning]p1:
6212 // [...] "The nested-name-specifier of the qualified declarator-id shall
6213 // not begin with a decltype-specifer"
6214 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6215 while (SpecLoc.getPrefix())
6216 SpecLoc = SpecLoc.getPrefix();
6217 if (isa_and_nonnull<DecltypeType>(
6218 SpecLoc.getNestedNameSpecifier()->getAsType()))
6219 Diag(Loc, diag::err_decltype_in_declarator)
6220 << SpecLoc.getTypeLoc().getSourceRange();
6221
6222 return false;
6223 }
6224
HandleDeclarator(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParamLists)6225 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6226 MultiTemplateParamsArg TemplateParamLists) {
6227 // TODO: consider using NameInfo for diagnostic.
6228 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6229 DeclarationName Name = NameInfo.getName();
6230
6231 // All of these full declarators require an identifier. If it doesn't have
6232 // one, the ParsedFreeStandingDeclSpec action should be used.
6233 if (D.isDecompositionDeclarator()) {
6234 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6235 } else if (!Name) {
6236 if (!D.isInvalidType()) // Reject this if we think it is valid.
6237 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6238 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6239 return nullptr;
6240 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6241 return nullptr;
6242
6243 // The scope passed in may not be a decl scope. Zip up the scope tree until
6244 // we find one that is.
6245 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6246 (S->getFlags() & Scope::TemplateParamScope) != 0)
6247 S = S->getParent();
6248
6249 DeclContext *DC = CurContext;
6250 if (D.getCXXScopeSpec().isInvalid())
6251 D.setInvalidType();
6252 else if (D.getCXXScopeSpec().isSet()) {
6253 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6254 UPPC_DeclarationQualifier))
6255 return nullptr;
6256
6257 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6258 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6259 if (!DC || isa<EnumDecl>(DC)) {
6260 // If we could not compute the declaration context, it's because the
6261 // declaration context is dependent but does not refer to a class,
6262 // class template, or class template partial specialization. Complain
6263 // and return early, to avoid the coming semantic disaster.
6264 Diag(D.getIdentifierLoc(),
6265 diag::err_template_qualified_declarator_no_match)
6266 << D.getCXXScopeSpec().getScopeRep()
6267 << D.getCXXScopeSpec().getRange();
6268 return nullptr;
6269 }
6270 bool IsDependentContext = DC->isDependentContext();
6271
6272 if (!IsDependentContext &&
6273 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6274 return nullptr;
6275
6276 // If a class is incomplete, do not parse entities inside it.
6277 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6278 Diag(D.getIdentifierLoc(),
6279 diag::err_member_def_undefined_record)
6280 << Name << DC << D.getCXXScopeSpec().getRange();
6281 return nullptr;
6282 }
6283 if (!D.getDeclSpec().isFriendSpecified()) {
6284 if (diagnoseQualifiedDeclaration(
6285 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6286 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6287 if (DC->isRecord())
6288 return nullptr;
6289
6290 D.setInvalidType();
6291 }
6292 }
6293
6294 // Check whether we need to rebuild the type of the given
6295 // declaration in the current instantiation.
6296 if (EnteringContext && IsDependentContext &&
6297 TemplateParamLists.size() != 0) {
6298 ContextRAII SavedContext(*this, DC);
6299 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6300 D.setInvalidType();
6301 }
6302 }
6303
6304 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6305 QualType R = TInfo->getType();
6306
6307 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6308 UPPC_DeclarationType))
6309 D.setInvalidType();
6310
6311 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6312 forRedeclarationInCurContext());
6313
6314 // See if this is a redefinition of a variable in the same scope.
6315 if (!D.getCXXScopeSpec().isSet()) {
6316 bool IsLinkageLookup = false;
6317 bool CreateBuiltins = false;
6318
6319 // If the declaration we're planning to build will be a function
6320 // or object with linkage, then look for another declaration with
6321 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6322 //
6323 // If the declaration we're planning to build will be declared with
6324 // external linkage in the translation unit, create any builtin with
6325 // the same name.
6326 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6327 /* Do nothing*/;
6328 else if (CurContext->isFunctionOrMethod() &&
6329 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6330 R->isFunctionType())) {
6331 IsLinkageLookup = true;
6332 CreateBuiltins =
6333 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6334 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6335 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6336 CreateBuiltins = true;
6337
6338 if (IsLinkageLookup) {
6339 Previous.clear(LookupRedeclarationWithLinkage);
6340 Previous.setRedeclarationKind(ForExternalRedeclaration);
6341 }
6342
6343 LookupName(Previous, S, CreateBuiltins);
6344 } else { // Something like "int foo::x;"
6345 LookupQualifiedName(Previous, DC);
6346
6347 // C++ [dcl.meaning]p1:
6348 // When the declarator-id is qualified, the declaration shall refer to a
6349 // previously declared member of the class or namespace to which the
6350 // qualifier refers (or, in the case of a namespace, of an element of the
6351 // inline namespace set of that namespace (7.3.1)) or to a specialization
6352 // thereof; [...]
6353 //
6354 // Note that we already checked the context above, and that we do not have
6355 // enough information to make sure that Previous contains the declaration
6356 // we want to match. For example, given:
6357 //
6358 // class X {
6359 // void f();
6360 // void f(float);
6361 // };
6362 //
6363 // void X::f(int) { } // ill-formed
6364 //
6365 // In this case, Previous will point to the overload set
6366 // containing the two f's declared in X, but neither of them
6367 // matches.
6368
6369 // C++ [dcl.meaning]p1:
6370 // [...] the member shall not merely have been introduced by a
6371 // using-declaration in the scope of the class or namespace nominated by
6372 // the nested-name-specifier of the declarator-id.
6373 RemoveUsingDecls(Previous);
6374 }
6375
6376 if (Previous.isSingleResult() &&
6377 Previous.getFoundDecl()->isTemplateParameter()) {
6378 // Maybe we will complain about the shadowed template parameter.
6379 if (!D.isInvalidType())
6380 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6381 Previous.getFoundDecl());
6382
6383 // Just pretend that we didn't see the previous declaration.
6384 Previous.clear();
6385 }
6386
6387 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6388 // Forget that the previous declaration is the injected-class-name.
6389 Previous.clear();
6390
6391 // In C++, the previous declaration we find might be a tag type
6392 // (class or enum). In this case, the new declaration will hide the
6393 // tag type. Note that this applies to functions, function templates, and
6394 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6395 if (Previous.isSingleTagDecl() &&
6396 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6397 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6398 Previous.clear();
6399
6400 // Check that there are no default arguments other than in the parameters
6401 // of a function declaration (C++ only).
6402 if (getLangOpts().CPlusPlus)
6403 CheckExtraCXXDefaultArguments(D);
6404
6405 NamedDecl *New;
6406
6407 bool AddToScope = true;
6408 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6409 if (TemplateParamLists.size()) {
6410 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6411 return nullptr;
6412 }
6413
6414 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6415 } else if (R->isFunctionType()) {
6416 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6417 TemplateParamLists,
6418 AddToScope);
6419 } else {
6420 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6421 AddToScope);
6422 }
6423
6424 if (!New)
6425 return nullptr;
6426
6427 // If this has an identifier and is not a function template specialization,
6428 // add it to the scope stack.
6429 if (New->getDeclName() && AddToScope)
6430 PushOnScopeChains(New, S);
6431
6432 if (isInOpenMPDeclareTargetContext())
6433 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6434
6435 return New;
6436 }
6437
6438 /// Helper method to turn variable array types into constant array
6439 /// types in certain situations which would otherwise be errors (for
6440 /// GCC compatibility).
TryToFixInvalidVariablyModifiedType(QualType T,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)6441 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6442 ASTContext &Context,
6443 bool &SizeIsNegative,
6444 llvm::APSInt &Oversized) {
6445 // This method tries to turn a variable array into a constant
6446 // array even when the size isn't an ICE. This is necessary
6447 // for compatibility with code that depends on gcc's buggy
6448 // constant expression folding, like struct {char x[(int)(char*)2];}
6449 SizeIsNegative = false;
6450 Oversized = 0;
6451
6452 if (T->isDependentType())
6453 return QualType();
6454
6455 QualifierCollector Qs;
6456 const Type *Ty = Qs.strip(T);
6457
6458 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6459 QualType Pointee = PTy->getPointeeType();
6460 QualType FixedType =
6461 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6462 Oversized);
6463 if (FixedType.isNull()) return FixedType;
6464 FixedType = Context.getPointerType(FixedType);
6465 return Qs.apply(Context, FixedType);
6466 }
6467 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6468 QualType Inner = PTy->getInnerType();
6469 QualType FixedType =
6470 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6471 Oversized);
6472 if (FixedType.isNull()) return FixedType;
6473 FixedType = Context.getParenType(FixedType);
6474 return Qs.apply(Context, FixedType);
6475 }
6476
6477 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6478 if (!VLATy)
6479 return QualType();
6480
6481 QualType ElemTy = VLATy->getElementType();
6482 if (ElemTy->isVariablyModifiedType()) {
6483 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6484 SizeIsNegative, Oversized);
6485 if (ElemTy.isNull())
6486 return QualType();
6487 }
6488
6489 Expr::EvalResult Result;
6490 if (!VLATy->getSizeExpr() ||
6491 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6492 return QualType();
6493
6494 llvm::APSInt Res = Result.Val.getInt();
6495
6496 // Check whether the array size is negative.
6497 if (Res.isSigned() && Res.isNegative()) {
6498 SizeIsNegative = true;
6499 return QualType();
6500 }
6501
6502 // Check whether the array is too large to be addressed.
6503 unsigned ActiveSizeBits =
6504 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6505 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6506 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6507 : Res.getActiveBits();
6508 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6509 Oversized = Res;
6510 return QualType();
6511 }
6512
6513 QualType FoldedArrayType = Context.getConstantArrayType(
6514 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6515 return Qs.apply(Context, FoldedArrayType);
6516 }
6517
6518 static void
FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL,TypeLoc DstTL)6519 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6520 SrcTL = SrcTL.getUnqualifiedLoc();
6521 DstTL = DstTL.getUnqualifiedLoc();
6522 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6523 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6524 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6525 DstPTL.getPointeeLoc());
6526 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6527 return;
6528 }
6529 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6530 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6531 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6532 DstPTL.getInnerLoc());
6533 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6534 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6535 return;
6536 }
6537 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6538 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6539 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6540 TypeLoc DstElemTL = DstATL.getElementLoc();
6541 if (VariableArrayTypeLoc SrcElemATL =
6542 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6543 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6544 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6545 } else {
6546 DstElemTL.initializeFullCopy(SrcElemTL);
6547 }
6548 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6549 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6550 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6551 }
6552
6553 /// Helper method to turn variable array types into constant array
6554 /// types in certain situations which would otherwise be errors (for
6555 /// GCC compatibility).
6556 static TypeSourceInfo*
TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo * TInfo,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)6557 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6558 ASTContext &Context,
6559 bool &SizeIsNegative,
6560 llvm::APSInt &Oversized) {
6561 QualType FixedTy
6562 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6563 SizeIsNegative, Oversized);
6564 if (FixedTy.isNull())
6565 return nullptr;
6566 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6567 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6568 FixedTInfo->getTypeLoc());
6569 return FixedTInfo;
6570 }
6571
6572 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6573 /// true if we were successful.
tryToFixVariablyModifiedVarType(TypeSourceInfo * & TInfo,QualType & T,SourceLocation Loc,unsigned FailedFoldDiagID)6574 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6575 QualType &T, SourceLocation Loc,
6576 unsigned FailedFoldDiagID) {
6577 bool SizeIsNegative;
6578 llvm::APSInt Oversized;
6579 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6580 TInfo, Context, SizeIsNegative, Oversized);
6581 if (FixedTInfo) {
6582 Diag(Loc, diag::ext_vla_folded_to_constant);
6583 TInfo = FixedTInfo;
6584 T = FixedTInfo->getType();
6585 return true;
6586 }
6587
6588 if (SizeIsNegative)
6589 Diag(Loc, diag::err_typecheck_negative_array_size);
6590 else if (Oversized.getBoolValue())
6591 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6592 else if (FailedFoldDiagID)
6593 Diag(Loc, FailedFoldDiagID);
6594 return false;
6595 }
6596
6597 /// Register the given locally-scoped extern "C" declaration so
6598 /// that it can be found later for redeclarations. We include any extern "C"
6599 /// declaration that is not visible in the translation unit here, not just
6600 /// function-scope declarations.
6601 void
RegisterLocallyScopedExternCDecl(NamedDecl * ND,Scope * S)6602 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6603 if (!getLangOpts().CPlusPlus &&
6604 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6605 // Don't need to track declarations in the TU in C.
6606 return;
6607
6608 // Note that we have a locally-scoped external with this name.
6609 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6610 }
6611
findLocallyScopedExternCDecl(DeclarationName Name)6612 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6613 // FIXME: We can have multiple results via __attribute__((overloadable)).
6614 auto Result = Context.getExternCContextDecl()->lookup(Name);
6615 return Result.empty() ? nullptr : *Result.begin();
6616 }
6617
6618 /// Diagnose function specifiers on a declaration of an identifier that
6619 /// does not identify a function.
DiagnoseFunctionSpecifiers(const DeclSpec & DS)6620 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6621 // FIXME: We should probably indicate the identifier in question to avoid
6622 // confusion for constructs like "virtual int a(), b;"
6623 if (DS.isVirtualSpecified())
6624 Diag(DS.getVirtualSpecLoc(),
6625 diag::err_virtual_non_function);
6626
6627 if (DS.hasExplicitSpecifier())
6628 Diag(DS.getExplicitSpecLoc(),
6629 diag::err_explicit_non_function);
6630
6631 if (DS.isNoreturnSpecified())
6632 Diag(DS.getNoreturnSpecLoc(),
6633 diag::err_noreturn_non_function);
6634 }
6635
6636 NamedDecl*
ActOnTypedefDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous)6637 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6638 TypeSourceInfo *TInfo, LookupResult &Previous) {
6639 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6640 if (D.getCXXScopeSpec().isSet()) {
6641 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6642 << D.getCXXScopeSpec().getRange();
6643 D.setInvalidType();
6644 // Pretend we didn't see the scope specifier.
6645 DC = CurContext;
6646 Previous.clear();
6647 }
6648
6649 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6650
6651 if (D.getDeclSpec().isInlineSpecified())
6652 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6653 << getLangOpts().CPlusPlus17;
6654 if (D.getDeclSpec().hasConstexprSpecifier())
6655 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6656 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6657
6658 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6659 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6660 Diag(D.getName().StartLocation,
6661 diag::err_deduction_guide_invalid_specifier)
6662 << "typedef";
6663 else
6664 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6665 << D.getName().getSourceRange();
6666 return nullptr;
6667 }
6668
6669 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6670 if (!NewTD) return nullptr;
6671
6672 // Handle attributes prior to checking for duplicates in MergeVarDecl
6673 ProcessDeclAttributes(S, NewTD, D);
6674
6675 CheckTypedefForVariablyModifiedType(S, NewTD);
6676
6677 bool Redeclaration = D.isRedeclaration();
6678 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6679 D.setRedeclaration(Redeclaration);
6680 return ND;
6681 }
6682
6683 void
CheckTypedefForVariablyModifiedType(Scope * S,TypedefNameDecl * NewTD)6684 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6685 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6686 // then it shall have block scope.
6687 // Note that variably modified types must be fixed before merging the decl so
6688 // that redeclarations will match.
6689 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6690 QualType T = TInfo->getType();
6691 if (T->isVariablyModifiedType()) {
6692 setFunctionHasBranchProtectedScope();
6693
6694 if (S->getFnParent() == nullptr) {
6695 bool SizeIsNegative;
6696 llvm::APSInt Oversized;
6697 TypeSourceInfo *FixedTInfo =
6698 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6699 SizeIsNegative,
6700 Oversized);
6701 if (FixedTInfo) {
6702 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6703 NewTD->setTypeSourceInfo(FixedTInfo);
6704 } else {
6705 if (SizeIsNegative)
6706 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6707 else if (T->isVariableArrayType())
6708 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6709 else if (Oversized.getBoolValue())
6710 Diag(NewTD->getLocation(), diag::err_array_too_large)
6711 << toString(Oversized, 10);
6712 else
6713 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6714 NewTD->setInvalidDecl();
6715 }
6716 }
6717 }
6718 }
6719
6720 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6721 /// declares a typedef-name, either using the 'typedef' type specifier or via
6722 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6723 NamedDecl*
ActOnTypedefNameDecl(Scope * S,DeclContext * DC,TypedefNameDecl * NewTD,LookupResult & Previous,bool & Redeclaration)6724 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6725 LookupResult &Previous, bool &Redeclaration) {
6726
6727 // Find the shadowed declaration before filtering for scope.
6728 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6729
6730 // Merge the decl with the existing one if appropriate. If the decl is
6731 // in an outer scope, it isn't the same thing.
6732 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6733 /*AllowInlineNamespace*/false);
6734 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6735 if (!Previous.empty()) {
6736 Redeclaration = true;
6737 MergeTypedefNameDecl(S, NewTD, Previous);
6738 } else {
6739 inferGslPointerAttribute(NewTD);
6740 }
6741
6742 if (ShadowedDecl && !Redeclaration)
6743 CheckShadow(NewTD, ShadowedDecl, Previous);
6744
6745 // If this is the C FILE type, notify the AST context.
6746 if (IdentifierInfo *II = NewTD->getIdentifier())
6747 if (!NewTD->isInvalidDecl() &&
6748 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6749 if (II->isStr("FILE"))
6750 Context.setFILEDecl(NewTD);
6751 else if (II->isStr("jmp_buf"))
6752 Context.setjmp_bufDecl(NewTD);
6753 else if (II->isStr("sigjmp_buf"))
6754 Context.setsigjmp_bufDecl(NewTD);
6755 else if (II->isStr("ucontext_t"))
6756 Context.setucontext_tDecl(NewTD);
6757 }
6758
6759 return NewTD;
6760 }
6761
6762 /// Determines whether the given declaration is an out-of-scope
6763 /// previous declaration.
6764 ///
6765 /// This routine should be invoked when name lookup has found a
6766 /// previous declaration (PrevDecl) that is not in the scope where a
6767 /// new declaration by the same name is being introduced. If the new
6768 /// declaration occurs in a local scope, previous declarations with
6769 /// linkage may still be considered previous declarations (C99
6770 /// 6.2.2p4-5, C++ [basic.link]p6).
6771 ///
6772 /// \param PrevDecl the previous declaration found by name
6773 /// lookup
6774 ///
6775 /// \param DC the context in which the new declaration is being
6776 /// declared.
6777 ///
6778 /// \returns true if PrevDecl is an out-of-scope previous declaration
6779 /// for a new delcaration with the same name.
6780 static bool
isOutOfScopePreviousDeclaration(NamedDecl * PrevDecl,DeclContext * DC,ASTContext & Context)6781 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6782 ASTContext &Context) {
6783 if (!PrevDecl)
6784 return false;
6785
6786 if (!PrevDecl->hasLinkage())
6787 return false;
6788
6789 if (Context.getLangOpts().CPlusPlus) {
6790 // C++ [basic.link]p6:
6791 // If there is a visible declaration of an entity with linkage
6792 // having the same name and type, ignoring entities declared
6793 // outside the innermost enclosing namespace scope, the block
6794 // scope declaration declares that same entity and receives the
6795 // linkage of the previous declaration.
6796 DeclContext *OuterContext = DC->getRedeclContext();
6797 if (!OuterContext->isFunctionOrMethod())
6798 // This rule only applies to block-scope declarations.
6799 return false;
6800
6801 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6802 if (PrevOuterContext->isRecord())
6803 // We found a member function: ignore it.
6804 return false;
6805
6806 // Find the innermost enclosing namespace for the new and
6807 // previous declarations.
6808 OuterContext = OuterContext->getEnclosingNamespaceContext();
6809 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6810
6811 // The previous declaration is in a different namespace, so it
6812 // isn't the same function.
6813 if (!OuterContext->Equals(PrevOuterContext))
6814 return false;
6815 }
6816
6817 return true;
6818 }
6819
SetNestedNameSpecifier(Sema & S,DeclaratorDecl * DD,Declarator & D)6820 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6821 CXXScopeSpec &SS = D.getCXXScopeSpec();
6822 if (!SS.isSet()) return;
6823 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6824 }
6825
inferObjCARCLifetime(ValueDecl * decl)6826 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6827 QualType type = decl->getType();
6828 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6829 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6830 // Various kinds of declaration aren't allowed to be __autoreleasing.
6831 unsigned kind = -1U;
6832 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6833 if (var->hasAttr<BlocksAttr>())
6834 kind = 0; // __block
6835 else if (!var->hasLocalStorage())
6836 kind = 1; // global
6837 } else if (isa<ObjCIvarDecl>(decl)) {
6838 kind = 3; // ivar
6839 } else if (isa<FieldDecl>(decl)) {
6840 kind = 2; // field
6841 }
6842
6843 if (kind != -1U) {
6844 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6845 << kind;
6846 }
6847 } else if (lifetime == Qualifiers::OCL_None) {
6848 // Try to infer lifetime.
6849 if (!type->isObjCLifetimeType())
6850 return false;
6851
6852 lifetime = type->getObjCARCImplicitLifetime();
6853 type = Context.getLifetimeQualifiedType(type, lifetime);
6854 decl->setType(type);
6855 }
6856
6857 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6858 // Thread-local variables cannot have lifetime.
6859 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6860 var->getTLSKind()) {
6861 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6862 << var->getType();
6863 return true;
6864 }
6865 }
6866
6867 return false;
6868 }
6869
deduceOpenCLAddressSpace(ValueDecl * Decl)6870 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6871 if (Decl->getType().hasAddressSpace())
6872 return;
6873 if (Decl->getType()->isDependentType())
6874 return;
6875 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6876 QualType Type = Var->getType();
6877 if (Type->isSamplerT() || Type->isVoidType())
6878 return;
6879 LangAS ImplAS = LangAS::opencl_private;
6880 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6881 // __opencl_c_program_scope_global_variables feature, the address space
6882 // for a variable at program scope or a static or extern variable inside
6883 // a function are inferred to be __global.
6884 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6885 Var->hasGlobalStorage())
6886 ImplAS = LangAS::opencl_global;
6887 // If the original type from a decayed type is an array type and that array
6888 // type has no address space yet, deduce it now.
6889 if (auto DT = dyn_cast<DecayedType>(Type)) {
6890 auto OrigTy = DT->getOriginalType();
6891 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6892 // Add the address space to the original array type and then propagate
6893 // that to the element type through `getAsArrayType`.
6894 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6895 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6896 // Re-generate the decayed type.
6897 Type = Context.getDecayedType(OrigTy);
6898 }
6899 }
6900 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6901 // Apply any qualifiers (including address space) from the array type to
6902 // the element type. This implements C99 6.7.3p8: "If the specification of
6903 // an array type includes any type qualifiers, the element type is so
6904 // qualified, not the array type."
6905 if (Type->isArrayType())
6906 Type = QualType(Context.getAsArrayType(Type), 0);
6907 Decl->setType(Type);
6908 }
6909 }
6910
checkAttributesAfterMerging(Sema & S,NamedDecl & ND)6911 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6912 // Ensure that an auto decl is deduced otherwise the checks below might cache
6913 // the wrong linkage.
6914 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6915
6916 // 'weak' only applies to declarations with external linkage.
6917 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6918 if (!ND.isExternallyVisible()) {
6919 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6920 ND.dropAttr<WeakAttr>();
6921 }
6922 }
6923 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6924 if (ND.isExternallyVisible()) {
6925 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6926 ND.dropAttr<WeakRefAttr>();
6927 ND.dropAttr<AliasAttr>();
6928 }
6929 }
6930
6931 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6932 if (VD->hasInit()) {
6933 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6934 assert(VD->isThisDeclarationADefinition() &&
6935 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6936 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6937 VD->dropAttr<AliasAttr>();
6938 }
6939 }
6940 }
6941
6942 // 'selectany' only applies to externally visible variable declarations.
6943 // It does not apply to functions.
6944 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6945 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6946 S.Diag(Attr->getLocation(),
6947 diag::err_attribute_selectany_non_extern_data);
6948 ND.dropAttr<SelectAnyAttr>();
6949 }
6950 }
6951
6952 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6953 auto *VD = dyn_cast<VarDecl>(&ND);
6954 bool IsAnonymousNS = false;
6955 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6956 if (VD) {
6957 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6958 while (NS && !IsAnonymousNS) {
6959 IsAnonymousNS = NS->isAnonymousNamespace();
6960 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6961 }
6962 }
6963 // dll attributes require external linkage. Static locals may have external
6964 // linkage but still cannot be explicitly imported or exported.
6965 // In Microsoft mode, a variable defined in anonymous namespace must have
6966 // external linkage in order to be exported.
6967 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6968 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6969 (!AnonNSInMicrosoftMode &&
6970 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6971 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6972 << &ND << Attr;
6973 ND.setInvalidDecl();
6974 }
6975 }
6976
6977 // Check the attributes on the function type, if any.
6978 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6979 // Don't declare this variable in the second operand of the for-statement;
6980 // GCC miscompiles that by ending its lifetime before evaluating the
6981 // third operand. See gcc.gnu.org/PR86769.
6982 AttributedTypeLoc ATL;
6983 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6984 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6985 TL = ATL.getModifiedLoc()) {
6986 // The [[lifetimebound]] attribute can be applied to the implicit object
6987 // parameter of a non-static member function (other than a ctor or dtor)
6988 // by applying it to the function type.
6989 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6990 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6991 if (!MD || MD->isStatic()) {
6992 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6993 << !MD << A->getRange();
6994 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6995 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6996 << isa<CXXDestructorDecl>(MD) << A->getRange();
6997 }
6998 }
6999 }
7000 }
7001 }
7002
checkDLLAttributeRedeclaration(Sema & S,NamedDecl * OldDecl,NamedDecl * NewDecl,bool IsSpecialization,bool IsDefinition)7003 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7004 NamedDecl *NewDecl,
7005 bool IsSpecialization,
7006 bool IsDefinition) {
7007 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7008 return;
7009
7010 bool IsTemplate = false;
7011 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7012 OldDecl = OldTD->getTemplatedDecl();
7013 IsTemplate = true;
7014 if (!IsSpecialization)
7015 IsDefinition = false;
7016 }
7017 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7018 NewDecl = NewTD->getTemplatedDecl();
7019 IsTemplate = true;
7020 }
7021
7022 if (!OldDecl || !NewDecl)
7023 return;
7024
7025 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7026 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7027 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7028 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7029
7030 // dllimport and dllexport are inheritable attributes so we have to exclude
7031 // inherited attribute instances.
7032 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7033 (NewExportAttr && !NewExportAttr->isInherited());
7034
7035 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7036 // the only exception being explicit specializations.
7037 // Implicitly generated declarations are also excluded for now because there
7038 // is no other way to switch these to use dllimport or dllexport.
7039 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7040
7041 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7042 // Allow with a warning for free functions and global variables.
7043 bool JustWarn = false;
7044 if (!OldDecl->isCXXClassMember()) {
7045 auto *VD = dyn_cast<VarDecl>(OldDecl);
7046 if (VD && !VD->getDescribedVarTemplate())
7047 JustWarn = true;
7048 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7049 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7050 JustWarn = true;
7051 }
7052
7053 // We cannot change a declaration that's been used because IR has already
7054 // been emitted. Dllimported functions will still work though (modulo
7055 // address equality) as they can use the thunk.
7056 if (OldDecl->isUsed())
7057 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7058 JustWarn = false;
7059
7060 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7061 : diag::err_attribute_dll_redeclaration;
7062 S.Diag(NewDecl->getLocation(), DiagID)
7063 << NewDecl
7064 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7065 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7066 if (!JustWarn) {
7067 NewDecl->setInvalidDecl();
7068 return;
7069 }
7070 }
7071
7072 // A redeclaration is not allowed to drop a dllimport attribute, the only
7073 // exceptions being inline function definitions (except for function
7074 // templates), local extern declarations, qualified friend declarations or
7075 // special MSVC extension: in the last case, the declaration is treated as if
7076 // it were marked dllexport.
7077 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7078 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7079 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7080 // Ignore static data because out-of-line definitions are diagnosed
7081 // separately.
7082 IsStaticDataMember = VD->isStaticDataMember();
7083 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7084 VarDecl::DeclarationOnly;
7085 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7086 IsInline = FD->isInlined();
7087 IsQualifiedFriend = FD->getQualifier() &&
7088 FD->getFriendObjectKind() == Decl::FOK_Declared;
7089 }
7090
7091 if (OldImportAttr && !HasNewAttr &&
7092 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7093 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7094 if (IsMicrosoftABI && IsDefinition) {
7095 if (IsSpecialization) {
7096 S.Diag(
7097 NewDecl->getLocation(),
7098 diag::err_attribute_dllimport_function_specialization_definition);
7099 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7100 NewDecl->dropAttr<DLLImportAttr>();
7101 } else {
7102 S.Diag(NewDecl->getLocation(),
7103 diag::warn_redeclaration_without_import_attribute)
7104 << NewDecl;
7105 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7106 NewDecl->dropAttr<DLLImportAttr>();
7107 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7108 S.Context, NewImportAttr->getRange()));
7109 }
7110 } else if (IsMicrosoftABI && IsSpecialization) {
7111 assert(!IsDefinition);
7112 // MSVC allows this. Keep the inherited attribute.
7113 } else {
7114 S.Diag(NewDecl->getLocation(),
7115 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7116 << NewDecl << OldImportAttr;
7117 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7118 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7119 OldDecl->dropAttr<DLLImportAttr>();
7120 NewDecl->dropAttr<DLLImportAttr>();
7121 }
7122 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7123 // In MinGW, seeing a function declared inline drops the dllimport
7124 // attribute.
7125 OldDecl->dropAttr<DLLImportAttr>();
7126 NewDecl->dropAttr<DLLImportAttr>();
7127 S.Diag(NewDecl->getLocation(),
7128 diag::warn_dllimport_dropped_from_inline_function)
7129 << NewDecl << OldImportAttr;
7130 }
7131
7132 // A specialization of a class template member function is processed here
7133 // since it's a redeclaration. If the parent class is dllexport, the
7134 // specialization inherits that attribute. This doesn't happen automatically
7135 // since the parent class isn't instantiated until later.
7136 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7137 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7138 !NewImportAttr && !NewExportAttr) {
7139 if (const DLLExportAttr *ParentExportAttr =
7140 MD->getParent()->getAttr<DLLExportAttr>()) {
7141 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7142 NewAttr->setInherited(true);
7143 NewDecl->addAttr(NewAttr);
7144 }
7145 }
7146 }
7147 }
7148
7149 /// Given that we are within the definition of the given function,
7150 /// will that definition behave like C99's 'inline', where the
7151 /// definition is discarded except for optimization purposes?
isFunctionDefinitionDiscarded(Sema & S,FunctionDecl * FD)7152 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7153 // Try to avoid calling GetGVALinkageForFunction.
7154
7155 // All cases of this require the 'inline' keyword.
7156 if (!FD->isInlined()) return false;
7157
7158 // This is only possible in C++ with the gnu_inline attribute.
7159 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7160 return false;
7161
7162 // Okay, go ahead and call the relatively-more-expensive function.
7163 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7164 }
7165
7166 /// Determine whether a variable is extern "C" prior to attaching
7167 /// an initializer. We can't just call isExternC() here, because that
7168 /// will also compute and cache whether the declaration is externally
7169 /// visible, which might change when we attach the initializer.
7170 ///
7171 /// This can only be used if the declaration is known to not be a
7172 /// redeclaration of an internal linkage declaration.
7173 ///
7174 /// For instance:
7175 ///
7176 /// auto x = []{};
7177 ///
7178 /// Attaching the initializer here makes this declaration not externally
7179 /// visible, because its type has internal linkage.
7180 ///
7181 /// FIXME: This is a hack.
7182 template<typename T>
isIncompleteDeclExternC(Sema & S,const T * D)7183 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7184 if (S.getLangOpts().CPlusPlus) {
7185 // In C++, the overloadable attribute negates the effects of extern "C".
7186 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7187 return false;
7188
7189 // So do CUDA's host/device attributes.
7190 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7191 D->template hasAttr<CUDAHostAttr>()))
7192 return false;
7193 }
7194 return D->isExternC();
7195 }
7196
shouldConsiderLinkage(const VarDecl * VD)7197 static bool shouldConsiderLinkage(const VarDecl *VD) {
7198 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7199 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7200 isa<OMPDeclareMapperDecl>(DC))
7201 return VD->hasExternalStorage();
7202 if (DC->isFileContext())
7203 return true;
7204 if (DC->isRecord())
7205 return false;
7206 if (DC->getDeclKind() == Decl::HLSLBuffer)
7207 return false;
7208
7209 if (isa<RequiresExprBodyDecl>(DC))
7210 return false;
7211 llvm_unreachable("Unexpected context");
7212 }
7213
shouldConsiderLinkage(const FunctionDecl * FD)7214 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7215 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7216 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7217 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7218 return true;
7219 if (DC->isRecord())
7220 return false;
7221 llvm_unreachable("Unexpected context");
7222 }
7223
hasParsedAttr(Scope * S,const Declarator & PD,ParsedAttr::Kind Kind)7224 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7225 ParsedAttr::Kind Kind) {
7226 // Check decl attributes on the DeclSpec.
7227 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7228 return true;
7229
7230 // Walk the declarator structure, checking decl attributes that were in a type
7231 // position to the decl itself.
7232 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7233 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7234 return true;
7235 }
7236
7237 // Finally, check attributes on the decl itself.
7238 return PD.getAttributes().hasAttribute(Kind) ||
7239 PD.getDeclarationAttributes().hasAttribute(Kind);
7240 }
7241
7242 /// Adjust the \c DeclContext for a function or variable that might be a
7243 /// function-local external declaration.
adjustContextForLocalExternDecl(DeclContext * & DC)7244 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7245 if (!DC->isFunctionOrMethod())
7246 return false;
7247
7248 // If this is a local extern function or variable declared within a function
7249 // template, don't add it into the enclosing namespace scope until it is
7250 // instantiated; it might have a dependent type right now.
7251 if (DC->isDependentContext())
7252 return true;
7253
7254 // C++11 [basic.link]p7:
7255 // When a block scope declaration of an entity with linkage is not found to
7256 // refer to some other declaration, then that entity is a member of the
7257 // innermost enclosing namespace.
7258 //
7259 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7260 // semantically-enclosing namespace, not a lexically-enclosing one.
7261 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7262 DC = DC->getParent();
7263 return true;
7264 }
7265
7266 /// Returns true if given declaration has external C language linkage.
isDeclExternC(const Decl * D)7267 static bool isDeclExternC(const Decl *D) {
7268 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7269 return FD->isExternC();
7270 if (const auto *VD = dyn_cast<VarDecl>(D))
7271 return VD->isExternC();
7272
7273 llvm_unreachable("Unknown type of decl!");
7274 }
7275
7276 /// Returns true if there hasn't been any invalid type diagnosed.
diagnoseOpenCLTypes(Sema & Se,VarDecl * NewVD)7277 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7278 DeclContext *DC = NewVD->getDeclContext();
7279 QualType R = NewVD->getType();
7280
7281 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7282 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7283 // argument.
7284 if (R->isImageType() || R->isPipeType()) {
7285 Se.Diag(NewVD->getLocation(),
7286 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7287 << R;
7288 NewVD->setInvalidDecl();
7289 return false;
7290 }
7291
7292 // OpenCL v1.2 s6.9.r:
7293 // The event type cannot be used to declare a program scope variable.
7294 // OpenCL v2.0 s6.9.q:
7295 // The clk_event_t and reserve_id_t types cannot be declared in program
7296 // scope.
7297 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7298 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7299 Se.Diag(NewVD->getLocation(),
7300 diag::err_invalid_type_for_program_scope_var)
7301 << R;
7302 NewVD->setInvalidDecl();
7303 return false;
7304 }
7305 }
7306
7307 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7308 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7309 Se.getLangOpts())) {
7310 QualType NR = R.getCanonicalType();
7311 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7312 NR->isReferenceType()) {
7313 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7314 NR->isFunctionReferenceType()) {
7315 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7316 << NR->isReferenceType();
7317 NewVD->setInvalidDecl();
7318 return false;
7319 }
7320 NR = NR->getPointeeType();
7321 }
7322 }
7323
7324 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7325 Se.getLangOpts())) {
7326 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7327 // half array type (unless the cl_khr_fp16 extension is enabled).
7328 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7329 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7330 NewVD->setInvalidDecl();
7331 return false;
7332 }
7333 }
7334
7335 // OpenCL v1.2 s6.9.r:
7336 // The event type cannot be used with the __local, __constant and __global
7337 // address space qualifiers.
7338 if (R->isEventT()) {
7339 if (R.getAddressSpace() != LangAS::opencl_private) {
7340 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7341 NewVD->setInvalidDecl();
7342 return false;
7343 }
7344 }
7345
7346 if (R->isSamplerT()) {
7347 // OpenCL v1.2 s6.9.b p4:
7348 // The sampler type cannot be used with the __local and __global address
7349 // space qualifiers.
7350 if (R.getAddressSpace() == LangAS::opencl_local ||
7351 R.getAddressSpace() == LangAS::opencl_global) {
7352 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7353 NewVD->setInvalidDecl();
7354 }
7355
7356 // OpenCL v1.2 s6.12.14.1:
7357 // A global sampler must be declared with either the constant address
7358 // space qualifier or with the const qualifier.
7359 if (DC->isTranslationUnit() &&
7360 !(R.getAddressSpace() == LangAS::opencl_constant ||
7361 R.isConstQualified())) {
7362 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7363 NewVD->setInvalidDecl();
7364 }
7365 if (NewVD->isInvalidDecl())
7366 return false;
7367 }
7368
7369 return true;
7370 }
7371
7372 template <typename AttrTy>
copyAttrFromTypedefToDecl(Sema & S,Decl * D,const TypedefType * TT)7373 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7374 const TypedefNameDecl *TND = TT->getDecl();
7375 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7376 AttrTy *Clone = Attribute->clone(S.Context);
7377 Clone->setInherited(true);
7378 D->addAttr(Clone);
7379 }
7380 }
7381
7382 // This function emits warning and a corresponding note based on the
7383 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7384 // declarations of an annotated type must be const qualified.
emitReadOnlyPlacementAttrWarning(Sema & S,const VarDecl * VD)7385 void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7386 QualType VarType = VD->getType().getCanonicalType();
7387
7388 // Ignore local declarations (for now) and those with const qualification.
7389 // TODO: Local variables should not be allowed if their type declaration has
7390 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7391 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7392 return;
7393
7394 if (VarType->isArrayType()) {
7395 // Retrieve element type for array declarations.
7396 VarType = S.getASTContext().getBaseElementType(VarType);
7397 }
7398
7399 const RecordDecl *RD = VarType->getAsRecordDecl();
7400
7401 // Check if the record declaration is present and if it has any attributes.
7402 if (RD == nullptr)
7403 return;
7404
7405 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7406 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7407 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7408 return;
7409 }
7410 }
7411
ActOnVariableDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamLists,bool & AddToScope,ArrayRef<BindingDecl * > Bindings)7412 NamedDecl *Sema::ActOnVariableDeclarator(
7413 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7414 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7415 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7416 QualType R = TInfo->getType();
7417 DeclarationName Name = GetNameForDeclarator(D).getName();
7418
7419 IdentifierInfo *II = Name.getAsIdentifierInfo();
7420
7421 if (D.isDecompositionDeclarator()) {
7422 // Take the name of the first declarator as our name for diagnostic
7423 // purposes.
7424 auto &Decomp = D.getDecompositionDeclarator();
7425 if (!Decomp.bindings().empty()) {
7426 II = Decomp.bindings()[0].Name;
7427 Name = II;
7428 }
7429 } else if (!II) {
7430 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7431 return nullptr;
7432 }
7433
7434
7435 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7436 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7437
7438 // dllimport globals without explicit storage class are treated as extern. We
7439 // have to change the storage class this early to get the right DeclContext.
7440 if (SC == SC_None && !DC->isRecord() &&
7441 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7442 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7443 SC = SC_Extern;
7444
7445 DeclContext *OriginalDC = DC;
7446 bool IsLocalExternDecl = SC == SC_Extern &&
7447 adjustContextForLocalExternDecl(DC);
7448
7449 if (SCSpec == DeclSpec::SCS_mutable) {
7450 // mutable can only appear on non-static class members, so it's always
7451 // an error here
7452 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7453 D.setInvalidType();
7454 SC = SC_None;
7455 }
7456
7457 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7458 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7459 D.getDeclSpec().getStorageClassSpecLoc())) {
7460 // In C++11, the 'register' storage class specifier is deprecated.
7461 // Suppress the warning in system macros, it's used in macros in some
7462 // popular C system headers, such as in glibc's htonl() macro.
7463 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7464 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7465 : diag::warn_deprecated_register)
7466 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7467 }
7468
7469 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7470
7471 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7472 // C99 6.9p2: The storage-class specifiers auto and register shall not
7473 // appear in the declaration specifiers in an external declaration.
7474 // Global Register+Asm is a GNU extension we support.
7475 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7476 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7477 D.setInvalidType();
7478 }
7479 }
7480
7481 // If this variable has a VLA type and an initializer, try to
7482 // fold to a constant-sized type. This is otherwise invalid.
7483 if (D.hasInitializer() && R->isVariableArrayType())
7484 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7485 /*DiagID=*/0);
7486
7487 bool IsMemberSpecialization = false;
7488 bool IsVariableTemplateSpecialization = false;
7489 bool IsPartialSpecialization = false;
7490 bool IsVariableTemplate = false;
7491 VarDecl *NewVD = nullptr;
7492 VarTemplateDecl *NewTemplate = nullptr;
7493 TemplateParameterList *TemplateParams = nullptr;
7494 if (!getLangOpts().CPlusPlus) {
7495 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7496 II, R, TInfo, SC);
7497
7498 if (R->getContainedDeducedType())
7499 ParsingInitForAutoVars.insert(NewVD);
7500
7501 if (D.isInvalidType())
7502 NewVD->setInvalidDecl();
7503
7504 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7505 NewVD->hasLocalStorage())
7506 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7507 NTCUC_AutoVar, NTCUK_Destruct);
7508 } else {
7509 bool Invalid = false;
7510
7511 if (DC->isRecord() && !CurContext->isRecord()) {
7512 // This is an out-of-line definition of a static data member.
7513 switch (SC) {
7514 case SC_None:
7515 break;
7516 case SC_Static:
7517 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7518 diag::err_static_out_of_line)
7519 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7520 break;
7521 case SC_Auto:
7522 case SC_Register:
7523 case SC_Extern:
7524 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7525 // to names of variables declared in a block or to function parameters.
7526 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7527 // of class members
7528
7529 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7530 diag::err_storage_class_for_static_member)
7531 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7532 break;
7533 case SC_PrivateExtern:
7534 llvm_unreachable("C storage class in c++!");
7535 }
7536 }
7537
7538 if (SC == SC_Static && CurContext->isRecord()) {
7539 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7540 // Walk up the enclosing DeclContexts to check for any that are
7541 // incompatible with static data members.
7542 const DeclContext *FunctionOrMethod = nullptr;
7543 const CXXRecordDecl *AnonStruct = nullptr;
7544 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7545 if (Ctxt->isFunctionOrMethod()) {
7546 FunctionOrMethod = Ctxt;
7547 break;
7548 }
7549 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7550 if (ParentDecl && !ParentDecl->getDeclName()) {
7551 AnonStruct = ParentDecl;
7552 break;
7553 }
7554 }
7555 if (FunctionOrMethod) {
7556 // C++ [class.static.data]p5: A local class shall not have static data
7557 // members.
7558 Diag(D.getIdentifierLoc(),
7559 diag::err_static_data_member_not_allowed_in_local_class)
7560 << Name << RD->getDeclName() << RD->getTagKind();
7561 } else if (AnonStruct) {
7562 // C++ [class.static.data]p4: Unnamed classes and classes contained
7563 // directly or indirectly within unnamed classes shall not contain
7564 // static data members.
7565 Diag(D.getIdentifierLoc(),
7566 diag::err_static_data_member_not_allowed_in_anon_struct)
7567 << Name << AnonStruct->getTagKind();
7568 Invalid = true;
7569 } else if (RD->isUnion()) {
7570 // C++98 [class.union]p1: If a union contains a static data member,
7571 // the program is ill-formed. C++11 drops this restriction.
7572 Diag(D.getIdentifierLoc(),
7573 getLangOpts().CPlusPlus11
7574 ? diag::warn_cxx98_compat_static_data_member_in_union
7575 : diag::ext_static_data_member_in_union) << Name;
7576 }
7577 }
7578 }
7579
7580 // Match up the template parameter lists with the scope specifier, then
7581 // determine whether we have a template or a template specialization.
7582 bool InvalidScope = false;
7583 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7584 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7585 D.getCXXScopeSpec(),
7586 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7587 ? D.getName().TemplateId
7588 : nullptr,
7589 TemplateParamLists,
7590 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7591 Invalid |= InvalidScope;
7592
7593 if (TemplateParams) {
7594 if (!TemplateParams->size() &&
7595 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7596 // There is an extraneous 'template<>' for this variable. Complain
7597 // about it, but allow the declaration of the variable.
7598 Diag(TemplateParams->getTemplateLoc(),
7599 diag::err_template_variable_noparams)
7600 << II
7601 << SourceRange(TemplateParams->getTemplateLoc(),
7602 TemplateParams->getRAngleLoc());
7603 TemplateParams = nullptr;
7604 } else {
7605 // Check that we can declare a template here.
7606 if (CheckTemplateDeclScope(S, TemplateParams))
7607 return nullptr;
7608
7609 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7610 // This is an explicit specialization or a partial specialization.
7611 IsVariableTemplateSpecialization = true;
7612 IsPartialSpecialization = TemplateParams->size() > 0;
7613 } else { // if (TemplateParams->size() > 0)
7614 // This is a template declaration.
7615 IsVariableTemplate = true;
7616
7617 // Only C++1y supports variable templates (N3651).
7618 Diag(D.getIdentifierLoc(),
7619 getLangOpts().CPlusPlus14
7620 ? diag::warn_cxx11_compat_variable_template
7621 : diag::ext_variable_template);
7622 }
7623 }
7624 } else {
7625 // Check that we can declare a member specialization here.
7626 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7627 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7628 return nullptr;
7629 assert((Invalid ||
7630 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7631 "should have a 'template<>' for this decl");
7632 }
7633
7634 if (IsVariableTemplateSpecialization) {
7635 SourceLocation TemplateKWLoc =
7636 TemplateParamLists.size() > 0
7637 ? TemplateParamLists[0]->getTemplateLoc()
7638 : SourceLocation();
7639 DeclResult Res = ActOnVarTemplateSpecialization(
7640 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7641 IsPartialSpecialization);
7642 if (Res.isInvalid())
7643 return nullptr;
7644 NewVD = cast<VarDecl>(Res.get());
7645 AddToScope = false;
7646 } else if (D.isDecompositionDeclarator()) {
7647 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7648 D.getIdentifierLoc(), R, TInfo, SC,
7649 Bindings);
7650 } else
7651 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7652 D.getIdentifierLoc(), II, R, TInfo, SC);
7653
7654 // If this is supposed to be a variable template, create it as such.
7655 if (IsVariableTemplate) {
7656 NewTemplate =
7657 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7658 TemplateParams, NewVD);
7659 NewVD->setDescribedVarTemplate(NewTemplate);
7660 }
7661
7662 // If this decl has an auto type in need of deduction, make a note of the
7663 // Decl so we can diagnose uses of it in its own initializer.
7664 if (R->getContainedDeducedType())
7665 ParsingInitForAutoVars.insert(NewVD);
7666
7667 if (D.isInvalidType() || Invalid) {
7668 NewVD->setInvalidDecl();
7669 if (NewTemplate)
7670 NewTemplate->setInvalidDecl();
7671 }
7672
7673 SetNestedNameSpecifier(*this, NewVD, D);
7674
7675 // If we have any template parameter lists that don't directly belong to
7676 // the variable (matching the scope specifier), store them.
7677 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7678 if (TemplateParamLists.size() > VDTemplateParamLists)
7679 NewVD->setTemplateParameterListsInfo(
7680 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7681 }
7682
7683 if (D.getDeclSpec().isInlineSpecified()) {
7684 if (!getLangOpts().CPlusPlus) {
7685 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7686 << 0;
7687 } else if (CurContext->isFunctionOrMethod()) {
7688 // 'inline' is not allowed on block scope variable declaration.
7689 Diag(D.getDeclSpec().getInlineSpecLoc(),
7690 diag::err_inline_declaration_block_scope) << Name
7691 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7692 } else {
7693 Diag(D.getDeclSpec().getInlineSpecLoc(),
7694 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7695 : diag::ext_inline_variable);
7696 NewVD->setInlineSpecified();
7697 }
7698 }
7699
7700 // Set the lexical context. If the declarator has a C++ scope specifier, the
7701 // lexical context will be different from the semantic context.
7702 NewVD->setLexicalDeclContext(CurContext);
7703 if (NewTemplate)
7704 NewTemplate->setLexicalDeclContext(CurContext);
7705
7706 if (IsLocalExternDecl) {
7707 if (D.isDecompositionDeclarator())
7708 for (auto *B : Bindings)
7709 B->setLocalExternDecl();
7710 else
7711 NewVD->setLocalExternDecl();
7712 }
7713
7714 bool EmitTLSUnsupportedError = false;
7715 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7716 // C++11 [dcl.stc]p4:
7717 // When thread_local is applied to a variable of block scope the
7718 // storage-class-specifier static is implied if it does not appear
7719 // explicitly.
7720 // Core issue: 'static' is not implied if the variable is declared
7721 // 'extern'.
7722 if (NewVD->hasLocalStorage() &&
7723 (SCSpec != DeclSpec::SCS_unspecified ||
7724 TSCS != DeclSpec::TSCS_thread_local ||
7725 !DC->isFunctionOrMethod()))
7726 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7727 diag::err_thread_non_global)
7728 << DeclSpec::getSpecifierName(TSCS);
7729 else if (!Context.getTargetInfo().isTLSSupported()) {
7730 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7731 getLangOpts().SYCLIsDevice) {
7732 // Postpone error emission until we've collected attributes required to
7733 // figure out whether it's a host or device variable and whether the
7734 // error should be ignored.
7735 EmitTLSUnsupportedError = true;
7736 // We still need to mark the variable as TLS so it shows up in AST with
7737 // proper storage class for other tools to use even if we're not going
7738 // to emit any code for it.
7739 NewVD->setTSCSpec(TSCS);
7740 } else
7741 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7742 diag::err_thread_unsupported);
7743 } else
7744 NewVD->setTSCSpec(TSCS);
7745 }
7746
7747 switch (D.getDeclSpec().getConstexprSpecifier()) {
7748 case ConstexprSpecKind::Unspecified:
7749 break;
7750
7751 case ConstexprSpecKind::Consteval:
7752 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7753 diag::err_constexpr_wrong_decl_kind)
7754 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7755 [[fallthrough]];
7756
7757 case ConstexprSpecKind::Constexpr:
7758 NewVD->setConstexpr(true);
7759 // C++1z [dcl.spec.constexpr]p1:
7760 // A static data member declared with the constexpr specifier is
7761 // implicitly an inline variable.
7762 if (NewVD->isStaticDataMember() &&
7763 (getLangOpts().CPlusPlus17 ||
7764 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7765 NewVD->setImplicitlyInline();
7766 break;
7767
7768 case ConstexprSpecKind::Constinit:
7769 if (!NewVD->hasGlobalStorage())
7770 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7771 diag::err_constinit_local_variable);
7772 else
7773 NewVD->addAttr(ConstInitAttr::Create(
7774 Context, D.getDeclSpec().getConstexprSpecLoc(),
7775 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7776 break;
7777 }
7778
7779 // C99 6.7.4p3
7780 // An inline definition of a function with external linkage shall
7781 // not contain a definition of a modifiable object with static or
7782 // thread storage duration...
7783 // We only apply this when the function is required to be defined
7784 // elsewhere, i.e. when the function is not 'extern inline'. Note
7785 // that a local variable with thread storage duration still has to
7786 // be marked 'static'. Also note that it's possible to get these
7787 // semantics in C++ using __attribute__((gnu_inline)).
7788 if (SC == SC_Static && S->getFnParent() != nullptr &&
7789 !NewVD->getType().isConstQualified()) {
7790 FunctionDecl *CurFD = getCurFunctionDecl();
7791 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7792 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7793 diag::warn_static_local_in_extern_inline);
7794 MaybeSuggestAddingStaticToDecl(CurFD);
7795 }
7796 }
7797
7798 if (D.getDeclSpec().isModulePrivateSpecified()) {
7799 if (IsVariableTemplateSpecialization)
7800 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7801 << (IsPartialSpecialization ? 1 : 0)
7802 << FixItHint::CreateRemoval(
7803 D.getDeclSpec().getModulePrivateSpecLoc());
7804 else if (IsMemberSpecialization)
7805 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7806 << 2
7807 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7808 else if (NewVD->hasLocalStorage())
7809 Diag(NewVD->getLocation(), diag::err_module_private_local)
7810 << 0 << NewVD
7811 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7812 << FixItHint::CreateRemoval(
7813 D.getDeclSpec().getModulePrivateSpecLoc());
7814 else {
7815 NewVD->setModulePrivate();
7816 if (NewTemplate)
7817 NewTemplate->setModulePrivate();
7818 for (auto *B : Bindings)
7819 B->setModulePrivate();
7820 }
7821 }
7822
7823 if (getLangOpts().OpenCL) {
7824 deduceOpenCLAddressSpace(NewVD);
7825
7826 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7827 if (TSC != TSCS_unspecified) {
7828 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7829 diag::err_opencl_unknown_type_specifier)
7830 << getLangOpts().getOpenCLVersionString()
7831 << DeclSpec::getSpecifierName(TSC) << 1;
7832 NewVD->setInvalidDecl();
7833 }
7834 }
7835
7836 // Handle attributes prior to checking for duplicates in MergeVarDecl
7837 ProcessDeclAttributes(S, NewVD, D);
7838
7839 // FIXME: This is probably the wrong location to be doing this and we should
7840 // probably be doing this for more attributes (especially for function
7841 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7842 // the code to copy attributes would be generated by TableGen.
7843 if (R->isFunctionPointerType())
7844 if (const auto *TT = R->getAs<TypedefType>())
7845 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7846
7847 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7848 getLangOpts().SYCLIsDevice) {
7849 if (EmitTLSUnsupportedError &&
7850 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7851 (getLangOpts().OpenMPIsDevice &&
7852 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7853 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7854 diag::err_thread_unsupported);
7855
7856 if (EmitTLSUnsupportedError &&
7857 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7858 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7859 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7860 // storage [duration]."
7861 if (SC == SC_None && S->getFnParent() != nullptr &&
7862 (NewVD->hasAttr<CUDASharedAttr>() ||
7863 NewVD->hasAttr<CUDAConstantAttr>())) {
7864 NewVD->setStorageClass(SC_Static);
7865 }
7866 }
7867
7868 // Ensure that dllimport globals without explicit storage class are treated as
7869 // extern. The storage class is set above using parsed attributes. Now we can
7870 // check the VarDecl itself.
7871 assert(!NewVD->hasAttr<DLLImportAttr>() ||
7872 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7873 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7874
7875 // In auto-retain/release, infer strong retension for variables of
7876 // retainable type.
7877 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7878 NewVD->setInvalidDecl();
7879
7880 // Handle GNU asm-label extension (encoded as an attribute).
7881 if (Expr *E = (Expr*)D.getAsmLabel()) {
7882 // The parser guarantees this is a string.
7883 StringLiteral *SE = cast<StringLiteral>(E);
7884 StringRef Label = SE->getString();
7885 if (S->getFnParent() != nullptr) {
7886 switch (SC) {
7887 case SC_None:
7888 case SC_Auto:
7889 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7890 break;
7891 case SC_Register:
7892 // Local Named register
7893 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7894 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7895 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7896 break;
7897 case SC_Static:
7898 case SC_Extern:
7899 case SC_PrivateExtern:
7900 break;
7901 }
7902 } else if (SC == SC_Register) {
7903 // Global Named register
7904 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7905 const auto &TI = Context.getTargetInfo();
7906 bool HasSizeMismatch;
7907
7908 if (!TI.isValidGCCRegisterName(Label))
7909 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7910 else if (!TI.validateGlobalRegisterVariable(Label,
7911 Context.getTypeSize(R),
7912 HasSizeMismatch))
7913 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7914 else if (HasSizeMismatch)
7915 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7916 }
7917
7918 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7919 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7920 NewVD->setInvalidDecl(true);
7921 }
7922 }
7923
7924 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7925 /*IsLiteralLabel=*/true,
7926 SE->getStrTokenLoc(0)));
7927 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7928 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7929 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7930 if (I != ExtnameUndeclaredIdentifiers.end()) {
7931 if (isDeclExternC(NewVD)) {
7932 NewVD->addAttr(I->second);
7933 ExtnameUndeclaredIdentifiers.erase(I);
7934 } else
7935 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7936 << /*Variable*/1 << NewVD;
7937 }
7938 }
7939
7940 // Find the shadowed declaration before filtering for scope.
7941 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7942 ? getShadowedDeclaration(NewVD, Previous)
7943 : nullptr;
7944
7945 // Don't consider existing declarations that are in a different
7946 // scope and are out-of-semantic-context declarations (if the new
7947 // declaration has linkage).
7948 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7949 D.getCXXScopeSpec().isNotEmpty() ||
7950 IsMemberSpecialization ||
7951 IsVariableTemplateSpecialization);
7952
7953 // Check whether the previous declaration is in the same block scope. This
7954 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7955 if (getLangOpts().CPlusPlus &&
7956 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7957 NewVD->setPreviousDeclInSameBlockScope(
7958 Previous.isSingleResult() && !Previous.isShadowed() &&
7959 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7960
7961 if (!getLangOpts().CPlusPlus) {
7962 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7963 } else {
7964 // If this is an explicit specialization of a static data member, check it.
7965 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7966 CheckMemberSpecialization(NewVD, Previous))
7967 NewVD->setInvalidDecl();
7968
7969 // Merge the decl with the existing one if appropriate.
7970 if (!Previous.empty()) {
7971 if (Previous.isSingleResult() &&
7972 isa<FieldDecl>(Previous.getFoundDecl()) &&
7973 D.getCXXScopeSpec().isSet()) {
7974 // The user tried to define a non-static data member
7975 // out-of-line (C++ [dcl.meaning]p1).
7976 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7977 << D.getCXXScopeSpec().getRange();
7978 Previous.clear();
7979 NewVD->setInvalidDecl();
7980 }
7981 } else if (D.getCXXScopeSpec().isSet()) {
7982 // No previous declaration in the qualifying scope.
7983 Diag(D.getIdentifierLoc(), diag::err_no_member)
7984 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7985 << D.getCXXScopeSpec().getRange();
7986 NewVD->setInvalidDecl();
7987 }
7988
7989 if (!IsVariableTemplateSpecialization)
7990 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7991
7992 if (NewTemplate) {
7993 VarTemplateDecl *PrevVarTemplate =
7994 NewVD->getPreviousDecl()
7995 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7996 : nullptr;
7997
7998 // Check the template parameter list of this declaration, possibly
7999 // merging in the template parameter list from the previous variable
8000 // template declaration.
8001 if (CheckTemplateParameterList(
8002 TemplateParams,
8003 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8004 : nullptr,
8005 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8006 DC->isDependentContext())
8007 ? TPC_ClassTemplateMember
8008 : TPC_VarTemplate))
8009 NewVD->setInvalidDecl();
8010
8011 // If we are providing an explicit specialization of a static variable
8012 // template, make a note of that.
8013 if (PrevVarTemplate &&
8014 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8015 PrevVarTemplate->setMemberSpecialization();
8016 }
8017 }
8018
8019 // Diagnose shadowed variables iff this isn't a redeclaration.
8020 if (ShadowedDecl && !D.isRedeclaration())
8021 CheckShadow(NewVD, ShadowedDecl, Previous);
8022
8023 ProcessPragmaWeak(S, NewVD);
8024
8025 // If this is the first declaration of an extern C variable, update
8026 // the map of such variables.
8027 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8028 isIncompleteDeclExternC(*this, NewVD))
8029 RegisterLocallyScopedExternCDecl(NewVD, S);
8030
8031 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8032 MangleNumberingContext *MCtx;
8033 Decl *ManglingContextDecl;
8034 std::tie(MCtx, ManglingContextDecl) =
8035 getCurrentMangleNumberContext(NewVD->getDeclContext());
8036 if (MCtx) {
8037 Context.setManglingNumber(
8038 NewVD, MCtx->getManglingNumber(
8039 NewVD, getMSManglingNumber(getLangOpts(), S)));
8040 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8041 }
8042 }
8043
8044 // Special handling of variable named 'main'.
8045 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8046 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8047 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8048
8049 // C++ [basic.start.main]p3
8050 // A program that declares a variable main at global scope is ill-formed.
8051 if (getLangOpts().CPlusPlus)
8052 Diag(D.getBeginLoc(), diag::err_main_global_variable);
8053
8054 // In C, and external-linkage variable named main results in undefined
8055 // behavior.
8056 else if (NewVD->hasExternalFormalLinkage())
8057 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8058 }
8059
8060 if (D.isRedeclaration() && !Previous.empty()) {
8061 NamedDecl *Prev = Previous.getRepresentativeDecl();
8062 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8063 D.isFunctionDefinition());
8064 }
8065
8066 if (NewTemplate) {
8067 if (NewVD->isInvalidDecl())
8068 NewTemplate->setInvalidDecl();
8069 ActOnDocumentableDecl(NewTemplate);
8070 return NewTemplate;
8071 }
8072
8073 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8074 CompleteMemberSpecialization(NewVD, Previous);
8075
8076 emitReadOnlyPlacementAttrWarning(*this, NewVD);
8077
8078 return NewVD;
8079 }
8080
8081 /// Enum describing the %select options in diag::warn_decl_shadow.
8082 enum ShadowedDeclKind {
8083 SDK_Local,
8084 SDK_Global,
8085 SDK_StaticMember,
8086 SDK_Field,
8087 SDK_Typedef,
8088 SDK_Using,
8089 SDK_StructuredBinding
8090 };
8091
8092 /// Determine what kind of declaration we're shadowing.
computeShadowedDeclKind(const NamedDecl * ShadowedDecl,const DeclContext * OldDC)8093 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8094 const DeclContext *OldDC) {
8095 if (isa<TypeAliasDecl>(ShadowedDecl))
8096 return SDK_Using;
8097 else if (isa<TypedefDecl>(ShadowedDecl))
8098 return SDK_Typedef;
8099 else if (isa<BindingDecl>(ShadowedDecl))
8100 return SDK_StructuredBinding;
8101 else if (isa<RecordDecl>(OldDC))
8102 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8103
8104 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8105 }
8106
8107 /// Return the location of the capture if the given lambda captures the given
8108 /// variable \p VD, or an invalid source location otherwise.
getCaptureLocation(const LambdaScopeInfo * LSI,const VarDecl * VD)8109 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8110 const VarDecl *VD) {
8111 for (const Capture &Capture : LSI->Captures) {
8112 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8113 return Capture.getLocation();
8114 }
8115 return SourceLocation();
8116 }
8117
shouldWarnIfShadowedDecl(const DiagnosticsEngine & Diags,const LookupResult & R)8118 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8119 const LookupResult &R) {
8120 // Only diagnose if we're shadowing an unambiguous field or variable.
8121 if (R.getResultKind() != LookupResult::Found)
8122 return false;
8123
8124 // Return false if warning is ignored.
8125 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8126 }
8127
8128 /// Return the declaration shadowed by the given variable \p D, or null
8129 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
getShadowedDeclaration(const VarDecl * D,const LookupResult & R)8130 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8131 const LookupResult &R) {
8132 if (!shouldWarnIfShadowedDecl(Diags, R))
8133 return nullptr;
8134
8135 // Don't diagnose declarations at file scope.
8136 if (D->hasGlobalStorage())
8137 return nullptr;
8138
8139 NamedDecl *ShadowedDecl = R.getFoundDecl();
8140 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8141 : nullptr;
8142 }
8143
8144 /// Return the declaration shadowed by the given typedef \p D, or null
8145 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
getShadowedDeclaration(const TypedefNameDecl * D,const LookupResult & R)8146 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8147 const LookupResult &R) {
8148 // Don't warn if typedef declaration is part of a class
8149 if (D->getDeclContext()->isRecord())
8150 return nullptr;
8151
8152 if (!shouldWarnIfShadowedDecl(Diags, R))
8153 return nullptr;
8154
8155 NamedDecl *ShadowedDecl = R.getFoundDecl();
8156 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8157 }
8158
8159 /// Return the declaration shadowed by the given variable \p D, or null
8160 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
getShadowedDeclaration(const BindingDecl * D,const LookupResult & R)8161 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8162 const LookupResult &R) {
8163 if (!shouldWarnIfShadowedDecl(Diags, R))
8164 return nullptr;
8165
8166 NamedDecl *ShadowedDecl = R.getFoundDecl();
8167 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8168 : nullptr;
8169 }
8170
8171 /// Diagnose variable or built-in function shadowing. Implements
8172 /// -Wshadow.
8173 ///
8174 /// This method is called whenever a VarDecl is added to a "useful"
8175 /// scope.
8176 ///
8177 /// \param ShadowedDecl the declaration that is shadowed by the given variable
8178 /// \param R the lookup of the name
8179 ///
CheckShadow(NamedDecl * D,NamedDecl * ShadowedDecl,const LookupResult & R)8180 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8181 const LookupResult &R) {
8182 DeclContext *NewDC = D->getDeclContext();
8183
8184 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8185 // Fields are not shadowed by variables in C++ static methods.
8186 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8187 if (MD->isStatic())
8188 return;
8189
8190 // Fields shadowed by constructor parameters are a special case. Usually
8191 // the constructor initializes the field with the parameter.
8192 if (isa<CXXConstructorDecl>(NewDC))
8193 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8194 // Remember that this was shadowed so we can either warn about its
8195 // modification or its existence depending on warning settings.
8196 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8197 return;
8198 }
8199 }
8200
8201 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8202 if (shadowedVar->isExternC()) {
8203 // For shadowing external vars, make sure that we point to the global
8204 // declaration, not a locally scoped extern declaration.
8205 for (auto *I : shadowedVar->redecls())
8206 if (I->isFileVarDecl()) {
8207 ShadowedDecl = I;
8208 break;
8209 }
8210 }
8211
8212 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8213
8214 unsigned WarningDiag = diag::warn_decl_shadow;
8215 SourceLocation CaptureLoc;
8216 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8217 isa<CXXMethodDecl>(NewDC)) {
8218 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8219 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8220 if (RD->getLambdaCaptureDefault() == LCD_None) {
8221 // Try to avoid warnings for lambdas with an explicit capture list.
8222 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8223 // Warn only when the lambda captures the shadowed decl explicitly.
8224 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8225 if (CaptureLoc.isInvalid())
8226 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8227 } else {
8228 // Remember that this was shadowed so we can avoid the warning if the
8229 // shadowed decl isn't captured and the warning settings allow it.
8230 cast<LambdaScopeInfo>(getCurFunction())
8231 ->ShadowingDecls.push_back(
8232 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8233 return;
8234 }
8235 }
8236
8237 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8238 // A variable can't shadow a local variable in an enclosing scope, if
8239 // they are separated by a non-capturing declaration context.
8240 for (DeclContext *ParentDC = NewDC;
8241 ParentDC && !ParentDC->Equals(OldDC);
8242 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8243 // Only block literals, captured statements, and lambda expressions
8244 // can capture; other scopes don't.
8245 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8246 !isLambdaCallOperator(ParentDC)) {
8247 return;
8248 }
8249 }
8250 }
8251 }
8252 }
8253
8254 // Only warn about certain kinds of shadowing for class members.
8255 if (NewDC && NewDC->isRecord()) {
8256 // In particular, don't warn about shadowing non-class members.
8257 if (!OldDC->isRecord())
8258 return;
8259
8260 // TODO: should we warn about static data members shadowing
8261 // static data members from base classes?
8262
8263 // TODO: don't diagnose for inaccessible shadowed members.
8264 // This is hard to do perfectly because we might friend the
8265 // shadowing context, but that's just a false negative.
8266 }
8267
8268
8269 DeclarationName Name = R.getLookupName();
8270
8271 // Emit warning and note.
8272 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8273 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8274 if (!CaptureLoc.isInvalid())
8275 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8276 << Name << /*explicitly*/ 1;
8277 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8278 }
8279
8280 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8281 /// when these variables are captured by the lambda.
DiagnoseShadowingLambdaDecls(const LambdaScopeInfo * LSI)8282 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8283 for (const auto &Shadow : LSI->ShadowingDecls) {
8284 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8285 // Try to avoid the warning when the shadowed decl isn't captured.
8286 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8287 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8288 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8289 ? diag::warn_decl_shadow_uncaptured_local
8290 : diag::warn_decl_shadow)
8291 << Shadow.VD->getDeclName()
8292 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8293 if (!CaptureLoc.isInvalid())
8294 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8295 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8296 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8297 }
8298 }
8299
8300 /// Check -Wshadow without the advantage of a previous lookup.
CheckShadow(Scope * S,VarDecl * D)8301 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8302 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8303 return;
8304
8305 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8306 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8307 LookupName(R, S);
8308 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8309 CheckShadow(D, ShadowedDecl, R);
8310 }
8311
8312 /// Check if 'E', which is an expression that is about to be modified, refers
8313 /// to a constructor parameter that shadows a field.
CheckShadowingDeclModification(Expr * E,SourceLocation Loc)8314 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8315 // Quickly ignore expressions that can't be shadowing ctor parameters.
8316 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8317 return;
8318 E = E->IgnoreParenImpCasts();
8319 auto *DRE = dyn_cast<DeclRefExpr>(E);
8320 if (!DRE)
8321 return;
8322 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8323 auto I = ShadowingDecls.find(D);
8324 if (I == ShadowingDecls.end())
8325 return;
8326 const NamedDecl *ShadowedDecl = I->second;
8327 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8328 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8329 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8330 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8331
8332 // Avoid issuing multiple warnings about the same decl.
8333 ShadowingDecls.erase(I);
8334 }
8335
8336 /// Check for conflict between this global or extern "C" declaration and
8337 /// previous global or extern "C" declarations. This is only used in C++.
8338 template<typename T>
checkGlobalOrExternCConflict(Sema & S,const T * ND,bool IsGlobal,LookupResult & Previous)8339 static bool checkGlobalOrExternCConflict(
8340 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8341 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8342 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8343
8344 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8345 // The common case: this global doesn't conflict with any extern "C"
8346 // declaration.
8347 return false;
8348 }
8349
8350 if (Prev) {
8351 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8352 // Both the old and new declarations have C language linkage. This is a
8353 // redeclaration.
8354 Previous.clear();
8355 Previous.addDecl(Prev);
8356 return true;
8357 }
8358
8359 // This is a global, non-extern "C" declaration, and there is a previous
8360 // non-global extern "C" declaration. Diagnose if this is a variable
8361 // declaration.
8362 if (!isa<VarDecl>(ND))
8363 return false;
8364 } else {
8365 // The declaration is extern "C". Check for any declaration in the
8366 // translation unit which might conflict.
8367 if (IsGlobal) {
8368 // We have already performed the lookup into the translation unit.
8369 IsGlobal = false;
8370 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8371 I != E; ++I) {
8372 if (isa<VarDecl>(*I)) {
8373 Prev = *I;
8374 break;
8375 }
8376 }
8377 } else {
8378 DeclContext::lookup_result R =
8379 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8380 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8381 I != E; ++I) {
8382 if (isa<VarDecl>(*I)) {
8383 Prev = *I;
8384 break;
8385 }
8386 // FIXME: If we have any other entity with this name in global scope,
8387 // the declaration is ill-formed, but that is a defect: it breaks the
8388 // 'stat' hack, for instance. Only variables can have mangled name
8389 // clashes with extern "C" declarations, so only they deserve a
8390 // diagnostic.
8391 }
8392 }
8393
8394 if (!Prev)
8395 return false;
8396 }
8397
8398 // Use the first declaration's location to ensure we point at something which
8399 // is lexically inside an extern "C" linkage-spec.
8400 assert(Prev && "should have found a previous declaration to diagnose");
8401 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8402 Prev = FD->getFirstDecl();
8403 else
8404 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8405
8406 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8407 << IsGlobal << ND;
8408 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8409 << IsGlobal;
8410 return false;
8411 }
8412
8413 /// Apply special rules for handling extern "C" declarations. Returns \c true
8414 /// if we have found that this is a redeclaration of some prior entity.
8415 ///
8416 /// Per C++ [dcl.link]p6:
8417 /// Two declarations [for a function or variable] with C language linkage
8418 /// with the same name that appear in different scopes refer to the same
8419 /// [entity]. An entity with C language linkage shall not be declared with
8420 /// the same name as an entity in global scope.
8421 template<typename T>
checkForConflictWithNonVisibleExternC(Sema & S,const T * ND,LookupResult & Previous)8422 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8423 LookupResult &Previous) {
8424 if (!S.getLangOpts().CPlusPlus) {
8425 // In C, when declaring a global variable, look for a corresponding 'extern'
8426 // variable declared in function scope. We don't need this in C++, because
8427 // we find local extern decls in the surrounding file-scope DeclContext.
8428 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8429 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8430 Previous.clear();
8431 Previous.addDecl(Prev);
8432 return true;
8433 }
8434 }
8435 return false;
8436 }
8437
8438 // A declaration in the translation unit can conflict with an extern "C"
8439 // declaration.
8440 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8441 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8442
8443 // An extern "C" declaration can conflict with a declaration in the
8444 // translation unit or can be a redeclaration of an extern "C" declaration
8445 // in another scope.
8446 if (isIncompleteDeclExternC(S,ND))
8447 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8448
8449 // Neither global nor extern "C": nothing to do.
8450 return false;
8451 }
8452
CheckVariableDeclarationType(VarDecl * NewVD)8453 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8454 // If the decl is already known invalid, don't check it.
8455 if (NewVD->isInvalidDecl())
8456 return;
8457
8458 QualType T = NewVD->getType();
8459
8460 // Defer checking an 'auto' type until its initializer is attached.
8461 if (T->isUndeducedType())
8462 return;
8463
8464 if (NewVD->hasAttrs())
8465 CheckAlignasUnderalignment(NewVD);
8466
8467 if (T->isObjCObjectType()) {
8468 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8469 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8470 T = Context.getObjCObjectPointerType(T);
8471 NewVD->setType(T);
8472 }
8473
8474 // Emit an error if an address space was applied to decl with local storage.
8475 // This includes arrays of objects with address space qualifiers, but not
8476 // automatic variables that point to other address spaces.
8477 // ISO/IEC TR 18037 S5.1.2
8478 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8479 T.getAddressSpace() != LangAS::Default) {
8480 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8481 NewVD->setInvalidDecl();
8482 return;
8483 }
8484
8485 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8486 // scope.
8487 if (getLangOpts().OpenCLVersion == 120 &&
8488 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8489 getLangOpts()) &&
8490 NewVD->isStaticLocal()) {
8491 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8492 NewVD->setInvalidDecl();
8493 return;
8494 }
8495
8496 if (getLangOpts().OpenCL) {
8497 if (!diagnoseOpenCLTypes(*this, NewVD))
8498 return;
8499
8500 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8501 if (NewVD->hasAttr<BlocksAttr>()) {
8502 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8503 return;
8504 }
8505
8506 if (T->isBlockPointerType()) {
8507 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8508 // can't use 'extern' storage class.
8509 if (!T.isConstQualified()) {
8510 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8511 << 0 /*const*/;
8512 NewVD->setInvalidDecl();
8513 return;
8514 }
8515 if (NewVD->hasExternalStorage()) {
8516 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8517 NewVD->setInvalidDecl();
8518 return;
8519 }
8520 }
8521
8522 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8523 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8524 NewVD->hasExternalStorage()) {
8525 if (!T->isSamplerT() && !T->isDependentType() &&
8526 !(T.getAddressSpace() == LangAS::opencl_constant ||
8527 (T.getAddressSpace() == LangAS::opencl_global &&
8528 getOpenCLOptions().areProgramScopeVariablesSupported(
8529 getLangOpts())))) {
8530 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8531 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8532 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8533 << Scope << "global or constant";
8534 else
8535 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8536 << Scope << "constant";
8537 NewVD->setInvalidDecl();
8538 return;
8539 }
8540 } else {
8541 if (T.getAddressSpace() == LangAS::opencl_global) {
8542 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8543 << 1 /*is any function*/ << "global";
8544 NewVD->setInvalidDecl();
8545 return;
8546 }
8547 if (T.getAddressSpace() == LangAS::opencl_constant ||
8548 T.getAddressSpace() == LangAS::opencl_local) {
8549 FunctionDecl *FD = getCurFunctionDecl();
8550 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8551 // in functions.
8552 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8553 if (T.getAddressSpace() == LangAS::opencl_constant)
8554 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8555 << 0 /*non-kernel only*/ << "constant";
8556 else
8557 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8558 << 0 /*non-kernel only*/ << "local";
8559 NewVD->setInvalidDecl();
8560 return;
8561 }
8562 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8563 // in the outermost scope of a kernel function.
8564 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8565 if (!getCurScope()->isFunctionScope()) {
8566 if (T.getAddressSpace() == LangAS::opencl_constant)
8567 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8568 << "constant";
8569 else
8570 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8571 << "local";
8572 NewVD->setInvalidDecl();
8573 return;
8574 }
8575 }
8576 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8577 // If we are parsing a template we didn't deduce an addr
8578 // space yet.
8579 T.getAddressSpace() != LangAS::Default) {
8580 // Do not allow other address spaces on automatic variable.
8581 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8582 NewVD->setInvalidDecl();
8583 return;
8584 }
8585 }
8586 }
8587
8588 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8589 && !NewVD->hasAttr<BlocksAttr>()) {
8590 if (getLangOpts().getGC() != LangOptions::NonGC)
8591 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8592 else {
8593 assert(!getLangOpts().ObjCAutoRefCount);
8594 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8595 }
8596 }
8597
8598 bool isVM = T->isVariablyModifiedType();
8599 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8600 NewVD->hasAttr<BlocksAttr>())
8601 setFunctionHasBranchProtectedScope();
8602
8603 if ((isVM && NewVD->hasLinkage()) ||
8604 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8605 bool SizeIsNegative;
8606 llvm::APSInt Oversized;
8607 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8608 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8609 QualType FixedT;
8610 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8611 FixedT = FixedTInfo->getType();
8612 else if (FixedTInfo) {
8613 // Type and type-as-written are canonically different. We need to fix up
8614 // both types separately.
8615 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8616 Oversized);
8617 }
8618 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8619 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8620 // FIXME: This won't give the correct result for
8621 // int a[10][n];
8622 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8623
8624 if (NewVD->isFileVarDecl())
8625 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8626 << SizeRange;
8627 else if (NewVD->isStaticLocal())
8628 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8629 << SizeRange;
8630 else
8631 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8632 << SizeRange;
8633 NewVD->setInvalidDecl();
8634 return;
8635 }
8636
8637 if (!FixedTInfo) {
8638 if (NewVD->isFileVarDecl())
8639 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8640 else
8641 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8642 NewVD->setInvalidDecl();
8643 return;
8644 }
8645
8646 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8647 NewVD->setType(FixedT);
8648 NewVD->setTypeSourceInfo(FixedTInfo);
8649 }
8650
8651 if (T->isVoidType()) {
8652 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8653 // of objects and functions.
8654 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8655 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8656 << T;
8657 NewVD->setInvalidDecl();
8658 return;
8659 }
8660 }
8661
8662 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8663 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8664 NewVD->setInvalidDecl();
8665 return;
8666 }
8667
8668 if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8669 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8670 NewVD->setInvalidDecl();
8671 return;
8672 }
8673
8674 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8675 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8676 NewVD->setInvalidDecl();
8677 return;
8678 }
8679
8680 if (NewVD->isConstexpr() && !T->isDependentType() &&
8681 RequireLiteralType(NewVD->getLocation(), T,
8682 diag::err_constexpr_var_non_literal)) {
8683 NewVD->setInvalidDecl();
8684 return;
8685 }
8686
8687 // PPC MMA non-pointer types are not allowed as non-local variable types.
8688 if (Context.getTargetInfo().getTriple().isPPC64() &&
8689 !NewVD->isLocalVarDecl() &&
8690 CheckPPCMMAType(T, NewVD->getLocation())) {
8691 NewVD->setInvalidDecl();
8692 return;
8693 }
8694
8695 // Check that SVE types are only used in functions with SVE available.
8696 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8697 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8698 llvm::StringMap<bool> CallerFeatureMap;
8699 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8700 if (!Builtin::evaluateRequiredTargetFeatures(
8701 "sve", CallerFeatureMap)) {
8702 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8703 NewVD->setInvalidDecl();
8704 return;
8705 }
8706 }
8707 }
8708
8709 /// Perform semantic checking on a newly-created variable
8710 /// declaration.
8711 ///
8712 /// This routine performs all of the type-checking required for a
8713 /// variable declaration once it has been built. It is used both to
8714 /// check variables after they have been parsed and their declarators
8715 /// have been translated into a declaration, and to check variables
8716 /// that have been instantiated from a template.
8717 ///
8718 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8719 ///
8720 /// Returns true if the variable declaration is a redeclaration.
CheckVariableDeclaration(VarDecl * NewVD,LookupResult & Previous)8721 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8722 CheckVariableDeclarationType(NewVD);
8723
8724 // If the decl is already known invalid, don't check it.
8725 if (NewVD->isInvalidDecl())
8726 return false;
8727
8728 // If we did not find anything by this name, look for a non-visible
8729 // extern "C" declaration with the same name.
8730 if (Previous.empty() &&
8731 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8732 Previous.setShadowed();
8733
8734 if (!Previous.empty()) {
8735 MergeVarDecl(NewVD, Previous);
8736 return true;
8737 }
8738 return false;
8739 }
8740
8741 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8742 /// and if so, check that it's a valid override and remember it.
AddOverriddenMethods(CXXRecordDecl * DC,CXXMethodDecl * MD)8743 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8744 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8745
8746 // Look for methods in base classes that this method might override.
8747 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8748 /*DetectVirtual=*/false);
8749 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8750 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8751 DeclarationName Name = MD->getDeclName();
8752
8753 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8754 // We really want to find the base class destructor here.
8755 QualType T = Context.getTypeDeclType(BaseRecord);
8756 CanQualType CT = Context.getCanonicalType(T);
8757 Name = Context.DeclarationNames.getCXXDestructorName(CT);
8758 }
8759
8760 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8761 CXXMethodDecl *BaseMD =
8762 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8763 if (!BaseMD || !BaseMD->isVirtual() ||
8764 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8765 /*ConsiderCudaAttrs=*/true,
8766 // C++2a [class.virtual]p2 does not consider requires
8767 // clauses when overriding.
8768 /*ConsiderRequiresClauses=*/false))
8769 continue;
8770
8771 if (Overridden.insert(BaseMD).second) {
8772 MD->addOverriddenMethod(BaseMD);
8773 CheckOverridingFunctionReturnType(MD, BaseMD);
8774 CheckOverridingFunctionAttributes(MD, BaseMD);
8775 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8776 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8777 }
8778
8779 // A method can only override one function from each base class. We
8780 // don't track indirectly overridden methods from bases of bases.
8781 return true;
8782 }
8783
8784 return false;
8785 };
8786
8787 DC->lookupInBases(VisitBase, Paths);
8788 return !Overridden.empty();
8789 }
8790
8791 namespace {
8792 // Struct for holding all of the extra arguments needed by
8793 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8794 struct ActOnFDArgs {
8795 Scope *S;
8796 Declarator &D;
8797 MultiTemplateParamsArg TemplateParamLists;
8798 bool AddToScope;
8799 };
8800 } // end anonymous namespace
8801
8802 namespace {
8803
8804 // Callback to only accept typo corrections that have a non-zero edit distance.
8805 // Also only accept corrections that have the same parent decl.
8806 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8807 public:
DifferentNameValidatorCCC(ASTContext & Context,FunctionDecl * TypoFD,CXXRecordDecl * Parent)8808 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8809 CXXRecordDecl *Parent)
8810 : Context(Context), OriginalFD(TypoFD),
8811 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8812
ValidateCandidate(const TypoCorrection & candidate)8813 bool ValidateCandidate(const TypoCorrection &candidate) override {
8814 if (candidate.getEditDistance() == 0)
8815 return false;
8816
8817 SmallVector<unsigned, 1> MismatchedParams;
8818 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8819 CDeclEnd = candidate.end();
8820 CDecl != CDeclEnd; ++CDecl) {
8821 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8822
8823 if (FD && !FD->hasBody() &&
8824 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8825 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8826 CXXRecordDecl *Parent = MD->getParent();
8827 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8828 return true;
8829 } else if (!ExpectedParent) {
8830 return true;
8831 }
8832 }
8833 }
8834
8835 return false;
8836 }
8837
clone()8838 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8839 return std::make_unique<DifferentNameValidatorCCC>(*this);
8840 }
8841
8842 private:
8843 ASTContext &Context;
8844 FunctionDecl *OriginalFD;
8845 CXXRecordDecl *ExpectedParent;
8846 };
8847
8848 } // end anonymous namespace
8849
MarkTypoCorrectedFunctionDefinition(const NamedDecl * F)8850 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8851 TypoCorrectedFunctionDefinitions.insert(F);
8852 }
8853
8854 /// Generate diagnostics for an invalid function redeclaration.
8855 ///
8856 /// This routine handles generating the diagnostic messages for an invalid
8857 /// function redeclaration, including finding possible similar declarations
8858 /// or performing typo correction if there are no previous declarations with
8859 /// the same name.
8860 ///
8861 /// Returns a NamedDecl iff typo correction was performed and substituting in
8862 /// the new declaration name does not cause new errors.
DiagnoseInvalidRedeclaration(Sema & SemaRef,LookupResult & Previous,FunctionDecl * NewFD,ActOnFDArgs & ExtraArgs,bool IsLocalFriend,Scope * S)8863 static NamedDecl *DiagnoseInvalidRedeclaration(
8864 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8865 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8866 DeclarationName Name = NewFD->getDeclName();
8867 DeclContext *NewDC = NewFD->getDeclContext();
8868 SmallVector<unsigned, 1> MismatchedParams;
8869 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8870 TypoCorrection Correction;
8871 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8872 unsigned DiagMsg =
8873 IsLocalFriend ? diag::err_no_matching_local_friend :
8874 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8875 diag::err_member_decl_does_not_match;
8876 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8877 IsLocalFriend ? Sema::LookupLocalFriendName
8878 : Sema::LookupOrdinaryName,
8879 Sema::ForVisibleRedeclaration);
8880
8881 NewFD->setInvalidDecl();
8882 if (IsLocalFriend)
8883 SemaRef.LookupName(Prev, S);
8884 else
8885 SemaRef.LookupQualifiedName(Prev, NewDC);
8886 assert(!Prev.isAmbiguous() &&
8887 "Cannot have an ambiguity in previous-declaration lookup");
8888 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8889 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8890 MD ? MD->getParent() : nullptr);
8891 if (!Prev.empty()) {
8892 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8893 Func != FuncEnd; ++Func) {
8894 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8895 if (FD &&
8896 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8897 // Add 1 to the index so that 0 can mean the mismatch didn't
8898 // involve a parameter
8899 unsigned ParamNum =
8900 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8901 NearMatches.push_back(std::make_pair(FD, ParamNum));
8902 }
8903 }
8904 // If the qualified name lookup yielded nothing, try typo correction
8905 } else if ((Correction = SemaRef.CorrectTypo(
8906 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8907 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8908 IsLocalFriend ? nullptr : NewDC))) {
8909 // Set up everything for the call to ActOnFunctionDeclarator
8910 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8911 ExtraArgs.D.getIdentifierLoc());
8912 Previous.clear();
8913 Previous.setLookupName(Correction.getCorrection());
8914 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8915 CDeclEnd = Correction.end();
8916 CDecl != CDeclEnd; ++CDecl) {
8917 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8918 if (FD && !FD->hasBody() &&
8919 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8920 Previous.addDecl(FD);
8921 }
8922 }
8923 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8924
8925 NamedDecl *Result;
8926 // Retry building the function declaration with the new previous
8927 // declarations, and with errors suppressed.
8928 {
8929 // Trap errors.
8930 Sema::SFINAETrap Trap(SemaRef);
8931
8932 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8933 // pieces need to verify the typo-corrected C++ declaration and hopefully
8934 // eliminate the need for the parameter pack ExtraArgs.
8935 Result = SemaRef.ActOnFunctionDeclarator(
8936 ExtraArgs.S, ExtraArgs.D,
8937 Correction.getCorrectionDecl()->getDeclContext(),
8938 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8939 ExtraArgs.AddToScope);
8940
8941 if (Trap.hasErrorOccurred())
8942 Result = nullptr;
8943 }
8944
8945 if (Result) {
8946 // Determine which correction we picked.
8947 Decl *Canonical = Result->getCanonicalDecl();
8948 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8949 I != E; ++I)
8950 if ((*I)->getCanonicalDecl() == Canonical)
8951 Correction.setCorrectionDecl(*I);
8952
8953 // Let Sema know about the correction.
8954 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8955 SemaRef.diagnoseTypo(
8956 Correction,
8957 SemaRef.PDiag(IsLocalFriend
8958 ? diag::err_no_matching_local_friend_suggest
8959 : diag::err_member_decl_does_not_match_suggest)
8960 << Name << NewDC << IsDefinition);
8961 return Result;
8962 }
8963
8964 // Pretend the typo correction never occurred
8965 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8966 ExtraArgs.D.getIdentifierLoc());
8967 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8968 Previous.clear();
8969 Previous.setLookupName(Name);
8970 }
8971
8972 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8973 << Name << NewDC << IsDefinition << NewFD->getLocation();
8974
8975 bool NewFDisConst = false;
8976 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8977 NewFDisConst = NewMD->isConst();
8978
8979 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8980 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8981 NearMatch != NearMatchEnd; ++NearMatch) {
8982 FunctionDecl *FD = NearMatch->first;
8983 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8984 bool FDisConst = MD && MD->isConst();
8985 bool IsMember = MD || !IsLocalFriend;
8986
8987 // FIXME: These notes are poorly worded for the local friend case.
8988 if (unsigned Idx = NearMatch->second) {
8989 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8990 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8991 if (Loc.isInvalid()) Loc = FD->getLocation();
8992 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8993 : diag::note_local_decl_close_param_match)
8994 << Idx << FDParam->getType()
8995 << NewFD->getParamDecl(Idx - 1)->getType();
8996 } else if (FDisConst != NewFDisConst) {
8997 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8998 << NewFDisConst << FD->getSourceRange().getEnd()
8999 << (NewFDisConst
9000 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9001 .getConstQualifierLoc())
9002 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9003 .getRParenLoc()
9004 .getLocWithOffset(1),
9005 " const"));
9006 } else
9007 SemaRef.Diag(FD->getLocation(),
9008 IsMember ? diag::note_member_def_close_match
9009 : diag::note_local_decl_close_match);
9010 }
9011 return nullptr;
9012 }
9013
getFunctionStorageClass(Sema & SemaRef,Declarator & D)9014 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9015 switch (D.getDeclSpec().getStorageClassSpec()) {
9016 default: llvm_unreachable("Unknown storage class!");
9017 case DeclSpec::SCS_auto:
9018 case DeclSpec::SCS_register:
9019 case DeclSpec::SCS_mutable:
9020 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9021 diag::err_typecheck_sclass_func);
9022 D.getMutableDeclSpec().ClearStorageClassSpecs();
9023 D.setInvalidType();
9024 break;
9025 case DeclSpec::SCS_unspecified: break;
9026 case DeclSpec::SCS_extern:
9027 if (D.getDeclSpec().isExternInLinkageSpec())
9028 return SC_None;
9029 return SC_Extern;
9030 case DeclSpec::SCS_static: {
9031 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9032 // C99 6.7.1p5:
9033 // The declaration of an identifier for a function that has
9034 // block scope shall have no explicit storage-class specifier
9035 // other than extern
9036 // See also (C++ [dcl.stc]p4).
9037 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9038 diag::err_static_block_func);
9039 break;
9040 } else
9041 return SC_Static;
9042 }
9043 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9044 }
9045
9046 // No explicit storage class has already been returned
9047 return SC_None;
9048 }
9049
CreateNewFunctionDecl(Sema & SemaRef,Declarator & D,DeclContext * DC,QualType & R,TypeSourceInfo * TInfo,StorageClass SC,bool & IsVirtualOkay)9050 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9051 DeclContext *DC, QualType &R,
9052 TypeSourceInfo *TInfo,
9053 StorageClass SC,
9054 bool &IsVirtualOkay) {
9055 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9056 DeclarationName Name = NameInfo.getName();
9057
9058 FunctionDecl *NewFD = nullptr;
9059 bool isInline = D.getDeclSpec().isInlineSpecified();
9060
9061 if (!SemaRef.getLangOpts().CPlusPlus) {
9062 // Determine whether the function was written with a prototype. This is
9063 // true when:
9064 // - there is a prototype in the declarator, or
9065 // - the type R of the function is some kind of typedef or other non-
9066 // attributed reference to a type name (which eventually refers to a
9067 // function type). Note, we can't always look at the adjusted type to
9068 // check this case because attributes may cause a non-function
9069 // declarator to still have a function type. e.g.,
9070 // typedef void func(int a);
9071 // __attribute__((noreturn)) func other_func; // This has a prototype
9072 bool HasPrototype =
9073 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9074 (D.getDeclSpec().isTypeRep() &&
9075 D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
9076 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9077 assert(
9078 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9079 "Strict prototypes are required");
9080
9081 NewFD = FunctionDecl::Create(
9082 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9083 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9084 ConstexprSpecKind::Unspecified,
9085 /*TrailingRequiresClause=*/nullptr);
9086 if (D.isInvalidType())
9087 NewFD->setInvalidDecl();
9088
9089 return NewFD;
9090 }
9091
9092 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9093
9094 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9095 if (ConstexprKind == ConstexprSpecKind::Constinit) {
9096 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9097 diag::err_constexpr_wrong_decl_kind)
9098 << static_cast<int>(ConstexprKind);
9099 ConstexprKind = ConstexprSpecKind::Unspecified;
9100 D.getMutableDeclSpec().ClearConstexprSpec();
9101 }
9102 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9103
9104 // Check that the return type is not an abstract class type.
9105 // For record types, this is done by the AbstractClassUsageDiagnoser once
9106 // the class has been completely parsed.
9107 if (!DC->isRecord() &&
9108 SemaRef.RequireNonAbstractType(
9109 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
9110 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
9111 D.setInvalidType();
9112
9113 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9114 // This is a C++ constructor declaration.
9115 assert(DC->isRecord() &&
9116 "Constructors can only be declared in a member context");
9117
9118 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9119 return CXXConstructorDecl::Create(
9120 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9121 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
9122 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9123 InheritedConstructor(), TrailingRequiresClause);
9124
9125 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9126 // This is a C++ destructor declaration.
9127 if (DC->isRecord()) {
9128 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9129 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9130 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9131 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9132 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9133 /*isImplicitlyDeclared=*/false, ConstexprKind,
9134 TrailingRequiresClause);
9135 // User defined destructors start as not selected if the class definition is still
9136 // not done.
9137 if (Record->isBeingDefined())
9138 NewDD->setIneligibleOrNotSelected(true);
9139
9140 // If the destructor needs an implicit exception specification, set it
9141 // now. FIXME: It'd be nice to be able to create the right type to start
9142 // with, but the type needs to reference the destructor declaration.
9143 if (SemaRef.getLangOpts().CPlusPlus11)
9144 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9145
9146 IsVirtualOkay = true;
9147 return NewDD;
9148
9149 } else {
9150 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9151 D.setInvalidType();
9152
9153 // Create a FunctionDecl to satisfy the function definition parsing
9154 // code path.
9155 return FunctionDecl::Create(
9156 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9157 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9158 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9159 }
9160
9161 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9162 if (!DC->isRecord()) {
9163 SemaRef.Diag(D.getIdentifierLoc(),
9164 diag::err_conv_function_not_member);
9165 return nullptr;
9166 }
9167
9168 SemaRef.CheckConversionDeclarator(D, R, SC);
9169 if (D.isInvalidType())
9170 return nullptr;
9171
9172 IsVirtualOkay = true;
9173 return CXXConversionDecl::Create(
9174 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9175 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9176 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9177 TrailingRequiresClause);
9178
9179 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9180 if (TrailingRequiresClause)
9181 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9182 diag::err_trailing_requires_clause_on_deduction_guide)
9183 << TrailingRequiresClause->getSourceRange();
9184 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
9185
9186 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9187 ExplicitSpecifier, NameInfo, R, TInfo,
9188 D.getEndLoc());
9189 } else if (DC->isRecord()) {
9190 // If the name of the function is the same as the name of the record,
9191 // then this must be an invalid constructor that has a return type.
9192 // (The parser checks for a return type and makes the declarator a
9193 // constructor if it has no return type).
9194 if (Name.getAsIdentifierInfo() &&
9195 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9196 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9197 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9198 << SourceRange(D.getIdentifierLoc());
9199 return nullptr;
9200 }
9201
9202 // This is a C++ method declaration.
9203 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9204 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9205 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9206 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9207 IsVirtualOkay = !Ret->isStatic();
9208 return Ret;
9209 } else {
9210 bool isFriend =
9211 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9212 if (!isFriend && SemaRef.CurContext->isRecord())
9213 return nullptr;
9214
9215 // Determine whether the function was written with a
9216 // prototype. This true when:
9217 // - we're in C++ (where every function has a prototype),
9218 return FunctionDecl::Create(
9219 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9220 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9221 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9222 }
9223 }
9224
9225 enum OpenCLParamType {
9226 ValidKernelParam,
9227 PtrPtrKernelParam,
9228 PtrKernelParam,
9229 InvalidAddrSpacePtrKernelParam,
9230 InvalidKernelParam,
9231 RecordKernelParam
9232 };
9233
isOpenCLSizeDependentType(ASTContext & C,QualType Ty)9234 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9235 // Size dependent types are just typedefs to normal integer types
9236 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9237 // integers other than by their names.
9238 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9239
9240 // Remove typedefs one by one until we reach a typedef
9241 // for a size dependent type.
9242 QualType DesugaredTy = Ty;
9243 do {
9244 ArrayRef<StringRef> Names(SizeTypeNames);
9245 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9246 if (Names.end() != Match)
9247 return true;
9248
9249 Ty = DesugaredTy;
9250 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9251 } while (DesugaredTy != Ty);
9252
9253 return false;
9254 }
9255
getOpenCLKernelParameterType(Sema & S,QualType PT)9256 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9257 if (PT->isDependentType())
9258 return InvalidKernelParam;
9259
9260 if (PT->isPointerType() || PT->isReferenceType()) {
9261 QualType PointeeType = PT->getPointeeType();
9262 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9263 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9264 PointeeType.getAddressSpace() == LangAS::Default)
9265 return InvalidAddrSpacePtrKernelParam;
9266
9267 if (PointeeType->isPointerType()) {
9268 // This is a pointer to pointer parameter.
9269 // Recursively check inner type.
9270 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9271 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9272 ParamKind == InvalidKernelParam)
9273 return ParamKind;
9274
9275 return PtrPtrKernelParam;
9276 }
9277
9278 // C++ for OpenCL v1.0 s2.4:
9279 // Moreover the types used in parameters of the kernel functions must be:
9280 // Standard layout types for pointer parameters. The same applies to
9281 // reference if an implementation supports them in kernel parameters.
9282 if (S.getLangOpts().OpenCLCPlusPlus &&
9283 !S.getOpenCLOptions().isAvailableOption(
9284 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9285 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9286 bool IsStandardLayoutType = true;
9287 if (CXXRec) {
9288 // If template type is not ODR-used its definition is only available
9289 // in the template definition not its instantiation.
9290 // FIXME: This logic doesn't work for types that depend on template
9291 // parameter (PR58590).
9292 if (!CXXRec->hasDefinition())
9293 CXXRec = CXXRec->getTemplateInstantiationPattern();
9294 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9295 IsStandardLayoutType = false;
9296 }
9297 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9298 !IsStandardLayoutType)
9299 return InvalidKernelParam;
9300 }
9301
9302 return PtrKernelParam;
9303 }
9304
9305 // OpenCL v1.2 s6.9.k:
9306 // Arguments to kernel functions in a program cannot be declared with the
9307 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9308 // uintptr_t or a struct and/or union that contain fields declared to be one
9309 // of these built-in scalar types.
9310 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9311 return InvalidKernelParam;
9312
9313 if (PT->isImageType())
9314 return PtrKernelParam;
9315
9316 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9317 return InvalidKernelParam;
9318
9319 // OpenCL extension spec v1.2 s9.5:
9320 // This extension adds support for half scalar and vector types as built-in
9321 // types that can be used for arithmetic operations, conversions etc.
9322 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9323 PT->isHalfType())
9324 return InvalidKernelParam;
9325
9326 // Look into an array argument to check if it has a forbidden type.
9327 if (PT->isArrayType()) {
9328 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9329 // Call ourself to check an underlying type of an array. Since the
9330 // getPointeeOrArrayElementType returns an innermost type which is not an
9331 // array, this recursive call only happens once.
9332 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9333 }
9334
9335 // C++ for OpenCL v1.0 s2.4:
9336 // Moreover the types used in parameters of the kernel functions must be:
9337 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9338 // types) for parameters passed by value;
9339 if (S.getLangOpts().OpenCLCPlusPlus &&
9340 !S.getOpenCLOptions().isAvailableOption(
9341 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9342 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9343 return InvalidKernelParam;
9344
9345 if (PT->isRecordType())
9346 return RecordKernelParam;
9347
9348 return ValidKernelParam;
9349 }
9350
checkIsValidOpenCLKernelParameter(Sema & S,Declarator & D,ParmVarDecl * Param,llvm::SmallPtrSetImpl<const Type * > & ValidTypes)9351 static void checkIsValidOpenCLKernelParameter(
9352 Sema &S,
9353 Declarator &D,
9354 ParmVarDecl *Param,
9355 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9356 QualType PT = Param->getType();
9357
9358 // Cache the valid types we encounter to avoid rechecking structs that are
9359 // used again
9360 if (ValidTypes.count(PT.getTypePtr()))
9361 return;
9362
9363 switch (getOpenCLKernelParameterType(S, PT)) {
9364 case PtrPtrKernelParam:
9365 // OpenCL v3.0 s6.11.a:
9366 // A kernel function argument cannot be declared as a pointer to a pointer
9367 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9368 if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9369 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9370 D.setInvalidType();
9371 return;
9372 }
9373
9374 ValidTypes.insert(PT.getTypePtr());
9375 return;
9376
9377 case InvalidAddrSpacePtrKernelParam:
9378 // OpenCL v1.0 s6.5:
9379 // __kernel function arguments declared to be a pointer of a type can point
9380 // to one of the following address spaces only : __global, __local or
9381 // __constant.
9382 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9383 D.setInvalidType();
9384 return;
9385
9386 // OpenCL v1.2 s6.9.k:
9387 // Arguments to kernel functions in a program cannot be declared with the
9388 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9389 // uintptr_t or a struct and/or union that contain fields declared to be
9390 // one of these built-in scalar types.
9391
9392 case InvalidKernelParam:
9393 // OpenCL v1.2 s6.8 n:
9394 // A kernel function argument cannot be declared
9395 // of event_t type.
9396 // Do not diagnose half type since it is diagnosed as invalid argument
9397 // type for any function elsewhere.
9398 if (!PT->isHalfType()) {
9399 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9400
9401 // Explain what typedefs are involved.
9402 const TypedefType *Typedef = nullptr;
9403 while ((Typedef = PT->getAs<TypedefType>())) {
9404 SourceLocation Loc = Typedef->getDecl()->getLocation();
9405 // SourceLocation may be invalid for a built-in type.
9406 if (Loc.isValid())
9407 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9408 PT = Typedef->desugar();
9409 }
9410 }
9411
9412 D.setInvalidType();
9413 return;
9414
9415 case PtrKernelParam:
9416 case ValidKernelParam:
9417 ValidTypes.insert(PT.getTypePtr());
9418 return;
9419
9420 case RecordKernelParam:
9421 break;
9422 }
9423
9424 // Track nested structs we will inspect
9425 SmallVector<const Decl *, 4> VisitStack;
9426
9427 // Track where we are in the nested structs. Items will migrate from
9428 // VisitStack to HistoryStack as we do the DFS for bad field.
9429 SmallVector<const FieldDecl *, 4> HistoryStack;
9430 HistoryStack.push_back(nullptr);
9431
9432 // At this point we already handled everything except of a RecordType or
9433 // an ArrayType of a RecordType.
9434 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9435 const RecordType *RecTy =
9436 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9437 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9438
9439 VisitStack.push_back(RecTy->getDecl());
9440 assert(VisitStack.back() && "First decl null?");
9441
9442 do {
9443 const Decl *Next = VisitStack.pop_back_val();
9444 if (!Next) {
9445 assert(!HistoryStack.empty());
9446 // Found a marker, we have gone up a level
9447 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9448 ValidTypes.insert(Hist->getType().getTypePtr());
9449
9450 continue;
9451 }
9452
9453 // Adds everything except the original parameter declaration (which is not a
9454 // field itself) to the history stack.
9455 const RecordDecl *RD;
9456 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9457 HistoryStack.push_back(Field);
9458
9459 QualType FieldTy = Field->getType();
9460 // Other field types (known to be valid or invalid) are handled while we
9461 // walk around RecordDecl::fields().
9462 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9463 "Unexpected type.");
9464 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9465
9466 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9467 } else {
9468 RD = cast<RecordDecl>(Next);
9469 }
9470
9471 // Add a null marker so we know when we've gone back up a level
9472 VisitStack.push_back(nullptr);
9473
9474 for (const auto *FD : RD->fields()) {
9475 QualType QT = FD->getType();
9476
9477 if (ValidTypes.count(QT.getTypePtr()))
9478 continue;
9479
9480 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9481 if (ParamType == ValidKernelParam)
9482 continue;
9483
9484 if (ParamType == RecordKernelParam) {
9485 VisitStack.push_back(FD);
9486 continue;
9487 }
9488
9489 // OpenCL v1.2 s6.9.p:
9490 // Arguments to kernel functions that are declared to be a struct or union
9491 // do not allow OpenCL objects to be passed as elements of the struct or
9492 // union.
9493 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9494 ParamType == InvalidAddrSpacePtrKernelParam) {
9495 S.Diag(Param->getLocation(),
9496 diag::err_record_with_pointers_kernel_param)
9497 << PT->isUnionType()
9498 << PT;
9499 } else {
9500 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9501 }
9502
9503 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9504 << OrigRecDecl->getDeclName();
9505
9506 // We have an error, now let's go back up through history and show where
9507 // the offending field came from
9508 for (ArrayRef<const FieldDecl *>::const_iterator
9509 I = HistoryStack.begin() + 1,
9510 E = HistoryStack.end();
9511 I != E; ++I) {
9512 const FieldDecl *OuterField = *I;
9513 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9514 << OuterField->getType();
9515 }
9516
9517 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9518 << QT->isPointerType()
9519 << QT;
9520 D.setInvalidType();
9521 return;
9522 }
9523 } while (!VisitStack.empty());
9524 }
9525
9526 /// Find the DeclContext in which a tag is implicitly declared if we see an
9527 /// elaborated type specifier in the specified context, and lookup finds
9528 /// nothing.
getTagInjectionContext(DeclContext * DC)9529 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9530 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9531 DC = DC->getParent();
9532 return DC;
9533 }
9534
9535 /// Find the Scope in which a tag is implicitly declared if we see an
9536 /// elaborated type specifier in the specified context, and lookup finds
9537 /// nothing.
getTagInjectionScope(Scope * S,const LangOptions & LangOpts)9538 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9539 while (S->isClassScope() ||
9540 (LangOpts.CPlusPlus &&
9541 S->isFunctionPrototypeScope()) ||
9542 ((S->getFlags() & Scope::DeclScope) == 0) ||
9543 (S->getEntity() && S->getEntity()->isTransparentContext()))
9544 S = S->getParent();
9545 return S;
9546 }
9547
9548 /// Determine whether a declaration matches a known function in namespace std.
isStdBuiltin(ASTContext & Ctx,FunctionDecl * FD,unsigned BuiltinID)9549 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9550 unsigned BuiltinID) {
9551 switch (BuiltinID) {
9552 case Builtin::BI__GetExceptionInfo:
9553 // No type checking whatsoever.
9554 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9555
9556 case Builtin::BIaddressof:
9557 case Builtin::BI__addressof:
9558 case Builtin::BIforward:
9559 case Builtin::BImove:
9560 case Builtin::BImove_if_noexcept:
9561 case Builtin::BIas_const: {
9562 // Ensure that we don't treat the algorithm
9563 // OutputIt std::move(InputIt, InputIt, OutputIt)
9564 // as the builtin std::move.
9565 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9566 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9567 }
9568
9569 default:
9570 return false;
9571 }
9572 }
9573
9574 NamedDecl*
ActOnFunctionDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamListsRef,bool & AddToScope)9575 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9576 TypeSourceInfo *TInfo, LookupResult &Previous,
9577 MultiTemplateParamsArg TemplateParamListsRef,
9578 bool &AddToScope) {
9579 QualType R = TInfo->getType();
9580
9581 assert(R->isFunctionType());
9582 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9583 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9584
9585 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9586 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9587 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9588 if (!TemplateParamLists.empty() &&
9589 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9590 TemplateParamLists.back() = Invented;
9591 else
9592 TemplateParamLists.push_back(Invented);
9593 }
9594
9595 // TODO: consider using NameInfo for diagnostic.
9596 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9597 DeclarationName Name = NameInfo.getName();
9598 StorageClass SC = getFunctionStorageClass(*this, D);
9599
9600 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9601 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9602 diag::err_invalid_thread)
9603 << DeclSpec::getSpecifierName(TSCS);
9604
9605 if (D.isFirstDeclarationOfMember())
9606 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9607 D.getIdentifierLoc());
9608
9609 bool isFriend = false;
9610 FunctionTemplateDecl *FunctionTemplate = nullptr;
9611 bool isMemberSpecialization = false;
9612 bool isFunctionTemplateSpecialization = false;
9613
9614 bool isDependentClassScopeExplicitSpecialization = false;
9615 bool HasExplicitTemplateArgs = false;
9616 TemplateArgumentListInfo TemplateArgs;
9617
9618 bool isVirtualOkay = false;
9619
9620 DeclContext *OriginalDC = DC;
9621 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9622
9623 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9624 isVirtualOkay);
9625 if (!NewFD) return nullptr;
9626
9627 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9628 NewFD->setTopLevelDeclInObjCContainer();
9629
9630 // Set the lexical context. If this is a function-scope declaration, or has a
9631 // C++ scope specifier, or is the object of a friend declaration, the lexical
9632 // context will be different from the semantic context.
9633 NewFD->setLexicalDeclContext(CurContext);
9634
9635 if (IsLocalExternDecl)
9636 NewFD->setLocalExternDecl();
9637
9638 if (getLangOpts().CPlusPlus) {
9639 // The rules for implicit inlines changed in C++20 for methods and friends
9640 // with an in-class definition (when such a definition is not attached to
9641 // the global module). User-specified 'inline' overrides this (set when
9642 // the function decl is created above).
9643 // FIXME: We need a better way to separate C++ standard and clang modules.
9644 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9645 !NewFD->getOwningModule() ||
9646 NewFD->getOwningModule()->isGlobalModule() ||
9647 NewFD->getOwningModule()->isHeaderLikeModule();
9648 bool isInline = D.getDeclSpec().isInlineSpecified();
9649 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9650 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9651 isFriend = D.getDeclSpec().isFriendSpecified();
9652 if (isFriend && !isInline && D.isFunctionDefinition()) {
9653 // Pre-C++20 [class.friend]p5
9654 // A function can be defined in a friend declaration of a
9655 // class . . . . Such a function is implicitly inline.
9656 // Post C++20 [class.friend]p7
9657 // Such a function is implicitly an inline function if it is attached
9658 // to the global module.
9659 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9660 }
9661
9662 // If this is a method defined in an __interface, and is not a constructor
9663 // or an overloaded operator, then set the pure flag (isVirtual will already
9664 // return true).
9665 if (const CXXRecordDecl *Parent =
9666 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9667 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9668 NewFD->setPure(true);
9669
9670 // C++ [class.union]p2
9671 // A union can have member functions, but not virtual functions.
9672 if (isVirtual && Parent->isUnion()) {
9673 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9674 NewFD->setInvalidDecl();
9675 }
9676 if ((Parent->isClass() || Parent->isStruct()) &&
9677 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9678 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9679 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9680 if (auto *Def = Parent->getDefinition())
9681 Def->setInitMethod(true);
9682 }
9683 }
9684
9685 SetNestedNameSpecifier(*this, NewFD, D);
9686 isMemberSpecialization = false;
9687 isFunctionTemplateSpecialization = false;
9688 if (D.isInvalidType())
9689 NewFD->setInvalidDecl();
9690
9691 // Match up the template parameter lists with the scope specifier, then
9692 // determine whether we have a template or a template specialization.
9693 bool Invalid = false;
9694 TemplateParameterList *TemplateParams =
9695 MatchTemplateParametersToScopeSpecifier(
9696 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9697 D.getCXXScopeSpec(),
9698 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9699 ? D.getName().TemplateId
9700 : nullptr,
9701 TemplateParamLists, isFriend, isMemberSpecialization,
9702 Invalid);
9703 if (TemplateParams) {
9704 // Check that we can declare a template here.
9705 if (CheckTemplateDeclScope(S, TemplateParams))
9706 NewFD->setInvalidDecl();
9707
9708 if (TemplateParams->size() > 0) {
9709 // This is a function template
9710
9711 // A destructor cannot be a template.
9712 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9713 Diag(NewFD->getLocation(), diag::err_destructor_template);
9714 NewFD->setInvalidDecl();
9715 }
9716
9717 // If we're adding a template to a dependent context, we may need to
9718 // rebuilding some of the types used within the template parameter list,
9719 // now that we know what the current instantiation is.
9720 if (DC->isDependentContext()) {
9721 ContextRAII SavedContext(*this, DC);
9722 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9723 Invalid = true;
9724 }
9725
9726 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9727 NewFD->getLocation(),
9728 Name, TemplateParams,
9729 NewFD);
9730 FunctionTemplate->setLexicalDeclContext(CurContext);
9731 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9732
9733 // For source fidelity, store the other template param lists.
9734 if (TemplateParamLists.size() > 1) {
9735 NewFD->setTemplateParameterListsInfo(Context,
9736 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9737 .drop_back(1));
9738 }
9739 } else {
9740 // This is a function template specialization.
9741 isFunctionTemplateSpecialization = true;
9742 // For source fidelity, store all the template param lists.
9743 if (TemplateParamLists.size() > 0)
9744 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9745
9746 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9747 if (isFriend) {
9748 // We want to remove the "template<>", found here.
9749 SourceRange RemoveRange = TemplateParams->getSourceRange();
9750
9751 // If we remove the template<> and the name is not a
9752 // template-id, we're actually silently creating a problem:
9753 // the friend declaration will refer to an untemplated decl,
9754 // and clearly the user wants a template specialization. So
9755 // we need to insert '<>' after the name.
9756 SourceLocation InsertLoc;
9757 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9758 InsertLoc = D.getName().getSourceRange().getEnd();
9759 InsertLoc = getLocForEndOfToken(InsertLoc);
9760 }
9761
9762 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9763 << Name << RemoveRange
9764 << FixItHint::CreateRemoval(RemoveRange)
9765 << FixItHint::CreateInsertion(InsertLoc, "<>");
9766 Invalid = true;
9767 }
9768 }
9769 } else {
9770 // Check that we can declare a template here.
9771 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9772 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9773 NewFD->setInvalidDecl();
9774
9775 // All template param lists were matched against the scope specifier:
9776 // this is NOT (an explicit specialization of) a template.
9777 if (TemplateParamLists.size() > 0)
9778 // For source fidelity, store all the template param lists.
9779 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9780 }
9781
9782 if (Invalid) {
9783 NewFD->setInvalidDecl();
9784 if (FunctionTemplate)
9785 FunctionTemplate->setInvalidDecl();
9786 }
9787
9788 // C++ [dcl.fct.spec]p5:
9789 // The virtual specifier shall only be used in declarations of
9790 // nonstatic class member functions that appear within a
9791 // member-specification of a class declaration; see 10.3.
9792 //
9793 if (isVirtual && !NewFD->isInvalidDecl()) {
9794 if (!isVirtualOkay) {
9795 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9796 diag::err_virtual_non_function);
9797 } else if (!CurContext->isRecord()) {
9798 // 'virtual' was specified outside of the class.
9799 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9800 diag::err_virtual_out_of_class)
9801 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9802 } else if (NewFD->getDescribedFunctionTemplate()) {
9803 // C++ [temp.mem]p3:
9804 // A member function template shall not be virtual.
9805 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9806 diag::err_virtual_member_function_template)
9807 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9808 } else {
9809 // Okay: Add virtual to the method.
9810 NewFD->setVirtualAsWritten(true);
9811 }
9812
9813 if (getLangOpts().CPlusPlus14 &&
9814 NewFD->getReturnType()->isUndeducedType())
9815 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9816 }
9817
9818 if (getLangOpts().CPlusPlus14 &&
9819 (NewFD->isDependentContext() ||
9820 (isFriend && CurContext->isDependentContext())) &&
9821 NewFD->getReturnType()->isUndeducedType()) {
9822 // If the function template is referenced directly (for instance, as a
9823 // member of the current instantiation), pretend it has a dependent type.
9824 // This is not really justified by the standard, but is the only sane
9825 // thing to do.
9826 // FIXME: For a friend function, we have not marked the function as being
9827 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9828 const FunctionProtoType *FPT =
9829 NewFD->getType()->castAs<FunctionProtoType>();
9830 QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9831 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9832 FPT->getExtProtoInfo()));
9833 }
9834
9835 // C++ [dcl.fct.spec]p3:
9836 // The inline specifier shall not appear on a block scope function
9837 // declaration.
9838 if (isInline && !NewFD->isInvalidDecl()) {
9839 if (CurContext->isFunctionOrMethod()) {
9840 // 'inline' is not allowed on block scope function declaration.
9841 Diag(D.getDeclSpec().getInlineSpecLoc(),
9842 diag::err_inline_declaration_block_scope) << Name
9843 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9844 }
9845 }
9846
9847 // C++ [dcl.fct.spec]p6:
9848 // The explicit specifier shall be used only in the declaration of a
9849 // constructor or conversion function within its class definition;
9850 // see 12.3.1 and 12.3.2.
9851 if (hasExplicit && !NewFD->isInvalidDecl() &&
9852 !isa<CXXDeductionGuideDecl>(NewFD)) {
9853 if (!CurContext->isRecord()) {
9854 // 'explicit' was specified outside of the class.
9855 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9856 diag::err_explicit_out_of_class)
9857 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9858 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9859 !isa<CXXConversionDecl>(NewFD)) {
9860 // 'explicit' was specified on a function that wasn't a constructor
9861 // or conversion function.
9862 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9863 diag::err_explicit_non_ctor_or_conv_function)
9864 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9865 }
9866 }
9867
9868 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9869 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9870 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9871 // are implicitly inline.
9872 NewFD->setImplicitlyInline();
9873
9874 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9875 // be either constructors or to return a literal type. Therefore,
9876 // destructors cannot be declared constexpr.
9877 if (isa<CXXDestructorDecl>(NewFD) &&
9878 (!getLangOpts().CPlusPlus20 ||
9879 ConstexprKind == ConstexprSpecKind::Consteval)) {
9880 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9881 << static_cast<int>(ConstexprKind);
9882 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9883 ? ConstexprSpecKind::Unspecified
9884 : ConstexprSpecKind::Constexpr);
9885 }
9886 // C++20 [dcl.constexpr]p2: An allocation function, or a
9887 // deallocation function shall not be declared with the consteval
9888 // specifier.
9889 if (ConstexprKind == ConstexprSpecKind::Consteval &&
9890 (NewFD->getOverloadedOperator() == OO_New ||
9891 NewFD->getOverloadedOperator() == OO_Array_New ||
9892 NewFD->getOverloadedOperator() == OO_Delete ||
9893 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9894 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9895 diag::err_invalid_consteval_decl_kind)
9896 << NewFD;
9897 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9898 }
9899 }
9900
9901 // If __module_private__ was specified, mark the function accordingly.
9902 if (D.getDeclSpec().isModulePrivateSpecified()) {
9903 if (isFunctionTemplateSpecialization) {
9904 SourceLocation ModulePrivateLoc
9905 = D.getDeclSpec().getModulePrivateSpecLoc();
9906 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9907 << 0
9908 << FixItHint::CreateRemoval(ModulePrivateLoc);
9909 } else {
9910 NewFD->setModulePrivate();
9911 if (FunctionTemplate)
9912 FunctionTemplate->setModulePrivate();
9913 }
9914 }
9915
9916 if (isFriend) {
9917 if (FunctionTemplate) {
9918 FunctionTemplate->setObjectOfFriendDecl();
9919 FunctionTemplate->setAccess(AS_public);
9920 }
9921 NewFD->setObjectOfFriendDecl();
9922 NewFD->setAccess(AS_public);
9923 }
9924
9925 // If a function is defined as defaulted or deleted, mark it as such now.
9926 // We'll do the relevant checks on defaulted / deleted functions later.
9927 switch (D.getFunctionDefinitionKind()) {
9928 case FunctionDefinitionKind::Declaration:
9929 case FunctionDefinitionKind::Definition:
9930 break;
9931
9932 case FunctionDefinitionKind::Defaulted:
9933 NewFD->setDefaulted();
9934 break;
9935
9936 case FunctionDefinitionKind::Deleted:
9937 NewFD->setDeletedAsWritten();
9938 break;
9939 }
9940
9941 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9942 D.isFunctionDefinition() && !isInline) {
9943 // Pre C++20 [class.mfct]p2:
9944 // A member function may be defined (8.4) in its class definition, in
9945 // which case it is an inline member function (7.1.2)
9946 // Post C++20 [class.mfct]p1:
9947 // If a member function is attached to the global module and is defined
9948 // in its class definition, it is inline.
9949 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9950 }
9951
9952 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9953 !CurContext->isRecord()) {
9954 // C++ [class.static]p1:
9955 // A data or function member of a class may be declared static
9956 // in a class definition, in which case it is a static member of
9957 // the class.
9958
9959 // Complain about the 'static' specifier if it's on an out-of-line
9960 // member function definition.
9961
9962 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9963 // member function template declaration and class member template
9964 // declaration (MSVC versions before 2015), warn about this.
9965 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9966 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9967 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9968 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9969 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9970 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9971 }
9972
9973 // C++11 [except.spec]p15:
9974 // A deallocation function with no exception-specification is treated
9975 // as if it were specified with noexcept(true).
9976 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9977 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9978 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9979 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9980 NewFD->setType(Context.getFunctionType(
9981 FPT->getReturnType(), FPT->getParamTypes(),
9982 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9983
9984 // C++20 [dcl.inline]/7
9985 // If an inline function or variable that is attached to a named module
9986 // is declared in a definition domain, it shall be defined in that
9987 // domain.
9988 // So, if the current declaration does not have a definition, we must
9989 // check at the end of the TU (or when the PMF starts) to see that we
9990 // have a definition at that point.
9991 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
9992 NewFD->hasOwningModule() &&
9993 NewFD->getOwningModule()->isModulePurview()) {
9994 PendingInlineFuncDecls.insert(NewFD);
9995 }
9996 }
9997
9998 // Filter out previous declarations that don't match the scope.
9999 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10000 D.getCXXScopeSpec().isNotEmpty() ||
10001 isMemberSpecialization ||
10002 isFunctionTemplateSpecialization);
10003
10004 // Handle GNU asm-label extension (encoded as an attribute).
10005 if (Expr *E = (Expr*) D.getAsmLabel()) {
10006 // The parser guarantees this is a string.
10007 StringLiteral *SE = cast<StringLiteral>(E);
10008 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10009 /*IsLiteralLabel=*/true,
10010 SE->getStrTokenLoc(0)));
10011 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10012 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10013 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10014 if (I != ExtnameUndeclaredIdentifiers.end()) {
10015 if (isDeclExternC(NewFD)) {
10016 NewFD->addAttr(I->second);
10017 ExtnameUndeclaredIdentifiers.erase(I);
10018 } else
10019 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10020 << /*Variable*/0 << NewFD;
10021 }
10022 }
10023
10024 // Copy the parameter declarations from the declarator D to the function
10025 // declaration NewFD, if they are available. First scavenge them into Params.
10026 SmallVector<ParmVarDecl*, 16> Params;
10027 unsigned FTIIdx;
10028 if (D.isFunctionDeclarator(FTIIdx)) {
10029 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10030
10031 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10032 // function that takes no arguments, not a function that takes a
10033 // single void argument.
10034 // We let through "const void" here because Sema::GetTypeForDeclarator
10035 // already checks for that case.
10036 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10037 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10038 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10039 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10040 Param->setDeclContext(NewFD);
10041 Params.push_back(Param);
10042
10043 if (Param->isInvalidDecl())
10044 NewFD->setInvalidDecl();
10045 }
10046 }
10047
10048 if (!getLangOpts().CPlusPlus) {
10049 // In C, find all the tag declarations from the prototype and move them
10050 // into the function DeclContext. Remove them from the surrounding tag
10051 // injection context of the function, which is typically but not always
10052 // the TU.
10053 DeclContext *PrototypeTagContext =
10054 getTagInjectionContext(NewFD->getLexicalDeclContext());
10055 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10056 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10057
10058 // We don't want to reparent enumerators. Look at their parent enum
10059 // instead.
10060 if (!TD) {
10061 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10062 TD = cast<EnumDecl>(ECD->getDeclContext());
10063 }
10064 if (!TD)
10065 continue;
10066 DeclContext *TagDC = TD->getLexicalDeclContext();
10067 if (!TagDC->containsDecl(TD))
10068 continue;
10069 TagDC->removeDecl(TD);
10070 TD->setDeclContext(NewFD);
10071 NewFD->addDecl(TD);
10072
10073 // Preserve the lexical DeclContext if it is not the surrounding tag
10074 // injection context of the FD. In this example, the semantic context of
10075 // E will be f and the lexical context will be S, while both the
10076 // semantic and lexical contexts of S will be f:
10077 // void f(struct S { enum E { a } f; } s);
10078 if (TagDC != PrototypeTagContext)
10079 TD->setLexicalDeclContext(TagDC);
10080 }
10081 }
10082 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10083 // When we're declaring a function with a typedef, typeof, etc as in the
10084 // following example, we'll need to synthesize (unnamed)
10085 // parameters for use in the declaration.
10086 //
10087 // @code
10088 // typedef void fn(int);
10089 // fn f;
10090 // @endcode
10091
10092 // Synthesize a parameter for each argument type.
10093 for (const auto &AI : FT->param_types()) {
10094 ParmVarDecl *Param =
10095 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10096 Param->setScopeInfo(0, Params.size());
10097 Params.push_back(Param);
10098 }
10099 } else {
10100 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10101 "Should not need args for typedef of non-prototype fn");
10102 }
10103
10104 // Finally, we know we have the right number of parameters, install them.
10105 NewFD->setParams(Params);
10106
10107 if (D.getDeclSpec().isNoreturnSpecified())
10108 NewFD->addAttr(C11NoReturnAttr::Create(Context,
10109 D.getDeclSpec().getNoreturnSpecLoc(),
10110 AttributeCommonInfo::AS_Keyword));
10111
10112 // Functions returning a variably modified type violate C99 6.7.5.2p2
10113 // because all functions have linkage.
10114 if (!NewFD->isInvalidDecl() &&
10115 NewFD->getReturnType()->isVariablyModifiedType()) {
10116 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10117 NewFD->setInvalidDecl();
10118 }
10119
10120 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10121 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10122 !NewFD->hasAttr<SectionAttr>())
10123 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10124 Context, PragmaClangTextSection.SectionName,
10125 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
10126
10127 // Apply an implicit SectionAttr if #pragma code_seg is active.
10128 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10129 !NewFD->hasAttr<SectionAttr>()) {
10130 NewFD->addAttr(SectionAttr::CreateImplicit(
10131 Context, CodeSegStack.CurrentValue->getString(),
10132 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10133 SectionAttr::Declspec_allocate));
10134 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10135 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10136 ASTContext::PSF_Read,
10137 NewFD))
10138 NewFD->dropAttr<SectionAttr>();
10139 }
10140
10141 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10142 // active.
10143 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10144 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10145 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10146 Context, PragmaClangTextSection.PragmaLocation,
10147 AttributeCommonInfo::AS_Pragma));
10148
10149 // Apply an implicit CodeSegAttr from class declspec or
10150 // apply an implicit SectionAttr from #pragma code_seg if active.
10151 if (!NewFD->hasAttr<CodeSegAttr>()) {
10152 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10153 D.isFunctionDefinition())) {
10154 NewFD->addAttr(SAttr);
10155 }
10156 }
10157
10158 // Handle attributes.
10159 ProcessDeclAttributes(S, NewFD, D);
10160 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10161 if (NewTVA && !NewTVA->isDefaultVersion() &&
10162 !Context.getTargetInfo().hasFeature("fmv")) {
10163 // Don't add to scope fmv functions declarations if fmv disabled
10164 AddToScope = false;
10165 return NewFD;
10166 }
10167
10168 if (getLangOpts().OpenCL) {
10169 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10170 // type declaration will generate a compilation error.
10171 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10172 if (AddressSpace != LangAS::Default) {
10173 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10174 NewFD->setInvalidDecl();
10175 }
10176 }
10177
10178 if (getLangOpts().HLSL) {
10179 auto &TargetInfo = getASTContext().getTargetInfo();
10180 // Skip operator overload which not identifier.
10181 // Also make sure NewFD is in translation-unit scope.
10182 if (!NewFD->isInvalidDecl() && Name.isIdentifier() &&
10183 NewFD->getName() == TargetInfo.getTargetOpts().HLSLEntry &&
10184 S->getDepth() == 0) {
10185 CheckHLSLEntryPoint(NewFD);
10186 if (!NewFD->isInvalidDecl()) {
10187 auto Env = TargetInfo.getTriple().getEnvironment();
10188 AttributeCommonInfo AL(NewFD->getBeginLoc());
10189 HLSLShaderAttr::ShaderType ShaderType =
10190 static_cast<HLSLShaderAttr::ShaderType>(
10191 hlsl::getStageFromEnvironment(Env));
10192 // To share code with HLSLShaderAttr, add HLSLShaderAttr to entry
10193 // function.
10194 if (HLSLShaderAttr *Attr = mergeHLSLShaderAttr(NewFD, AL, ShaderType))
10195 NewFD->addAttr(Attr);
10196 }
10197 }
10198 // HLSL does not support specifying an address space on a function return
10199 // type.
10200 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10201 if (AddressSpace != LangAS::Default) {
10202 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10203 NewFD->setInvalidDecl();
10204 }
10205 }
10206
10207 if (!getLangOpts().CPlusPlus) {
10208 // Perform semantic checking on the function declaration.
10209 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10210 CheckMain(NewFD, D.getDeclSpec());
10211
10212 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10213 CheckMSVCRTEntryPoint(NewFD);
10214
10215 if (!NewFD->isInvalidDecl())
10216 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10217 isMemberSpecialization,
10218 D.isFunctionDefinition()));
10219 else if (!Previous.empty())
10220 // Recover gracefully from an invalid redeclaration.
10221 D.setRedeclaration(true);
10222 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10223 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10224 "previous declaration set still overloaded");
10225
10226 // Diagnose no-prototype function declarations with calling conventions that
10227 // don't support variadic calls. Only do this in C and do it after merging
10228 // possibly prototyped redeclarations.
10229 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10230 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10231 CallingConv CC = FT->getExtInfo().getCC();
10232 if (!supportsVariadicCall(CC)) {
10233 // Windows system headers sometimes accidentally use stdcall without
10234 // (void) parameters, so we relax this to a warning.
10235 int DiagID =
10236 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10237 Diag(NewFD->getLocation(), DiagID)
10238 << FunctionType::getNameForCallConv(CC);
10239 }
10240 }
10241
10242 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10243 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10244 checkNonTrivialCUnion(NewFD->getReturnType(),
10245 NewFD->getReturnTypeSourceRange().getBegin(),
10246 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10247 } else {
10248 // C++11 [replacement.functions]p3:
10249 // The program's definitions shall not be specified as inline.
10250 //
10251 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10252 //
10253 // Suppress the diagnostic if the function is __attribute__((used)), since
10254 // that forces an external definition to be emitted.
10255 if (D.getDeclSpec().isInlineSpecified() &&
10256 NewFD->isReplaceableGlobalAllocationFunction() &&
10257 !NewFD->hasAttr<UsedAttr>())
10258 Diag(D.getDeclSpec().getInlineSpecLoc(),
10259 diag::ext_operator_new_delete_declared_inline)
10260 << NewFD->getDeclName();
10261
10262 // If the declarator is a template-id, translate the parser's template
10263 // argument list into our AST format.
10264 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10265 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
10266 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10267 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10268 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10269 TemplateId->NumArgs);
10270 translateTemplateArguments(TemplateArgsPtr,
10271 TemplateArgs);
10272
10273 HasExplicitTemplateArgs = true;
10274
10275 if (NewFD->isInvalidDecl()) {
10276 HasExplicitTemplateArgs = false;
10277 } else if (FunctionTemplate) {
10278 // Function template with explicit template arguments.
10279 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10280 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10281
10282 HasExplicitTemplateArgs = false;
10283 } else {
10284 assert((isFunctionTemplateSpecialization ||
10285 D.getDeclSpec().isFriendSpecified()) &&
10286 "should have a 'template<>' for this decl");
10287 // "friend void foo<>(int);" is an implicit specialization decl.
10288 isFunctionTemplateSpecialization = true;
10289 }
10290 } else if (isFriend && isFunctionTemplateSpecialization) {
10291 // This combination is only possible in a recovery case; the user
10292 // wrote something like:
10293 // template <> friend void foo(int);
10294 // which we're recovering from as if the user had written:
10295 // friend void foo<>(int);
10296 // Go ahead and fake up a template id.
10297 HasExplicitTemplateArgs = true;
10298 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10299 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10300 }
10301
10302 // We do not add HD attributes to specializations here because
10303 // they may have different constexpr-ness compared to their
10304 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10305 // may end up with different effective targets. Instead, a
10306 // specialization inherits its target attributes from its template
10307 // in the CheckFunctionTemplateSpecialization() call below.
10308 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10309 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10310
10311 // If it's a friend (and only if it's a friend), it's possible
10312 // that either the specialized function type or the specialized
10313 // template is dependent, and therefore matching will fail. In
10314 // this case, don't check the specialization yet.
10315 if (isFunctionTemplateSpecialization && isFriend &&
10316 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
10317 TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
10318 TemplateArgs.arguments()))) {
10319 assert(HasExplicitTemplateArgs &&
10320 "friend function specialization without template args");
10321 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
10322 Previous))
10323 NewFD->setInvalidDecl();
10324 } else if (isFunctionTemplateSpecialization) {
10325 if (CurContext->isDependentContext() && CurContext->isRecord()
10326 && !isFriend) {
10327 isDependentClassScopeExplicitSpecialization = true;
10328 } else if (!NewFD->isInvalidDecl() &&
10329 CheckFunctionTemplateSpecialization(
10330 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
10331 Previous))
10332 NewFD->setInvalidDecl();
10333
10334 // C++ [dcl.stc]p1:
10335 // A storage-class-specifier shall not be specified in an explicit
10336 // specialization (14.7.3)
10337 FunctionTemplateSpecializationInfo *Info =
10338 NewFD->getTemplateSpecializationInfo();
10339 if (Info && SC != SC_None) {
10340 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10341 Diag(NewFD->getLocation(),
10342 diag::err_explicit_specialization_inconsistent_storage_class)
10343 << SC
10344 << FixItHint::CreateRemoval(
10345 D.getDeclSpec().getStorageClassSpecLoc());
10346
10347 else
10348 Diag(NewFD->getLocation(),
10349 diag::ext_explicit_specialization_storage_class)
10350 << FixItHint::CreateRemoval(
10351 D.getDeclSpec().getStorageClassSpecLoc());
10352 }
10353 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10354 if (CheckMemberSpecialization(NewFD, Previous))
10355 NewFD->setInvalidDecl();
10356 }
10357
10358 // Perform semantic checking on the function declaration.
10359 if (!isDependentClassScopeExplicitSpecialization) {
10360 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10361 CheckMain(NewFD, D.getDeclSpec());
10362
10363 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10364 CheckMSVCRTEntryPoint(NewFD);
10365
10366 if (!NewFD->isInvalidDecl())
10367 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10368 isMemberSpecialization,
10369 D.isFunctionDefinition()));
10370 else if (!Previous.empty())
10371 // Recover gracefully from an invalid redeclaration.
10372 D.setRedeclaration(true);
10373 }
10374
10375 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10376 !D.isRedeclaration() ||
10377 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10378 "previous declaration set still overloaded");
10379
10380 NamedDecl *PrincipalDecl = (FunctionTemplate
10381 ? cast<NamedDecl>(FunctionTemplate)
10382 : NewFD);
10383
10384 if (isFriend && NewFD->getPreviousDecl()) {
10385 AccessSpecifier Access = AS_public;
10386 if (!NewFD->isInvalidDecl())
10387 Access = NewFD->getPreviousDecl()->getAccess();
10388
10389 NewFD->setAccess(Access);
10390 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10391 }
10392
10393 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10394 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10395 PrincipalDecl->setNonMemberOperator();
10396
10397 // If we have a function template, check the template parameter
10398 // list. This will check and merge default template arguments.
10399 if (FunctionTemplate) {
10400 FunctionTemplateDecl *PrevTemplate =
10401 FunctionTemplate->getPreviousDecl();
10402 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10403 PrevTemplate ? PrevTemplate->getTemplateParameters()
10404 : nullptr,
10405 D.getDeclSpec().isFriendSpecified()
10406 ? (D.isFunctionDefinition()
10407 ? TPC_FriendFunctionTemplateDefinition
10408 : TPC_FriendFunctionTemplate)
10409 : (D.getCXXScopeSpec().isSet() &&
10410 DC && DC->isRecord() &&
10411 DC->isDependentContext())
10412 ? TPC_ClassTemplateMember
10413 : TPC_FunctionTemplate);
10414 }
10415
10416 if (NewFD->isInvalidDecl()) {
10417 // Ignore all the rest of this.
10418 } else if (!D.isRedeclaration()) {
10419 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10420 AddToScope };
10421 // Fake up an access specifier if it's supposed to be a class member.
10422 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10423 NewFD->setAccess(AS_public);
10424
10425 // Qualified decls generally require a previous declaration.
10426 if (D.getCXXScopeSpec().isSet()) {
10427 // ...with the major exception of templated-scope or
10428 // dependent-scope friend declarations.
10429
10430 // TODO: we currently also suppress this check in dependent
10431 // contexts because (1) the parameter depth will be off when
10432 // matching friend templates and (2) we might actually be
10433 // selecting a friend based on a dependent factor. But there
10434 // are situations where these conditions don't apply and we
10435 // can actually do this check immediately.
10436 //
10437 // Unless the scope is dependent, it's always an error if qualified
10438 // redeclaration lookup found nothing at all. Diagnose that now;
10439 // nothing will diagnose that error later.
10440 if (isFriend &&
10441 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10442 (!Previous.empty() && CurContext->isDependentContext()))) {
10443 // ignore these
10444 } else if (NewFD->isCPUDispatchMultiVersion() ||
10445 NewFD->isCPUSpecificMultiVersion()) {
10446 // ignore this, we allow the redeclaration behavior here to create new
10447 // versions of the function.
10448 } else {
10449 // The user tried to provide an out-of-line definition for a
10450 // function that is a member of a class or namespace, but there
10451 // was no such member function declared (C++ [class.mfct]p2,
10452 // C++ [namespace.memdef]p2). For example:
10453 //
10454 // class X {
10455 // void f() const;
10456 // };
10457 //
10458 // void X::f() { } // ill-formed
10459 //
10460 // Complain about this problem, and attempt to suggest close
10461 // matches (e.g., those that differ only in cv-qualifiers and
10462 // whether the parameter types are references).
10463
10464 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10465 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10466 AddToScope = ExtraArgs.AddToScope;
10467 return Result;
10468 }
10469 }
10470
10471 // Unqualified local friend declarations are required to resolve
10472 // to something.
10473 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10474 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10475 *this, Previous, NewFD, ExtraArgs, true, S)) {
10476 AddToScope = ExtraArgs.AddToScope;
10477 return Result;
10478 }
10479 }
10480 } else if (!D.isFunctionDefinition() &&
10481 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10482 !isFriend && !isFunctionTemplateSpecialization &&
10483 !isMemberSpecialization) {
10484 // An out-of-line member function declaration must also be a
10485 // definition (C++ [class.mfct]p2).
10486 // Note that this is not the case for explicit specializations of
10487 // function templates or member functions of class templates, per
10488 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10489 // extension for compatibility with old SWIG code which likes to
10490 // generate them.
10491 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10492 << D.getCXXScopeSpec().getRange();
10493 }
10494 }
10495
10496 // If this is the first declaration of a library builtin function, add
10497 // attributes as appropriate.
10498 if (!D.isRedeclaration()) {
10499 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10500 if (unsigned BuiltinID = II->getBuiltinID()) {
10501 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10502 if (!InStdNamespace &&
10503 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10504 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10505 // Validate the type matches unless this builtin is specified as
10506 // matching regardless of its declared type.
10507 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10508 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10509 } else {
10510 ASTContext::GetBuiltinTypeError Error;
10511 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10512 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10513
10514 if (!Error && !BuiltinType.isNull() &&
10515 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10516 NewFD->getType(), BuiltinType))
10517 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10518 }
10519 }
10520 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10521 isStdBuiltin(Context, NewFD, BuiltinID)) {
10522 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10523 }
10524 }
10525 }
10526 }
10527
10528 ProcessPragmaWeak(S, NewFD);
10529 checkAttributesAfterMerging(*this, *NewFD);
10530
10531 AddKnownFunctionAttributes(NewFD);
10532
10533 if (NewFD->hasAttr<OverloadableAttr>() &&
10534 !NewFD->getType()->getAs<FunctionProtoType>()) {
10535 Diag(NewFD->getLocation(),
10536 diag::err_attribute_overloadable_no_prototype)
10537 << NewFD;
10538 NewFD->dropAttr<OverloadableAttr>();
10539 }
10540
10541 // If there's a #pragma GCC visibility in scope, and this isn't a class
10542 // member, set the visibility of this function.
10543 if (!DC->isRecord() && NewFD->isExternallyVisible())
10544 AddPushedVisibilityAttribute(NewFD);
10545
10546 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10547 // marking the function.
10548 AddCFAuditedAttribute(NewFD);
10549
10550 // If this is a function definition, check if we have to apply any
10551 // attributes (i.e. optnone and no_builtin) due to a pragma.
10552 if (D.isFunctionDefinition()) {
10553 AddRangeBasedOptnone(NewFD);
10554 AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10555 AddSectionMSAllocText(NewFD);
10556 ModifyFnAttributesMSPragmaOptimize(NewFD);
10557 }
10558
10559 // If this is the first declaration of an extern C variable, update
10560 // the map of such variables.
10561 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10562 isIncompleteDeclExternC(*this, NewFD))
10563 RegisterLocallyScopedExternCDecl(NewFD, S);
10564
10565 // Set this FunctionDecl's range up to the right paren.
10566 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10567
10568 if (D.isRedeclaration() && !Previous.empty()) {
10569 NamedDecl *Prev = Previous.getRepresentativeDecl();
10570 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10571 isMemberSpecialization ||
10572 isFunctionTemplateSpecialization,
10573 D.isFunctionDefinition());
10574 }
10575
10576 if (getLangOpts().CUDA) {
10577 IdentifierInfo *II = NewFD->getIdentifier();
10578 if (II && II->isStr(getCudaConfigureFuncName()) &&
10579 !NewFD->isInvalidDecl() &&
10580 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10581 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10582 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10583 << getCudaConfigureFuncName();
10584 Context.setcudaConfigureCallDecl(NewFD);
10585 }
10586
10587 // Variadic functions, other than a *declaration* of printf, are not allowed
10588 // in device-side CUDA code, unless someone passed
10589 // -fcuda-allow-variadic-functions.
10590 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10591 (NewFD->hasAttr<CUDADeviceAttr>() ||
10592 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10593 !(II && II->isStr("printf") && NewFD->isExternC() &&
10594 !D.isFunctionDefinition())) {
10595 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10596 }
10597 }
10598
10599 MarkUnusedFileScopedDecl(NewFD);
10600
10601
10602
10603 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10604 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10605 if (SC == SC_Static) {
10606 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10607 D.setInvalidType();
10608 }
10609
10610 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10611 if (!NewFD->getReturnType()->isVoidType()) {
10612 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10613 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10614 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10615 : FixItHint());
10616 D.setInvalidType();
10617 }
10618
10619 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10620 for (auto *Param : NewFD->parameters())
10621 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10622
10623 if (getLangOpts().OpenCLCPlusPlus) {
10624 if (DC->isRecord()) {
10625 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10626 D.setInvalidType();
10627 }
10628 if (FunctionTemplate) {
10629 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10630 D.setInvalidType();
10631 }
10632 }
10633 }
10634
10635 if (getLangOpts().CPlusPlus) {
10636 // Precalculate whether this is a friend function template with a constraint
10637 // that depends on an enclosing template, per [temp.friend]p9.
10638 if (isFriend && FunctionTemplate &&
10639 FriendConstraintsDependOnEnclosingTemplate(NewFD))
10640 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10641
10642 if (FunctionTemplate) {
10643 if (NewFD->isInvalidDecl())
10644 FunctionTemplate->setInvalidDecl();
10645 return FunctionTemplate;
10646 }
10647
10648 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10649 CompleteMemberSpecialization(NewFD, Previous);
10650 }
10651
10652 for (const ParmVarDecl *Param : NewFD->parameters()) {
10653 QualType PT = Param->getType();
10654
10655 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10656 // types.
10657 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10658 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10659 QualType ElemTy = PipeTy->getElementType();
10660 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10661 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10662 D.setInvalidType();
10663 }
10664 }
10665 }
10666 }
10667
10668 // Here we have an function template explicit specialization at class scope.
10669 // The actual specialization will be postponed to template instatiation
10670 // time via the ClassScopeFunctionSpecializationDecl node.
10671 if (isDependentClassScopeExplicitSpecialization) {
10672 ClassScopeFunctionSpecializationDecl *NewSpec =
10673 ClassScopeFunctionSpecializationDecl::Create(
10674 Context, CurContext, NewFD->getLocation(),
10675 cast<CXXMethodDecl>(NewFD),
10676 HasExplicitTemplateArgs, TemplateArgs);
10677 CurContext->addDecl(NewSpec);
10678 AddToScope = false;
10679 }
10680
10681 // Diagnose availability attributes. Availability cannot be used on functions
10682 // that are run during load/unload.
10683 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10684 if (NewFD->hasAttr<ConstructorAttr>()) {
10685 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10686 << 1;
10687 NewFD->dropAttr<AvailabilityAttr>();
10688 }
10689 if (NewFD->hasAttr<DestructorAttr>()) {
10690 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10691 << 2;
10692 NewFD->dropAttr<AvailabilityAttr>();
10693 }
10694 }
10695
10696 // Diagnose no_builtin attribute on function declaration that are not a
10697 // definition.
10698 // FIXME: We should really be doing this in
10699 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10700 // the FunctionDecl and at this point of the code
10701 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10702 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10703 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10704 switch (D.getFunctionDefinitionKind()) {
10705 case FunctionDefinitionKind::Defaulted:
10706 case FunctionDefinitionKind::Deleted:
10707 Diag(NBA->getLocation(),
10708 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10709 << NBA->getSpelling();
10710 break;
10711 case FunctionDefinitionKind::Declaration:
10712 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10713 << NBA->getSpelling();
10714 break;
10715 case FunctionDefinitionKind::Definition:
10716 break;
10717 }
10718
10719 return NewFD;
10720 }
10721
10722 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
10723 /// when __declspec(code_seg) "is applied to a class, all member functions of
10724 /// the class and nested classes -- this includes compiler-generated special
10725 /// member functions -- are put in the specified segment."
10726 /// The actual behavior is a little more complicated. The Microsoft compiler
10727 /// won't check outer classes if there is an active value from #pragma code_seg.
10728 /// The CodeSeg is always applied from the direct parent but only from outer
10729 /// classes when the #pragma code_seg stack is empty. See:
10730 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10731 /// available since MS has removed the page.
getImplicitCodeSegAttrFromClass(Sema & S,const FunctionDecl * FD)10732 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10733 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10734 if (!Method)
10735 return nullptr;
10736 const CXXRecordDecl *Parent = Method->getParent();
10737 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10738 Attr *NewAttr = SAttr->clone(S.getASTContext());
10739 NewAttr->setImplicit(true);
10740 return NewAttr;
10741 }
10742
10743 // The Microsoft compiler won't check outer classes for the CodeSeg
10744 // when the #pragma code_seg stack is active.
10745 if (S.CodeSegStack.CurrentValue)
10746 return nullptr;
10747
10748 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10749 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10750 Attr *NewAttr = SAttr->clone(S.getASTContext());
10751 NewAttr->setImplicit(true);
10752 return NewAttr;
10753 }
10754 }
10755 return nullptr;
10756 }
10757
10758 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10759 /// containing class. Otherwise it will return implicit SectionAttr if the
10760 /// function is a definition and there is an active value on CodeSegStack
10761 /// (from the current #pragma code-seg value).
10762 ///
10763 /// \param FD Function being declared.
10764 /// \param IsDefinition Whether it is a definition or just a declaration.
10765 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10766 /// nullptr if no attribute should be added.
getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl * FD,bool IsDefinition)10767 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10768 bool IsDefinition) {
10769 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10770 return A;
10771 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10772 CodeSegStack.CurrentValue)
10773 return SectionAttr::CreateImplicit(
10774 getASTContext(), CodeSegStack.CurrentValue->getString(),
10775 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10776 SectionAttr::Declspec_allocate);
10777 return nullptr;
10778 }
10779
10780 /// Determines if we can perform a correct type check for \p D as a
10781 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10782 /// best-effort check.
10783 ///
10784 /// \param NewD The new declaration.
10785 /// \param OldD The old declaration.
10786 /// \param NewT The portion of the type of the new declaration to check.
10787 /// \param OldT The portion of the type of the old declaration to check.
canFullyTypeCheckRedeclaration(ValueDecl * NewD,ValueDecl * OldD,QualType NewT,QualType OldT)10788 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10789 QualType NewT, QualType OldT) {
10790 if (!NewD->getLexicalDeclContext()->isDependentContext())
10791 return true;
10792
10793 // For dependently-typed local extern declarations and friends, we can't
10794 // perform a correct type check in general until instantiation:
10795 //
10796 // int f();
10797 // template<typename T> void g() { T f(); }
10798 //
10799 // (valid if g() is only instantiated with T = int).
10800 if (NewT->isDependentType() &&
10801 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10802 return false;
10803
10804 // Similarly, if the previous declaration was a dependent local extern
10805 // declaration, we don't really know its type yet.
10806 if (OldT->isDependentType() && OldD->isLocalExternDecl())
10807 return false;
10808
10809 return true;
10810 }
10811
10812 /// Checks if the new declaration declared in dependent context must be
10813 /// put in the same redeclaration chain as the specified declaration.
10814 ///
10815 /// \param D Declaration that is checked.
10816 /// \param PrevDecl Previous declaration found with proper lookup method for the
10817 /// same declaration name.
10818 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10819 /// belongs to.
10820 ///
shouldLinkDependentDeclWithPrevious(Decl * D,Decl * PrevDecl)10821 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10822 if (!D->getLexicalDeclContext()->isDependentContext())
10823 return true;
10824
10825 // Don't chain dependent friend function definitions until instantiation, to
10826 // permit cases like
10827 //
10828 // void func();
10829 // template<typename T> class C1 { friend void func() {} };
10830 // template<typename T> class C2 { friend void func() {} };
10831 //
10832 // ... which is valid if only one of C1 and C2 is ever instantiated.
10833 //
10834 // FIXME: This need only apply to function definitions. For now, we proxy
10835 // this by checking for a file-scope function. We do not want this to apply
10836 // to friend declarations nominating member functions, because that gets in
10837 // the way of access checks.
10838 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10839 return false;
10840
10841 auto *VD = dyn_cast<ValueDecl>(D);
10842 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10843 return !VD || !PrevVD ||
10844 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10845 PrevVD->getType());
10846 }
10847
10848 /// Check the target or target_version attribute of the function for
10849 /// MultiVersion validity.
10850 ///
10851 /// Returns true if there was an error, false otherwise.
CheckMultiVersionValue(Sema & S,const FunctionDecl * FD)10852 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10853 const auto *TA = FD->getAttr<TargetAttr>();
10854 const auto *TVA = FD->getAttr<TargetVersionAttr>();
10855 assert(
10856 (TA || TVA) &&
10857 "MultiVersion candidate requires a target or target_version attribute");
10858 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10859 enum ErrType { Feature = 0, Architecture = 1 };
10860
10861 if (TA) {
10862 ParsedTargetAttr ParseInfo =
10863 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
10864 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
10865 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10866 << Architecture << ParseInfo.CPU;
10867 return true;
10868 }
10869 for (const auto &Feat : ParseInfo.Features) {
10870 auto BareFeat = StringRef{Feat}.substr(1);
10871 if (Feat[0] == '-') {
10872 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10873 << Feature << ("no-" + BareFeat).str();
10874 return true;
10875 }
10876
10877 if (!TargetInfo.validateCpuSupports(BareFeat) ||
10878 !TargetInfo.isValidFeatureName(BareFeat)) {
10879 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10880 << Feature << BareFeat;
10881 return true;
10882 }
10883 }
10884 }
10885
10886 if (TVA) {
10887 llvm::SmallVector<StringRef, 8> Feats;
10888 TVA->getFeatures(Feats);
10889 for (const auto &Feat : Feats) {
10890 if (!TargetInfo.validateCpuSupports(Feat)) {
10891 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10892 << Feature << Feat;
10893 return true;
10894 }
10895 }
10896 }
10897 return false;
10898 }
10899
10900 // Provide a white-list of attributes that are allowed to be combined with
10901 // multiversion functions.
AttrCompatibleWithMultiVersion(attr::Kind Kind,MultiVersionKind MVKind)10902 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10903 MultiVersionKind MVKind) {
10904 // Note: this list/diagnosis must match the list in
10905 // checkMultiversionAttributesAllSame.
10906 switch (Kind) {
10907 default:
10908 return false;
10909 case attr::Used:
10910 return MVKind == MultiVersionKind::Target;
10911 case attr::NonNull:
10912 case attr::NoThrow:
10913 return true;
10914 }
10915 }
10916
checkNonMultiVersionCompatAttributes(Sema & S,const FunctionDecl * FD,const FunctionDecl * CausedFD,MultiVersionKind MVKind)10917 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10918 const FunctionDecl *FD,
10919 const FunctionDecl *CausedFD,
10920 MultiVersionKind MVKind) {
10921 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10922 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10923 << static_cast<unsigned>(MVKind) << A;
10924 if (CausedFD)
10925 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10926 return true;
10927 };
10928
10929 for (const Attr *A : FD->attrs()) {
10930 switch (A->getKind()) {
10931 case attr::CPUDispatch:
10932 case attr::CPUSpecific:
10933 if (MVKind != MultiVersionKind::CPUDispatch &&
10934 MVKind != MultiVersionKind::CPUSpecific)
10935 return Diagnose(S, A);
10936 break;
10937 case attr::Target:
10938 if (MVKind != MultiVersionKind::Target)
10939 return Diagnose(S, A);
10940 break;
10941 case attr::TargetVersion:
10942 if (MVKind != MultiVersionKind::TargetVersion)
10943 return Diagnose(S, A);
10944 break;
10945 case attr::TargetClones:
10946 if (MVKind != MultiVersionKind::TargetClones)
10947 return Diagnose(S, A);
10948 break;
10949 default:
10950 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10951 return Diagnose(S, A);
10952 break;
10953 }
10954 }
10955 return false;
10956 }
10957
areMultiversionVariantFunctionsCompatible(const FunctionDecl * OldFD,const FunctionDecl * NewFD,const PartialDiagnostic & NoProtoDiagID,const PartialDiagnosticAt & NoteCausedDiagIDAt,const PartialDiagnosticAt & NoSupportDiagIDAt,const PartialDiagnosticAt & DiffDiagIDAt,bool TemplatesSupported,bool ConstexprSupported,bool CLinkageMayDiffer)10958 bool Sema::areMultiversionVariantFunctionsCompatible(
10959 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10960 const PartialDiagnostic &NoProtoDiagID,
10961 const PartialDiagnosticAt &NoteCausedDiagIDAt,
10962 const PartialDiagnosticAt &NoSupportDiagIDAt,
10963 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10964 bool ConstexprSupported, bool CLinkageMayDiffer) {
10965 enum DoesntSupport {
10966 FuncTemplates = 0,
10967 VirtFuncs = 1,
10968 DeducedReturn = 2,
10969 Constructors = 3,
10970 Destructors = 4,
10971 DeletedFuncs = 5,
10972 DefaultedFuncs = 6,
10973 ConstexprFuncs = 7,
10974 ConstevalFuncs = 8,
10975 Lambda = 9,
10976 };
10977 enum Different {
10978 CallingConv = 0,
10979 ReturnType = 1,
10980 ConstexprSpec = 2,
10981 InlineSpec = 3,
10982 Linkage = 4,
10983 LanguageLinkage = 5,
10984 };
10985
10986 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10987 !OldFD->getType()->getAs<FunctionProtoType>()) {
10988 Diag(OldFD->getLocation(), NoProtoDiagID);
10989 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10990 return true;
10991 }
10992
10993 if (NoProtoDiagID.getDiagID() != 0 &&
10994 !NewFD->getType()->getAs<FunctionProtoType>())
10995 return Diag(NewFD->getLocation(), NoProtoDiagID);
10996
10997 if (!TemplatesSupported &&
10998 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10999 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11000 << FuncTemplates;
11001
11002 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11003 if (NewCXXFD->isVirtual())
11004 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11005 << VirtFuncs;
11006
11007 if (isa<CXXConstructorDecl>(NewCXXFD))
11008 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11009 << Constructors;
11010
11011 if (isa<CXXDestructorDecl>(NewCXXFD))
11012 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11013 << Destructors;
11014 }
11015
11016 if (NewFD->isDeleted())
11017 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11018 << DeletedFuncs;
11019
11020 if (NewFD->isDefaulted())
11021 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11022 << DefaultedFuncs;
11023
11024 if (!ConstexprSupported && NewFD->isConstexpr())
11025 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11026 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11027
11028 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11029 const auto *NewType = cast<FunctionType>(NewQType);
11030 QualType NewReturnType = NewType->getReturnType();
11031
11032 if (NewReturnType->isUndeducedType())
11033 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11034 << DeducedReturn;
11035
11036 // Ensure the return type is identical.
11037 if (OldFD) {
11038 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11039 const auto *OldType = cast<FunctionType>(OldQType);
11040 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11041 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11042
11043 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11044 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11045
11046 QualType OldReturnType = OldType->getReturnType();
11047
11048 if (OldReturnType != NewReturnType)
11049 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11050
11051 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11052 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11053
11054 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11055 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11056
11057 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11058 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11059
11060 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11061 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11062
11063 if (CheckEquivalentExceptionSpec(
11064 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11065 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11066 return true;
11067 }
11068 return false;
11069 }
11070
CheckMultiVersionAdditionalRules(Sema & S,const FunctionDecl * OldFD,const FunctionDecl * NewFD,bool CausesMV,MultiVersionKind MVKind)11071 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11072 const FunctionDecl *NewFD,
11073 bool CausesMV,
11074 MultiVersionKind MVKind) {
11075 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11076 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11077 if (OldFD)
11078 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11079 return true;
11080 }
11081
11082 bool IsCPUSpecificCPUDispatchMVKind =
11083 MVKind == MultiVersionKind::CPUDispatch ||
11084 MVKind == MultiVersionKind::CPUSpecific;
11085
11086 if (CausesMV && OldFD &&
11087 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11088 return true;
11089
11090 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11091 return true;
11092
11093 // Only allow transition to MultiVersion if it hasn't been used.
11094 if (OldFD && CausesMV && OldFD->isUsed(false))
11095 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11096
11097 return S.areMultiversionVariantFunctionsCompatible(
11098 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11099 PartialDiagnosticAt(NewFD->getLocation(),
11100 S.PDiag(diag::note_multiversioning_caused_here)),
11101 PartialDiagnosticAt(NewFD->getLocation(),
11102 S.PDiag(diag::err_multiversion_doesnt_support)
11103 << static_cast<unsigned>(MVKind)),
11104 PartialDiagnosticAt(NewFD->getLocation(),
11105 S.PDiag(diag::err_multiversion_diff)),
11106 /*TemplatesSupported=*/false,
11107 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11108 /*CLinkageMayDiffer=*/false);
11109 }
11110
11111 /// Check the validity of a multiversion function declaration that is the
11112 /// first of its kind. Also sets the multiversion'ness' of the function itself.
11113 ///
11114 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11115 ///
11116 /// Returns true if there was an error, false otherwise.
CheckMultiVersionFirstFunction(Sema & S,FunctionDecl * FD)11117 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11118 MultiVersionKind MVKind = FD->getMultiVersionKind();
11119 assert(MVKind != MultiVersionKind::None &&
11120 "Function lacks multiversion attribute");
11121 const auto *TA = FD->getAttr<TargetAttr>();
11122 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11123 // Target and target_version only causes MV if it is default, otherwise this
11124 // is a normal function.
11125 if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion()))
11126 return false;
11127
11128 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11129 FD->setInvalidDecl();
11130 return true;
11131 }
11132
11133 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11134 FD->setInvalidDecl();
11135 return true;
11136 }
11137
11138 FD->setIsMultiVersion();
11139 return false;
11140 }
11141
PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl * FD)11142 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11143 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11144 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11145 return true;
11146 }
11147
11148 return false;
11149 }
11150
CheckTargetCausesMultiVersioning(Sema & S,FunctionDecl * OldFD,FunctionDecl * NewFD,bool & Redeclaration,NamedDecl * & OldDecl,LookupResult & Previous)11151 static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11152 FunctionDecl *NewFD,
11153 bool &Redeclaration,
11154 NamedDecl *&OldDecl,
11155 LookupResult &Previous) {
11156 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11157 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11158 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11159 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11160 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11161 // to change, this is a simple redeclaration.
11162 if ((NewTA && !NewTA->isDefaultVersion() &&
11163 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11164 (NewTVA && !NewTVA->isDefaultVersion() &&
11165 (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11166 return false;
11167
11168 // Otherwise, this decl causes MultiVersioning.
11169 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11170 NewTVA ? MultiVersionKind::TargetVersion
11171 : MultiVersionKind::Target)) {
11172 NewFD->setInvalidDecl();
11173 return true;
11174 }
11175
11176 if (CheckMultiVersionValue(S, NewFD)) {
11177 NewFD->setInvalidDecl();
11178 return true;
11179 }
11180
11181 // If this is 'default', permit the forward declaration.
11182 if (!OldFD->isMultiVersion() &&
11183 ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11184 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) {
11185 Redeclaration = true;
11186 OldDecl = OldFD;
11187 OldFD->setIsMultiVersion();
11188 NewFD->setIsMultiVersion();
11189 return false;
11190 }
11191
11192 if (CheckMultiVersionValue(S, OldFD)) {
11193 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11194 NewFD->setInvalidDecl();
11195 return true;
11196 }
11197
11198 if (NewTA) {
11199 ParsedTargetAttr OldParsed =
11200 S.getASTContext().getTargetInfo().parseTargetAttr(
11201 OldTA->getFeaturesStr());
11202 llvm::sort(OldParsed.Features);
11203 ParsedTargetAttr NewParsed =
11204 S.getASTContext().getTargetInfo().parseTargetAttr(
11205 NewTA->getFeaturesStr());
11206 // Sort order doesn't matter, it just needs to be consistent.
11207 llvm::sort(NewParsed.Features);
11208 if (OldParsed == NewParsed) {
11209 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11210 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11211 NewFD->setInvalidDecl();
11212 return true;
11213 }
11214 }
11215
11216 if (NewTVA) {
11217 llvm::SmallVector<StringRef, 8> Feats;
11218 OldTVA->getFeatures(Feats);
11219 llvm::sort(Feats);
11220 llvm::SmallVector<StringRef, 8> NewFeats;
11221 NewTVA->getFeatures(NewFeats);
11222 llvm::sort(NewFeats);
11223
11224 if (Feats == NewFeats) {
11225 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11226 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11227 NewFD->setInvalidDecl();
11228 return true;
11229 }
11230 }
11231
11232 for (const auto *FD : OldFD->redecls()) {
11233 const auto *CurTA = FD->getAttr<TargetAttr>();
11234 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11235 // We allow forward declarations before ANY multiversioning attributes, but
11236 // nothing after the fact.
11237 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11238 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11239 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11240 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11241 << (NewTA ? 0 : 2);
11242 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11243 NewFD->setInvalidDecl();
11244 return true;
11245 }
11246 }
11247
11248 OldFD->setIsMultiVersion();
11249 NewFD->setIsMultiVersion();
11250 Redeclaration = false;
11251 OldDecl = nullptr;
11252 Previous.clear();
11253 return false;
11254 }
11255
MultiVersionTypesCompatible(MultiVersionKind Old,MultiVersionKind New)11256 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
11257 MultiVersionKind New) {
11258 if (Old == New || Old == MultiVersionKind::None ||
11259 New == MultiVersionKind::None)
11260 return true;
11261
11262 return (Old == MultiVersionKind::CPUDispatch &&
11263 New == MultiVersionKind::CPUSpecific) ||
11264 (Old == MultiVersionKind::CPUSpecific &&
11265 New == MultiVersionKind::CPUDispatch);
11266 }
11267
11268 /// Check the validity of a new function declaration being added to an existing
11269 /// multiversioned declaration collection.
CheckMultiVersionAdditionalDecl(Sema & S,FunctionDecl * OldFD,FunctionDecl * NewFD,MultiVersionKind NewMVKind,const CPUDispatchAttr * NewCPUDisp,const CPUSpecificAttr * NewCPUSpec,const TargetClonesAttr * NewClones,bool & Redeclaration,NamedDecl * & OldDecl,LookupResult & Previous)11270 static bool CheckMultiVersionAdditionalDecl(
11271 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11272 MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
11273 const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
11274 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
11275 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11276 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11277 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11278 // Disallow mixing of multiversioning types.
11279 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
11280 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11281 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11282 NewFD->setInvalidDecl();
11283 return true;
11284 }
11285
11286 ParsedTargetAttr NewParsed;
11287 if (NewTA) {
11288 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11289 NewTA->getFeaturesStr());
11290 llvm::sort(NewParsed.Features);
11291 }
11292 llvm::SmallVector<StringRef, 8> NewFeats;
11293 if (NewTVA) {
11294 NewTVA->getFeatures(NewFeats);
11295 llvm::sort(NewFeats);
11296 }
11297
11298 bool UseMemberUsingDeclRules =
11299 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11300
11301 bool MayNeedOverloadableChecks =
11302 AllowOverloadingOfFunction(Previous, S.Context, NewFD);
11303
11304 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11305 // of a previous member of the MultiVersion set.
11306 for (NamedDecl *ND : Previous) {
11307 FunctionDecl *CurFD = ND->getAsFunction();
11308 if (!CurFD || CurFD->isInvalidDecl())
11309 continue;
11310 if (MayNeedOverloadableChecks &&
11311 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11312 continue;
11313
11314 if (NewMVKind == MultiVersionKind::None &&
11315 OldMVKind == MultiVersionKind::TargetVersion) {
11316 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11317 S.Context, "default", NewFD->getSourceRange(),
11318 AttributeCommonInfo::AS_GNU));
11319 NewFD->setIsMultiVersion();
11320 NewMVKind = MultiVersionKind::TargetVersion;
11321 if (!NewTVA) {
11322 NewTVA = NewFD->getAttr<TargetVersionAttr>();
11323 NewTVA->getFeatures(NewFeats);
11324 llvm::sort(NewFeats);
11325 }
11326 }
11327
11328 switch (NewMVKind) {
11329 case MultiVersionKind::None:
11330 assert(OldMVKind == MultiVersionKind::TargetClones &&
11331 "Only target_clones can be omitted in subsequent declarations");
11332 break;
11333 case MultiVersionKind::Target: {
11334 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11335 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11336 NewFD->setIsMultiVersion();
11337 Redeclaration = true;
11338 OldDecl = ND;
11339 return false;
11340 }
11341
11342 ParsedTargetAttr CurParsed =
11343 S.getASTContext().getTargetInfo().parseTargetAttr(
11344 CurTA->getFeaturesStr());
11345 llvm::sort(CurParsed.Features);
11346 if (CurParsed == NewParsed) {
11347 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11348 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11349 NewFD->setInvalidDecl();
11350 return true;
11351 }
11352 break;
11353 }
11354 case MultiVersionKind::TargetVersion: {
11355 const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
11356 if (CurTVA->getName() == NewTVA->getName()) {
11357 NewFD->setIsMultiVersion();
11358 Redeclaration = true;
11359 OldDecl = ND;
11360 return false;
11361 }
11362 llvm::SmallVector<StringRef, 8> CurFeats;
11363 if (CurTVA) {
11364 CurTVA->getFeatures(CurFeats);
11365 llvm::sort(CurFeats);
11366 }
11367 if (CurFeats == NewFeats) {
11368 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11369 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11370 NewFD->setInvalidDecl();
11371 return true;
11372 }
11373 break;
11374 }
11375 case MultiVersionKind::TargetClones: {
11376 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11377 Redeclaration = true;
11378 OldDecl = CurFD;
11379 NewFD->setIsMultiVersion();
11380
11381 if (CurClones && NewClones &&
11382 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11383 !std::equal(CurClones->featuresStrs_begin(),
11384 CurClones->featuresStrs_end(),
11385 NewClones->featuresStrs_begin()))) {
11386 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11387 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11388 NewFD->setInvalidDecl();
11389 return true;
11390 }
11391
11392 return false;
11393 }
11394 case MultiVersionKind::CPUSpecific:
11395 case MultiVersionKind::CPUDispatch: {
11396 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11397 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11398 // Handle CPUDispatch/CPUSpecific versions.
11399 // Only 1 CPUDispatch function is allowed, this will make it go through
11400 // the redeclaration errors.
11401 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11402 CurFD->hasAttr<CPUDispatchAttr>()) {
11403 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11404 std::equal(
11405 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11406 NewCPUDisp->cpus_begin(),
11407 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11408 return Cur->getName() == New->getName();
11409 })) {
11410 NewFD->setIsMultiVersion();
11411 Redeclaration = true;
11412 OldDecl = ND;
11413 return false;
11414 }
11415
11416 // If the declarations don't match, this is an error condition.
11417 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11418 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11419 NewFD->setInvalidDecl();
11420 return true;
11421 }
11422 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11423 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11424 std::equal(
11425 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11426 NewCPUSpec->cpus_begin(),
11427 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11428 return Cur->getName() == New->getName();
11429 })) {
11430 NewFD->setIsMultiVersion();
11431 Redeclaration = true;
11432 OldDecl = ND;
11433 return false;
11434 }
11435
11436 // Only 1 version of CPUSpecific is allowed for each CPU.
11437 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11438 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11439 if (CurII == NewII) {
11440 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11441 << NewII;
11442 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11443 NewFD->setInvalidDecl();
11444 return true;
11445 }
11446 }
11447 }
11448 }
11449 break;
11450 }
11451 }
11452 }
11453
11454 // Else, this is simply a non-redecl case. Checking the 'value' is only
11455 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11456 // handled in the attribute adding step.
11457 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11458 NewMVKind == MultiVersionKind::Target) &&
11459 CheckMultiVersionValue(S, NewFD)) {
11460 NewFD->setInvalidDecl();
11461 return true;
11462 }
11463
11464 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11465 !OldFD->isMultiVersion(), NewMVKind)) {
11466 NewFD->setInvalidDecl();
11467 return true;
11468 }
11469
11470 // Permit forward declarations in the case where these two are compatible.
11471 if (!OldFD->isMultiVersion()) {
11472 OldFD->setIsMultiVersion();
11473 NewFD->setIsMultiVersion();
11474 Redeclaration = true;
11475 OldDecl = OldFD;
11476 return false;
11477 }
11478
11479 NewFD->setIsMultiVersion();
11480 Redeclaration = false;
11481 OldDecl = nullptr;
11482 Previous.clear();
11483 return false;
11484 }
11485
11486 /// Check the validity of a mulitversion function declaration.
11487 /// Also sets the multiversion'ness' of the function itself.
11488 ///
11489 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11490 ///
11491 /// Returns true if there was an error, false otherwise.
CheckMultiVersionFunction(Sema & S,FunctionDecl * NewFD,bool & Redeclaration,NamedDecl * & OldDecl,LookupResult & Previous)11492 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11493 bool &Redeclaration, NamedDecl *&OldDecl,
11494 LookupResult &Previous) {
11495 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11496 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11497 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11498 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11499 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11500 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11501
11502 // Main isn't allowed to become a multiversion function, however it IS
11503 // permitted to have 'main' be marked with the 'target' optimization hint,
11504 // for 'target_version' only default is allowed.
11505 if (NewFD->isMain()) {
11506 if (MVKind != MultiVersionKind::None &&
11507 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11508 !(MVKind == MultiVersionKind::TargetVersion &&
11509 NewTVA->isDefaultVersion())) {
11510 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11511 NewFD->setInvalidDecl();
11512 return true;
11513 }
11514 return false;
11515 }
11516
11517 if (!OldDecl || !OldDecl->getAsFunction() ||
11518 OldDecl->getDeclContext()->getRedeclContext() !=
11519 NewFD->getDeclContext()->getRedeclContext()) {
11520 // If there's no previous declaration, AND this isn't attempting to cause
11521 // multiversioning, this isn't an error condition.
11522 if (MVKind == MultiVersionKind::None)
11523 return false;
11524 return CheckMultiVersionFirstFunction(S, NewFD);
11525 }
11526
11527 FunctionDecl *OldFD = OldDecl->getAsFunction();
11528
11529 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11530 // No target_version attributes mean default
11531 if (!NewTVA) {
11532 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11533 if (OldTVA) {
11534 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11535 S.Context, "default", NewFD->getSourceRange(),
11536 AttributeCommonInfo::AS_GNU));
11537 NewFD->setIsMultiVersion();
11538 OldFD->setIsMultiVersion();
11539 OldDecl = OldFD;
11540 Redeclaration = true;
11541 return true;
11542 }
11543 }
11544 return false;
11545 }
11546
11547 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11548 // for target_clones and target_version.
11549 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11550 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11551 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11552 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11553 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11554 NewFD->setInvalidDecl();
11555 return true;
11556 }
11557
11558 if (!OldFD->isMultiVersion()) {
11559 switch (MVKind) {
11560 case MultiVersionKind::Target:
11561 case MultiVersionKind::TargetVersion:
11562 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11563 OldDecl, Previous);
11564 case MultiVersionKind::TargetClones:
11565 if (OldFD->isUsed(false)) {
11566 NewFD->setInvalidDecl();
11567 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11568 }
11569 OldFD->setIsMultiVersion();
11570 break;
11571
11572 case MultiVersionKind::CPUDispatch:
11573 case MultiVersionKind::CPUSpecific:
11574 case MultiVersionKind::None:
11575 break;
11576 }
11577 }
11578
11579 // At this point, we have a multiversion function decl (in OldFD) AND an
11580 // appropriate attribute in the current function decl. Resolve that these are
11581 // still compatible with previous declarations.
11582 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
11583 NewCPUSpec, NewClones, Redeclaration,
11584 OldDecl, Previous);
11585 }
11586
11587 /// Perform semantic checking of a new function declaration.
11588 ///
11589 /// Performs semantic analysis of the new function declaration
11590 /// NewFD. This routine performs all semantic checking that does not
11591 /// require the actual declarator involved in the declaration, and is
11592 /// used both for the declaration of functions as they are parsed
11593 /// (called via ActOnDeclarator) and for the declaration of functions
11594 /// that have been instantiated via C++ template instantiation (called
11595 /// via InstantiateDecl).
11596 ///
11597 /// \param IsMemberSpecialization whether this new function declaration is
11598 /// a member specialization (that replaces any definition provided by the
11599 /// previous declaration).
11600 ///
11601 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11602 ///
11603 /// \returns true if the function declaration is a redeclaration.
CheckFunctionDeclaration(Scope * S,FunctionDecl * NewFD,LookupResult & Previous,bool IsMemberSpecialization,bool DeclIsDefn)11604 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11605 LookupResult &Previous,
11606 bool IsMemberSpecialization,
11607 bool DeclIsDefn) {
11608 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11609 "Variably modified return types are not handled here");
11610
11611 // Determine whether the type of this function should be merged with
11612 // a previous visible declaration. This never happens for functions in C++,
11613 // and always happens in C if the previous declaration was visible.
11614 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11615 !Previous.isShadowed();
11616
11617 bool Redeclaration = false;
11618 NamedDecl *OldDecl = nullptr;
11619 bool MayNeedOverloadableChecks = false;
11620
11621 // Merge or overload the declaration with an existing declaration of
11622 // the same name, if appropriate.
11623 if (!Previous.empty()) {
11624 // Determine whether NewFD is an overload of PrevDecl or
11625 // a declaration that requires merging. If it's an overload,
11626 // there's no more work to do here; we'll just add the new
11627 // function to the scope.
11628 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11629 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11630 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11631 Redeclaration = true;
11632 OldDecl = Candidate;
11633 }
11634 } else {
11635 MayNeedOverloadableChecks = true;
11636 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11637 /*NewIsUsingDecl*/ false)) {
11638 case Ovl_Match:
11639 Redeclaration = true;
11640 break;
11641
11642 case Ovl_NonFunction:
11643 Redeclaration = true;
11644 break;
11645
11646 case Ovl_Overload:
11647 Redeclaration = false;
11648 break;
11649 }
11650 }
11651 }
11652
11653 // Check for a previous extern "C" declaration with this name.
11654 if (!Redeclaration &&
11655 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11656 if (!Previous.empty()) {
11657 // This is an extern "C" declaration with the same name as a previous
11658 // declaration, and thus redeclares that entity...
11659 Redeclaration = true;
11660 OldDecl = Previous.getFoundDecl();
11661 MergeTypeWithPrevious = false;
11662
11663 // ... except in the presence of __attribute__((overloadable)).
11664 if (OldDecl->hasAttr<OverloadableAttr>() ||
11665 NewFD->hasAttr<OverloadableAttr>()) {
11666 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11667 MayNeedOverloadableChecks = true;
11668 Redeclaration = false;
11669 OldDecl = nullptr;
11670 }
11671 }
11672 }
11673 }
11674
11675 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11676 return Redeclaration;
11677
11678 // PPC MMA non-pointer types are not allowed as function return types.
11679 if (Context.getTargetInfo().getTriple().isPPC64() &&
11680 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11681 NewFD->setInvalidDecl();
11682 }
11683
11684 // C++11 [dcl.constexpr]p8:
11685 // A constexpr specifier for a non-static member function that is not
11686 // a constructor declares that member function to be const.
11687 //
11688 // This needs to be delayed until we know whether this is an out-of-line
11689 // definition of a static member function.
11690 //
11691 // This rule is not present in C++1y, so we produce a backwards
11692 // compatibility warning whenever it happens in C++11.
11693 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11694 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11695 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11696 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11697 CXXMethodDecl *OldMD = nullptr;
11698 if (OldDecl)
11699 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11700 if (!OldMD || !OldMD->isStatic()) {
11701 const FunctionProtoType *FPT =
11702 MD->getType()->castAs<FunctionProtoType>();
11703 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11704 EPI.TypeQuals.addConst();
11705 MD->setType(Context.getFunctionType(FPT->getReturnType(),
11706 FPT->getParamTypes(), EPI));
11707
11708 // Warn that we did this, if we're not performing template instantiation.
11709 // In that case, we'll have warned already when the template was defined.
11710 if (!inTemplateInstantiation()) {
11711 SourceLocation AddConstLoc;
11712 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11713 .IgnoreParens().getAs<FunctionTypeLoc>())
11714 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11715
11716 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11717 << FixItHint::CreateInsertion(AddConstLoc, " const");
11718 }
11719 }
11720 }
11721
11722 if (Redeclaration) {
11723 // NewFD and OldDecl represent declarations that need to be
11724 // merged.
11725 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11726 DeclIsDefn)) {
11727 NewFD->setInvalidDecl();
11728 return Redeclaration;
11729 }
11730
11731 Previous.clear();
11732 Previous.addDecl(OldDecl);
11733
11734 if (FunctionTemplateDecl *OldTemplateDecl =
11735 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11736 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11737 FunctionTemplateDecl *NewTemplateDecl
11738 = NewFD->getDescribedFunctionTemplate();
11739 assert(NewTemplateDecl && "Template/non-template mismatch");
11740
11741 // The call to MergeFunctionDecl above may have created some state in
11742 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11743 // can add it as a redeclaration.
11744 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11745
11746 NewFD->setPreviousDeclaration(OldFD);
11747 if (NewFD->isCXXClassMember()) {
11748 NewFD->setAccess(OldTemplateDecl->getAccess());
11749 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11750 }
11751
11752 // If this is an explicit specialization of a member that is a function
11753 // template, mark it as a member specialization.
11754 if (IsMemberSpecialization &&
11755 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11756 NewTemplateDecl->setMemberSpecialization();
11757 assert(OldTemplateDecl->isMemberSpecialization());
11758 // Explicit specializations of a member template do not inherit deleted
11759 // status from the parent member template that they are specializing.
11760 if (OldFD->isDeleted()) {
11761 // FIXME: This assert will not hold in the presence of modules.
11762 assert(OldFD->getCanonicalDecl() == OldFD);
11763 // FIXME: We need an update record for this AST mutation.
11764 OldFD->setDeletedAsWritten(false);
11765 }
11766 }
11767
11768 } else {
11769 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11770 auto *OldFD = cast<FunctionDecl>(OldDecl);
11771 // This needs to happen first so that 'inline' propagates.
11772 NewFD->setPreviousDeclaration(OldFD);
11773 if (NewFD->isCXXClassMember())
11774 NewFD->setAccess(OldFD->getAccess());
11775 }
11776 }
11777 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11778 !NewFD->getAttr<OverloadableAttr>()) {
11779 assert((Previous.empty() ||
11780 llvm::any_of(Previous,
11781 [](const NamedDecl *ND) {
11782 return ND->hasAttr<OverloadableAttr>();
11783 })) &&
11784 "Non-redecls shouldn't happen without overloadable present");
11785
11786 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11787 const auto *FD = dyn_cast<FunctionDecl>(ND);
11788 return FD && !FD->hasAttr<OverloadableAttr>();
11789 });
11790
11791 if (OtherUnmarkedIter != Previous.end()) {
11792 Diag(NewFD->getLocation(),
11793 diag::err_attribute_overloadable_multiple_unmarked_overloads);
11794 Diag((*OtherUnmarkedIter)->getLocation(),
11795 diag::note_attribute_overloadable_prev_overload)
11796 << false;
11797
11798 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11799 }
11800 }
11801
11802 if (LangOpts.OpenMP)
11803 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11804
11805 // Semantic checking for this function declaration (in isolation).
11806
11807 if (getLangOpts().CPlusPlus) {
11808 // C++-specific checks.
11809 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11810 CheckConstructor(Constructor);
11811 } else if (CXXDestructorDecl *Destructor =
11812 dyn_cast<CXXDestructorDecl>(NewFD)) {
11813 // We check here for invalid destructor names.
11814 // If we have a friend destructor declaration that is dependent, we can't
11815 // diagnose right away because cases like this are still valid:
11816 // template <class T> struct A { friend T::X::~Y(); };
11817 // struct B { struct Y { ~Y(); }; using X = Y; };
11818 // template struct A<B>;
11819 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
11820 !Destructor->getThisType()->isDependentType()) {
11821 CXXRecordDecl *Record = Destructor->getParent();
11822 QualType ClassType = Context.getTypeDeclType(Record);
11823
11824 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
11825 Context.getCanonicalType(ClassType));
11826 if (NewFD->getDeclName() != Name) {
11827 Diag(NewFD->getLocation(), diag::err_destructor_name);
11828 NewFD->setInvalidDecl();
11829 return Redeclaration;
11830 }
11831 }
11832 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11833 if (auto *TD = Guide->getDescribedFunctionTemplate())
11834 CheckDeductionGuideTemplate(TD);
11835
11836 // A deduction guide is not on the list of entities that can be
11837 // explicitly specialized.
11838 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11839 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11840 << /*explicit specialization*/ 1;
11841 }
11842
11843 // Find any virtual functions that this function overrides.
11844 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11845 if (!Method->isFunctionTemplateSpecialization() &&
11846 !Method->getDescribedFunctionTemplate() &&
11847 Method->isCanonicalDecl()) {
11848 AddOverriddenMethods(Method->getParent(), Method);
11849 }
11850 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11851 // C++2a [class.virtual]p6
11852 // A virtual method shall not have a requires-clause.
11853 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11854 diag::err_constrained_virtual_method);
11855
11856 if (Method->isStatic())
11857 checkThisInStaticMemberFunctionType(Method);
11858 }
11859
11860 // C++20: dcl.decl.general p4:
11861 // The optional requires-clause ([temp.pre]) in an init-declarator or
11862 // member-declarator shall be present only if the declarator declares a
11863 // templated function ([dcl.fct]).
11864 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11865 if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
11866 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11867 }
11868
11869 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11870 ActOnConversionDeclarator(Conversion);
11871
11872 // Extra checking for C++ overloaded operators (C++ [over.oper]).
11873 if (NewFD->isOverloadedOperator() &&
11874 CheckOverloadedOperatorDeclaration(NewFD)) {
11875 NewFD->setInvalidDecl();
11876 return Redeclaration;
11877 }
11878
11879 // Extra checking for C++0x literal operators (C++0x [over.literal]).
11880 if (NewFD->getLiteralIdentifier() &&
11881 CheckLiteralOperatorDeclaration(NewFD)) {
11882 NewFD->setInvalidDecl();
11883 return Redeclaration;
11884 }
11885
11886 // In C++, check default arguments now that we have merged decls. Unless
11887 // the lexical context is the class, because in this case this is done
11888 // during delayed parsing anyway.
11889 if (!CurContext->isRecord())
11890 CheckCXXDefaultArguments(NewFD);
11891
11892 // If this function is declared as being extern "C", then check to see if
11893 // the function returns a UDT (class, struct, or union type) that is not C
11894 // compatible, and if it does, warn the user.
11895 // But, issue any diagnostic on the first declaration only.
11896 if (Previous.empty() && NewFD->isExternC()) {
11897 QualType R = NewFD->getReturnType();
11898 if (R->isIncompleteType() && !R->isVoidType())
11899 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11900 << NewFD << R;
11901 else if (!R.isPODType(Context) && !R->isVoidType() &&
11902 !R->isObjCObjectPointerType())
11903 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11904 }
11905
11906 // C++1z [dcl.fct]p6:
11907 // [...] whether the function has a non-throwing exception-specification
11908 // [is] part of the function type
11909 //
11910 // This results in an ABI break between C++14 and C++17 for functions whose
11911 // declared type includes an exception-specification in a parameter or
11912 // return type. (Exception specifications on the function itself are OK in
11913 // most cases, and exception specifications are not permitted in most other
11914 // contexts where they could make it into a mangling.)
11915 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11916 auto HasNoexcept = [&](QualType T) -> bool {
11917 // Strip off declarator chunks that could be between us and a function
11918 // type. We don't need to look far, exception specifications are very
11919 // restricted prior to C++17.
11920 if (auto *RT = T->getAs<ReferenceType>())
11921 T = RT->getPointeeType();
11922 else if (T->isAnyPointerType())
11923 T = T->getPointeeType();
11924 else if (auto *MPT = T->getAs<MemberPointerType>())
11925 T = MPT->getPointeeType();
11926 if (auto *FPT = T->getAs<FunctionProtoType>())
11927 if (FPT->isNothrow())
11928 return true;
11929 return false;
11930 };
11931
11932 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11933 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11934 for (QualType T : FPT->param_types())
11935 AnyNoexcept |= HasNoexcept(T);
11936 if (AnyNoexcept)
11937 Diag(NewFD->getLocation(),
11938 diag::warn_cxx17_compat_exception_spec_in_signature)
11939 << NewFD;
11940 }
11941
11942 if (!Redeclaration && LangOpts.CUDA)
11943 checkCUDATargetOverload(NewFD, Previous);
11944 }
11945 return Redeclaration;
11946 }
11947
CheckMain(FunctionDecl * FD,const DeclSpec & DS)11948 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11949 // C++11 [basic.start.main]p3:
11950 // A program that [...] declares main to be inline, static or
11951 // constexpr is ill-formed.
11952 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
11953 // appear in a declaration of main.
11954 // static main is not an error under C99, but we should warn about it.
11955 // We accept _Noreturn main as an extension.
11956 if (FD->getStorageClass() == SC_Static)
11957 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11958 ? diag::err_static_main : diag::warn_static_main)
11959 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11960 if (FD->isInlineSpecified())
11961 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11962 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11963 if (DS.isNoreturnSpecified()) {
11964 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11965 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11966 Diag(NoreturnLoc, diag::ext_noreturn_main);
11967 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11968 << FixItHint::CreateRemoval(NoreturnRange);
11969 }
11970 if (FD->isConstexpr()) {
11971 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11972 << FD->isConsteval()
11973 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11974 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11975 }
11976
11977 if (getLangOpts().OpenCL) {
11978 Diag(FD->getLocation(), diag::err_opencl_no_main)
11979 << FD->hasAttr<OpenCLKernelAttr>();
11980 FD->setInvalidDecl();
11981 return;
11982 }
11983
11984 // Functions named main in hlsl are default entries, but don't have specific
11985 // signatures they are required to conform to.
11986 if (getLangOpts().HLSL)
11987 return;
11988
11989 QualType T = FD->getType();
11990 assert(T->isFunctionType() && "function decl is not of function type");
11991 const FunctionType* FT = T->castAs<FunctionType>();
11992
11993 // Set default calling convention for main()
11994 if (FT->getCallConv() != CC_C) {
11995 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11996 FD->setType(QualType(FT, 0));
11997 T = Context.getCanonicalType(FD->getType());
11998 }
11999
12000 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12001 // In C with GNU extensions we allow main() to have non-integer return
12002 // type, but we should warn about the extension, and we disable the
12003 // implicit-return-zero rule.
12004
12005 // GCC in C mode accepts qualified 'int'.
12006 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12007 FD->setHasImplicitReturnZero(true);
12008 else {
12009 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12010 SourceRange RTRange = FD->getReturnTypeSourceRange();
12011 if (RTRange.isValid())
12012 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12013 << FixItHint::CreateReplacement(RTRange, "int");
12014 }
12015 } else {
12016 // In C and C++, main magically returns 0 if you fall off the end;
12017 // set the flag which tells us that.
12018 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12019
12020 // All the standards say that main() should return 'int'.
12021 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12022 FD->setHasImplicitReturnZero(true);
12023 else {
12024 // Otherwise, this is just a flat-out error.
12025 SourceRange RTRange = FD->getReturnTypeSourceRange();
12026 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12027 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12028 : FixItHint());
12029 FD->setInvalidDecl(true);
12030 }
12031 }
12032
12033 // Treat protoless main() as nullary.
12034 if (isa<FunctionNoProtoType>(FT)) return;
12035
12036 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12037 unsigned nparams = FTP->getNumParams();
12038 assert(FD->getNumParams() == nparams);
12039
12040 bool HasExtraParameters = (nparams > 3);
12041
12042 if (FTP->isVariadic()) {
12043 Diag(FD->getLocation(), diag::ext_variadic_main);
12044 // FIXME: if we had information about the location of the ellipsis, we
12045 // could add a FixIt hint to remove it as a parameter.
12046 }
12047
12048 // Darwin passes an undocumented fourth argument of type char**. If
12049 // other platforms start sprouting these, the logic below will start
12050 // getting shifty.
12051 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12052 HasExtraParameters = false;
12053
12054 if (HasExtraParameters) {
12055 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12056 FD->setInvalidDecl(true);
12057 nparams = 3;
12058 }
12059
12060 // FIXME: a lot of the following diagnostics would be improved
12061 // if we had some location information about types.
12062
12063 QualType CharPP =
12064 Context.getPointerType(Context.getPointerType(Context.CharTy));
12065 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12066
12067 for (unsigned i = 0; i < nparams; ++i) {
12068 QualType AT = FTP->getParamType(i);
12069
12070 bool mismatch = true;
12071
12072 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12073 mismatch = false;
12074 else if (Expected[i] == CharPP) {
12075 // As an extension, the following forms are okay:
12076 // char const **
12077 // char const * const *
12078 // char * const *
12079
12080 QualifierCollector qs;
12081 const PointerType* PT;
12082 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12083 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12084 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12085 Context.CharTy)) {
12086 qs.removeConst();
12087 mismatch = !qs.empty();
12088 }
12089 }
12090
12091 if (mismatch) {
12092 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12093 // TODO: suggest replacing given type with expected type
12094 FD->setInvalidDecl(true);
12095 }
12096 }
12097
12098 if (nparams == 1 && !FD->isInvalidDecl()) {
12099 Diag(FD->getLocation(), diag::warn_main_one_arg);
12100 }
12101
12102 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12103 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12104 FD->setInvalidDecl();
12105 }
12106 }
12107
isDefaultStdCall(FunctionDecl * FD,Sema & S)12108 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12109
12110 // Default calling convention for main and wmain is __cdecl
12111 if (FD->getName() == "main" || FD->getName() == "wmain")
12112 return false;
12113
12114 // Default calling convention for MinGW is __cdecl
12115 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12116 if (T.isWindowsGNUEnvironment())
12117 return false;
12118
12119 // Default calling convention for WinMain, wWinMain and DllMain
12120 // is __stdcall on 32 bit Windows
12121 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12122 return true;
12123
12124 return false;
12125 }
12126
CheckMSVCRTEntryPoint(FunctionDecl * FD)12127 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12128 QualType T = FD->getType();
12129 assert(T->isFunctionType() && "function decl is not of function type");
12130 const FunctionType *FT = T->castAs<FunctionType>();
12131
12132 // Set an implicit return of 'zero' if the function can return some integral,
12133 // enumeration, pointer or nullptr type.
12134 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12135 FT->getReturnType()->isAnyPointerType() ||
12136 FT->getReturnType()->isNullPtrType())
12137 // DllMain is exempt because a return value of zero means it failed.
12138 if (FD->getName() != "DllMain")
12139 FD->setHasImplicitReturnZero(true);
12140
12141 // Explicity specified calling conventions are applied to MSVC entry points
12142 if (!hasExplicitCallingConv(T)) {
12143 if (isDefaultStdCall(FD, *this)) {
12144 if (FT->getCallConv() != CC_X86StdCall) {
12145 FT = Context.adjustFunctionType(
12146 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
12147 FD->setType(QualType(FT, 0));
12148 }
12149 } else if (FT->getCallConv() != CC_C) {
12150 FT = Context.adjustFunctionType(FT,
12151 FT->getExtInfo().withCallingConv(CC_C));
12152 FD->setType(QualType(FT, 0));
12153 }
12154 }
12155
12156 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12157 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12158 FD->setInvalidDecl();
12159 }
12160 }
12161
CheckHLSLEntryPoint(FunctionDecl * FD)12162 void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) {
12163 auto &TargetInfo = getASTContext().getTargetInfo();
12164 auto const Triple = TargetInfo.getTriple();
12165 switch (Triple.getEnvironment()) {
12166 default:
12167 // FIXME: check all shader profiles.
12168 break;
12169 case llvm::Triple::EnvironmentType::Compute:
12170 if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
12171 Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
12172 << Triple.getEnvironmentName();
12173 FD->setInvalidDecl();
12174 }
12175 break;
12176 }
12177
12178 for (const auto *Param : FD->parameters()) {
12179 if (!Param->hasAttr<HLSLAnnotationAttr>()) {
12180 // FIXME: Handle struct parameters where annotations are on struct fields.
12181 // See: https://github.com/llvm/llvm-project/issues/57875
12182 Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
12183 Diag(Param->getLocation(), diag::note_previous_decl) << Param;
12184 FD->setInvalidDecl();
12185 }
12186 }
12187 // FIXME: Verify return type semantic annotation.
12188 }
12189
CheckForConstantInitializer(Expr * Init,QualType DclT)12190 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
12191 // FIXME: Need strict checking. In C89, we need to check for
12192 // any assignment, increment, decrement, function-calls, or
12193 // commas outside of a sizeof. In C99, it's the same list,
12194 // except that the aforementioned are allowed in unevaluated
12195 // expressions. Everything else falls under the
12196 // "may accept other forms of constant expressions" exception.
12197 //
12198 // Regular C++ code will not end up here (exceptions: language extensions,
12199 // OpenCL C++ etc), so the constant expression rules there don't matter.
12200 if (Init->isValueDependent()) {
12201 assert(Init->containsErrors() &&
12202 "Dependent code should only occur in error-recovery path.");
12203 return true;
12204 }
12205 const Expr *Culprit;
12206 if (Init->isConstantInitializer(Context, false, &Culprit))
12207 return false;
12208 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
12209 << Culprit->getSourceRange();
12210 return true;
12211 }
12212
12213 namespace {
12214 // Visits an initialization expression to see if OrigDecl is evaluated in
12215 // its own initialization and throws a warning if it does.
12216 class SelfReferenceChecker
12217 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12218 Sema &S;
12219 Decl *OrigDecl;
12220 bool isRecordType;
12221 bool isPODType;
12222 bool isReferenceType;
12223
12224 bool isInitList;
12225 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12226
12227 public:
12228 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12229
SelfReferenceChecker(Sema & S,Decl * OrigDecl)12230 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12231 S(S), OrigDecl(OrigDecl) {
12232 isPODType = false;
12233 isRecordType = false;
12234 isReferenceType = false;
12235 isInitList = false;
12236 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12237 isPODType = VD->getType().isPODType(S.Context);
12238 isRecordType = VD->getType()->isRecordType();
12239 isReferenceType = VD->getType()->isReferenceType();
12240 }
12241 }
12242
12243 // For most expressions, just call the visitor. For initializer lists,
12244 // track the index of the field being initialized since fields are
12245 // initialized in order allowing use of previously initialized fields.
CheckExpr(Expr * E)12246 void CheckExpr(Expr *E) {
12247 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12248 if (!InitList) {
12249 Visit(E);
12250 return;
12251 }
12252
12253 // Track and increment the index here.
12254 isInitList = true;
12255 InitFieldIndex.push_back(0);
12256 for (auto *Child : InitList->children()) {
12257 CheckExpr(cast<Expr>(Child));
12258 ++InitFieldIndex.back();
12259 }
12260 InitFieldIndex.pop_back();
12261 }
12262
12263 // Returns true if MemberExpr is checked and no further checking is needed.
12264 // Returns false if additional checking is required.
CheckInitListMemberExpr(MemberExpr * E,bool CheckReference)12265 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12266 llvm::SmallVector<FieldDecl*, 4> Fields;
12267 Expr *Base = E;
12268 bool ReferenceField = false;
12269
12270 // Get the field members used.
12271 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12272 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12273 if (!FD)
12274 return false;
12275 Fields.push_back(FD);
12276 if (FD->getType()->isReferenceType())
12277 ReferenceField = true;
12278 Base = ME->getBase()->IgnoreParenImpCasts();
12279 }
12280
12281 // Keep checking only if the base Decl is the same.
12282 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12283 if (!DRE || DRE->getDecl() != OrigDecl)
12284 return false;
12285
12286 // A reference field can be bound to an unininitialized field.
12287 if (CheckReference && !ReferenceField)
12288 return true;
12289
12290 // Convert FieldDecls to their index number.
12291 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12292 for (const FieldDecl *I : llvm::reverse(Fields))
12293 UsedFieldIndex.push_back(I->getFieldIndex());
12294
12295 // See if a warning is needed by checking the first difference in index
12296 // numbers. If field being used has index less than the field being
12297 // initialized, then the use is safe.
12298 for (auto UsedIter = UsedFieldIndex.begin(),
12299 UsedEnd = UsedFieldIndex.end(),
12300 OrigIter = InitFieldIndex.begin(),
12301 OrigEnd = InitFieldIndex.end();
12302 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12303 if (*UsedIter < *OrigIter)
12304 return true;
12305 if (*UsedIter > *OrigIter)
12306 break;
12307 }
12308
12309 // TODO: Add a different warning which will print the field names.
12310 HandleDeclRefExpr(DRE);
12311 return true;
12312 }
12313
12314 // For most expressions, the cast is directly above the DeclRefExpr.
12315 // For conditional operators, the cast can be outside the conditional
12316 // operator if both expressions are DeclRefExpr's.
HandleValue(Expr * E)12317 void HandleValue(Expr *E) {
12318 E = E->IgnoreParens();
12319 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12320 HandleDeclRefExpr(DRE);
12321 return;
12322 }
12323
12324 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12325 Visit(CO->getCond());
12326 HandleValue(CO->getTrueExpr());
12327 HandleValue(CO->getFalseExpr());
12328 return;
12329 }
12330
12331 if (BinaryConditionalOperator *BCO =
12332 dyn_cast<BinaryConditionalOperator>(E)) {
12333 Visit(BCO->getCond());
12334 HandleValue(BCO->getFalseExpr());
12335 return;
12336 }
12337
12338 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12339 HandleValue(OVE->getSourceExpr());
12340 return;
12341 }
12342
12343 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12344 if (BO->getOpcode() == BO_Comma) {
12345 Visit(BO->getLHS());
12346 HandleValue(BO->getRHS());
12347 return;
12348 }
12349 }
12350
12351 if (isa<MemberExpr>(E)) {
12352 if (isInitList) {
12353 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12354 false /*CheckReference*/))
12355 return;
12356 }
12357
12358 Expr *Base = E->IgnoreParenImpCasts();
12359 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12360 // Check for static member variables and don't warn on them.
12361 if (!isa<FieldDecl>(ME->getMemberDecl()))
12362 return;
12363 Base = ME->getBase()->IgnoreParenImpCasts();
12364 }
12365 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12366 HandleDeclRefExpr(DRE);
12367 return;
12368 }
12369
12370 Visit(E);
12371 }
12372
12373 // Reference types not handled in HandleValue are handled here since all
12374 // uses of references are bad, not just r-value uses.
VisitDeclRefExpr(DeclRefExpr * E)12375 void VisitDeclRefExpr(DeclRefExpr *E) {
12376 if (isReferenceType)
12377 HandleDeclRefExpr(E);
12378 }
12379
VisitImplicitCastExpr(ImplicitCastExpr * E)12380 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12381 if (E->getCastKind() == CK_LValueToRValue) {
12382 HandleValue(E->getSubExpr());
12383 return;
12384 }
12385
12386 Inherited::VisitImplicitCastExpr(E);
12387 }
12388
VisitMemberExpr(MemberExpr * E)12389 void VisitMemberExpr(MemberExpr *E) {
12390 if (isInitList) {
12391 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12392 return;
12393 }
12394
12395 // Don't warn on arrays since they can be treated as pointers.
12396 if (E->getType()->canDecayToPointerType()) return;
12397
12398 // Warn when a non-static method call is followed by non-static member
12399 // field accesses, which is followed by a DeclRefExpr.
12400 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12401 bool Warn = (MD && !MD->isStatic());
12402 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12403 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12404 if (!isa<FieldDecl>(ME->getMemberDecl()))
12405 Warn = false;
12406 Base = ME->getBase()->IgnoreParenImpCasts();
12407 }
12408
12409 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12410 if (Warn)
12411 HandleDeclRefExpr(DRE);
12412 return;
12413 }
12414
12415 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12416 // Visit that expression.
12417 Visit(Base);
12418 }
12419
VisitCXXOperatorCallExpr(CXXOperatorCallExpr * E)12420 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12421 Expr *Callee = E->getCallee();
12422
12423 if (isa<UnresolvedLookupExpr>(Callee))
12424 return Inherited::VisitCXXOperatorCallExpr(E);
12425
12426 Visit(Callee);
12427 for (auto Arg: E->arguments())
12428 HandleValue(Arg->IgnoreParenImpCasts());
12429 }
12430
VisitUnaryOperator(UnaryOperator * E)12431 void VisitUnaryOperator(UnaryOperator *E) {
12432 // For POD record types, addresses of its own members are well-defined.
12433 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12434 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12435 if (!isPODType)
12436 HandleValue(E->getSubExpr());
12437 return;
12438 }
12439
12440 if (E->isIncrementDecrementOp()) {
12441 HandleValue(E->getSubExpr());
12442 return;
12443 }
12444
12445 Inherited::VisitUnaryOperator(E);
12446 }
12447
VisitObjCMessageExpr(ObjCMessageExpr * E)12448 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12449
VisitCXXConstructExpr(CXXConstructExpr * E)12450 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12451 if (E->getConstructor()->isCopyConstructor()) {
12452 Expr *ArgExpr = E->getArg(0);
12453 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12454 if (ILE->getNumInits() == 1)
12455 ArgExpr = ILE->getInit(0);
12456 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12457 if (ICE->getCastKind() == CK_NoOp)
12458 ArgExpr = ICE->getSubExpr();
12459 HandleValue(ArgExpr);
12460 return;
12461 }
12462 Inherited::VisitCXXConstructExpr(E);
12463 }
12464
VisitCallExpr(CallExpr * E)12465 void VisitCallExpr(CallExpr *E) {
12466 // Treat std::move as a use.
12467 if (E->isCallToStdMove()) {
12468 HandleValue(E->getArg(0));
12469 return;
12470 }
12471
12472 Inherited::VisitCallExpr(E);
12473 }
12474
VisitBinaryOperator(BinaryOperator * E)12475 void VisitBinaryOperator(BinaryOperator *E) {
12476 if (E->isCompoundAssignmentOp()) {
12477 HandleValue(E->getLHS());
12478 Visit(E->getRHS());
12479 return;
12480 }
12481
12482 Inherited::VisitBinaryOperator(E);
12483 }
12484
12485 // A custom visitor for BinaryConditionalOperator is needed because the
12486 // regular visitor would check the condition and true expression separately
12487 // but both point to the same place giving duplicate diagnostics.
VisitBinaryConditionalOperator(BinaryConditionalOperator * E)12488 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12489 Visit(E->getCond());
12490 Visit(E->getFalseExpr());
12491 }
12492
HandleDeclRefExpr(DeclRefExpr * DRE)12493 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12494 Decl* ReferenceDecl = DRE->getDecl();
12495 if (OrigDecl != ReferenceDecl) return;
12496 unsigned diag;
12497 if (isReferenceType) {
12498 diag = diag::warn_uninit_self_reference_in_reference_init;
12499 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12500 diag = diag::warn_static_self_reference_in_init;
12501 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12502 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12503 DRE->getDecl()->getType()->isRecordType()) {
12504 diag = diag::warn_uninit_self_reference_in_init;
12505 } else {
12506 // Local variables will be handled by the CFG analysis.
12507 return;
12508 }
12509
12510 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12511 S.PDiag(diag)
12512 << DRE->getDecl() << OrigDecl->getLocation()
12513 << DRE->getSourceRange());
12514 }
12515 };
12516
12517 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
CheckSelfReference(Sema & S,Decl * OrigDecl,Expr * E,bool DirectInit)12518 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12519 bool DirectInit) {
12520 // Parameters arguments are occassionially constructed with itself,
12521 // for instance, in recursive functions. Skip them.
12522 if (isa<ParmVarDecl>(OrigDecl))
12523 return;
12524
12525 E = E->IgnoreParens();
12526
12527 // Skip checking T a = a where T is not a record or reference type.
12528 // Doing so is a way to silence uninitialized warnings.
12529 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12530 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12531 if (ICE->getCastKind() == CK_LValueToRValue)
12532 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12533 if (DRE->getDecl() == OrigDecl)
12534 return;
12535
12536 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12537 }
12538 } // end anonymous namespace
12539
12540 namespace {
12541 // Simple wrapper to add the name of a variable or (if no variable is
12542 // available) a DeclarationName into a diagnostic.
12543 struct VarDeclOrName {
12544 VarDecl *VDecl;
12545 DeclarationName Name;
12546
12547 friend const Sema::SemaDiagnosticBuilder &
operator <<(const Sema::SemaDiagnosticBuilder & Diag,VarDeclOrName VN)12548 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12549 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12550 }
12551 };
12552 } // end anonymous namespace
12553
deduceVarTypeFromInitializer(VarDecl * VDecl,DeclarationName Name,QualType Type,TypeSourceInfo * TSI,SourceRange Range,bool DirectInit,Expr * Init)12554 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12555 DeclarationName Name, QualType Type,
12556 TypeSourceInfo *TSI,
12557 SourceRange Range, bool DirectInit,
12558 Expr *Init) {
12559 bool IsInitCapture = !VDecl;
12560 assert((!VDecl || !VDecl->isInitCapture()) &&
12561 "init captures are expected to be deduced prior to initialization");
12562
12563 VarDeclOrName VN{VDecl, Name};
12564
12565 DeducedType *Deduced = Type->getContainedDeducedType();
12566 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12567
12568 // C++11 [dcl.spec.auto]p3
12569 if (!Init) {
12570 assert(VDecl && "no init for init capture deduction?");
12571
12572 // Except for class argument deduction, and then for an initializing
12573 // declaration only, i.e. no static at class scope or extern.
12574 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12575 VDecl->hasExternalStorage() ||
12576 VDecl->isStaticDataMember()) {
12577 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12578 << VDecl->getDeclName() << Type;
12579 return QualType();
12580 }
12581 }
12582
12583 ArrayRef<Expr*> DeduceInits;
12584 if (Init)
12585 DeduceInits = Init;
12586
12587 if (DirectInit) {
12588 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12589 DeduceInits = PL->exprs();
12590 }
12591
12592 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12593 assert(VDecl && "non-auto type for init capture deduction?");
12594 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12595 InitializationKind Kind = InitializationKind::CreateForInit(
12596 VDecl->getLocation(), DirectInit, Init);
12597 // FIXME: Initialization should not be taking a mutable list of inits.
12598 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12599 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12600 InitsCopy);
12601 }
12602
12603 if (DirectInit) {
12604 if (auto *IL = dyn_cast<InitListExpr>(Init))
12605 DeduceInits = IL->inits();
12606 }
12607
12608 // Deduction only works if we have exactly one source expression.
12609 if (DeduceInits.empty()) {
12610 // It isn't possible to write this directly, but it is possible to
12611 // end up in this situation with "auto x(some_pack...);"
12612 Diag(Init->getBeginLoc(), IsInitCapture
12613 ? diag::err_init_capture_no_expression
12614 : diag::err_auto_var_init_no_expression)
12615 << VN << Type << Range;
12616 return QualType();
12617 }
12618
12619 if (DeduceInits.size() > 1) {
12620 Diag(DeduceInits[1]->getBeginLoc(),
12621 IsInitCapture ? diag::err_init_capture_multiple_expressions
12622 : diag::err_auto_var_init_multiple_expressions)
12623 << VN << Type << Range;
12624 return QualType();
12625 }
12626
12627 Expr *DeduceInit = DeduceInits[0];
12628 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12629 Diag(Init->getBeginLoc(), IsInitCapture
12630 ? diag::err_init_capture_paren_braces
12631 : diag::err_auto_var_init_paren_braces)
12632 << isa<InitListExpr>(Init) << VN << Type << Range;
12633 return QualType();
12634 }
12635
12636 // Expressions default to 'id' when we're in a debugger.
12637 bool DefaultedAnyToId = false;
12638 if (getLangOpts().DebuggerCastResultToId &&
12639 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12640 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12641 if (Result.isInvalid()) {
12642 return QualType();
12643 }
12644 Init = Result.get();
12645 DefaultedAnyToId = true;
12646 }
12647
12648 // C++ [dcl.decomp]p1:
12649 // If the assignment-expression [...] has array type A and no ref-qualifier
12650 // is present, e has type cv A
12651 if (VDecl && isa<DecompositionDecl>(VDecl) &&
12652 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12653 DeduceInit->getType()->isConstantArrayType())
12654 return Context.getQualifiedType(DeduceInit->getType(),
12655 Type.getQualifiers());
12656
12657 QualType DeducedType;
12658 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12659 TemplateDeductionResult Result =
12660 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12661 if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) {
12662 if (!IsInitCapture)
12663 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12664 else if (isa<InitListExpr>(Init))
12665 Diag(Range.getBegin(),
12666 diag::err_init_capture_deduction_failure_from_init_list)
12667 << VN
12668 << (DeduceInit->getType().isNull() ? TSI->getType()
12669 : DeduceInit->getType())
12670 << DeduceInit->getSourceRange();
12671 else
12672 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12673 << VN << TSI->getType()
12674 << (DeduceInit->getType().isNull() ? TSI->getType()
12675 : DeduceInit->getType())
12676 << DeduceInit->getSourceRange();
12677 }
12678
12679 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12680 // 'id' instead of a specific object type prevents most of our usual
12681 // checks.
12682 // We only want to warn outside of template instantiations, though:
12683 // inside a template, the 'id' could have come from a parameter.
12684 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12685 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12686 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12687 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12688 }
12689
12690 return DeducedType;
12691 }
12692
DeduceVariableDeclarationType(VarDecl * VDecl,bool DirectInit,Expr * Init)12693 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12694 Expr *Init) {
12695 assert(!Init || !Init->containsErrors());
12696 QualType DeducedType = deduceVarTypeFromInitializer(
12697 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12698 VDecl->getSourceRange(), DirectInit, Init);
12699 if (DeducedType.isNull()) {
12700 VDecl->setInvalidDecl();
12701 return true;
12702 }
12703
12704 VDecl->setType(DeducedType);
12705 assert(VDecl->isLinkageValid());
12706
12707 // In ARC, infer lifetime.
12708 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12709 VDecl->setInvalidDecl();
12710
12711 if (getLangOpts().OpenCL)
12712 deduceOpenCLAddressSpace(VDecl);
12713
12714 // If this is a redeclaration, check that the type we just deduced matches
12715 // the previously declared type.
12716 if (VarDecl *Old = VDecl->getPreviousDecl()) {
12717 // We never need to merge the type, because we cannot form an incomplete
12718 // array of auto, nor deduce such a type.
12719 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12720 }
12721
12722 // Check the deduced type is valid for a variable declaration.
12723 CheckVariableDeclarationType(VDecl);
12724 return VDecl->isInvalidDecl();
12725 }
12726
checkNonTrivialCUnionInInitializer(const Expr * Init,SourceLocation Loc)12727 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12728 SourceLocation Loc) {
12729 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12730 Init = EWC->getSubExpr();
12731
12732 if (auto *CE = dyn_cast<ConstantExpr>(Init))
12733 Init = CE->getSubExpr();
12734
12735 QualType InitType = Init->getType();
12736 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12737 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12738 "shouldn't be called if type doesn't have a non-trivial C struct");
12739 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12740 for (auto *I : ILE->inits()) {
12741 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12742 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12743 continue;
12744 SourceLocation SL = I->getExprLoc();
12745 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12746 }
12747 return;
12748 }
12749
12750 if (isa<ImplicitValueInitExpr>(Init)) {
12751 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12752 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12753 NTCUK_Init);
12754 } else {
12755 // Assume all other explicit initializers involving copying some existing
12756 // object.
12757 // TODO: ignore any explicit initializers where we can guarantee
12758 // copy-elision.
12759 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12760 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12761 }
12762 }
12763
12764 namespace {
12765
shouldIgnoreForRecordTriviality(const FieldDecl * FD)12766 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12767 // Ignore unavailable fields. A field can be marked as unavailable explicitly
12768 // in the source code or implicitly by the compiler if it is in a union
12769 // defined in a system header and has non-trivial ObjC ownership
12770 // qualifications. We don't want those fields to participate in determining
12771 // whether the containing union is non-trivial.
12772 return FD->hasAttr<UnavailableAttr>();
12773 }
12774
12775 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12776 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12777 void> {
12778 using Super =
12779 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12780 void>;
12781
DiagNonTrivalCUnionDefaultInitializeVisitor__anon82674d9a1d11::DiagNonTrivalCUnionDefaultInitializeVisitor12782 DiagNonTrivalCUnionDefaultInitializeVisitor(
12783 QualType OrigTy, SourceLocation OrigLoc,
12784 Sema::NonTrivialCUnionContext UseContext, Sema &S)
12785 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12786
visitWithKind__anon82674d9a1d11::DiagNonTrivalCUnionDefaultInitializeVisitor12787 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12788 const FieldDecl *FD, bool InNonTrivialUnion) {
12789 if (const auto *AT = S.Context.getAsArrayType(QT))
12790 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12791 InNonTrivialUnion);
12792 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12793 }
12794
visitARCStrong__anon82674d9a1d11::DiagNonTrivalCUnionDefaultInitializeVisitor12795 void visitARCStrong(QualType QT, const FieldDecl *FD,
12796 bool InNonTrivialUnion) {
12797 if (InNonTrivialUnion)
12798 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12799 << 1 << 0 << QT << FD->getName();
12800 }
12801
visitARCWeak__anon82674d9a1d11::DiagNonTrivalCUnionDefaultInitializeVisitor12802 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12803 if (InNonTrivialUnion)
12804 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12805 << 1 << 0 << QT << FD->getName();
12806 }
12807
visitStruct__anon82674d9a1d11::DiagNonTrivalCUnionDefaultInitializeVisitor12808 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12809 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12810 if (RD->isUnion()) {
12811 if (OrigLoc.isValid()) {
12812 bool IsUnion = false;
12813 if (auto *OrigRD = OrigTy->getAsRecordDecl())
12814 IsUnion = OrigRD->isUnion();
12815 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12816 << 0 << OrigTy << IsUnion << UseContext;
12817 // Reset OrigLoc so that this diagnostic is emitted only once.
12818 OrigLoc = SourceLocation();
12819 }
12820 InNonTrivialUnion = true;
12821 }
12822
12823 if (InNonTrivialUnion)
12824 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12825 << 0 << 0 << QT.getUnqualifiedType() << "";
12826
12827 for (const FieldDecl *FD : RD->fields())
12828 if (!shouldIgnoreForRecordTriviality(FD))
12829 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12830 }
12831
visitTrivial__anon82674d9a1d11::DiagNonTrivalCUnionDefaultInitializeVisitor12832 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12833
12834 // The non-trivial C union type or the struct/union type that contains a
12835 // non-trivial C union.
12836 QualType OrigTy;
12837 SourceLocation OrigLoc;
12838 Sema::NonTrivialCUnionContext UseContext;
12839 Sema &S;
12840 };
12841
12842 struct DiagNonTrivalCUnionDestructedTypeVisitor
12843 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12844 using Super =
12845 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12846
DiagNonTrivalCUnionDestructedTypeVisitor__anon82674d9a1d11::DiagNonTrivalCUnionDestructedTypeVisitor12847 DiagNonTrivalCUnionDestructedTypeVisitor(
12848 QualType OrigTy, SourceLocation OrigLoc,
12849 Sema::NonTrivialCUnionContext UseContext, Sema &S)
12850 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12851
visitWithKind__anon82674d9a1d11::DiagNonTrivalCUnionDestructedTypeVisitor12852 void visitWithKind(QualType::DestructionKind DK, QualType QT,
12853 const FieldDecl *FD, bool InNonTrivialUnion) {
12854 if (const auto *AT = S.Context.getAsArrayType(QT))
12855 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12856 InNonTrivialUnion);
12857 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12858 }
12859
visitARCStrong__anon82674d9a1d11::DiagNonTrivalCUnionDestructedTypeVisitor12860 void visitARCStrong(QualType QT, const FieldDecl *FD,
12861 bool InNonTrivialUnion) {
12862 if (InNonTrivialUnion)
12863 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12864 << 1 << 1 << QT << FD->getName();
12865 }
12866
visitARCWeak__anon82674d9a1d11::DiagNonTrivalCUnionDestructedTypeVisitor12867 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12868 if (InNonTrivialUnion)
12869 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12870 << 1 << 1 << QT << FD->getName();
12871 }
12872
visitStruct__anon82674d9a1d11::DiagNonTrivalCUnionDestructedTypeVisitor12873 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12874 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12875 if (RD->isUnion()) {
12876 if (OrigLoc.isValid()) {
12877 bool IsUnion = false;
12878 if (auto *OrigRD = OrigTy->getAsRecordDecl())
12879 IsUnion = OrigRD->isUnion();
12880 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12881 << 1 << OrigTy << IsUnion << UseContext;
12882 // Reset OrigLoc so that this diagnostic is emitted only once.
12883 OrigLoc = SourceLocation();
12884 }
12885 InNonTrivialUnion = true;
12886 }
12887
12888 if (InNonTrivialUnion)
12889 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12890 << 0 << 1 << QT.getUnqualifiedType() << "";
12891
12892 for (const FieldDecl *FD : RD->fields())
12893 if (!shouldIgnoreForRecordTriviality(FD))
12894 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12895 }
12896
visitTrivial__anon82674d9a1d11::DiagNonTrivalCUnionDestructedTypeVisitor12897 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
visitCXXDestructor__anon82674d9a1d11::DiagNonTrivalCUnionDestructedTypeVisitor12898 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12899 bool InNonTrivialUnion) {}
12900
12901 // The non-trivial C union type or the struct/union type that contains a
12902 // non-trivial C union.
12903 QualType OrigTy;
12904 SourceLocation OrigLoc;
12905 Sema::NonTrivialCUnionContext UseContext;
12906 Sema &S;
12907 };
12908
12909 struct DiagNonTrivalCUnionCopyVisitor
12910 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12911 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12912
DiagNonTrivalCUnionCopyVisitor__anon82674d9a1d11::DiagNonTrivalCUnionCopyVisitor12913 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12914 Sema::NonTrivialCUnionContext UseContext,
12915 Sema &S)
12916 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12917
visitWithKind__anon82674d9a1d11::DiagNonTrivalCUnionCopyVisitor12918 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12919 const FieldDecl *FD, bool InNonTrivialUnion) {
12920 if (const auto *AT = S.Context.getAsArrayType(QT))
12921 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12922 InNonTrivialUnion);
12923 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12924 }
12925
visitARCStrong__anon82674d9a1d11::DiagNonTrivalCUnionCopyVisitor12926 void visitARCStrong(QualType QT, const FieldDecl *FD,
12927 bool InNonTrivialUnion) {
12928 if (InNonTrivialUnion)
12929 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12930 << 1 << 2 << QT << FD->getName();
12931 }
12932
visitARCWeak__anon82674d9a1d11::DiagNonTrivalCUnionCopyVisitor12933 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12934 if (InNonTrivialUnion)
12935 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12936 << 1 << 2 << QT << FD->getName();
12937 }
12938
visitStruct__anon82674d9a1d11::DiagNonTrivalCUnionCopyVisitor12939 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12940 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12941 if (RD->isUnion()) {
12942 if (OrigLoc.isValid()) {
12943 bool IsUnion = false;
12944 if (auto *OrigRD = OrigTy->getAsRecordDecl())
12945 IsUnion = OrigRD->isUnion();
12946 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12947 << 2 << OrigTy << IsUnion << UseContext;
12948 // Reset OrigLoc so that this diagnostic is emitted only once.
12949 OrigLoc = SourceLocation();
12950 }
12951 InNonTrivialUnion = true;
12952 }
12953
12954 if (InNonTrivialUnion)
12955 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12956 << 0 << 2 << QT.getUnqualifiedType() << "";
12957
12958 for (const FieldDecl *FD : RD->fields())
12959 if (!shouldIgnoreForRecordTriviality(FD))
12960 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12961 }
12962
preVisit__anon82674d9a1d11::DiagNonTrivalCUnionCopyVisitor12963 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12964 const FieldDecl *FD, bool InNonTrivialUnion) {}
visitTrivial__anon82674d9a1d11::DiagNonTrivalCUnionCopyVisitor12965 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
visitVolatileTrivial__anon82674d9a1d11::DiagNonTrivalCUnionCopyVisitor12966 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12967 bool InNonTrivialUnion) {}
12968
12969 // The non-trivial C union type or the struct/union type that contains a
12970 // non-trivial C union.
12971 QualType OrigTy;
12972 SourceLocation OrigLoc;
12973 Sema::NonTrivialCUnionContext UseContext;
12974 Sema &S;
12975 };
12976
12977 } // namespace
12978
checkNonTrivialCUnion(QualType QT,SourceLocation Loc,NonTrivialCUnionContext UseContext,unsigned NonTrivialKind)12979 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12980 NonTrivialCUnionContext UseContext,
12981 unsigned NonTrivialKind) {
12982 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12983 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12984 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12985 "shouldn't be called if type doesn't have a non-trivial C union");
12986
12987 if ((NonTrivialKind & NTCUK_Init) &&
12988 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12989 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12990 .visit(QT, nullptr, false);
12991 if ((NonTrivialKind & NTCUK_Destruct) &&
12992 QT.hasNonTrivialToPrimitiveDestructCUnion())
12993 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12994 .visit(QT, nullptr, false);
12995 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12996 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12997 .visit(QT, nullptr, false);
12998 }
12999
13000 /// AddInitializerToDecl - Adds the initializer Init to the
13001 /// declaration dcl. If DirectInit is true, this is C++ direct
13002 /// initialization rather than copy initialization.
AddInitializerToDecl(Decl * RealDecl,Expr * Init,bool DirectInit)13003 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13004 // If there is no declaration, there was an error parsing it. Just ignore
13005 // the initializer.
13006 if (!RealDecl || RealDecl->isInvalidDecl()) {
13007 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13008 return;
13009 }
13010
13011 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13012 // Pure-specifiers are handled in ActOnPureSpecifier.
13013 Diag(Method->getLocation(), diag::err_member_function_initialization)
13014 << Method->getDeclName() << Init->getSourceRange();
13015 Method->setInvalidDecl();
13016 return;
13017 }
13018
13019 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13020 if (!VDecl) {
13021 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13022 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13023 RealDecl->setInvalidDecl();
13024 return;
13025 }
13026
13027 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13028 if (VDecl->getType()->isUndeducedType()) {
13029 // Attempt typo correction early so that the type of the init expression can
13030 // be deduced based on the chosen correction if the original init contains a
13031 // TypoExpr.
13032 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13033 if (!Res.isUsable()) {
13034 // There are unresolved typos in Init, just drop them.
13035 // FIXME: improve the recovery strategy to preserve the Init.
13036 RealDecl->setInvalidDecl();
13037 return;
13038 }
13039 if (Res.get()->containsErrors()) {
13040 // Invalidate the decl as we don't know the type for recovery-expr yet.
13041 RealDecl->setInvalidDecl();
13042 VDecl->setInit(Res.get());
13043 return;
13044 }
13045 Init = Res.get();
13046
13047 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13048 return;
13049 }
13050
13051 // dllimport cannot be used on variable definitions.
13052 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13053 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13054 VDecl->setInvalidDecl();
13055 return;
13056 }
13057
13058 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13059 // the identifier has external or internal linkage, the declaration shall
13060 // have no initializer for the identifier.
13061 // C++14 [dcl.init]p5 is the same restriction for C++.
13062 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13063 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13064 VDecl->setInvalidDecl();
13065 return;
13066 }
13067
13068 if (!VDecl->getType()->isDependentType()) {
13069 // A definition must end up with a complete type, which means it must be
13070 // complete with the restriction that an array type might be completed by
13071 // the initializer; note that later code assumes this restriction.
13072 QualType BaseDeclType = VDecl->getType();
13073 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13074 BaseDeclType = Array->getElementType();
13075 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13076 diag::err_typecheck_decl_incomplete_type)) {
13077 RealDecl->setInvalidDecl();
13078 return;
13079 }
13080
13081 // The variable can not have an abstract class type.
13082 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13083 diag::err_abstract_type_in_decl,
13084 AbstractVariableType))
13085 VDecl->setInvalidDecl();
13086 }
13087
13088 // C++ [module.import/6] external definitions are not permitted in header
13089 // units.
13090 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13091 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13092 VDecl->getFormalLinkage() == Linkage::ExternalLinkage &&
13093 !VDecl->isInline() && !VDecl->isTemplated() &&
13094 !isa<VarTemplateSpecializationDecl>(VDecl)) {
13095 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13096 VDecl->setInvalidDecl();
13097 }
13098
13099 // If adding the initializer will turn this declaration into a definition,
13100 // and we already have a definition for this variable, diagnose or otherwise
13101 // handle the situation.
13102 if (VarDecl *Def = VDecl->getDefinition())
13103 if (Def != VDecl &&
13104 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13105 !VDecl->isThisDeclarationADemotedDefinition() &&
13106 checkVarDeclRedefinition(Def, VDecl))
13107 return;
13108
13109 if (getLangOpts().CPlusPlus) {
13110 // C++ [class.static.data]p4
13111 // If a static data member is of const integral or const
13112 // enumeration type, its declaration in the class definition can
13113 // specify a constant-initializer which shall be an integral
13114 // constant expression (5.19). In that case, the member can appear
13115 // in integral constant expressions. The member shall still be
13116 // defined in a namespace scope if it is used in the program and the
13117 // namespace scope definition shall not contain an initializer.
13118 //
13119 // We already performed a redefinition check above, but for static
13120 // data members we also need to check whether there was an in-class
13121 // declaration with an initializer.
13122 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13123 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13124 << VDecl->getDeclName();
13125 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13126 diag::note_previous_initializer)
13127 << 0;
13128 return;
13129 }
13130
13131 if (VDecl->hasLocalStorage())
13132 setFunctionHasBranchProtectedScope();
13133
13134 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13135 VDecl->setInvalidDecl();
13136 return;
13137 }
13138 }
13139
13140 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13141 // a kernel function cannot be initialized."
13142 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13143 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13144 VDecl->setInvalidDecl();
13145 return;
13146 }
13147
13148 // The LoaderUninitialized attribute acts as a definition (of undef).
13149 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13150 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13151 VDecl->setInvalidDecl();
13152 return;
13153 }
13154
13155 // Get the decls type and save a reference for later, since
13156 // CheckInitializerTypes may change it.
13157 QualType DclT = VDecl->getType(), SavT = DclT;
13158
13159 // Expressions default to 'id' when we're in a debugger
13160 // and we are assigning it to a variable of Objective-C pointer type.
13161 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13162 Init->getType() == Context.UnknownAnyTy) {
13163 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13164 if (Result.isInvalid()) {
13165 VDecl->setInvalidDecl();
13166 return;
13167 }
13168 Init = Result.get();
13169 }
13170
13171 // Perform the initialization.
13172 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13173 bool IsParenListInit = false;
13174 if (!VDecl->isInvalidDecl()) {
13175 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
13176 InitializationKind Kind = InitializationKind::CreateForInit(
13177 VDecl->getLocation(), DirectInit, Init);
13178
13179 MultiExprArg Args = Init;
13180 if (CXXDirectInit)
13181 Args = MultiExprArg(CXXDirectInit->getExprs(),
13182 CXXDirectInit->getNumExprs());
13183
13184 // Try to correct any TypoExprs in the initialization arguments.
13185 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13186 ExprResult Res = CorrectDelayedTyposInExpr(
13187 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13188 [this, Entity, Kind](Expr *E) {
13189 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13190 return Init.Failed() ? ExprError() : E;
13191 });
13192 if (Res.isInvalid()) {
13193 VDecl->setInvalidDecl();
13194 } else if (Res.get() != Args[Idx]) {
13195 Args[Idx] = Res.get();
13196 }
13197 }
13198 if (VDecl->isInvalidDecl())
13199 return;
13200
13201 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13202 /*TopLevelOfInitList=*/false,
13203 /*TreatUnavailableAsInvalid=*/false);
13204 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13205 if (Result.isInvalid()) {
13206 // If the provided initializer fails to initialize the var decl,
13207 // we attach a recovery expr for better recovery.
13208 auto RecoveryExpr =
13209 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13210 if (RecoveryExpr.get())
13211 VDecl->setInit(RecoveryExpr.get());
13212 return;
13213 }
13214
13215 Init = Result.getAs<Expr>();
13216 IsParenListInit = !InitSeq.steps().empty() &&
13217 InitSeq.step_begin()->Kind ==
13218 InitializationSequence::SK_ParenthesizedListInit;
13219 }
13220
13221 // Check for self-references within variable initializers.
13222 // Variables declared within a function/method body (except for references)
13223 // are handled by a dataflow analysis.
13224 // This is undefined behavior in C++, but valid in C.
13225 if (getLangOpts().CPlusPlus)
13226 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13227 VDecl->getType()->isReferenceType())
13228 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13229
13230 // If the type changed, it means we had an incomplete type that was
13231 // completed by the initializer. For example:
13232 // int ary[] = { 1, 3, 5 };
13233 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13234 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13235 VDecl->setType(DclT);
13236
13237 if (!VDecl->isInvalidDecl()) {
13238 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13239
13240 if (VDecl->hasAttr<BlocksAttr>())
13241 checkRetainCycles(VDecl, Init);
13242
13243 // It is safe to assign a weak reference into a strong variable.
13244 // Although this code can still have problems:
13245 // id x = self.weakProp;
13246 // id y = self.weakProp;
13247 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13248 // paths through the function. This should be revisited if
13249 // -Wrepeated-use-of-weak is made flow-sensitive.
13250 if (FunctionScopeInfo *FSI = getCurFunction())
13251 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13252 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13253 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13254 Init->getBeginLoc()))
13255 FSI->markSafeWeakUse(Init);
13256 }
13257
13258 // The initialization is usually a full-expression.
13259 //
13260 // FIXME: If this is a braced initialization of an aggregate, it is not
13261 // an expression, and each individual field initializer is a separate
13262 // full-expression. For instance, in:
13263 //
13264 // struct Temp { ~Temp(); };
13265 // struct S { S(Temp); };
13266 // struct T { S a, b; } t = { Temp(), Temp() }
13267 //
13268 // we should destroy the first Temp before constructing the second.
13269 ExprResult Result =
13270 ActOnFinishFullExpr(Init, VDecl->getLocation(),
13271 /*DiscardedValue*/ false, VDecl->isConstexpr());
13272 if (Result.isInvalid()) {
13273 VDecl->setInvalidDecl();
13274 return;
13275 }
13276 Init = Result.get();
13277
13278 // Attach the initializer to the decl.
13279 VDecl->setInit(Init);
13280
13281 if (VDecl->isLocalVarDecl()) {
13282 // Don't check the initializer if the declaration is malformed.
13283 if (VDecl->isInvalidDecl()) {
13284 // do nothing
13285
13286 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13287 // This is true even in C++ for OpenCL.
13288 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13289 CheckForConstantInitializer(Init, DclT);
13290
13291 // Otherwise, C++ does not restrict the initializer.
13292 } else if (getLangOpts().CPlusPlus) {
13293 // do nothing
13294
13295 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13296 // static storage duration shall be constant expressions or string literals.
13297 } else if (VDecl->getStorageClass() == SC_Static) {
13298 CheckForConstantInitializer(Init, DclT);
13299
13300 // C89 is stricter than C99 for aggregate initializers.
13301 // C89 6.5.7p3: All the expressions [...] in an initializer list
13302 // for an object that has aggregate or union type shall be
13303 // constant expressions.
13304 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13305 isa<InitListExpr>(Init)) {
13306 const Expr *Culprit;
13307 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
13308 Diag(Culprit->getExprLoc(),
13309 diag::ext_aggregate_init_not_constant)
13310 << Culprit->getSourceRange();
13311 }
13312 }
13313
13314 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13315 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13316 if (VDecl->hasLocalStorage())
13317 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13318 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13319 VDecl->getLexicalDeclContext()->isRecord()) {
13320 // This is an in-class initialization for a static data member, e.g.,
13321 //
13322 // struct S {
13323 // static const int value = 17;
13324 // };
13325
13326 // C++ [class.mem]p4:
13327 // A member-declarator can contain a constant-initializer only
13328 // if it declares a static member (9.4) of const integral or
13329 // const enumeration type, see 9.4.2.
13330 //
13331 // C++11 [class.static.data]p3:
13332 // If a non-volatile non-inline const static data member is of integral
13333 // or enumeration type, its declaration in the class definition can
13334 // specify a brace-or-equal-initializer in which every initializer-clause
13335 // that is an assignment-expression is a constant expression. A static
13336 // data member of literal type can be declared in the class definition
13337 // with the constexpr specifier; if so, its declaration shall specify a
13338 // brace-or-equal-initializer in which every initializer-clause that is
13339 // an assignment-expression is a constant expression.
13340
13341 // Do nothing on dependent types.
13342 if (DclT->isDependentType()) {
13343
13344 // Allow any 'static constexpr' members, whether or not they are of literal
13345 // type. We separately check that every constexpr variable is of literal
13346 // type.
13347 } else if (VDecl->isConstexpr()) {
13348
13349 // Require constness.
13350 } else if (!DclT.isConstQualified()) {
13351 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13352 << Init->getSourceRange();
13353 VDecl->setInvalidDecl();
13354
13355 // We allow integer constant expressions in all cases.
13356 } else if (DclT->isIntegralOrEnumerationType()) {
13357 // Check whether the expression is a constant expression.
13358 SourceLocation Loc;
13359 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13360 // In C++11, a non-constexpr const static data member with an
13361 // in-class initializer cannot be volatile.
13362 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13363 else if (Init->isValueDependent())
13364 ; // Nothing to check.
13365 else if (Init->isIntegerConstantExpr(Context, &Loc))
13366 ; // Ok, it's an ICE!
13367 else if (Init->getType()->isScopedEnumeralType() &&
13368 Init->isCXX11ConstantExpr(Context))
13369 ; // Ok, it is a scoped-enum constant expression.
13370 else if (Init->isEvaluatable(Context)) {
13371 // If we can constant fold the initializer through heroics, accept it,
13372 // but report this as a use of an extension for -pedantic.
13373 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13374 << Init->getSourceRange();
13375 } else {
13376 // Otherwise, this is some crazy unknown case. Report the issue at the
13377 // location provided by the isIntegerConstantExpr failed check.
13378 Diag(Loc, diag::err_in_class_initializer_non_constant)
13379 << Init->getSourceRange();
13380 VDecl->setInvalidDecl();
13381 }
13382
13383 // We allow foldable floating-point constants as an extension.
13384 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13385 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13386 // it anyway and provide a fixit to add the 'constexpr'.
13387 if (getLangOpts().CPlusPlus11) {
13388 Diag(VDecl->getLocation(),
13389 diag::ext_in_class_initializer_float_type_cxx11)
13390 << DclT << Init->getSourceRange();
13391 Diag(VDecl->getBeginLoc(),
13392 diag::note_in_class_initializer_float_type_cxx11)
13393 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13394 } else {
13395 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13396 << DclT << Init->getSourceRange();
13397
13398 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13399 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13400 << Init->getSourceRange();
13401 VDecl->setInvalidDecl();
13402 }
13403 }
13404
13405 // Suggest adding 'constexpr' in C++11 for literal types.
13406 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13407 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13408 << DclT << Init->getSourceRange()
13409 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13410 VDecl->setConstexpr(true);
13411
13412 } else {
13413 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13414 << DclT << Init->getSourceRange();
13415 VDecl->setInvalidDecl();
13416 }
13417 } else if (VDecl->isFileVarDecl()) {
13418 // In C, extern is typically used to avoid tentative definitions when
13419 // declaring variables in headers, but adding an intializer makes it a
13420 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13421 // In C++, extern is often used to give implictly static const variables
13422 // external linkage, so don't warn in that case. If selectany is present,
13423 // this might be header code intended for C and C++ inclusion, so apply the
13424 // C++ rules.
13425 if (VDecl->getStorageClass() == SC_Extern &&
13426 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13427 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13428 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13429 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13430 Diag(VDecl->getLocation(), diag::warn_extern_init);
13431
13432 // In Microsoft C++ mode, a const variable defined in namespace scope has
13433 // external linkage by default if the variable is declared with
13434 // __declspec(dllexport).
13435 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13436 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13437 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13438 VDecl->setStorageClass(SC_Extern);
13439
13440 // C99 6.7.8p4. All file scoped initializers need to be constant.
13441 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
13442 CheckForConstantInitializer(Init, DclT);
13443 }
13444
13445 QualType InitType = Init->getType();
13446 if (!InitType.isNull() &&
13447 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13448 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
13449 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13450
13451 // We will represent direct-initialization similarly to copy-initialization:
13452 // int x(1); -as-> int x = 1;
13453 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13454 //
13455 // Clients that want to distinguish between the two forms, can check for
13456 // direct initializer using VarDecl::getInitStyle().
13457 // A major benefit is that clients that don't particularly care about which
13458 // exactly form was it (like the CodeGen) can handle both cases without
13459 // special case code.
13460
13461 // C++ 8.5p11:
13462 // The form of initialization (using parentheses or '=') is generally
13463 // insignificant, but does matter when the entity being initialized has a
13464 // class type.
13465 if (CXXDirectInit) {
13466 assert(DirectInit && "Call-style initializer must be direct init.");
13467 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13468 : VarDecl::CallInit);
13469 } else if (DirectInit) {
13470 // This must be list-initialization. No other way is direct-initialization.
13471 VDecl->setInitStyle(VarDecl::ListInit);
13472 }
13473
13474 if (LangOpts.OpenMP &&
13475 (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
13476 VDecl->isFileVarDecl())
13477 DeclsToCheckForDeferredDiags.insert(VDecl);
13478 CheckCompleteVariableDeclaration(VDecl);
13479 }
13480
13481 /// ActOnInitializerError - Given that there was an error parsing an
13482 /// initializer for the given declaration, try to at least re-establish
13483 /// invariants such as whether a variable's type is either dependent or
13484 /// complete.
ActOnInitializerError(Decl * D)13485 void Sema::ActOnInitializerError(Decl *D) {
13486 // Our main concern here is re-establishing invariants like "a
13487 // variable's type is either dependent or complete".
13488 if (!D || D->isInvalidDecl()) return;
13489
13490 VarDecl *VD = dyn_cast<VarDecl>(D);
13491 if (!VD) return;
13492
13493 // Bindings are not usable if we can't make sense of the initializer.
13494 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13495 for (auto *BD : DD->bindings())
13496 BD->setInvalidDecl();
13497
13498 // Auto types are meaningless if we can't make sense of the initializer.
13499 if (VD->getType()->isUndeducedType()) {
13500 D->setInvalidDecl();
13501 return;
13502 }
13503
13504 QualType Ty = VD->getType();
13505 if (Ty->isDependentType()) return;
13506
13507 // Require a complete type.
13508 if (RequireCompleteType(VD->getLocation(),
13509 Context.getBaseElementType(Ty),
13510 diag::err_typecheck_decl_incomplete_type)) {
13511 VD->setInvalidDecl();
13512 return;
13513 }
13514
13515 // Require a non-abstract type.
13516 if (RequireNonAbstractType(VD->getLocation(), Ty,
13517 diag::err_abstract_type_in_decl,
13518 AbstractVariableType)) {
13519 VD->setInvalidDecl();
13520 return;
13521 }
13522
13523 // Don't bother complaining about constructors or destructors,
13524 // though.
13525 }
13526
ActOnUninitializedDecl(Decl * RealDecl)13527 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13528 // If there is no declaration, there was an error parsing it. Just ignore it.
13529 if (!RealDecl)
13530 return;
13531
13532 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13533 QualType Type = Var->getType();
13534
13535 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13536 if (isa<DecompositionDecl>(RealDecl)) {
13537 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13538 Var->setInvalidDecl();
13539 return;
13540 }
13541
13542 if (Type->isUndeducedType() &&
13543 DeduceVariableDeclarationType(Var, false, nullptr))
13544 return;
13545
13546 // C++11 [class.static.data]p3: A static data member can be declared with
13547 // the constexpr specifier; if so, its declaration shall specify
13548 // a brace-or-equal-initializer.
13549 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13550 // the definition of a variable [...] or the declaration of a static data
13551 // member.
13552 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13553 !Var->isThisDeclarationADemotedDefinition()) {
13554 if (Var->isStaticDataMember()) {
13555 // C++1z removes the relevant rule; the in-class declaration is always
13556 // a definition there.
13557 if (!getLangOpts().CPlusPlus17 &&
13558 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13559 Diag(Var->getLocation(),
13560 diag::err_constexpr_static_mem_var_requires_init)
13561 << Var;
13562 Var->setInvalidDecl();
13563 return;
13564 }
13565 } else {
13566 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13567 Var->setInvalidDecl();
13568 return;
13569 }
13570 }
13571
13572 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13573 // be initialized.
13574 if (!Var->isInvalidDecl() &&
13575 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13576 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13577 bool HasConstExprDefaultConstructor = false;
13578 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13579 for (auto *Ctor : RD->ctors()) {
13580 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13581 Ctor->getMethodQualifiers().getAddressSpace() ==
13582 LangAS::opencl_constant) {
13583 HasConstExprDefaultConstructor = true;
13584 }
13585 }
13586 }
13587 if (!HasConstExprDefaultConstructor) {
13588 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13589 Var->setInvalidDecl();
13590 return;
13591 }
13592 }
13593
13594 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13595 if (Var->getStorageClass() == SC_Extern) {
13596 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13597 << Var;
13598 Var->setInvalidDecl();
13599 return;
13600 }
13601 if (RequireCompleteType(Var->getLocation(), Var->getType(),
13602 diag::err_typecheck_decl_incomplete_type)) {
13603 Var->setInvalidDecl();
13604 return;
13605 }
13606 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13607 if (!RD->hasTrivialDefaultConstructor()) {
13608 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13609 Var->setInvalidDecl();
13610 return;
13611 }
13612 }
13613 // The declaration is unitialized, no need for further checks.
13614 return;
13615 }
13616
13617 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13618 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13619 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13620 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13621 NTCUC_DefaultInitializedObject, NTCUK_Init);
13622
13623
13624 switch (DefKind) {
13625 case VarDecl::Definition:
13626 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13627 break;
13628
13629 // We have an out-of-line definition of a static data member
13630 // that has an in-class initializer, so we type-check this like
13631 // a declaration.
13632 //
13633 [[fallthrough]];
13634
13635 case VarDecl::DeclarationOnly:
13636 // It's only a declaration.
13637
13638 // Block scope. C99 6.7p7: If an identifier for an object is
13639 // declared with no linkage (C99 6.2.2p6), the type for the
13640 // object shall be complete.
13641 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13642 !Var->hasLinkage() && !Var->isInvalidDecl() &&
13643 RequireCompleteType(Var->getLocation(), Type,
13644 diag::err_typecheck_decl_incomplete_type))
13645 Var->setInvalidDecl();
13646
13647 // Make sure that the type is not abstract.
13648 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13649 RequireNonAbstractType(Var->getLocation(), Type,
13650 diag::err_abstract_type_in_decl,
13651 AbstractVariableType))
13652 Var->setInvalidDecl();
13653 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13654 Var->getStorageClass() == SC_PrivateExtern) {
13655 Diag(Var->getLocation(), diag::warn_private_extern);
13656 Diag(Var->getLocation(), diag::note_private_extern);
13657 }
13658
13659 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13660 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13661 ExternalDeclarations.push_back(Var);
13662
13663 return;
13664
13665 case VarDecl::TentativeDefinition:
13666 // File scope. C99 6.9.2p2: A declaration of an identifier for an
13667 // object that has file scope without an initializer, and without a
13668 // storage-class specifier or with the storage-class specifier "static",
13669 // constitutes a tentative definition. Note: A tentative definition with
13670 // external linkage is valid (C99 6.2.2p5).
13671 if (!Var->isInvalidDecl()) {
13672 if (const IncompleteArrayType *ArrayT
13673 = Context.getAsIncompleteArrayType(Type)) {
13674 if (RequireCompleteSizedType(
13675 Var->getLocation(), ArrayT->getElementType(),
13676 diag::err_array_incomplete_or_sizeless_type))
13677 Var->setInvalidDecl();
13678 } else if (Var->getStorageClass() == SC_Static) {
13679 // C99 6.9.2p3: If the declaration of an identifier for an object is
13680 // a tentative definition and has internal linkage (C99 6.2.2p3), the
13681 // declared type shall not be an incomplete type.
13682 // NOTE: code such as the following
13683 // static struct s;
13684 // struct s { int a; };
13685 // is accepted by gcc. Hence here we issue a warning instead of
13686 // an error and we do not invalidate the static declaration.
13687 // NOTE: to avoid multiple warnings, only check the first declaration.
13688 if (Var->isFirstDecl())
13689 RequireCompleteType(Var->getLocation(), Type,
13690 diag::ext_typecheck_decl_incomplete_type);
13691 }
13692 }
13693
13694 // Record the tentative definition; we're done.
13695 if (!Var->isInvalidDecl())
13696 TentativeDefinitions.push_back(Var);
13697 return;
13698 }
13699
13700 // Provide a specific diagnostic for uninitialized variable
13701 // definitions with incomplete array type.
13702 if (Type->isIncompleteArrayType()) {
13703 if (Var->isConstexpr())
13704 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
13705 << Var;
13706 else
13707 Diag(Var->getLocation(),
13708 diag::err_typecheck_incomplete_array_needs_initializer);
13709 Var->setInvalidDecl();
13710 return;
13711 }
13712
13713 // Provide a specific diagnostic for uninitialized variable
13714 // definitions with reference type.
13715 if (Type->isReferenceType()) {
13716 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13717 << Var << SourceRange(Var->getLocation(), Var->getLocation());
13718 return;
13719 }
13720
13721 // Do not attempt to type-check the default initializer for a
13722 // variable with dependent type.
13723 if (Type->isDependentType())
13724 return;
13725
13726 if (Var->isInvalidDecl())
13727 return;
13728
13729 if (!Var->hasAttr<AliasAttr>()) {
13730 if (RequireCompleteType(Var->getLocation(),
13731 Context.getBaseElementType(Type),
13732 diag::err_typecheck_decl_incomplete_type)) {
13733 Var->setInvalidDecl();
13734 return;
13735 }
13736 } else {
13737 return;
13738 }
13739
13740 // The variable can not have an abstract class type.
13741 if (RequireNonAbstractType(Var->getLocation(), Type,
13742 diag::err_abstract_type_in_decl,
13743 AbstractVariableType)) {
13744 Var->setInvalidDecl();
13745 return;
13746 }
13747
13748 // Check for jumps past the implicit initializer. C++0x
13749 // clarifies that this applies to a "variable with automatic
13750 // storage duration", not a "local variable".
13751 // C++11 [stmt.dcl]p3
13752 // A program that jumps from a point where a variable with automatic
13753 // storage duration is not in scope to a point where it is in scope is
13754 // ill-formed unless the variable has scalar type, class type with a
13755 // trivial default constructor and a trivial destructor, a cv-qualified
13756 // version of one of these types, or an array of one of the preceding
13757 // types and is declared without an initializer.
13758 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13759 if (const RecordType *Record
13760 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13761 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13762 // Mark the function (if we're in one) for further checking even if the
13763 // looser rules of C++11 do not require such checks, so that we can
13764 // diagnose incompatibilities with C++98.
13765 if (!CXXRecord->isPOD())
13766 setFunctionHasBranchProtectedScope();
13767 }
13768 }
13769 // In OpenCL, we can't initialize objects in the __local address space,
13770 // even implicitly, so don't synthesize an implicit initializer.
13771 if (getLangOpts().OpenCL &&
13772 Var->getType().getAddressSpace() == LangAS::opencl_local)
13773 return;
13774 // C++03 [dcl.init]p9:
13775 // If no initializer is specified for an object, and the
13776 // object is of (possibly cv-qualified) non-POD class type (or
13777 // array thereof), the object shall be default-initialized; if
13778 // the object is of const-qualified type, the underlying class
13779 // type shall have a user-declared default
13780 // constructor. Otherwise, if no initializer is specified for
13781 // a non- static object, the object and its subobjects, if
13782 // any, have an indeterminate initial value); if the object
13783 // or any of its subobjects are of const-qualified type, the
13784 // program is ill-formed.
13785 // C++0x [dcl.init]p11:
13786 // If no initializer is specified for an object, the object is
13787 // default-initialized; [...].
13788 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13789 InitializationKind Kind
13790 = InitializationKind::CreateDefault(Var->getLocation());
13791
13792 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
13793 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
13794
13795 if (Init.get()) {
13796 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13797 // This is important for template substitution.
13798 Var->setInitStyle(VarDecl::CallInit);
13799 } else if (Init.isInvalid()) {
13800 // If default-init fails, attach a recovery-expr initializer to track
13801 // that initialization was attempted and failed.
13802 auto RecoveryExpr =
13803 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13804 if (RecoveryExpr.get())
13805 Var->setInit(RecoveryExpr.get());
13806 }
13807
13808 CheckCompleteVariableDeclaration(Var);
13809 }
13810 }
13811
ActOnCXXForRangeDecl(Decl * D)13812 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13813 // If there is no declaration, there was an error parsing it. Ignore it.
13814 if (!D)
13815 return;
13816
13817 VarDecl *VD = dyn_cast<VarDecl>(D);
13818 if (!VD) {
13819 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13820 D->setInvalidDecl();
13821 return;
13822 }
13823
13824 VD->setCXXForRangeDecl(true);
13825
13826 // for-range-declaration cannot be given a storage class specifier.
13827 int Error = -1;
13828 switch (VD->getStorageClass()) {
13829 case SC_None:
13830 break;
13831 case SC_Extern:
13832 Error = 0;
13833 break;
13834 case SC_Static:
13835 Error = 1;
13836 break;
13837 case SC_PrivateExtern:
13838 Error = 2;
13839 break;
13840 case SC_Auto:
13841 Error = 3;
13842 break;
13843 case SC_Register:
13844 Error = 4;
13845 break;
13846 }
13847
13848 // for-range-declaration cannot be given a storage class specifier con't.
13849 switch (VD->getTSCSpec()) {
13850 case TSCS_thread_local:
13851 Error = 6;
13852 break;
13853 case TSCS___thread:
13854 case TSCS__Thread_local:
13855 case TSCS_unspecified:
13856 break;
13857 }
13858
13859 if (Error != -1) {
13860 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13861 << VD << Error;
13862 D->setInvalidDecl();
13863 }
13864 }
13865
ActOnCXXForRangeIdentifier(Scope * S,SourceLocation IdentLoc,IdentifierInfo * Ident,ParsedAttributes & Attrs)13866 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13867 IdentifierInfo *Ident,
13868 ParsedAttributes &Attrs) {
13869 // C++1y [stmt.iter]p1:
13870 // A range-based for statement of the form
13871 // for ( for-range-identifier : for-range-initializer ) statement
13872 // is equivalent to
13873 // for ( auto&& for-range-identifier : for-range-initializer ) statement
13874 DeclSpec DS(Attrs.getPool().getFactory());
13875
13876 const char *PrevSpec;
13877 unsigned DiagID;
13878 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13879 getPrintingPolicy());
13880
13881 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
13882 D.SetIdentifier(Ident, IdentLoc);
13883 D.takeAttributes(Attrs);
13884
13885 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13886 IdentLoc);
13887 Decl *Var = ActOnDeclarator(S, D);
13888 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13889 FinalizeDeclaration(Var);
13890 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13891 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13892 : IdentLoc);
13893 }
13894
CheckCompleteVariableDeclaration(VarDecl * var)13895 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13896 if (var->isInvalidDecl()) return;
13897
13898 MaybeAddCUDAConstantAttr(var);
13899
13900 if (getLangOpts().OpenCL) {
13901 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13902 // initialiser
13903 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13904 !var->hasInit()) {
13905 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13906 << 1 /*Init*/;
13907 var->setInvalidDecl();
13908 return;
13909 }
13910 }
13911
13912 // In Objective-C, don't allow jumps past the implicit initialization of a
13913 // local retaining variable.
13914 if (getLangOpts().ObjC &&
13915 var->hasLocalStorage()) {
13916 switch (var->getType().getObjCLifetime()) {
13917 case Qualifiers::OCL_None:
13918 case Qualifiers::OCL_ExplicitNone:
13919 case Qualifiers::OCL_Autoreleasing:
13920 break;
13921
13922 case Qualifiers::OCL_Weak:
13923 case Qualifiers::OCL_Strong:
13924 setFunctionHasBranchProtectedScope();
13925 break;
13926 }
13927 }
13928
13929 if (var->hasLocalStorage() &&
13930 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13931 setFunctionHasBranchProtectedScope();
13932
13933 // Warn about externally-visible variables being defined without a
13934 // prior declaration. We only want to do this for global
13935 // declarations, but we also specifically need to avoid doing it for
13936 // class members because the linkage of an anonymous class can
13937 // change if it's later given a typedef name.
13938 if (var->isThisDeclarationADefinition() &&
13939 var->getDeclContext()->getRedeclContext()->isFileContext() &&
13940 var->isExternallyVisible() && var->hasLinkage() &&
13941 !var->isInline() && !var->getDescribedVarTemplate() &&
13942 !isa<VarTemplatePartialSpecializationDecl>(var) &&
13943 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13944 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13945 var->getLocation())) {
13946 // Find a previous declaration that's not a definition.
13947 VarDecl *prev = var->getPreviousDecl();
13948 while (prev && prev->isThisDeclarationADefinition())
13949 prev = prev->getPreviousDecl();
13950
13951 if (!prev) {
13952 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13953 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13954 << /* variable */ 0;
13955 }
13956 }
13957
13958 // Cache the result of checking for constant initialization.
13959 std::optional<bool> CacheHasConstInit;
13960 const Expr *CacheCulprit = nullptr;
13961 auto checkConstInit = [&]() mutable {
13962 if (!CacheHasConstInit)
13963 CacheHasConstInit = var->getInit()->isConstantInitializer(
13964 Context, var->getType()->isReferenceType(), &CacheCulprit);
13965 return *CacheHasConstInit;
13966 };
13967
13968 if (var->getTLSKind() == VarDecl::TLS_Static) {
13969 if (var->getType().isDestructedType()) {
13970 // GNU C++98 edits for __thread, [basic.start.term]p3:
13971 // The type of an object with thread storage duration shall not
13972 // have a non-trivial destructor.
13973 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13974 if (getLangOpts().CPlusPlus11)
13975 Diag(var->getLocation(), diag::note_use_thread_local);
13976 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13977 if (!checkConstInit()) {
13978 // GNU C++98 edits for __thread, [basic.start.init]p4:
13979 // An object of thread storage duration shall not require dynamic
13980 // initialization.
13981 // FIXME: Need strict checking here.
13982 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13983 << CacheCulprit->getSourceRange();
13984 if (getLangOpts().CPlusPlus11)
13985 Diag(var->getLocation(), diag::note_use_thread_local);
13986 }
13987 }
13988 }
13989
13990
13991 if (!var->getType()->isStructureType() && var->hasInit() &&
13992 isa<InitListExpr>(var->getInit())) {
13993 const auto *ILE = cast<InitListExpr>(var->getInit());
13994 unsigned NumInits = ILE->getNumInits();
13995 if (NumInits > 2)
13996 for (unsigned I = 0; I < NumInits; ++I) {
13997 const auto *Init = ILE->getInit(I);
13998 if (!Init)
13999 break;
14000 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14001 if (!SL)
14002 break;
14003
14004 unsigned NumConcat = SL->getNumConcatenated();
14005 // Diagnose missing comma in string array initialization.
14006 // Do not warn when all the elements in the initializer are concatenated
14007 // together. Do not warn for macros too.
14008 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14009 bool OnlyOneMissingComma = true;
14010 for (unsigned J = I + 1; J < NumInits; ++J) {
14011 const auto *Init = ILE->getInit(J);
14012 if (!Init)
14013 break;
14014 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14015 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14016 OnlyOneMissingComma = false;
14017 break;
14018 }
14019 }
14020
14021 if (OnlyOneMissingComma) {
14022 SmallVector<FixItHint, 1> Hints;
14023 for (unsigned i = 0; i < NumConcat - 1; ++i)
14024 Hints.push_back(FixItHint::CreateInsertion(
14025 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14026
14027 Diag(SL->getStrTokenLoc(1),
14028 diag::warn_concatenated_literal_array_init)
14029 << Hints;
14030 Diag(SL->getBeginLoc(),
14031 diag::note_concatenated_string_literal_silence);
14032 }
14033 // In any case, stop now.
14034 break;
14035 }
14036 }
14037 }
14038
14039
14040 QualType type = var->getType();
14041
14042 if (var->hasAttr<BlocksAttr>())
14043 getCurFunction()->addByrefBlockVar(var);
14044
14045 Expr *Init = var->getInit();
14046 bool GlobalStorage = var->hasGlobalStorage();
14047 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14048 QualType baseType = Context.getBaseElementType(type);
14049 bool HasConstInit = true;
14050
14051 // Check whether the initializer is sufficiently constant.
14052 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
14053 !Init->isValueDependent() &&
14054 (GlobalStorage || var->isConstexpr() ||
14055 var->mightBeUsableInConstantExpressions(Context))) {
14056 // If this variable might have a constant initializer or might be usable in
14057 // constant expressions, check whether or not it actually is now. We can't
14058 // do this lazily, because the result might depend on things that change
14059 // later, such as which constexpr functions happen to be defined.
14060 SmallVector<PartialDiagnosticAt, 8> Notes;
14061 if (!getLangOpts().CPlusPlus11) {
14062 // Prior to C++11, in contexts where a constant initializer is required,
14063 // the set of valid constant initializers is described by syntactic rules
14064 // in [expr.const]p2-6.
14065 // FIXME: Stricter checking for these rules would be useful for constinit /
14066 // -Wglobal-constructors.
14067 HasConstInit = checkConstInit();
14068
14069 // Compute and cache the constant value, and remember that we have a
14070 // constant initializer.
14071 if (HasConstInit) {
14072 (void)var->checkForConstantInitialization(Notes);
14073 Notes.clear();
14074 } else if (CacheCulprit) {
14075 Notes.emplace_back(CacheCulprit->getExprLoc(),
14076 PDiag(diag::note_invalid_subexpr_in_const_expr));
14077 Notes.back().second << CacheCulprit->getSourceRange();
14078 }
14079 } else {
14080 // Evaluate the initializer to see if it's a constant initializer.
14081 HasConstInit = var->checkForConstantInitialization(Notes);
14082 }
14083
14084 if (HasConstInit) {
14085 // FIXME: Consider replacing the initializer with a ConstantExpr.
14086 } else if (var->isConstexpr()) {
14087 SourceLocation DiagLoc = var->getLocation();
14088 // If the note doesn't add any useful information other than a source
14089 // location, fold it into the primary diagnostic.
14090 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14091 diag::note_invalid_subexpr_in_const_expr) {
14092 DiagLoc = Notes[0].first;
14093 Notes.clear();
14094 }
14095 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14096 << var << Init->getSourceRange();
14097 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14098 Diag(Notes[I].first, Notes[I].second);
14099 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14100 auto *Attr = var->getAttr<ConstInitAttr>();
14101 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14102 << Init->getSourceRange();
14103 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14104 << Attr->getRange() << Attr->isConstinit();
14105 for (auto &it : Notes)
14106 Diag(it.first, it.second);
14107 } else if (IsGlobal &&
14108 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14109 var->getLocation())) {
14110 // Warn about globals which don't have a constant initializer. Don't
14111 // warn about globals with a non-trivial destructor because we already
14112 // warned about them.
14113 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14114 if (!(RD && !RD->hasTrivialDestructor())) {
14115 // checkConstInit() here permits trivial default initialization even in
14116 // C++11 onwards, where such an initializer is not a constant initializer
14117 // but nonetheless doesn't require a global constructor.
14118 if (!checkConstInit())
14119 Diag(var->getLocation(), diag::warn_global_constructor)
14120 << Init->getSourceRange();
14121 }
14122 }
14123 }
14124
14125 // Apply section attributes and pragmas to global variables.
14126 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14127 !inTemplateInstantiation()) {
14128 PragmaStack<StringLiteral *> *Stack = nullptr;
14129 int SectionFlags = ASTContext::PSF_Read;
14130 if (var->getType().isConstQualified()) {
14131 if (HasConstInit)
14132 Stack = &ConstSegStack;
14133 else {
14134 Stack = &BSSSegStack;
14135 SectionFlags |= ASTContext::PSF_Write;
14136 }
14137 } else if (var->hasInit() && HasConstInit) {
14138 Stack = &DataSegStack;
14139 SectionFlags |= ASTContext::PSF_Write;
14140 } else {
14141 Stack = &BSSSegStack;
14142 SectionFlags |= ASTContext::PSF_Write;
14143 }
14144 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14145 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14146 SectionFlags |= ASTContext::PSF_Implicit;
14147 UnifySection(SA->getName(), SectionFlags, var);
14148 } else if (Stack->CurrentValue) {
14149 SectionFlags |= ASTContext::PSF_Implicit;
14150 auto SectionName = Stack->CurrentValue->getString();
14151 var->addAttr(SectionAttr::CreateImplicit(
14152 Context, SectionName, Stack->CurrentPragmaLocation,
14153 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
14154 if (UnifySection(SectionName, SectionFlags, var))
14155 var->dropAttr<SectionAttr>();
14156 }
14157
14158 // Apply the init_seg attribute if this has an initializer. If the
14159 // initializer turns out to not be dynamic, we'll end up ignoring this
14160 // attribute.
14161 if (CurInitSeg && var->getInit())
14162 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14163 CurInitSegLoc,
14164 AttributeCommonInfo::AS_Pragma));
14165 }
14166
14167 // All the following checks are C++ only.
14168 if (!getLangOpts().CPlusPlus) {
14169 // If this variable must be emitted, add it as an initializer for the
14170 // current module.
14171 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14172 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14173 return;
14174 }
14175
14176 // Require the destructor.
14177 if (!type->isDependentType())
14178 if (const RecordType *recordType = baseType->getAs<RecordType>())
14179 FinalizeVarWithDestructor(var, recordType);
14180
14181 // If this variable must be emitted, add it as an initializer for the current
14182 // module.
14183 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14184 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14185
14186 // Build the bindings if this is a structured binding declaration.
14187 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14188 CheckCompleteDecompositionDeclaration(DD);
14189 }
14190
14191 /// Check if VD needs to be dllexport/dllimport due to being in a
14192 /// dllexport/import function.
CheckStaticLocalForDllExport(VarDecl * VD)14193 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14194 assert(VD->isStaticLocal());
14195
14196 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14197
14198 // Find outermost function when VD is in lambda function.
14199 while (FD && !getDLLAttr(FD) &&
14200 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14201 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14202 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14203 }
14204
14205 if (!FD)
14206 return;
14207
14208 // Static locals inherit dll attributes from their function.
14209 if (Attr *A = getDLLAttr(FD)) {
14210 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14211 NewAttr->setInherited(true);
14212 VD->addAttr(NewAttr);
14213 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14214 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14215 NewAttr->setInherited(true);
14216 VD->addAttr(NewAttr);
14217
14218 // Export this function to enforce exporting this static variable even
14219 // if it is not used in this compilation unit.
14220 if (!FD->hasAttr<DLLExportAttr>())
14221 FD->addAttr(NewAttr);
14222
14223 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14224 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14225 NewAttr->setInherited(true);
14226 VD->addAttr(NewAttr);
14227 }
14228 }
14229
CheckThreadLocalForLargeAlignment(VarDecl * VD)14230 void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14231 assert(VD->getTLSKind());
14232
14233 // Perform TLS alignment check here after attributes attached to the variable
14234 // which may affect the alignment have been processed. Only perform the check
14235 // if the target has a maximum TLS alignment (zero means no constraints).
14236 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14237 // Protect the check so that it's not performed on dependent types and
14238 // dependent alignments (we can't determine the alignment in that case).
14239 if (!VD->hasDependentAlignment()) {
14240 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14241 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14242 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14243 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14244 << (unsigned)MaxAlignChars.getQuantity();
14245 }
14246 }
14247 }
14248 }
14249
14250 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14251 /// any semantic actions necessary after any initializer has been attached.
FinalizeDeclaration(Decl * ThisDecl)14252 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14253 // Note that we are no longer parsing the initializer for this declaration.
14254 ParsingInitForAutoVars.erase(ThisDecl);
14255
14256 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14257 if (!VD)
14258 return;
14259
14260 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14261 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14262 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14263 if (PragmaClangBSSSection.Valid)
14264 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14265 Context, PragmaClangBSSSection.SectionName,
14266 PragmaClangBSSSection.PragmaLocation,
14267 AttributeCommonInfo::AS_Pragma));
14268 if (PragmaClangDataSection.Valid)
14269 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14270 Context, PragmaClangDataSection.SectionName,
14271 PragmaClangDataSection.PragmaLocation,
14272 AttributeCommonInfo::AS_Pragma));
14273 if (PragmaClangRodataSection.Valid)
14274 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14275 Context, PragmaClangRodataSection.SectionName,
14276 PragmaClangRodataSection.PragmaLocation,
14277 AttributeCommonInfo::AS_Pragma));
14278 if (PragmaClangRelroSection.Valid)
14279 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14280 Context, PragmaClangRelroSection.SectionName,
14281 PragmaClangRelroSection.PragmaLocation,
14282 AttributeCommonInfo::AS_Pragma));
14283 }
14284
14285 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14286 for (auto *BD : DD->bindings()) {
14287 FinalizeDeclaration(BD);
14288 }
14289 }
14290
14291 checkAttributesAfterMerging(*this, *VD);
14292
14293 if (VD->isStaticLocal())
14294 CheckStaticLocalForDllExport(VD);
14295
14296 if (VD->getTLSKind())
14297 CheckThreadLocalForLargeAlignment(VD);
14298
14299 // Perform check for initializers of device-side global variables.
14300 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14301 // 7.5). We must also apply the same checks to all __shared__
14302 // variables whether they are local or not. CUDA also allows
14303 // constant initializers for __constant__ and __device__ variables.
14304 if (getLangOpts().CUDA)
14305 checkAllowedCUDAInitializer(VD);
14306
14307 // Grab the dllimport or dllexport attribute off of the VarDecl.
14308 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14309
14310 // Imported static data members cannot be defined out-of-line.
14311 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14312 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14313 VD->isThisDeclarationADefinition()) {
14314 // We allow definitions of dllimport class template static data members
14315 // with a warning.
14316 CXXRecordDecl *Context =
14317 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14318 bool IsClassTemplateMember =
14319 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14320 Context->getDescribedClassTemplate();
14321
14322 Diag(VD->getLocation(),
14323 IsClassTemplateMember
14324 ? diag::warn_attribute_dllimport_static_field_definition
14325 : diag::err_attribute_dllimport_static_field_definition);
14326 Diag(IA->getLocation(), diag::note_attribute);
14327 if (!IsClassTemplateMember)
14328 VD->setInvalidDecl();
14329 }
14330 }
14331
14332 // dllimport/dllexport variables cannot be thread local, their TLS index
14333 // isn't exported with the variable.
14334 if (DLLAttr && VD->getTLSKind()) {
14335 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14336 if (F && getDLLAttr(F)) {
14337 assert(VD->isStaticLocal());
14338 // But if this is a static local in a dlimport/dllexport function, the
14339 // function will never be inlined, which means the var would never be
14340 // imported, so having it marked import/export is safe.
14341 } else {
14342 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14343 << DLLAttr;
14344 VD->setInvalidDecl();
14345 }
14346 }
14347
14348 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14349 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14350 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14351 << Attr;
14352 VD->dropAttr<UsedAttr>();
14353 }
14354 }
14355 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14356 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14357 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14358 << Attr;
14359 VD->dropAttr<RetainAttr>();
14360 }
14361 }
14362
14363 const DeclContext *DC = VD->getDeclContext();
14364 // If there's a #pragma GCC visibility in scope, and this isn't a class
14365 // member, set the visibility of this variable.
14366 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14367 AddPushedVisibilityAttribute(VD);
14368
14369 // FIXME: Warn on unused var template partial specializations.
14370 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14371 MarkUnusedFileScopedDecl(VD);
14372
14373 // Now we have parsed the initializer and can update the table of magic
14374 // tag values.
14375 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14376 !VD->getType()->isIntegralOrEnumerationType())
14377 return;
14378
14379 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14380 const Expr *MagicValueExpr = VD->getInit();
14381 if (!MagicValueExpr) {
14382 continue;
14383 }
14384 std::optional<llvm::APSInt> MagicValueInt;
14385 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14386 Diag(I->getRange().getBegin(),
14387 diag::err_type_tag_for_datatype_not_ice)
14388 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14389 continue;
14390 }
14391 if (MagicValueInt->getActiveBits() > 64) {
14392 Diag(I->getRange().getBegin(),
14393 diag::err_type_tag_for_datatype_too_large)
14394 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14395 continue;
14396 }
14397 uint64_t MagicValue = MagicValueInt->getZExtValue();
14398 RegisterTypeTagForDatatype(I->getArgumentKind(),
14399 MagicValue,
14400 I->getMatchingCType(),
14401 I->getLayoutCompatible(),
14402 I->getMustBeNull());
14403 }
14404 }
14405
hasDeducedAuto(DeclaratorDecl * DD)14406 static bool hasDeducedAuto(DeclaratorDecl *DD) {
14407 auto *VD = dyn_cast<VarDecl>(DD);
14408 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14409 }
14410
FinalizeDeclaratorGroup(Scope * S,const DeclSpec & DS,ArrayRef<Decl * > Group)14411 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14412 ArrayRef<Decl *> Group) {
14413 SmallVector<Decl*, 8> Decls;
14414
14415 if (DS.isTypeSpecOwned())
14416 Decls.push_back(DS.getRepAsDecl());
14417
14418 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14419 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14420 bool DiagnosedMultipleDecomps = false;
14421 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14422 bool DiagnosedNonDeducedAuto = false;
14423
14424 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14425 if (Decl *D = Group[i]) {
14426 // For declarators, there are some additional syntactic-ish checks we need
14427 // to perform.
14428 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14429 if (!FirstDeclaratorInGroup)
14430 FirstDeclaratorInGroup = DD;
14431 if (!FirstDecompDeclaratorInGroup)
14432 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14433 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14434 !hasDeducedAuto(DD))
14435 FirstNonDeducedAutoInGroup = DD;
14436
14437 if (FirstDeclaratorInGroup != DD) {
14438 // A decomposition declaration cannot be combined with any other
14439 // declaration in the same group.
14440 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14441 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14442 diag::err_decomp_decl_not_alone)
14443 << FirstDeclaratorInGroup->getSourceRange()
14444 << DD->getSourceRange();
14445 DiagnosedMultipleDecomps = true;
14446 }
14447
14448 // A declarator that uses 'auto' in any way other than to declare a
14449 // variable with a deduced type cannot be combined with any other
14450 // declarator in the same group.
14451 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14452 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14453 diag::err_auto_non_deduced_not_alone)
14454 << FirstNonDeducedAutoInGroup->getType()
14455 ->hasAutoForTrailingReturnType()
14456 << FirstDeclaratorInGroup->getSourceRange()
14457 << DD->getSourceRange();
14458 DiagnosedNonDeducedAuto = true;
14459 }
14460 }
14461 }
14462
14463 Decls.push_back(D);
14464 }
14465 }
14466
14467 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
14468 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14469 handleTagNumbering(Tag, S);
14470 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14471 getLangOpts().CPlusPlus)
14472 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14473 }
14474 }
14475
14476 return BuildDeclaratorGroup(Decls);
14477 }
14478
14479 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14480 /// group, performing any necessary semantic checking.
14481 Sema::DeclGroupPtrTy
BuildDeclaratorGroup(MutableArrayRef<Decl * > Group)14482 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14483 // C++14 [dcl.spec.auto]p7: (DR1347)
14484 // If the type that replaces the placeholder type is not the same in each
14485 // deduction, the program is ill-formed.
14486 if (Group.size() > 1) {
14487 QualType Deduced;
14488 VarDecl *DeducedDecl = nullptr;
14489 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14490 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14491 if (!D || D->isInvalidDecl())
14492 break;
14493 DeducedType *DT = D->getType()->getContainedDeducedType();
14494 if (!DT || DT->getDeducedType().isNull())
14495 continue;
14496 if (Deduced.isNull()) {
14497 Deduced = DT->getDeducedType();
14498 DeducedDecl = D;
14499 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14500 auto *AT = dyn_cast<AutoType>(DT);
14501 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14502 diag::err_auto_different_deductions)
14503 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14504 << DeducedDecl->getDeclName() << DT->getDeducedType()
14505 << D->getDeclName();
14506 if (DeducedDecl->hasInit())
14507 Dia << DeducedDecl->getInit()->getSourceRange();
14508 if (D->getInit())
14509 Dia << D->getInit()->getSourceRange();
14510 D->setInvalidDecl();
14511 break;
14512 }
14513 }
14514 }
14515
14516 ActOnDocumentableDecls(Group);
14517
14518 return DeclGroupPtrTy::make(
14519 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14520 }
14521
ActOnDocumentableDecl(Decl * D)14522 void Sema::ActOnDocumentableDecl(Decl *D) {
14523 ActOnDocumentableDecls(D);
14524 }
14525
ActOnDocumentableDecls(ArrayRef<Decl * > Group)14526 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14527 // Don't parse the comment if Doxygen diagnostics are ignored.
14528 if (Group.empty() || !Group[0])
14529 return;
14530
14531 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14532 Group[0]->getLocation()) &&
14533 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14534 Group[0]->getLocation()))
14535 return;
14536
14537 if (Group.size() >= 2) {
14538 // This is a decl group. Normally it will contain only declarations
14539 // produced from declarator list. But in case we have any definitions or
14540 // additional declaration references:
14541 // 'typedef struct S {} S;'
14542 // 'typedef struct S *S;'
14543 // 'struct S *pS;'
14544 // FinalizeDeclaratorGroup adds these as separate declarations.
14545 Decl *MaybeTagDecl = Group[0];
14546 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14547 Group = Group.slice(1);
14548 }
14549 }
14550
14551 // FIMXE: We assume every Decl in the group is in the same file.
14552 // This is false when preprocessor constructs the group from decls in
14553 // different files (e. g. macros or #include).
14554 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14555 }
14556
14557 /// Common checks for a parameter-declaration that should apply to both function
14558 /// parameters and non-type template parameters.
CheckFunctionOrTemplateParamDeclarator(Scope * S,Declarator & D)14559 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14560 // Check that there are no default arguments inside the type of this
14561 // parameter.
14562 if (getLangOpts().CPlusPlus)
14563 CheckExtraCXXDefaultArguments(D);
14564
14565 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14566 if (D.getCXXScopeSpec().isSet()) {
14567 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14568 << D.getCXXScopeSpec().getRange();
14569 }
14570
14571 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14572 // simple identifier except [...irrelevant cases...].
14573 switch (D.getName().getKind()) {
14574 case UnqualifiedIdKind::IK_Identifier:
14575 break;
14576
14577 case UnqualifiedIdKind::IK_OperatorFunctionId:
14578 case UnqualifiedIdKind::IK_ConversionFunctionId:
14579 case UnqualifiedIdKind::IK_LiteralOperatorId:
14580 case UnqualifiedIdKind::IK_ConstructorName:
14581 case UnqualifiedIdKind::IK_DestructorName:
14582 case UnqualifiedIdKind::IK_ImplicitSelfParam:
14583 case UnqualifiedIdKind::IK_DeductionGuideName:
14584 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14585 << GetNameForDeclarator(D).getName();
14586 break;
14587
14588 case UnqualifiedIdKind::IK_TemplateId:
14589 case UnqualifiedIdKind::IK_ConstructorTemplateId:
14590 // GetNameForDeclarator would not produce a useful name in this case.
14591 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14592 break;
14593 }
14594 }
14595
14596 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14597 /// to introduce parameters into function prototype scope.
ActOnParamDeclarator(Scope * S,Declarator & D)14598 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14599 const DeclSpec &DS = D.getDeclSpec();
14600
14601 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14602
14603 // C++03 [dcl.stc]p2 also permits 'auto'.
14604 StorageClass SC = SC_None;
14605 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14606 SC = SC_Register;
14607 // In C++11, the 'register' storage class specifier is deprecated.
14608 // In C++17, it is not allowed, but we tolerate it as an extension.
14609 if (getLangOpts().CPlusPlus11) {
14610 Diag(DS.getStorageClassSpecLoc(),
14611 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14612 : diag::warn_deprecated_register)
14613 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14614 }
14615 } else if (getLangOpts().CPlusPlus &&
14616 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14617 SC = SC_Auto;
14618 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14619 Diag(DS.getStorageClassSpecLoc(),
14620 diag::err_invalid_storage_class_in_func_decl);
14621 D.getMutableDeclSpec().ClearStorageClassSpecs();
14622 }
14623
14624 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14625 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14626 << DeclSpec::getSpecifierName(TSCS);
14627 if (DS.isInlineSpecified())
14628 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14629 << getLangOpts().CPlusPlus17;
14630 if (DS.hasConstexprSpecifier())
14631 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14632 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14633
14634 DiagnoseFunctionSpecifiers(DS);
14635
14636 CheckFunctionOrTemplateParamDeclarator(S, D);
14637
14638 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14639 QualType parmDeclType = TInfo->getType();
14640
14641 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14642 IdentifierInfo *II = D.getIdentifier();
14643 if (II) {
14644 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14645 ForVisibleRedeclaration);
14646 LookupName(R, S);
14647 if (R.isSingleResult()) {
14648 NamedDecl *PrevDecl = R.getFoundDecl();
14649 if (PrevDecl->isTemplateParameter()) {
14650 // Maybe we will complain about the shadowed template parameter.
14651 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14652 // Just pretend that we didn't see the previous declaration.
14653 PrevDecl = nullptr;
14654 } else if (S->isDeclScope(PrevDecl)) {
14655 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14656 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14657
14658 // Recover by removing the name
14659 II = nullptr;
14660 D.SetIdentifier(nullptr, D.getIdentifierLoc());
14661 D.setInvalidType(true);
14662 }
14663 }
14664 }
14665
14666 // Temporarily put parameter variables in the translation unit, not
14667 // the enclosing context. This prevents them from accidentally
14668 // looking like class members in C++.
14669 ParmVarDecl *New =
14670 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14671 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14672
14673 if (D.isInvalidType())
14674 New->setInvalidDecl();
14675
14676 assert(S->isFunctionPrototypeScope());
14677 assert(S->getFunctionPrototypeDepth() >= 1);
14678 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14679 S->getNextFunctionPrototypeIndex());
14680
14681 // Add the parameter declaration into this scope.
14682 S->AddDecl(New);
14683 if (II)
14684 IdResolver.AddDecl(New);
14685
14686 ProcessDeclAttributes(S, New, D);
14687
14688 if (D.getDeclSpec().isModulePrivateSpecified())
14689 Diag(New->getLocation(), diag::err_module_private_local)
14690 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14691 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14692
14693 if (New->hasAttr<BlocksAttr>()) {
14694 Diag(New->getLocation(), diag::err_block_on_nonlocal);
14695 }
14696
14697 if (getLangOpts().OpenCL)
14698 deduceOpenCLAddressSpace(New);
14699
14700 return New;
14701 }
14702
14703 /// Synthesizes a variable for a parameter arising from a
14704 /// typedef.
BuildParmVarDeclForTypedef(DeclContext * DC,SourceLocation Loc,QualType T)14705 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14706 SourceLocation Loc,
14707 QualType T) {
14708 /* FIXME: setting StartLoc == Loc.
14709 Would it be worth to modify callers so as to provide proper source
14710 location for the unnamed parameters, embedding the parameter's type? */
14711 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14712 T, Context.getTrivialTypeSourceInfo(T, Loc),
14713 SC_None, nullptr);
14714 Param->setImplicit();
14715 return Param;
14716 }
14717
DiagnoseUnusedParameters(ArrayRef<ParmVarDecl * > Parameters)14718 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14719 // Don't diagnose unused-parameter errors in template instantiations; we
14720 // will already have done so in the template itself.
14721 if (inTemplateInstantiation())
14722 return;
14723
14724 for (const ParmVarDecl *Parameter : Parameters) {
14725 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14726 !Parameter->hasAttr<UnusedAttr>()) {
14727 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14728 << Parameter->getDeclName();
14729 }
14730 }
14731 }
14732
DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl * > Parameters,QualType ReturnTy,NamedDecl * D)14733 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14734 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14735 if (LangOpts.NumLargeByValueCopy == 0) // No check.
14736 return;
14737
14738 // Warn if the return value is pass-by-value and larger than the specified
14739 // threshold.
14740 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14741 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14742 if (Size > LangOpts.NumLargeByValueCopy)
14743 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14744 }
14745
14746 // Warn if any parameter is pass-by-value and larger than the specified
14747 // threshold.
14748 for (const ParmVarDecl *Parameter : Parameters) {
14749 QualType T = Parameter->getType();
14750 if (T->isDependentType() || !T.isPODType(Context))
14751 continue;
14752 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14753 if (Size > LangOpts.NumLargeByValueCopy)
14754 Diag(Parameter->getLocation(), diag::warn_parameter_size)
14755 << Parameter << Size;
14756 }
14757 }
14758
CheckParameter(DeclContext * DC,SourceLocation StartLoc,SourceLocation NameLoc,IdentifierInfo * Name,QualType T,TypeSourceInfo * TSInfo,StorageClass SC)14759 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14760 SourceLocation NameLoc, IdentifierInfo *Name,
14761 QualType T, TypeSourceInfo *TSInfo,
14762 StorageClass SC) {
14763 // In ARC, infer a lifetime qualifier for appropriate parameter types.
14764 if (getLangOpts().ObjCAutoRefCount &&
14765 T.getObjCLifetime() == Qualifiers::OCL_None &&
14766 T->isObjCLifetimeType()) {
14767
14768 Qualifiers::ObjCLifetime lifetime;
14769
14770 // Special cases for arrays:
14771 // - if it's const, use __unsafe_unretained
14772 // - otherwise, it's an error
14773 if (T->isArrayType()) {
14774 if (!T.isConstQualified()) {
14775 if (DelayedDiagnostics.shouldDelayDiagnostics())
14776 DelayedDiagnostics.add(
14777 sema::DelayedDiagnostic::makeForbiddenType(
14778 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14779 else
14780 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14781 << TSInfo->getTypeLoc().getSourceRange();
14782 }
14783 lifetime = Qualifiers::OCL_ExplicitNone;
14784 } else {
14785 lifetime = T->getObjCARCImplicitLifetime();
14786 }
14787 T = Context.getLifetimeQualifiedType(T, lifetime);
14788 }
14789
14790 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14791 Context.getAdjustedParameterType(T),
14792 TSInfo, SC, nullptr);
14793
14794 // Make a note if we created a new pack in the scope of a lambda, so that
14795 // we know that references to that pack must also be expanded within the
14796 // lambda scope.
14797 if (New->isParameterPack())
14798 if (auto *LSI = getEnclosingLambda())
14799 LSI->LocalPacks.push_back(New);
14800
14801 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14802 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14803 checkNonTrivialCUnion(New->getType(), New->getLocation(),
14804 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14805
14806 // Parameters can not be abstract class types.
14807 // For record types, this is done by the AbstractClassUsageDiagnoser once
14808 // the class has been completely parsed.
14809 if (!CurContext->isRecord() &&
14810 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14811 AbstractParamType))
14812 New->setInvalidDecl();
14813
14814 // Parameter declarators cannot be interface types. All ObjC objects are
14815 // passed by reference.
14816 if (T->isObjCObjectType()) {
14817 SourceLocation TypeEndLoc =
14818 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14819 Diag(NameLoc,
14820 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14821 << FixItHint::CreateInsertion(TypeEndLoc, "*");
14822 T = Context.getObjCObjectPointerType(T);
14823 New->setType(T);
14824 }
14825
14826 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14827 // duration shall not be qualified by an address-space qualifier."
14828 // Since all parameters have automatic store duration, they can not have
14829 // an address space.
14830 if (T.getAddressSpace() != LangAS::Default &&
14831 // OpenCL allows function arguments declared to be an array of a type
14832 // to be qualified with an address space.
14833 !(getLangOpts().OpenCL &&
14834 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14835 Diag(NameLoc, diag::err_arg_with_address_space);
14836 New->setInvalidDecl();
14837 }
14838
14839 // PPC MMA non-pointer types are not allowed as function argument types.
14840 if (Context.getTargetInfo().getTriple().isPPC64() &&
14841 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14842 New->setInvalidDecl();
14843 }
14844
14845 return New;
14846 }
14847
ActOnFinishKNRParamDeclarations(Scope * S,Declarator & D,SourceLocation LocAfterDecls)14848 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14849 SourceLocation LocAfterDecls) {
14850 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14851
14852 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14853 // in the declaration list shall have at least one declarator, those
14854 // declarators shall only declare identifiers from the identifier list, and
14855 // every identifier in the identifier list shall be declared.
14856 //
14857 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14858 // identifiers it names shall be declared in the declaration list."
14859 //
14860 // This is why we only diagnose in C99 and later. Note, the other conditions
14861 // listed are checked elsewhere.
14862 if (!FTI.hasPrototype) {
14863 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14864 --i;
14865 if (FTI.Params[i].Param == nullptr) {
14866 if (getLangOpts().C99) {
14867 SmallString<256> Code;
14868 llvm::raw_svector_ostream(Code)
14869 << " int " << FTI.Params[i].Ident->getName() << ";\n";
14870 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14871 << FTI.Params[i].Ident
14872 << FixItHint::CreateInsertion(LocAfterDecls, Code);
14873 }
14874
14875 // Implicitly declare the argument as type 'int' for lack of a better
14876 // type.
14877 AttributeFactory attrs;
14878 DeclSpec DS(attrs);
14879 const char* PrevSpec; // unused
14880 unsigned DiagID; // unused
14881 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14882 DiagID, Context.getPrintingPolicy());
14883 // Use the identifier location for the type source range.
14884 DS.SetRangeStart(FTI.Params[i].IdentLoc);
14885 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14886 Declarator ParamD(DS, ParsedAttributesView::none(),
14887 DeclaratorContext::KNRTypeList);
14888 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14889 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14890 }
14891 }
14892 }
14893 }
14894
14895 Decl *
ActOnStartOfFunctionDef(Scope * FnBodyScope,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,SkipBodyInfo * SkipBody,FnBodyKind BodyKind)14896 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14897 MultiTemplateParamsArg TemplateParameterLists,
14898 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14899 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14900 assert(D.isFunctionDeclarator() && "Not a function declarator!");
14901 Scope *ParentScope = FnBodyScope->getParent();
14902
14903 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14904 // we define a non-templated function definition, we will create a declaration
14905 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14906 // The base function declaration will have the equivalent of an `omp declare
14907 // variant` annotation which specifies the mangled definition as a
14908 // specialization function under the OpenMP context defined as part of the
14909 // `omp begin declare variant`.
14910 SmallVector<FunctionDecl *, 4> Bases;
14911 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14912 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14913 ParentScope, D, TemplateParameterLists, Bases);
14914
14915 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14916 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14917 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14918
14919 if (!Bases.empty())
14920 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14921
14922 return Dcl;
14923 }
14924
ActOnFinishInlineFunctionDef(FunctionDecl * D)14925 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14926 Consumer.HandleInlineFunctionDefinition(D);
14927 }
14928
FindPossiblePrototype(const FunctionDecl * FD,const FunctionDecl * & PossiblePrototype)14929 static bool FindPossiblePrototype(const FunctionDecl *FD,
14930 const FunctionDecl *&PossiblePrototype) {
14931 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
14932 Prev = Prev->getPreviousDecl()) {
14933 // Ignore any declarations that occur in function or method
14934 // scope, because they aren't visible from the header.
14935 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14936 continue;
14937
14938 PossiblePrototype = Prev;
14939 return Prev->getType()->isFunctionProtoType();
14940 }
14941 return false;
14942 }
14943
14944 static bool
ShouldWarnAboutMissingPrototype(const FunctionDecl * FD,const FunctionDecl * & PossiblePrototype)14945 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14946 const FunctionDecl *&PossiblePrototype) {
14947 // Don't warn about invalid declarations.
14948 if (FD->isInvalidDecl())
14949 return false;
14950
14951 // Or declarations that aren't global.
14952 if (!FD->isGlobal())
14953 return false;
14954
14955 // Don't warn about C++ member functions.
14956 if (isa<CXXMethodDecl>(FD))
14957 return false;
14958
14959 // Don't warn about 'main'.
14960 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14961 if (IdentifierInfo *II = FD->getIdentifier())
14962 if (II->isStr("main") || II->isStr("efi_main"))
14963 return false;
14964
14965 // Don't warn about inline functions.
14966 if (FD->isInlined())
14967 return false;
14968
14969 // Don't warn about function templates.
14970 if (FD->getDescribedFunctionTemplate())
14971 return false;
14972
14973 // Don't warn about function template specializations.
14974 if (FD->isFunctionTemplateSpecialization())
14975 return false;
14976
14977 // Don't warn for OpenCL kernels.
14978 if (FD->hasAttr<OpenCLKernelAttr>())
14979 return false;
14980
14981 // Don't warn on explicitly deleted functions.
14982 if (FD->isDeleted())
14983 return false;
14984
14985 // Don't warn on implicitly local functions (such as having local-typed
14986 // parameters).
14987 if (!FD->isExternallyVisible())
14988 return false;
14989
14990 // If we were able to find a potential prototype, don't warn.
14991 if (FindPossiblePrototype(FD, PossiblePrototype))
14992 return false;
14993
14994 return true;
14995 }
14996
14997 void
CheckForFunctionRedefinition(FunctionDecl * FD,const FunctionDecl * EffectiveDefinition,SkipBodyInfo * SkipBody)14998 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14999 const FunctionDecl *EffectiveDefinition,
15000 SkipBodyInfo *SkipBody) {
15001 const FunctionDecl *Definition = EffectiveDefinition;
15002 if (!Definition &&
15003 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15004 return;
15005
15006 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15007 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15008 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15009 // A merged copy of the same function, instantiated as a member of
15010 // the same class, is OK.
15011 if (declaresSameEntity(OrigFD, OrigDef) &&
15012 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15013 cast<Decl>(FD->getLexicalDeclContext())))
15014 return;
15015 }
15016 }
15017 }
15018
15019 if (canRedefineFunction(Definition, getLangOpts()))
15020 return;
15021
15022 // Don't emit an error when this is redefinition of a typo-corrected
15023 // definition.
15024 if (TypoCorrectedFunctionDefinitions.count(Definition))
15025 return;
15026
15027 // If we don't have a visible definition of the function, and it's inline or
15028 // a template, skip the new definition.
15029 if (SkipBody && !hasVisibleDefinition(Definition) &&
15030 (Definition->getFormalLinkage() == InternalLinkage ||
15031 Definition->isInlined() ||
15032 Definition->getDescribedFunctionTemplate() ||
15033 Definition->getNumTemplateParameterLists())) {
15034 SkipBody->ShouldSkip = true;
15035 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15036 if (auto *TD = Definition->getDescribedFunctionTemplate())
15037 makeMergedDefinitionVisible(TD);
15038 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15039 return;
15040 }
15041
15042 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15043 Definition->getStorageClass() == SC_Extern)
15044 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15045 << FD << getLangOpts().CPlusPlus;
15046 else
15047 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15048
15049 Diag(Definition->getLocation(), diag::note_previous_definition);
15050 FD->setInvalidDecl();
15051 }
15052
RebuildLambdaScopeInfo(CXXMethodDecl * CallOperator,Sema & S)15053 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
15054 Sema &S) {
15055 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
15056
15057 LambdaScopeInfo *LSI = S.PushLambdaScope();
15058 LSI->CallOperator = CallOperator;
15059 LSI->Lambda = LambdaClass;
15060 LSI->ReturnType = CallOperator->getReturnType();
15061 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15062
15063 if (LCD == LCD_None)
15064 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15065 else if (LCD == LCD_ByCopy)
15066 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15067 else if (LCD == LCD_ByRef)
15068 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15069 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15070
15071 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15072 LSI->Mutable = !CallOperator->isConst();
15073
15074 // Add the captures to the LSI so they can be noted as already
15075 // captured within tryCaptureVar.
15076 auto I = LambdaClass->field_begin();
15077 for (const auto &C : LambdaClass->captures()) {
15078 if (C.capturesVariable()) {
15079 ValueDecl *VD = C.getCapturedVar();
15080 if (VD->isInitCapture())
15081 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15082 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15083 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15084 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15085 /*EllipsisLoc*/C.isPackExpansion()
15086 ? C.getEllipsisLoc() : SourceLocation(),
15087 I->getType(), /*Invalid*/false);
15088
15089 } else if (C.capturesThis()) {
15090 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15091 C.getCaptureKind() == LCK_StarThis);
15092 } else {
15093 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15094 I->getType());
15095 }
15096 ++I;
15097 }
15098 }
15099
ActOnStartOfFunctionDef(Scope * FnBodyScope,Decl * D,SkipBodyInfo * SkipBody,FnBodyKind BodyKind)15100 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15101 SkipBodyInfo *SkipBody,
15102 FnBodyKind BodyKind) {
15103 if (!D) {
15104 // Parsing the function declaration failed in some way. Push on a fake scope
15105 // anyway so we can try to parse the function body.
15106 PushFunctionScope();
15107 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15108 return D;
15109 }
15110
15111 FunctionDecl *FD = nullptr;
15112
15113 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15114 FD = FunTmpl->getTemplatedDecl();
15115 else
15116 FD = cast<FunctionDecl>(D);
15117
15118 // Do not push if it is a lambda because one is already pushed when building
15119 // the lambda in ActOnStartOfLambdaDefinition().
15120 if (!isLambdaCallOperator(FD))
15121 // [expr.const]/p14.1
15122 // An expression or conversion is in an immediate function context if it is
15123 // potentially evaluated and either: its innermost enclosing non-block scope
15124 // is a function parameter scope of an immediate function.
15125 PushExpressionEvaluationContext(
15126 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15127 : ExprEvalContexts.back().Context);
15128
15129 // Check for defining attributes before the check for redefinition.
15130 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15131 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15132 FD->dropAttr<AliasAttr>();
15133 FD->setInvalidDecl();
15134 }
15135 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15136 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15137 FD->dropAttr<IFuncAttr>();
15138 FD->setInvalidDecl();
15139 }
15140 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15141 if (!Context.getTargetInfo().hasFeature("fmv") &&
15142 !Attr->isDefaultVersion()) {
15143 // If function multi versioning disabled skip parsing function body
15144 // defined with non-default target_version attribute
15145 if (SkipBody)
15146 SkipBody->ShouldSkip = true;
15147 return nullptr;
15148 }
15149 }
15150
15151 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15152 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15153 Ctor->isDefaultConstructor() &&
15154 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15155 // If this is an MS ABI dllexport default constructor, instantiate any
15156 // default arguments.
15157 InstantiateDefaultCtorDefaultArgs(Ctor);
15158 }
15159 }
15160
15161 // See if this is a redefinition. If 'will have body' (or similar) is already
15162 // set, then these checks were already performed when it was set.
15163 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15164 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15165 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15166
15167 // If we're skipping the body, we're done. Don't enter the scope.
15168 if (SkipBody && SkipBody->ShouldSkip)
15169 return D;
15170 }
15171
15172 // Mark this function as "will have a body eventually". This lets users to
15173 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15174 // this function.
15175 FD->setWillHaveBody();
15176
15177 // If we are instantiating a generic lambda call operator, push
15178 // a LambdaScopeInfo onto the function stack. But use the information
15179 // that's already been calculated (ActOnLambdaExpr) to prime the current
15180 // LambdaScopeInfo.
15181 // When the template operator is being specialized, the LambdaScopeInfo,
15182 // has to be properly restored so that tryCaptureVariable doesn't try
15183 // and capture any new variables. In addition when calculating potential
15184 // captures during transformation of nested lambdas, it is necessary to
15185 // have the LSI properly restored.
15186 if (isGenericLambdaCallOperatorSpecialization(FD)) {
15187 assert(inTemplateInstantiation() &&
15188 "There should be an active template instantiation on the stack "
15189 "when instantiating a generic lambda!");
15190 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
15191 } else {
15192 // Enter a new function scope
15193 PushFunctionScope();
15194 }
15195
15196 // Builtin functions cannot be defined.
15197 if (unsigned BuiltinID = FD->getBuiltinID()) {
15198 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
15199 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
15200 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15201 FD->setInvalidDecl();
15202 }
15203 }
15204
15205 // The return type of a function definition must be complete (C99 6.9.1p3),
15206 // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
15207 QualType ResultType = FD->getReturnType();
15208 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15209 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15210 RequireCompleteType(FD->getLocation(), ResultType,
15211 diag::err_func_def_incomplete_result))
15212 FD->setInvalidDecl();
15213
15214 if (FnBodyScope)
15215 PushDeclContext(FnBodyScope, FD);
15216
15217 // Check the validity of our function parameters
15218 if (BodyKind != FnBodyKind::Delete)
15219 CheckParmsForFunctionDef(FD->parameters(),
15220 /*CheckParameterNames=*/true);
15221
15222 // Add non-parameter declarations already in the function to the current
15223 // scope.
15224 if (FnBodyScope) {
15225 for (Decl *NPD : FD->decls()) {
15226 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15227 if (!NonParmDecl)
15228 continue;
15229 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15230 "parameters should not be in newly created FD yet");
15231
15232 // If the decl has a name, make it accessible in the current scope.
15233 if (NonParmDecl->getDeclName())
15234 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15235
15236 // Similarly, dive into enums and fish their constants out, making them
15237 // accessible in this scope.
15238 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15239 for (auto *EI : ED->enumerators())
15240 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15241 }
15242 }
15243 }
15244
15245 // Introduce our parameters into the function scope
15246 for (auto *Param : FD->parameters()) {
15247 Param->setOwningFunction(FD);
15248
15249 // If this has an identifier, add it to the scope stack.
15250 if (Param->getIdentifier() && FnBodyScope) {
15251 CheckShadow(FnBodyScope, Param);
15252
15253 PushOnScopeChains(Param, FnBodyScope);
15254 }
15255 }
15256
15257 // C++ [module.import/6] external definitions are not permitted in header
15258 // units. Deleted and Defaulted functions are implicitly inline (but the
15259 // inline state is not set at this point, so check the BodyKind explicitly).
15260 // FIXME: Consider an alternate location for the test where the inlined()
15261 // state is complete.
15262 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15263 !FD->isInvalidDecl() && !FD->isInlined() &&
15264 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15265 FD->getFormalLinkage() == Linkage::ExternalLinkage &&
15266 !FD->isTemplated() && !FD->isTemplateInstantiation()) {
15267 assert(FD->isThisDeclarationADefinition());
15268 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15269 FD->setInvalidDecl();
15270 }
15271
15272 // Ensure that the function's exception specification is instantiated.
15273 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15274 ResolveExceptionSpec(D->getLocation(), FPT);
15275
15276 // dllimport cannot be applied to non-inline function definitions.
15277 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15278 !FD->isTemplateInstantiation()) {
15279 assert(!FD->hasAttr<DLLExportAttr>());
15280 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15281 FD->setInvalidDecl();
15282 return D;
15283 }
15284 // We want to attach documentation to original Decl (which might be
15285 // a function template).
15286 ActOnDocumentableDecl(D);
15287 if (getCurLexicalContext()->isObjCContainer() &&
15288 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15289 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15290 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15291
15292 return D;
15293 }
15294
15295 /// Given the set of return statements within a function body,
15296 /// compute the variables that are subject to the named return value
15297 /// optimization.
15298 ///
15299 /// Each of the variables that is subject to the named return value
15300 /// optimization will be marked as NRVO variables in the AST, and any
15301 /// return statement that has a marked NRVO variable as its NRVO candidate can
15302 /// use the named return value optimization.
15303 ///
15304 /// This function applies a very simplistic algorithm for NRVO: if every return
15305 /// statement in the scope of a variable has the same NRVO candidate, that
15306 /// candidate is an NRVO variable.
computeNRVO(Stmt * Body,FunctionScopeInfo * Scope)15307 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
15308 ReturnStmt **Returns = Scope->Returns.data();
15309
15310 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15311 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15312 if (!NRVOCandidate->isNRVOVariable())
15313 Returns[I]->setNRVOCandidate(nullptr);
15314 }
15315 }
15316 }
15317
canDelayFunctionBody(const Declarator & D)15318 bool Sema::canDelayFunctionBody(const Declarator &D) {
15319 // We can't delay parsing the body of a constexpr function template (yet).
15320 if (D.getDeclSpec().hasConstexprSpecifier())
15321 return false;
15322
15323 // We can't delay parsing the body of a function template with a deduced
15324 // return type (yet).
15325 if (D.getDeclSpec().hasAutoTypeSpec()) {
15326 // If the placeholder introduces a non-deduced trailing return type,
15327 // we can still delay parsing it.
15328 if (D.getNumTypeObjects()) {
15329 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15330 if (Outer.Kind == DeclaratorChunk::Function &&
15331 Outer.Fun.hasTrailingReturnType()) {
15332 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15333 return Ty.isNull() || !Ty->isUndeducedType();
15334 }
15335 }
15336 return false;
15337 }
15338
15339 return true;
15340 }
15341
canSkipFunctionBody(Decl * D)15342 bool Sema::canSkipFunctionBody(Decl *D) {
15343 // We cannot skip the body of a function (or function template) which is
15344 // constexpr, since we may need to evaluate its body in order to parse the
15345 // rest of the file.
15346 // We cannot skip the body of a function with an undeduced return type,
15347 // because any callers of that function need to know the type.
15348 if (const FunctionDecl *FD = D->getAsFunction()) {
15349 if (FD->isConstexpr())
15350 return false;
15351 // We can't simply call Type::isUndeducedType here, because inside template
15352 // auto can be deduced to a dependent type, which is not considered
15353 // "undeduced".
15354 if (FD->getReturnType()->getContainedDeducedType())
15355 return false;
15356 }
15357 return Consumer.shouldSkipFunctionBody(D);
15358 }
15359
ActOnSkippedFunctionBody(Decl * Decl)15360 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
15361 if (!Decl)
15362 return nullptr;
15363 if (FunctionDecl *FD = Decl->getAsFunction())
15364 FD->setHasSkippedBody();
15365 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15366 MD->setHasSkippedBody();
15367 return Decl;
15368 }
15369
ActOnFinishFunctionBody(Decl * D,Stmt * BodyArg)15370 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
15371 return ActOnFinishFunctionBody(D, BodyArg, false);
15372 }
15373
15374 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
15375 /// body.
15376 class ExitFunctionBodyRAII {
15377 public:
ExitFunctionBodyRAII(Sema & S,bool IsLambda)15378 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
~ExitFunctionBodyRAII()15379 ~ExitFunctionBodyRAII() {
15380 if (!IsLambda)
15381 S.PopExpressionEvaluationContext();
15382 }
15383
15384 private:
15385 Sema &S;
15386 bool IsLambda = false;
15387 };
15388
diagnoseImplicitlyRetainedSelf(Sema & S)15389 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
15390 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15391
15392 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15393 if (EscapeInfo.count(BD))
15394 return EscapeInfo[BD];
15395
15396 bool R = false;
15397 const BlockDecl *CurBD = BD;
15398
15399 do {
15400 R = !CurBD->doesNotEscape();
15401 if (R)
15402 break;
15403 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15404 } while (CurBD);
15405
15406 return EscapeInfo[BD] = R;
15407 };
15408
15409 // If the location where 'self' is implicitly retained is inside a escaping
15410 // block, emit a diagnostic.
15411 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15412 S.ImplicitlyRetainedSelfLocs)
15413 if (IsOrNestedInEscapingBlock(P.second))
15414 S.Diag(P.first, diag::warn_implicitly_retains_self)
15415 << FixItHint::CreateInsertion(P.first, "self->");
15416 }
15417
ActOnFinishFunctionBody(Decl * dcl,Stmt * Body,bool IsInstantiation)15418 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
15419 bool IsInstantiation) {
15420 FunctionScopeInfo *FSI = getCurFunction();
15421 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15422
15423 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15424 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15425
15426 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15427 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15428
15429 if (getLangOpts().Coroutines && FSI->isCoroutine())
15430 CheckCompletedCoroutineBody(FD, Body);
15431
15432 {
15433 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15434 // one is already popped when finishing the lambda in BuildLambdaExpr().
15435 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15436 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15437
15438 if (FD) {
15439 FD->setBody(Body);
15440 FD->setWillHaveBody(false);
15441
15442 if (getLangOpts().CPlusPlus14) {
15443 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15444 FD->getReturnType()->isUndeducedType()) {
15445 // For a function with a deduced result type to return void,
15446 // the result type as written must be 'auto' or 'decltype(auto)',
15447 // possibly cv-qualified or constrained, but not ref-qualified.
15448 if (!FD->getReturnType()->getAs<AutoType>()) {
15449 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15450 << FD->getReturnType();
15451 FD->setInvalidDecl();
15452 } else {
15453 // Falling off the end of the function is the same as 'return;'.
15454 Expr *Dummy = nullptr;
15455 if (DeduceFunctionTypeFromReturnExpr(
15456 FD, dcl->getLocation(), Dummy,
15457 FD->getReturnType()->getAs<AutoType>()))
15458 FD->setInvalidDecl();
15459 }
15460 }
15461 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
15462 // In C++11, we don't use 'auto' deduction rules for lambda call
15463 // operators because we don't support return type deduction.
15464 auto *LSI = getCurLambda();
15465 if (LSI->HasImplicitReturnType) {
15466 deduceClosureReturnType(*LSI);
15467
15468 // C++11 [expr.prim.lambda]p4:
15469 // [...] if there are no return statements in the compound-statement
15470 // [the deduced type is] the type void
15471 QualType RetType =
15472 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15473
15474 // Update the return type to the deduced type.
15475 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15476 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15477 Proto->getExtProtoInfo()));
15478 }
15479 }
15480
15481 // If the function implicitly returns zero (like 'main') or is naked,
15482 // don't complain about missing return statements.
15483 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15484 WP.disableCheckFallThrough();
15485
15486 // MSVC permits the use of pure specifier (=0) on function definition,
15487 // defined at class scope, warn about this non-standard construct.
15488 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
15489 Diag(FD->getLocation(), diag::ext_pure_function_definition);
15490
15491 if (!FD->isInvalidDecl()) {
15492 // Don't diagnose unused parameters of defaulted, deleted or naked
15493 // functions.
15494 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15495 !FD->hasAttr<NakedAttr>())
15496 DiagnoseUnusedParameters(FD->parameters());
15497 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
15498 FD->getReturnType(), FD);
15499
15500 // If this is a structor, we need a vtable.
15501 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15502 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15503 else if (CXXDestructorDecl *Destructor =
15504 dyn_cast<CXXDestructorDecl>(FD))
15505 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15506
15507 // Try to apply the named return value optimization. We have to check
15508 // if we can do this here because lambdas keep return statements around
15509 // to deduce an implicit return type.
15510 if (FD->getReturnType()->isRecordType() &&
15511 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15512 computeNRVO(Body, FSI);
15513 }
15514
15515 // GNU warning -Wmissing-prototypes:
15516 // Warn if a global function is defined without a previous
15517 // prototype declaration. This warning is issued even if the
15518 // definition itself provides a prototype. The aim is to detect
15519 // global functions that fail to be declared in header files.
15520 const FunctionDecl *PossiblePrototype = nullptr;
15521 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15522 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15523
15524 if (PossiblePrototype) {
15525 // We found a declaration that is not a prototype,
15526 // but that could be a zero-parameter prototype
15527 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15528 TypeLoc TL = TI->getTypeLoc();
15529 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15530 Diag(PossiblePrototype->getLocation(),
15531 diag::note_declaration_not_a_prototype)
15532 << (FD->getNumParams() != 0)
15533 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15534 FTL.getRParenLoc(), "void")
15535 : FixItHint{});
15536 }
15537 } else {
15538 // Returns true if the token beginning at this Loc is `const`.
15539 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15540 const LangOptions &LangOpts) {
15541 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15542 if (LocInfo.first.isInvalid())
15543 return false;
15544
15545 bool Invalid = false;
15546 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15547 if (Invalid)
15548 return false;
15549
15550 if (LocInfo.second > Buffer.size())
15551 return false;
15552
15553 const char *LexStart = Buffer.data() + LocInfo.second;
15554 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15555
15556 return StartTok.consume_front("const") &&
15557 (StartTok.empty() || isWhitespace(StartTok[0]) ||
15558 StartTok.startswith("/*") || StartTok.startswith("//"));
15559 };
15560
15561 auto findBeginLoc = [&]() {
15562 // If the return type has `const` qualifier, we want to insert
15563 // `static` before `const` (and not before the typename).
15564 if ((FD->getReturnType()->isAnyPointerType() &&
15565 FD->getReturnType()->getPointeeType().isConstQualified()) ||
15566 FD->getReturnType().isConstQualified()) {
15567 // But only do this if we can determine where the `const` is.
15568
15569 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15570 getLangOpts()))
15571
15572 return FD->getBeginLoc();
15573 }
15574 return FD->getTypeSpecStartLoc();
15575 };
15576 Diag(FD->getTypeSpecStartLoc(),
15577 diag::note_static_for_internal_linkage)
15578 << /* function */ 1
15579 << (FD->getStorageClass() == SC_None
15580 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15581 : FixItHint{});
15582 }
15583 }
15584
15585 // We might not have found a prototype because we didn't wish to warn on
15586 // the lack of a missing prototype. Try again without the checks for
15587 // whether we want to warn on the missing prototype.
15588 if (!PossiblePrototype)
15589 (void)FindPossiblePrototype(FD, PossiblePrototype);
15590
15591 // If the function being defined does not have a prototype, then we may
15592 // need to diagnose it as changing behavior in C2x because we now know
15593 // whether the function accepts arguments or not. This only handles the
15594 // case where the definition has no prototype but does have parameters
15595 // and either there is no previous potential prototype, or the previous
15596 // potential prototype also has no actual prototype. This handles cases
15597 // like:
15598 // void f(); void f(a) int a; {}
15599 // void g(a) int a; {}
15600 // See MergeFunctionDecl() for other cases of the behavior change
15601 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15602 // type without a prototype.
15603 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15604 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15605 !PossiblePrototype->isImplicit()))) {
15606 // The function definition has parameters, so this will change behavior
15607 // in C2x. If there is a possible prototype, it comes before the
15608 // function definition.
15609 // FIXME: The declaration may have already been diagnosed as being
15610 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15611 // there's no way to test for the "changes behavior" condition in
15612 // SemaType.cpp when forming the declaration's function type. So, we do
15613 // this awkward dance instead.
15614 //
15615 // If we have a possible prototype and it declares a function with a
15616 // prototype, we don't want to diagnose it; if we have a possible
15617 // prototype and it has no prototype, it may have already been
15618 // diagnosed in SemaType.cpp as deprecated depending on whether
15619 // -Wstrict-prototypes is enabled. If we already warned about it being
15620 // deprecated, add a note that it also changes behavior. If we didn't
15621 // warn about it being deprecated (because the diagnostic is not
15622 // enabled), warn now that it is deprecated and changes behavior.
15623
15624 // This K&R C function definition definitely changes behavior in C2x,
15625 // so diagnose it.
15626 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15627 << /*definition*/ 1 << /* not supported in C2x */ 0;
15628
15629 // If we have a possible prototype for the function which is a user-
15630 // visible declaration, we already tested that it has no prototype.
15631 // This will change behavior in C2x. This gets a warning rather than a
15632 // note because it's the same behavior-changing problem as with the
15633 // definition.
15634 if (PossiblePrototype)
15635 Diag(PossiblePrototype->getLocation(),
15636 diag::warn_non_prototype_changes_behavior)
15637 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15638 << /*definition*/ 1;
15639 }
15640
15641 // Warn on CPUDispatch with an actual body.
15642 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15643 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15644 if (!CmpndBody->body_empty())
15645 Diag(CmpndBody->body_front()->getBeginLoc(),
15646 diag::warn_dispatch_body_ignored);
15647
15648 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15649 const CXXMethodDecl *KeyFunction;
15650 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15651 MD->isVirtual() &&
15652 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15653 MD == KeyFunction->getCanonicalDecl()) {
15654 // Update the key-function state if necessary for this ABI.
15655 if (FD->isInlined() &&
15656 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15657 Context.setNonKeyFunction(MD);
15658
15659 // If the newly-chosen key function is already defined, then we
15660 // need to mark the vtable as used retroactively.
15661 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15662 const FunctionDecl *Definition;
15663 if (KeyFunction && KeyFunction->isDefined(Definition))
15664 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15665 } else {
15666 // We just defined they key function; mark the vtable as used.
15667 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15668 }
15669 }
15670 }
15671
15672 assert(
15673 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15674 "Function parsing confused");
15675 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15676 assert(MD == getCurMethodDecl() && "Method parsing confused");
15677 MD->setBody(Body);
15678 if (!MD->isInvalidDecl()) {
15679 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15680 MD->getReturnType(), MD);
15681
15682 if (Body)
15683 computeNRVO(Body, FSI);
15684 }
15685 if (FSI->ObjCShouldCallSuper) {
15686 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15687 << MD->getSelector().getAsString();
15688 FSI->ObjCShouldCallSuper = false;
15689 }
15690 if (FSI->ObjCWarnForNoDesignatedInitChain) {
15691 const ObjCMethodDecl *InitMethod = nullptr;
15692 bool isDesignated =
15693 MD->isDesignatedInitializerForTheInterface(&InitMethod);
15694 assert(isDesignated && InitMethod);
15695 (void)isDesignated;
15696
15697 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15698 auto IFace = MD->getClassInterface();
15699 if (!IFace)
15700 return false;
15701 auto SuperD = IFace->getSuperClass();
15702 if (!SuperD)
15703 return false;
15704 return SuperD->getIdentifier() ==
15705 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15706 };
15707 // Don't issue this warning for unavailable inits or direct subclasses
15708 // of NSObject.
15709 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15710 Diag(MD->getLocation(),
15711 diag::warn_objc_designated_init_missing_super_call);
15712 Diag(InitMethod->getLocation(),
15713 diag::note_objc_designated_init_marked_here);
15714 }
15715 FSI->ObjCWarnForNoDesignatedInitChain = false;
15716 }
15717 if (FSI->ObjCWarnForNoInitDelegation) {
15718 // Don't issue this warning for unavaialable inits.
15719 if (!MD->isUnavailable())
15720 Diag(MD->getLocation(),
15721 diag::warn_objc_secondary_init_missing_init_call);
15722 FSI->ObjCWarnForNoInitDelegation = false;
15723 }
15724
15725 diagnoseImplicitlyRetainedSelf(*this);
15726 } else {
15727 // Parsing the function declaration failed in some way. Pop the fake scope
15728 // we pushed on.
15729 PopFunctionScopeInfo(ActivePolicy, dcl);
15730 return nullptr;
15731 }
15732
15733 if (Body && FSI->HasPotentialAvailabilityViolations)
15734 DiagnoseUnguardedAvailabilityViolations(dcl);
15735
15736 assert(!FSI->ObjCShouldCallSuper &&
15737 "This should only be set for ObjC methods, which should have been "
15738 "handled in the block above.");
15739
15740 // Verify and clean out per-function state.
15741 if (Body && (!FD || !FD->isDefaulted())) {
15742 // C++ constructors that have function-try-blocks can't have return
15743 // statements in the handlers of that block. (C++ [except.handle]p14)
15744 // Verify this.
15745 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15746 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15747
15748 // Verify that gotos and switch cases don't jump into scopes illegally.
15749 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15750 DiagnoseInvalidJumps(Body);
15751
15752 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15753 if (!Destructor->getParent()->isDependentType())
15754 CheckDestructor(Destructor);
15755
15756 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15757 Destructor->getParent());
15758 }
15759
15760 // If any errors have occurred, clear out any temporaries that may have
15761 // been leftover. This ensures that these temporaries won't be picked up
15762 // for deletion in some later function.
15763 if (hasUncompilableErrorOccurred() ||
15764 getDiagnostics().getSuppressAllDiagnostics()) {
15765 DiscardCleanupsInEvaluationContext();
15766 }
15767 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15768 // Since the body is valid, issue any analysis-based warnings that are
15769 // enabled.
15770 ActivePolicy = &WP;
15771 }
15772
15773 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15774 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15775 FD->setInvalidDecl();
15776
15777 if (FD && FD->hasAttr<NakedAttr>()) {
15778 for (const Stmt *S : Body->children()) {
15779 // Allow local register variables without initializer as they don't
15780 // require prologue.
15781 bool RegisterVariables = false;
15782 if (auto *DS = dyn_cast<DeclStmt>(S)) {
15783 for (const auto *Decl : DS->decls()) {
15784 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15785 RegisterVariables =
15786 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15787 if (!RegisterVariables)
15788 break;
15789 }
15790 }
15791 }
15792 if (RegisterVariables)
15793 continue;
15794 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15795 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15796 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15797 FD->setInvalidDecl();
15798 break;
15799 }
15800 }
15801 }
15802
15803 assert(ExprCleanupObjects.size() ==
15804 ExprEvalContexts.back().NumCleanupObjects &&
15805 "Leftover temporaries in function");
15806 assert(!Cleanup.exprNeedsCleanups() &&
15807 "Unaccounted cleanups in function");
15808 assert(MaybeODRUseExprs.empty() &&
15809 "Leftover expressions for odr-use checking");
15810 }
15811 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15812 // the declaration context below. Otherwise, we're unable to transform
15813 // 'this' expressions when transforming immediate context functions.
15814
15815 if (!IsInstantiation)
15816 PopDeclContext();
15817
15818 PopFunctionScopeInfo(ActivePolicy, dcl);
15819 // If any errors have occurred, clear out any temporaries that may have
15820 // been leftover. This ensures that these temporaries won't be picked up for
15821 // deletion in some later function.
15822 if (hasUncompilableErrorOccurred()) {
15823 DiscardCleanupsInEvaluationContext();
15824 }
15825
15826 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15827 !LangOpts.OMPTargetTriples.empty())) ||
15828 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15829 auto ES = getEmissionStatus(FD);
15830 if (ES == Sema::FunctionEmissionStatus::Emitted ||
15831 ES == Sema::FunctionEmissionStatus::Unknown)
15832 DeclsToCheckForDeferredDiags.insert(FD);
15833 }
15834
15835 if (FD && !FD->isDeleted())
15836 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15837
15838 return dcl;
15839 }
15840
15841 /// When we finish delayed parsing of an attribute, we must attach it to the
15842 /// relevant Decl.
ActOnFinishDelayedAttribute(Scope * S,Decl * D,ParsedAttributes & Attrs)15843 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15844 ParsedAttributes &Attrs) {
15845 // Always attach attributes to the underlying decl.
15846 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15847 D = TD->getTemplatedDecl();
15848 ProcessDeclAttributeList(S, D, Attrs);
15849
15850 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15851 if (Method->isStatic())
15852 checkThisInStaticMemberFunctionAttributes(Method);
15853 }
15854
15855 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15856 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
ImplicitlyDefineFunction(SourceLocation Loc,IdentifierInfo & II,Scope * S)15857 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15858 IdentifierInfo &II, Scope *S) {
15859 // It is not valid to implicitly define a function in C2x.
15860 assert(LangOpts.implicitFunctionsAllowed() &&
15861 "Implicit function declarations aren't allowed in this language mode");
15862
15863 // Find the scope in which the identifier is injected and the corresponding
15864 // DeclContext.
15865 // FIXME: C89 does not say what happens if there is no enclosing block scope.
15866 // In that case, we inject the declaration into the translation unit scope
15867 // instead.
15868 Scope *BlockScope = S;
15869 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15870 BlockScope = BlockScope->getParent();
15871
15872 Scope *ContextScope = BlockScope;
15873 while (!ContextScope->getEntity())
15874 ContextScope = ContextScope->getParent();
15875 ContextRAII SavedContext(*this, ContextScope->getEntity());
15876
15877 // Before we produce a declaration for an implicitly defined
15878 // function, see whether there was a locally-scoped declaration of
15879 // this name as a function or variable. If so, use that
15880 // (non-visible) declaration, and complain about it.
15881 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15882 if (ExternCPrev) {
15883 // We still need to inject the function into the enclosing block scope so
15884 // that later (non-call) uses can see it.
15885 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15886
15887 // C89 footnote 38:
15888 // If in fact it is not defined as having type "function returning int",
15889 // the behavior is undefined.
15890 if (!isa<FunctionDecl>(ExternCPrev) ||
15891 !Context.typesAreCompatible(
15892 cast<FunctionDecl>(ExternCPrev)->getType(),
15893 Context.getFunctionNoProtoType(Context.IntTy))) {
15894 Diag(Loc, diag::ext_use_out_of_scope_declaration)
15895 << ExternCPrev << !getLangOpts().C99;
15896 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15897 return ExternCPrev;
15898 }
15899 }
15900
15901 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15902 unsigned diag_id;
15903 if (II.getName().startswith("__builtin_"))
15904 diag_id = diag::warn_builtin_unknown;
15905 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15906 else if (getLangOpts().C99)
15907 diag_id = diag::ext_implicit_function_decl_c99;
15908 else
15909 diag_id = diag::warn_implicit_function_decl;
15910
15911 TypoCorrection Corrected;
15912 // Because typo correction is expensive, only do it if the implicit
15913 // function declaration is going to be treated as an error.
15914 //
15915 // Perform the correction before issuing the main diagnostic, as some
15916 // consumers use typo-correction callbacks to enhance the main diagnostic.
15917 if (S && !ExternCPrev &&
15918 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15919 DeclFilterCCC<FunctionDecl> CCC{};
15920 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15921 S, nullptr, CCC, CTK_NonError);
15922 }
15923
15924 Diag(Loc, diag_id) << &II;
15925 if (Corrected) {
15926 // If the correction is going to suggest an implicitly defined function,
15927 // skip the correction as not being a particularly good idea.
15928 bool Diagnose = true;
15929 if (const auto *D = Corrected.getCorrectionDecl())
15930 Diagnose = !D->isImplicit();
15931 if (Diagnose)
15932 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15933 /*ErrorRecovery*/ false);
15934 }
15935
15936 // If we found a prior declaration of this function, don't bother building
15937 // another one. We've already pushed that one into scope, so there's nothing
15938 // more to do.
15939 if (ExternCPrev)
15940 return ExternCPrev;
15941
15942 // Set a Declarator for the implicit definition: int foo();
15943 const char *Dummy;
15944 AttributeFactory attrFactory;
15945 DeclSpec DS(attrFactory);
15946 unsigned DiagID;
15947 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15948 Context.getPrintingPolicy());
15949 (void)Error; // Silence warning.
15950 assert(!Error && "Error setting up implicit decl!");
15951 SourceLocation NoLoc;
15952 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
15953 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15954 /*IsAmbiguous=*/false,
15955 /*LParenLoc=*/NoLoc,
15956 /*Params=*/nullptr,
15957 /*NumParams=*/0,
15958 /*EllipsisLoc=*/NoLoc,
15959 /*RParenLoc=*/NoLoc,
15960 /*RefQualifierIsLvalueRef=*/true,
15961 /*RefQualifierLoc=*/NoLoc,
15962 /*MutableLoc=*/NoLoc, EST_None,
15963 /*ESpecRange=*/SourceRange(),
15964 /*Exceptions=*/nullptr,
15965 /*ExceptionRanges=*/nullptr,
15966 /*NumExceptions=*/0,
15967 /*NoexceptExpr=*/nullptr,
15968 /*ExceptionSpecTokens=*/nullptr,
15969 /*DeclsInPrototype=*/std::nullopt,
15970 Loc, Loc, D),
15971 std::move(DS.getAttributes()), SourceLocation());
15972 D.SetIdentifier(&II, Loc);
15973
15974 // Insert this function into the enclosing block scope.
15975 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15976 FD->setImplicit();
15977
15978 AddKnownFunctionAttributes(FD);
15979
15980 return FD;
15981 }
15982
15983 /// If this function is a C++ replaceable global allocation function
15984 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15985 /// adds any function attributes that we know a priori based on the standard.
15986 ///
15987 /// We need to check for duplicate attributes both here and where user-written
15988 /// attributes are applied to declarations.
AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl * FD)15989 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15990 FunctionDecl *FD) {
15991 if (FD->isInvalidDecl())
15992 return;
15993
15994 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15995 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15996 return;
15997
15998 std::optional<unsigned> AlignmentParam;
15999 bool IsNothrow = false;
16000 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16001 return;
16002
16003 // C++2a [basic.stc.dynamic.allocation]p4:
16004 // An allocation function that has a non-throwing exception specification
16005 // indicates failure by returning a null pointer value. Any other allocation
16006 // function never returns a null pointer value and indicates failure only by
16007 // throwing an exception [...]
16008 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
16009 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16010
16011 // C++2a [basic.stc.dynamic.allocation]p2:
16012 // An allocation function attempts to allocate the requested amount of
16013 // storage. [...] If the request succeeds, the value returned by a
16014 // replaceable allocation function is a [...] pointer value p0 different
16015 // from any previously returned value p1 [...]
16016 //
16017 // However, this particular information is being added in codegen,
16018 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16019
16020 // C++2a [basic.stc.dynamic.allocation]p2:
16021 // An allocation function attempts to allocate the requested amount of
16022 // storage. If it is successful, it returns the address of the start of a
16023 // block of storage whose length in bytes is at least as large as the
16024 // requested size.
16025 if (!FD->hasAttr<AllocSizeAttr>()) {
16026 FD->addAttr(AllocSizeAttr::CreateImplicit(
16027 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16028 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16029 }
16030
16031 // C++2a [basic.stc.dynamic.allocation]p3:
16032 // For an allocation function [...], the pointer returned on a successful
16033 // call shall represent the address of storage that is aligned as follows:
16034 // (3.1) If the allocation function takes an argument of type
16035 // std::align_val_t, the storage will have the alignment
16036 // specified by the value of this argument.
16037 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16038 FD->addAttr(AllocAlignAttr::CreateImplicit(
16039 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16040 }
16041
16042 // FIXME:
16043 // C++2a [basic.stc.dynamic.allocation]p3:
16044 // For an allocation function [...], the pointer returned on a successful
16045 // call shall represent the address of storage that is aligned as follows:
16046 // (3.2) Otherwise, if the allocation function is named operator new[],
16047 // the storage is aligned for any object that does not have
16048 // new-extended alignment ([basic.align]) and is no larger than the
16049 // requested size.
16050 // (3.3) Otherwise, the storage is aligned for any object that does not
16051 // have new-extended alignment and is of the requested size.
16052 }
16053
16054 /// Adds any function attributes that we know a priori based on
16055 /// the declaration of this function.
16056 ///
16057 /// These attributes can apply both to implicitly-declared builtins
16058 /// (like __builtin___printf_chk) or to library-declared functions
16059 /// like NSLog or printf.
16060 ///
16061 /// We need to check for duplicate attributes both here and where user-written
16062 /// attributes are applied to declarations.
AddKnownFunctionAttributes(FunctionDecl * FD)16063 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16064 if (FD->isInvalidDecl())
16065 return;
16066
16067 // If this is a built-in function, map its builtin attributes to
16068 // actual attributes.
16069 if (unsigned BuiltinID = FD->getBuiltinID()) {
16070 // Handle printf-formatting attributes.
16071 unsigned FormatIdx;
16072 bool HasVAListArg;
16073 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16074 if (!FD->hasAttr<FormatAttr>()) {
16075 const char *fmt = "printf";
16076 unsigned int NumParams = FD->getNumParams();
16077 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16078 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16079 fmt = "NSString";
16080 FD->addAttr(FormatAttr::CreateImplicit(Context,
16081 &Context.Idents.get(fmt),
16082 FormatIdx+1,
16083 HasVAListArg ? 0 : FormatIdx+2,
16084 FD->getLocation()));
16085 }
16086 }
16087 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16088 HasVAListArg)) {
16089 if (!FD->hasAttr<FormatAttr>())
16090 FD->addAttr(FormatAttr::CreateImplicit(Context,
16091 &Context.Idents.get("scanf"),
16092 FormatIdx+1,
16093 HasVAListArg ? 0 : FormatIdx+2,
16094 FD->getLocation()));
16095 }
16096
16097 // Handle automatically recognized callbacks.
16098 SmallVector<int, 4> Encoding;
16099 if (!FD->hasAttr<CallbackAttr>() &&
16100 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16101 FD->addAttr(CallbackAttr::CreateImplicit(
16102 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16103
16104 // Mark const if we don't care about errno and/or floating point exceptions
16105 // that are the only thing preventing the function from being const. This
16106 // allows IRgen to use LLVM intrinsics for such functions.
16107 bool NoExceptions =
16108 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16109 bool ConstWithoutErrnoAndExceptions =
16110 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
16111 bool ConstWithoutExceptions =
16112 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
16113 if (!FD->hasAttr<ConstAttr>() &&
16114 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16115 (!ConstWithoutErrnoAndExceptions ||
16116 (!getLangOpts().MathErrno && NoExceptions)) &&
16117 (!ConstWithoutExceptions || NoExceptions))
16118 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16119
16120 // We make "fma" on GNU or Windows const because we know it does not set
16121 // errno in those environments even though it could set errno based on the
16122 // C standard.
16123 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16124 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16125 !FD->hasAttr<ConstAttr>()) {
16126 switch (BuiltinID) {
16127 case Builtin::BI__builtin_fma:
16128 case Builtin::BI__builtin_fmaf:
16129 case Builtin::BI__builtin_fmal:
16130 case Builtin::BIfma:
16131 case Builtin::BIfmaf:
16132 case Builtin::BIfmal:
16133 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16134 break;
16135 default:
16136 break;
16137 }
16138 }
16139
16140 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16141 !FD->hasAttr<ReturnsTwiceAttr>())
16142 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16143 FD->getLocation()));
16144 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16145 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16146 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16147 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16148 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16149 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16150 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16151 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16152 // Add the appropriate attribute, depending on the CUDA compilation mode
16153 // and which target the builtin belongs to. For example, during host
16154 // compilation, aux builtins are __device__, while the rest are __host__.
16155 if (getLangOpts().CUDAIsDevice !=
16156 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16157 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16158 else
16159 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16160 }
16161
16162 // Add known guaranteed alignment for allocation functions.
16163 switch (BuiltinID) {
16164 case Builtin::BImemalign:
16165 case Builtin::BIaligned_alloc:
16166 if (!FD->hasAttr<AllocAlignAttr>())
16167 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16168 FD->getLocation()));
16169 break;
16170 default:
16171 break;
16172 }
16173
16174 // Add allocsize attribute for allocation functions.
16175 switch (BuiltinID) {
16176 case Builtin::BIcalloc:
16177 FD->addAttr(AllocSizeAttr::CreateImplicit(
16178 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16179 break;
16180 case Builtin::BImemalign:
16181 case Builtin::BIaligned_alloc:
16182 case Builtin::BIrealloc:
16183 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16184 ParamIdx(), FD->getLocation()));
16185 break;
16186 case Builtin::BImalloc:
16187 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16188 ParamIdx(), FD->getLocation()));
16189 break;
16190 default:
16191 break;
16192 }
16193
16194 // Add lifetime attribute to std::move, std::fowrard et al.
16195 switch (BuiltinID) {
16196 case Builtin::BIaddressof:
16197 case Builtin::BI__addressof:
16198 case Builtin::BI__builtin_addressof:
16199 case Builtin::BIas_const:
16200 case Builtin::BIforward:
16201 case Builtin::BImove:
16202 case Builtin::BImove_if_noexcept:
16203 if (ParmVarDecl *P = FD->getParamDecl(0u);
16204 !P->hasAttr<LifetimeBoundAttr>())
16205 P->addAttr(
16206 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16207 break;
16208 default:
16209 break;
16210 }
16211 }
16212
16213 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16214
16215 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16216 // throw, add an implicit nothrow attribute to any extern "C" function we come
16217 // across.
16218 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16219 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16220 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16221 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16222 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16223 }
16224
16225 IdentifierInfo *Name = FD->getIdentifier();
16226 if (!Name)
16227 return;
16228 if ((!getLangOpts().CPlusPlus &&
16229 FD->getDeclContext()->isTranslationUnit()) ||
16230 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16231 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16232 LinkageSpecDecl::lang_c)) {
16233 // Okay: this could be a libc/libm/Objective-C function we know
16234 // about.
16235 } else
16236 return;
16237
16238 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16239 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16240 // target-specific builtins, perhaps?
16241 if (!FD->hasAttr<FormatAttr>())
16242 FD->addAttr(FormatAttr::CreateImplicit(Context,
16243 &Context.Idents.get("printf"), 2,
16244 Name->isStr("vasprintf") ? 0 : 3,
16245 FD->getLocation()));
16246 }
16247
16248 if (Name->isStr("__CFStringMakeConstantString")) {
16249 // We already have a __builtin___CFStringMakeConstantString,
16250 // but builds that use -fno-constant-cfstrings don't go through that.
16251 if (!FD->hasAttr<FormatArgAttr>())
16252 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16253 FD->getLocation()));
16254 }
16255 }
16256
ParseTypedefDecl(Scope * S,Declarator & D,QualType T,TypeSourceInfo * TInfo)16257 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
16258 TypeSourceInfo *TInfo) {
16259 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16260 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16261
16262 if (!TInfo) {
16263 assert(D.isInvalidType() && "no declarator info for valid type");
16264 TInfo = Context.getTrivialTypeSourceInfo(T);
16265 }
16266
16267 // Scope manipulation handled by caller.
16268 TypedefDecl *NewTD =
16269 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
16270 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16271
16272 // Bail out immediately if we have an invalid declaration.
16273 if (D.isInvalidType()) {
16274 NewTD->setInvalidDecl();
16275 return NewTD;
16276 }
16277
16278 if (D.getDeclSpec().isModulePrivateSpecified()) {
16279 if (CurContext->isFunctionOrMethod())
16280 Diag(NewTD->getLocation(), diag::err_module_private_local)
16281 << 2 << NewTD
16282 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16283 << FixItHint::CreateRemoval(
16284 D.getDeclSpec().getModulePrivateSpecLoc());
16285 else
16286 NewTD->setModulePrivate();
16287 }
16288
16289 // C++ [dcl.typedef]p8:
16290 // If the typedef declaration defines an unnamed class (or
16291 // enum), the first typedef-name declared by the declaration
16292 // to be that class type (or enum type) is used to denote the
16293 // class type (or enum type) for linkage purposes only.
16294 // We need to check whether the type was declared in the declaration.
16295 switch (D.getDeclSpec().getTypeSpecType()) {
16296 case TST_enum:
16297 case TST_struct:
16298 case TST_interface:
16299 case TST_union:
16300 case TST_class: {
16301 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16302 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16303 break;
16304 }
16305
16306 default:
16307 break;
16308 }
16309
16310 return NewTD;
16311 }
16312
16313 /// Check that this is a valid underlying type for an enum declaration.
CheckEnumUnderlyingType(TypeSourceInfo * TI)16314 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
16315 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16316 QualType T = TI->getType();
16317
16318 if (T->isDependentType())
16319 return false;
16320
16321 // This doesn't use 'isIntegralType' despite the error message mentioning
16322 // integral type because isIntegralType would also allow enum types in C.
16323 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16324 if (BT->isInteger())
16325 return false;
16326
16327 if (T->isBitIntType())
16328 return false;
16329
16330 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
16331 }
16332
16333 /// Check whether this is a valid redeclaration of a previous enumeration.
16334 /// \return true if the redeclaration was invalid.
CheckEnumRedeclaration(SourceLocation EnumLoc,bool IsScoped,QualType EnumUnderlyingTy,bool IsFixed,const EnumDecl * Prev)16335 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
16336 QualType EnumUnderlyingTy, bool IsFixed,
16337 const EnumDecl *Prev) {
16338 if (IsScoped != Prev->isScoped()) {
16339 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16340 << Prev->isScoped();
16341 Diag(Prev->getLocation(), diag::note_previous_declaration);
16342 return true;
16343 }
16344
16345 if (IsFixed && Prev->isFixed()) {
16346 if (!EnumUnderlyingTy->isDependentType() &&
16347 !Prev->getIntegerType()->isDependentType() &&
16348 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16349 Prev->getIntegerType())) {
16350 // TODO: Highlight the underlying type of the redeclaration.
16351 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16352 << EnumUnderlyingTy << Prev->getIntegerType();
16353 Diag(Prev->getLocation(), diag::note_previous_declaration)
16354 << Prev->getIntegerTypeRange();
16355 return true;
16356 }
16357 } else if (IsFixed != Prev->isFixed()) {
16358 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16359 << Prev->isFixed();
16360 Diag(Prev->getLocation(), diag::note_previous_declaration);
16361 return true;
16362 }
16363
16364 return false;
16365 }
16366
16367 /// Get diagnostic %select index for tag kind for
16368 /// redeclaration diagnostic message.
16369 /// WARNING: Indexes apply to particular diagnostics only!
16370 ///
16371 /// \returns diagnostic %select index.
getRedeclDiagFromTagKind(TagTypeKind Tag)16372 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
16373 switch (Tag) {
16374 case TTK_Struct: return 0;
16375 case TTK_Interface: return 1;
16376 case TTK_Class: return 2;
16377 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16378 }
16379 }
16380
16381 /// Determine if tag kind is a class-key compatible with
16382 /// class for redeclaration (class, struct, or __interface).
16383 ///
16384 /// \returns true iff the tag kind is compatible.
isClassCompatTagKind(TagTypeKind Tag)16385 static bool isClassCompatTagKind(TagTypeKind Tag)
16386 {
16387 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
16388 }
16389
getNonTagTypeDeclKind(const Decl * PrevDecl,TagTypeKind TTK)16390 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
16391 TagTypeKind TTK) {
16392 if (isa<TypedefDecl>(PrevDecl))
16393 return NTK_Typedef;
16394 else if (isa<TypeAliasDecl>(PrevDecl))
16395 return NTK_TypeAlias;
16396 else if (isa<ClassTemplateDecl>(PrevDecl))
16397 return NTK_Template;
16398 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16399 return NTK_TypeAliasTemplate;
16400 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16401 return NTK_TemplateTemplateArgument;
16402 switch (TTK) {
16403 case TTK_Struct:
16404 case TTK_Interface:
16405 case TTK_Class:
16406 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16407 case TTK_Union:
16408 return NTK_NonUnion;
16409 case TTK_Enum:
16410 return NTK_NonEnum;
16411 }
16412 llvm_unreachable("invalid TTK");
16413 }
16414
16415 /// Determine whether a tag with a given kind is acceptable
16416 /// as a redeclaration of the given tag declaration.
16417 ///
16418 /// \returns true if the new tag kind is acceptable, false otherwise.
isAcceptableTagRedeclaration(const TagDecl * Previous,TagTypeKind NewTag,bool isDefinition,SourceLocation NewTagLoc,const IdentifierInfo * Name)16419 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
16420 TagTypeKind NewTag, bool isDefinition,
16421 SourceLocation NewTagLoc,
16422 const IdentifierInfo *Name) {
16423 // C++ [dcl.type.elab]p3:
16424 // The class-key or enum keyword present in the
16425 // elaborated-type-specifier shall agree in kind with the
16426 // declaration to which the name in the elaborated-type-specifier
16427 // refers. This rule also applies to the form of
16428 // elaborated-type-specifier that declares a class-name or
16429 // friend class since it can be construed as referring to the
16430 // definition of the class. Thus, in any
16431 // elaborated-type-specifier, the enum keyword shall be used to
16432 // refer to an enumeration (7.2), the union class-key shall be
16433 // used to refer to a union (clause 9), and either the class or
16434 // struct class-key shall be used to refer to a class (clause 9)
16435 // declared using the class or struct class-key.
16436 TagTypeKind OldTag = Previous->getTagKind();
16437 if (OldTag != NewTag &&
16438 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16439 return false;
16440
16441 // Tags are compatible, but we might still want to warn on mismatched tags.
16442 // Non-class tags can't be mismatched at this point.
16443 if (!isClassCompatTagKind(NewTag))
16444 return true;
16445
16446 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16447 // by our warning analysis. We don't want to warn about mismatches with (eg)
16448 // declarations in system headers that are designed to be specialized, but if
16449 // a user asks us to warn, we should warn if their code contains mismatched
16450 // declarations.
16451 auto IsIgnoredLoc = [&](SourceLocation Loc) {
16452 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16453 Loc);
16454 };
16455 if (IsIgnoredLoc(NewTagLoc))
16456 return true;
16457
16458 auto IsIgnored = [&](const TagDecl *Tag) {
16459 return IsIgnoredLoc(Tag->getLocation());
16460 };
16461 while (IsIgnored(Previous)) {
16462 Previous = Previous->getPreviousDecl();
16463 if (!Previous)
16464 return true;
16465 OldTag = Previous->getTagKind();
16466 }
16467
16468 bool isTemplate = false;
16469 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16470 isTemplate = Record->getDescribedClassTemplate();
16471
16472 if (inTemplateInstantiation()) {
16473 if (OldTag != NewTag) {
16474 // In a template instantiation, do not offer fix-its for tag mismatches
16475 // since they usually mess up the template instead of fixing the problem.
16476 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16477 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16478 << getRedeclDiagFromTagKind(OldTag);
16479 // FIXME: Note previous location?
16480 }
16481 return true;
16482 }
16483
16484 if (isDefinition) {
16485 // On definitions, check all previous tags and issue a fix-it for each
16486 // one that doesn't match the current tag.
16487 if (Previous->getDefinition()) {
16488 // Don't suggest fix-its for redefinitions.
16489 return true;
16490 }
16491
16492 bool previousMismatch = false;
16493 for (const TagDecl *I : Previous->redecls()) {
16494 if (I->getTagKind() != NewTag) {
16495 // Ignore previous declarations for which the warning was disabled.
16496 if (IsIgnored(I))
16497 continue;
16498
16499 if (!previousMismatch) {
16500 previousMismatch = true;
16501 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16502 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16503 << getRedeclDiagFromTagKind(I->getTagKind());
16504 }
16505 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16506 << getRedeclDiagFromTagKind(NewTag)
16507 << FixItHint::CreateReplacement(I->getInnerLocStart(),
16508 TypeWithKeyword::getTagTypeKindName(NewTag));
16509 }
16510 }
16511 return true;
16512 }
16513
16514 // Identify the prevailing tag kind: this is the kind of the definition (if
16515 // there is a non-ignored definition), or otherwise the kind of the prior
16516 // (non-ignored) declaration.
16517 const TagDecl *PrevDef = Previous->getDefinition();
16518 if (PrevDef && IsIgnored(PrevDef))
16519 PrevDef = nullptr;
16520 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16521 if (Redecl->getTagKind() != NewTag) {
16522 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16523 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16524 << getRedeclDiagFromTagKind(OldTag);
16525 Diag(Redecl->getLocation(), diag::note_previous_use);
16526
16527 // If there is a previous definition, suggest a fix-it.
16528 if (PrevDef) {
16529 Diag(NewTagLoc, diag::note_struct_class_suggestion)
16530 << getRedeclDiagFromTagKind(Redecl->getTagKind())
16531 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
16532 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
16533 }
16534 }
16535
16536 return true;
16537 }
16538
16539 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16540 /// from an outer enclosing namespace or file scope inside a friend declaration.
16541 /// This should provide the commented out code in the following snippet:
16542 /// namespace N {
16543 /// struct X;
16544 /// namespace M {
16545 /// struct Y { friend struct /*N::*/ X; };
16546 /// }
16547 /// }
createFriendTagNNSFixIt(Sema & SemaRef,NamedDecl * ND,Scope * S,SourceLocation NameLoc)16548 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
16549 SourceLocation NameLoc) {
16550 // While the decl is in a namespace, do repeated lookup of that name and see
16551 // if we get the same namespace back. If we do not, continue until
16552 // translation unit scope, at which point we have a fully qualified NNS.
16553 SmallVector<IdentifierInfo *, 4> Namespaces;
16554 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16555 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16556 // This tag should be declared in a namespace, which can only be enclosed by
16557 // other namespaces. Bail if there's an anonymous namespace in the chain.
16558 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16559 if (!Namespace || Namespace->isAnonymousNamespace())
16560 return FixItHint();
16561 IdentifierInfo *II = Namespace->getIdentifier();
16562 Namespaces.push_back(II);
16563 NamedDecl *Lookup = SemaRef.LookupSingleName(
16564 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16565 if (Lookup == Namespace)
16566 break;
16567 }
16568
16569 // Once we have all the namespaces, reverse them to go outermost first, and
16570 // build an NNS.
16571 SmallString<64> Insertion;
16572 llvm::raw_svector_ostream OS(Insertion);
16573 if (DC->isTranslationUnit())
16574 OS << "::";
16575 std::reverse(Namespaces.begin(), Namespaces.end());
16576 for (auto *II : Namespaces)
16577 OS << II->getName() << "::";
16578 return FixItHint::CreateInsertion(NameLoc, Insertion);
16579 }
16580
16581 /// Determine whether a tag originally declared in context \p OldDC can
16582 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16583 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16584 /// using-declaration).
isAcceptableTagRedeclContext(Sema & S,DeclContext * OldDC,DeclContext * NewDC)16585 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
16586 DeclContext *NewDC) {
16587 OldDC = OldDC->getRedeclContext();
16588 NewDC = NewDC->getRedeclContext();
16589
16590 if (OldDC->Equals(NewDC))
16591 return true;
16592
16593 // In MSVC mode, we allow a redeclaration if the contexts are related (either
16594 // encloses the other).
16595 if (S.getLangOpts().MSVCCompat &&
16596 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16597 return true;
16598
16599 return false;
16600 }
16601
16602 /// This is invoked when we see 'struct foo' or 'struct {'. In the
16603 /// former case, Name will be non-null. In the later case, Name will be null.
16604 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16605 /// reference/declaration/definition of a tag.
16606 ///
16607 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16608 /// trailing-type-specifier) other than one in an alias-declaration.
16609 ///
16610 /// \param SkipBody If non-null, will be set to indicate if the caller should
16611 /// skip the definition of this tag and treat it as if it were a declaration.
16612 DeclResult
ActOnTag(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,const ParsedAttributesView & Attrs,AccessSpecifier AS,SourceLocation ModulePrivateLoc,MultiTemplateParamsArg TemplateParameterLists,bool & OwnedDecl,bool & IsDependent,SourceLocation ScopedEnumKWLoc,bool ScopedEnumUsesClassTag,TypeResult UnderlyingType,bool IsTypeSpecifier,bool IsTemplateParamOrArg,OffsetOfKind OOK,SkipBodyInfo * SkipBody)16613 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
16614 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
16615 const ParsedAttributesView &Attrs, AccessSpecifier AS,
16616 SourceLocation ModulePrivateLoc,
16617 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
16618 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
16619 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16620 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16621 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
16622 // If this is not a definition, it must have a name.
16623 IdentifierInfo *OrigName = Name;
16624 assert((Name != nullptr || TUK == TUK_Definition) &&
16625 "Nameless record must be a definition!");
16626 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16627
16628 OwnedDecl = false;
16629 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16630 bool ScopedEnum = ScopedEnumKWLoc.isValid();
16631
16632 // FIXME: Check member specializations more carefully.
16633 bool isMemberSpecialization = false;
16634 bool Invalid = false;
16635
16636 // We only need to do this matching if we have template parameters
16637 // or a scope specifier, which also conveniently avoids this work
16638 // for non-C++ cases.
16639 if (TemplateParameterLists.size() > 0 ||
16640 (SS.isNotEmpty() && TUK != TUK_Reference)) {
16641 if (TemplateParameterList *TemplateParams =
16642 MatchTemplateParametersToScopeSpecifier(
16643 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16644 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16645 if (Kind == TTK_Enum) {
16646 Diag(KWLoc, diag::err_enum_template);
16647 return true;
16648 }
16649
16650 if (TemplateParams->size() > 0) {
16651 // This is a declaration or definition of a class template (which may
16652 // be a member of another template).
16653
16654 if (Invalid)
16655 return true;
16656
16657 OwnedDecl = false;
16658 DeclResult Result = CheckClassTemplate(
16659 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16660 AS, ModulePrivateLoc,
16661 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16662 TemplateParameterLists.data(), SkipBody);
16663 return Result.get();
16664 } else {
16665 // The "template<>" header is extraneous.
16666 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16667 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16668 isMemberSpecialization = true;
16669 }
16670 }
16671
16672 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16673 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16674 return true;
16675 }
16676
16677 // Figure out the underlying type if this a enum declaration. We need to do
16678 // this early, because it's needed to detect if this is an incompatible
16679 // redeclaration.
16680 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16681 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16682
16683 if (Kind == TTK_Enum) {
16684 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16685 // No underlying type explicitly specified, or we failed to parse the
16686 // type, default to int.
16687 EnumUnderlying = Context.IntTy.getTypePtr();
16688 } else if (UnderlyingType.get()) {
16689 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16690 // integral type; any cv-qualification is ignored.
16691 TypeSourceInfo *TI = nullptr;
16692 GetTypeFromParser(UnderlyingType.get(), &TI);
16693 EnumUnderlying = TI;
16694
16695 if (CheckEnumUnderlyingType(TI))
16696 // Recover by falling back to int.
16697 EnumUnderlying = Context.IntTy.getTypePtr();
16698
16699 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16700 UPPC_FixedUnderlyingType))
16701 EnumUnderlying = Context.IntTy.getTypePtr();
16702
16703 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16704 // For MSVC ABI compatibility, unfixed enums must use an underlying type
16705 // of 'int'. However, if this is an unfixed forward declaration, don't set
16706 // the underlying type unless the user enables -fms-compatibility. This
16707 // makes unfixed forward declared enums incomplete and is more conforming.
16708 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16709 EnumUnderlying = Context.IntTy.getTypePtr();
16710 }
16711 }
16712
16713 DeclContext *SearchDC = CurContext;
16714 DeclContext *DC = CurContext;
16715 bool isStdBadAlloc = false;
16716 bool isStdAlignValT = false;
16717
16718 RedeclarationKind Redecl = forRedeclarationInCurContext();
16719 if (TUK == TUK_Friend || TUK == TUK_Reference)
16720 Redecl = NotForRedeclaration;
16721
16722 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16723 /// implemented asks for structural equivalence checking, the returned decl
16724 /// here is passed back to the parser, allowing the tag body to be parsed.
16725 auto createTagFromNewDecl = [&]() -> TagDecl * {
16726 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16727 // If there is an identifier, use the location of the identifier as the
16728 // location of the decl, otherwise use the location of the struct/union
16729 // keyword.
16730 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16731 TagDecl *New = nullptr;
16732
16733 if (Kind == TTK_Enum) {
16734 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16735 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16736 // If this is an undefined enum, bail.
16737 if (TUK != TUK_Definition && !Invalid)
16738 return nullptr;
16739 if (EnumUnderlying) {
16740 EnumDecl *ED = cast<EnumDecl>(New);
16741 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16742 ED->setIntegerTypeSourceInfo(TI);
16743 else
16744 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16745 QualType EnumTy = ED->getIntegerType();
16746 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
16747 ? Context.getPromotedIntegerType(EnumTy)
16748 : EnumTy);
16749 }
16750 } else { // struct/union
16751 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16752 nullptr);
16753 }
16754
16755 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16756 // Add alignment attributes if necessary; these attributes are checked
16757 // when the ASTContext lays out the structure.
16758 //
16759 // It is important for implementing the correct semantics that this
16760 // happen here (in ActOnTag). The #pragma pack stack is
16761 // maintained as a result of parser callbacks which can occur at
16762 // many points during the parsing of a struct declaration (because
16763 // the #pragma tokens are effectively skipped over during the
16764 // parsing of the struct).
16765 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16766 AddAlignmentAttributesForRecord(RD);
16767 AddMsStructLayoutForRecord(RD);
16768 }
16769 }
16770 New->setLexicalDeclContext(CurContext);
16771 return New;
16772 };
16773
16774 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16775 if (Name && SS.isNotEmpty()) {
16776 // We have a nested-name tag ('struct foo::bar').
16777
16778 // Check for invalid 'foo::'.
16779 if (SS.isInvalid()) {
16780 Name = nullptr;
16781 goto CreateNewDecl;
16782 }
16783
16784 // If this is a friend or a reference to a class in a dependent
16785 // context, don't try to make a decl for it.
16786 if (TUK == TUK_Friend || TUK == TUK_Reference) {
16787 DC = computeDeclContext(SS, false);
16788 if (!DC) {
16789 IsDependent = true;
16790 return true;
16791 }
16792 } else {
16793 DC = computeDeclContext(SS, true);
16794 if (!DC) {
16795 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16796 << SS.getRange();
16797 return true;
16798 }
16799 }
16800
16801 if (RequireCompleteDeclContext(SS, DC))
16802 return true;
16803
16804 SearchDC = DC;
16805 // Look-up name inside 'foo::'.
16806 LookupQualifiedName(Previous, DC);
16807
16808 if (Previous.isAmbiguous())
16809 return true;
16810
16811 if (Previous.empty()) {
16812 // Name lookup did not find anything. However, if the
16813 // nested-name-specifier refers to the current instantiation,
16814 // and that current instantiation has any dependent base
16815 // classes, we might find something at instantiation time: treat
16816 // this as a dependent elaborated-type-specifier.
16817 // But this only makes any sense for reference-like lookups.
16818 if (Previous.wasNotFoundInCurrentInstantiation() &&
16819 (TUK == TUK_Reference || TUK == TUK_Friend)) {
16820 IsDependent = true;
16821 return true;
16822 }
16823
16824 // A tag 'foo::bar' must already exist.
16825 Diag(NameLoc, diag::err_not_tag_in_scope)
16826 << Kind << Name << DC << SS.getRange();
16827 Name = nullptr;
16828 Invalid = true;
16829 goto CreateNewDecl;
16830 }
16831 } else if (Name) {
16832 // C++14 [class.mem]p14:
16833 // If T is the name of a class, then each of the following shall have a
16834 // name different from T:
16835 // -- every member of class T that is itself a type
16836 if (TUK != TUK_Reference && TUK != TUK_Friend &&
16837 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16838 return true;
16839
16840 // If this is a named struct, check to see if there was a previous forward
16841 // declaration or definition.
16842 // FIXME: We're looking into outer scopes here, even when we
16843 // shouldn't be. Doing so can result in ambiguities that we
16844 // shouldn't be diagnosing.
16845 LookupName(Previous, S);
16846
16847 // When declaring or defining a tag, ignore ambiguities introduced
16848 // by types using'ed into this scope.
16849 if (Previous.isAmbiguous() &&
16850 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16851 LookupResult::Filter F = Previous.makeFilter();
16852 while (F.hasNext()) {
16853 NamedDecl *ND = F.next();
16854 if (!ND->getDeclContext()->getRedeclContext()->Equals(
16855 SearchDC->getRedeclContext()))
16856 F.erase();
16857 }
16858 F.done();
16859 }
16860
16861 // C++11 [namespace.memdef]p3:
16862 // If the name in a friend declaration is neither qualified nor
16863 // a template-id and the declaration is a function or an
16864 // elaborated-type-specifier, the lookup to determine whether
16865 // the entity has been previously declared shall not consider
16866 // any scopes outside the innermost enclosing namespace.
16867 //
16868 // MSVC doesn't implement the above rule for types, so a friend tag
16869 // declaration may be a redeclaration of a type declared in an enclosing
16870 // scope. They do implement this rule for friend functions.
16871 //
16872 // Does it matter that this should be by scope instead of by
16873 // semantic context?
16874 if (!Previous.empty() && TUK == TUK_Friend) {
16875 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16876 LookupResult::Filter F = Previous.makeFilter();
16877 bool FriendSawTagOutsideEnclosingNamespace = false;
16878 while (F.hasNext()) {
16879 NamedDecl *ND = F.next();
16880 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16881 if (DC->isFileContext() &&
16882 !EnclosingNS->Encloses(ND->getDeclContext())) {
16883 if (getLangOpts().MSVCCompat)
16884 FriendSawTagOutsideEnclosingNamespace = true;
16885 else
16886 F.erase();
16887 }
16888 }
16889 F.done();
16890
16891 // Diagnose this MSVC extension in the easy case where lookup would have
16892 // unambiguously found something outside the enclosing namespace.
16893 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16894 NamedDecl *ND = Previous.getFoundDecl();
16895 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16896 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16897 }
16898 }
16899
16900 // Note: there used to be some attempt at recovery here.
16901 if (Previous.isAmbiguous())
16902 return true;
16903
16904 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16905 // FIXME: This makes sure that we ignore the contexts associated
16906 // with C structs, unions, and enums when looking for a matching
16907 // tag declaration or definition. See the similar lookup tweak
16908 // in Sema::LookupName; is there a better way to deal with this?
16909 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16910 SearchDC = SearchDC->getParent();
16911 } else if (getLangOpts().CPlusPlus) {
16912 // Inside ObjCContainer want to keep it as a lexical decl context but go
16913 // past it (most often to TranslationUnit) to find the semantic decl
16914 // context.
16915 while (isa<ObjCContainerDecl>(SearchDC))
16916 SearchDC = SearchDC->getParent();
16917 }
16918 } else if (getLangOpts().CPlusPlus) {
16919 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16920 // TagDecl the same way as we skip it for named TagDecl.
16921 while (isa<ObjCContainerDecl>(SearchDC))
16922 SearchDC = SearchDC->getParent();
16923 }
16924
16925 if (Previous.isSingleResult() &&
16926 Previous.getFoundDecl()->isTemplateParameter()) {
16927 // Maybe we will complain about the shadowed template parameter.
16928 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16929 // Just pretend that we didn't see the previous declaration.
16930 Previous.clear();
16931 }
16932
16933 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16934 DC->Equals(getStdNamespace())) {
16935 if (Name->isStr("bad_alloc")) {
16936 // This is a declaration of or a reference to "std::bad_alloc".
16937 isStdBadAlloc = true;
16938
16939 // If std::bad_alloc has been implicitly declared (but made invisible to
16940 // name lookup), fill in this implicit declaration as the previous
16941 // declaration, so that the declarations get chained appropriately.
16942 if (Previous.empty() && StdBadAlloc)
16943 Previous.addDecl(getStdBadAlloc());
16944 } else if (Name->isStr("align_val_t")) {
16945 isStdAlignValT = true;
16946 if (Previous.empty() && StdAlignValT)
16947 Previous.addDecl(getStdAlignValT());
16948 }
16949 }
16950
16951 // If we didn't find a previous declaration, and this is a reference
16952 // (or friend reference), move to the correct scope. In C++, we
16953 // also need to do a redeclaration lookup there, just in case
16954 // there's a shadow friend decl.
16955 if (Name && Previous.empty() &&
16956 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16957 if (Invalid) goto CreateNewDecl;
16958 assert(SS.isEmpty());
16959
16960 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16961 // C++ [basic.scope.pdecl]p5:
16962 // -- for an elaborated-type-specifier of the form
16963 //
16964 // class-key identifier
16965 //
16966 // if the elaborated-type-specifier is used in the
16967 // decl-specifier-seq or parameter-declaration-clause of a
16968 // function defined in namespace scope, the identifier is
16969 // declared as a class-name in the namespace that contains
16970 // the declaration; otherwise, except as a friend
16971 // declaration, the identifier is declared in the smallest
16972 // non-class, non-function-prototype scope that contains the
16973 // declaration.
16974 //
16975 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16976 // C structs and unions.
16977 //
16978 // It is an error in C++ to declare (rather than define) an enum
16979 // type, including via an elaborated type specifier. We'll
16980 // diagnose that later; for now, declare the enum in the same
16981 // scope as we would have picked for any other tag type.
16982 //
16983 // GNU C also supports this behavior as part of its incomplete
16984 // enum types extension, while GNU C++ does not.
16985 //
16986 // Find the context where we'll be declaring the tag.
16987 // FIXME: We would like to maintain the current DeclContext as the
16988 // lexical context,
16989 SearchDC = getTagInjectionContext(SearchDC);
16990
16991 // Find the scope where we'll be declaring the tag.
16992 S = getTagInjectionScope(S, getLangOpts());
16993 } else {
16994 assert(TUK == TUK_Friend);
16995 // C++ [namespace.memdef]p3:
16996 // If a friend declaration in a non-local class first declares a
16997 // class or function, the friend class or function is a member of
16998 // the innermost enclosing namespace.
16999 SearchDC = SearchDC->getEnclosingNamespaceContext();
17000 }
17001
17002 // In C++, we need to do a redeclaration lookup to properly
17003 // diagnose some problems.
17004 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17005 // hidden declaration so that we don't get ambiguity errors when using a
17006 // type declared by an elaborated-type-specifier. In C that is not correct
17007 // and we should instead merge compatible types found by lookup.
17008 if (getLangOpts().CPlusPlus) {
17009 // FIXME: This can perform qualified lookups into function contexts,
17010 // which are meaningless.
17011 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17012 LookupQualifiedName(Previous, SearchDC);
17013 } else {
17014 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17015 LookupName(Previous, S);
17016 }
17017 }
17018
17019 // If we have a known previous declaration to use, then use it.
17020 if (Previous.empty() && SkipBody && SkipBody->Previous)
17021 Previous.addDecl(SkipBody->Previous);
17022
17023 if (!Previous.empty()) {
17024 NamedDecl *PrevDecl = Previous.getFoundDecl();
17025 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17026
17027 // It's okay to have a tag decl in the same scope as a typedef
17028 // which hides a tag decl in the same scope. Finding this
17029 // with a redeclaration lookup can only actually happen in C++.
17030 //
17031 // This is also okay for elaborated-type-specifiers, which is
17032 // technically forbidden by the current standard but which is
17033 // okay according to the likely resolution of an open issue;
17034 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17035 if (getLangOpts().CPlusPlus) {
17036 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17037 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17038 TagDecl *Tag = TT->getDecl();
17039 if (Tag->getDeclName() == Name &&
17040 Tag->getDeclContext()->getRedeclContext()
17041 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17042 PrevDecl = Tag;
17043 Previous.clear();
17044 Previous.addDecl(Tag);
17045 Previous.resolveKind();
17046 }
17047 }
17048 }
17049 }
17050
17051 // If this is a redeclaration of a using shadow declaration, it must
17052 // declare a tag in the same context. In MSVC mode, we allow a
17053 // redefinition if either context is within the other.
17054 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17055 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17056 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17057 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17058 !(OldTag && isAcceptableTagRedeclContext(
17059 *this, OldTag->getDeclContext(), SearchDC))) {
17060 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17061 Diag(Shadow->getTargetDecl()->getLocation(),
17062 diag::note_using_decl_target);
17063 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17064 << 0;
17065 // Recover by ignoring the old declaration.
17066 Previous.clear();
17067 goto CreateNewDecl;
17068 }
17069 }
17070
17071 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17072 // If this is a use of a previous tag, or if the tag is already declared
17073 // in the same scope (so that the definition/declaration completes or
17074 // rementions the tag), reuse the decl.
17075 if (TUK == TUK_Reference || TUK == TUK_Friend ||
17076 isDeclInScope(DirectPrevDecl, SearchDC, S,
17077 SS.isNotEmpty() || isMemberSpecialization)) {
17078 // Make sure that this wasn't declared as an enum and now used as a
17079 // struct or something similar.
17080 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17081 TUK == TUK_Definition, KWLoc,
17082 Name)) {
17083 bool SafeToContinue
17084 = (PrevTagDecl->getTagKind() != TTK_Enum &&
17085 Kind != TTK_Enum);
17086 if (SafeToContinue)
17087 Diag(KWLoc, diag::err_use_with_wrong_tag)
17088 << Name
17089 << FixItHint::CreateReplacement(SourceRange(KWLoc),
17090 PrevTagDecl->getKindName());
17091 else
17092 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17093 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17094
17095 if (SafeToContinue)
17096 Kind = PrevTagDecl->getTagKind();
17097 else {
17098 // Recover by making this an anonymous redefinition.
17099 Name = nullptr;
17100 Previous.clear();
17101 Invalid = true;
17102 }
17103 }
17104
17105 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
17106 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17107 if (TUK == TUK_Reference || TUK == TUK_Friend)
17108 return PrevTagDecl;
17109
17110 QualType EnumUnderlyingTy;
17111 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17112 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17113 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17114 EnumUnderlyingTy = QualType(T, 0);
17115
17116 // All conflicts with previous declarations are recovered by
17117 // returning the previous declaration, unless this is a definition,
17118 // in which case we want the caller to bail out.
17119 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17120 ScopedEnum, EnumUnderlyingTy,
17121 IsFixed, PrevEnum))
17122 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17123 }
17124
17125 // C++11 [class.mem]p1:
17126 // A member shall not be declared twice in the member-specification,
17127 // except that a nested class or member class template can be declared
17128 // and then later defined.
17129 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17130 S->isDeclScope(PrevDecl)) {
17131 Diag(NameLoc, diag::ext_member_redeclared);
17132 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17133 }
17134
17135 if (!Invalid) {
17136 // If this is a use, just return the declaration we found, unless
17137 // we have attributes.
17138 if (TUK == TUK_Reference || TUK == TUK_Friend) {
17139 if (!Attrs.empty()) {
17140 // FIXME: Diagnose these attributes. For now, we create a new
17141 // declaration to hold them.
17142 } else if (TUK == TUK_Reference &&
17143 (PrevTagDecl->getFriendObjectKind() ==
17144 Decl::FOK_Undeclared ||
17145 PrevDecl->getOwningModule() != getCurrentModule()) &&
17146 SS.isEmpty()) {
17147 // This declaration is a reference to an existing entity, but
17148 // has different visibility from that entity: it either makes
17149 // a friend visible or it makes a type visible in a new module.
17150 // In either case, create a new declaration. We only do this if
17151 // the declaration would have meant the same thing if no prior
17152 // declaration were found, that is, if it was found in the same
17153 // scope where we would have injected a declaration.
17154 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17155 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17156 return PrevTagDecl;
17157 // This is in the injected scope, create a new declaration in
17158 // that scope.
17159 S = getTagInjectionScope(S, getLangOpts());
17160 } else {
17161 return PrevTagDecl;
17162 }
17163 }
17164
17165 // Diagnose attempts to redefine a tag.
17166 if (TUK == TUK_Definition) {
17167 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17168 // If we're defining a specialization and the previous definition
17169 // is from an implicit instantiation, don't emit an error
17170 // here; we'll catch this in the general case below.
17171 bool IsExplicitSpecializationAfterInstantiation = false;
17172 if (isMemberSpecialization) {
17173 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17174 IsExplicitSpecializationAfterInstantiation =
17175 RD->getTemplateSpecializationKind() !=
17176 TSK_ExplicitSpecialization;
17177 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17178 IsExplicitSpecializationAfterInstantiation =
17179 ED->getTemplateSpecializationKind() !=
17180 TSK_ExplicitSpecialization;
17181 }
17182
17183 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17184 // not keep more that one definition around (merge them). However,
17185 // ensure the decl passes the structural compatibility check in
17186 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17187 NamedDecl *Hidden = nullptr;
17188 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17189 // There is a definition of this tag, but it is not visible. We
17190 // explicitly make use of C++'s one definition rule here, and
17191 // assume that this definition is identical to the hidden one
17192 // we already have. Make the existing definition visible and
17193 // use it in place of this one.
17194 if (!getLangOpts().CPlusPlus) {
17195 // Postpone making the old definition visible until after we
17196 // complete parsing the new one and do the structural
17197 // comparison.
17198 SkipBody->CheckSameAsPrevious = true;
17199 SkipBody->New = createTagFromNewDecl();
17200 SkipBody->Previous = Def;
17201 return Def;
17202 } else {
17203 SkipBody->ShouldSkip = true;
17204 SkipBody->Previous = Def;
17205 makeMergedDefinitionVisible(Hidden);
17206 // Carry on and handle it like a normal definition. We'll
17207 // skip starting the definitiion later.
17208 }
17209 } else if (!IsExplicitSpecializationAfterInstantiation) {
17210 // A redeclaration in function prototype scope in C isn't
17211 // visible elsewhere, so merely issue a warning.
17212 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17213 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17214 else
17215 Diag(NameLoc, diag::err_redefinition) << Name;
17216 notePreviousDefinition(Def,
17217 NameLoc.isValid() ? NameLoc : KWLoc);
17218 // If this is a redefinition, recover by making this
17219 // struct be anonymous, which will make any later
17220 // references get the previous definition.
17221 Name = nullptr;
17222 Previous.clear();
17223 Invalid = true;
17224 }
17225 } else {
17226 // If the type is currently being defined, complain
17227 // about a nested redefinition.
17228 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17229 if (TD->isBeingDefined()) {
17230 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17231 Diag(PrevTagDecl->getLocation(),
17232 diag::note_previous_definition);
17233 Name = nullptr;
17234 Previous.clear();
17235 Invalid = true;
17236 }
17237 }
17238
17239 // Okay, this is definition of a previously declared or referenced
17240 // tag. We're going to create a new Decl for it.
17241 }
17242
17243 // Okay, we're going to make a redeclaration. If this is some kind
17244 // of reference, make sure we build the redeclaration in the same DC
17245 // as the original, and ignore the current access specifier.
17246 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17247 SearchDC = PrevTagDecl->getDeclContext();
17248 AS = AS_none;
17249 }
17250 }
17251 // If we get here we have (another) forward declaration or we
17252 // have a definition. Just create a new decl.
17253
17254 } else {
17255 // If we get here, this is a definition of a new tag type in a nested
17256 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17257 // new decl/type. We set PrevDecl to NULL so that the entities
17258 // have distinct types.
17259 Previous.clear();
17260 }
17261 // If we get here, we're going to create a new Decl. If PrevDecl
17262 // is non-NULL, it's a definition of the tag declared by
17263 // PrevDecl. If it's NULL, we have a new definition.
17264
17265 // Otherwise, PrevDecl is not a tag, but was found with tag
17266 // lookup. This is only actually possible in C++, where a few
17267 // things like templates still live in the tag namespace.
17268 } else {
17269 // Use a better diagnostic if an elaborated-type-specifier
17270 // found the wrong kind of type on the first
17271 // (non-redeclaration) lookup.
17272 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
17273 !Previous.isForRedeclaration()) {
17274 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17275 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
17276 << Kind;
17277 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17278 Invalid = true;
17279
17280 // Otherwise, only diagnose if the declaration is in scope.
17281 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17282 SS.isNotEmpty() || isMemberSpecialization)) {
17283 // do nothing
17284
17285 // Diagnose implicit declarations introduced by elaborated types.
17286 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
17287 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17288 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17289 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17290 Invalid = true;
17291
17292 // Otherwise it's a declaration. Call out a particularly common
17293 // case here.
17294 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17295 unsigned Kind = 0;
17296 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17297 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17298 << Name << Kind << TND->getUnderlyingType();
17299 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17300 Invalid = true;
17301
17302 // Otherwise, diagnose.
17303 } else {
17304 // The tag name clashes with something else in the target scope,
17305 // issue an error and recover by making this tag be anonymous.
17306 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17307 notePreviousDefinition(PrevDecl, NameLoc);
17308 Name = nullptr;
17309 Invalid = true;
17310 }
17311
17312 // The existing declaration isn't relevant to us; we're in a
17313 // new scope, so clear out the previous declaration.
17314 Previous.clear();
17315 }
17316 }
17317
17318 CreateNewDecl:
17319
17320 TagDecl *PrevDecl = nullptr;
17321 if (Previous.isSingleResult())
17322 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17323
17324 // If there is an identifier, use the location of the identifier as the
17325 // location of the decl, otherwise use the location of the struct/union
17326 // keyword.
17327 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17328
17329 // Otherwise, create a new declaration. If there is a previous
17330 // declaration of the same entity, the two will be linked via
17331 // PrevDecl.
17332 TagDecl *New;
17333
17334 if (Kind == TTK_Enum) {
17335 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17336 // enum X { A, B, C } D; D should chain to X.
17337 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17338 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17339 ScopedEnumUsesClassTag, IsFixed);
17340
17341 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17342 StdAlignValT = cast<EnumDecl>(New);
17343
17344 // If this is an undefined enum, warn.
17345 if (TUK != TUK_Definition && !Invalid) {
17346 TagDecl *Def;
17347 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17348 // C++0x: 7.2p2: opaque-enum-declaration.
17349 // Conflicts are diagnosed above. Do nothing.
17350 }
17351 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17352 Diag(Loc, diag::ext_forward_ref_enum_def)
17353 << New;
17354 Diag(Def->getLocation(), diag::note_previous_definition);
17355 } else {
17356 unsigned DiagID = diag::ext_forward_ref_enum;
17357 if (getLangOpts().MSVCCompat)
17358 DiagID = diag::ext_ms_forward_ref_enum;
17359 else if (getLangOpts().CPlusPlus)
17360 DiagID = diag::err_forward_ref_enum;
17361 Diag(Loc, DiagID);
17362 }
17363 }
17364
17365 if (EnumUnderlying) {
17366 EnumDecl *ED = cast<EnumDecl>(New);
17367 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17368 ED->setIntegerTypeSourceInfo(TI);
17369 else
17370 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17371 QualType EnumTy = ED->getIntegerType();
17372 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17373 ? Context.getPromotedIntegerType(EnumTy)
17374 : EnumTy);
17375 assert(ED->isComplete() && "enum with type should be complete");
17376 }
17377 } else {
17378 // struct/union/class
17379
17380 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17381 // struct X { int A; } D; D should chain to X.
17382 if (getLangOpts().CPlusPlus) {
17383 // FIXME: Look for a way to use RecordDecl for simple structs.
17384 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17385 cast_or_null<CXXRecordDecl>(PrevDecl));
17386
17387 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17388 StdBadAlloc = cast<CXXRecordDecl>(New);
17389 } else
17390 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17391 cast_or_null<RecordDecl>(PrevDecl));
17392 }
17393
17394 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus)
17395 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17396 << (OOK == OOK_Macro) << New->getSourceRange();
17397
17398 // C++11 [dcl.type]p3:
17399 // A type-specifier-seq shall not define a class or enumeration [...].
17400 if (!Invalid && getLangOpts().CPlusPlus &&
17401 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
17402 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17403 << Context.getTagDeclType(New);
17404 Invalid = true;
17405 }
17406
17407 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
17408 DC->getDeclKind() == Decl::Enum) {
17409 Diag(New->getLocation(), diag::err_type_defined_in_enum)
17410 << Context.getTagDeclType(New);
17411 Invalid = true;
17412 }
17413
17414 // Maybe add qualifier info.
17415 if (SS.isNotEmpty()) {
17416 if (SS.isSet()) {
17417 // If this is either a declaration or a definition, check the
17418 // nested-name-specifier against the current context.
17419 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
17420 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17421 isMemberSpecialization))
17422 Invalid = true;
17423
17424 New->setQualifierInfo(SS.getWithLocInContext(Context));
17425 if (TemplateParameterLists.size() > 0) {
17426 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17427 }
17428 }
17429 else
17430 Invalid = true;
17431 }
17432
17433 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17434 // Add alignment attributes if necessary; these attributes are checked when
17435 // the ASTContext lays out the structure.
17436 //
17437 // It is important for implementing the correct semantics that this
17438 // happen here (in ActOnTag). The #pragma pack stack is
17439 // maintained as a result of parser callbacks which can occur at
17440 // many points during the parsing of a struct declaration (because
17441 // the #pragma tokens are effectively skipped over during the
17442 // parsing of the struct).
17443 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17444 AddAlignmentAttributesForRecord(RD);
17445 AddMsStructLayoutForRecord(RD);
17446 }
17447 }
17448
17449 if (ModulePrivateLoc.isValid()) {
17450 if (isMemberSpecialization)
17451 Diag(New->getLocation(), diag::err_module_private_specialization)
17452 << 2
17453 << FixItHint::CreateRemoval(ModulePrivateLoc);
17454 // __module_private__ does not apply to local classes. However, we only
17455 // diagnose this as an error when the declaration specifiers are
17456 // freestanding. Here, we just ignore the __module_private__.
17457 else if (!SearchDC->isFunctionOrMethod())
17458 New->setModulePrivate();
17459 }
17460
17461 // If this is a specialization of a member class (of a class template),
17462 // check the specialization.
17463 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17464 Invalid = true;
17465
17466 // If we're declaring or defining a tag in function prototype scope in C,
17467 // note that this type can only be used within the function and add it to
17468 // the list of decls to inject into the function definition scope.
17469 if ((Name || Kind == TTK_Enum) &&
17470 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17471 if (getLangOpts().CPlusPlus) {
17472 // C++ [dcl.fct]p6:
17473 // Types shall not be defined in return or parameter types.
17474 if (TUK == TUK_Definition && !IsTypeSpecifier) {
17475 Diag(Loc, diag::err_type_defined_in_param_type)
17476 << Name;
17477 Invalid = true;
17478 }
17479 } else if (!PrevDecl) {
17480 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17481 }
17482 }
17483
17484 if (Invalid)
17485 New->setInvalidDecl();
17486
17487 // Set the lexical context. If the tag has a C++ scope specifier, the
17488 // lexical context will be different from the semantic context.
17489 New->setLexicalDeclContext(CurContext);
17490
17491 // Mark this as a friend decl if applicable.
17492 // In Microsoft mode, a friend declaration also acts as a forward
17493 // declaration so we always pass true to setObjectOfFriendDecl to make
17494 // the tag name visible.
17495 if (TUK == TUK_Friend)
17496 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17497
17498 // Set the access specifier.
17499 if (!Invalid && SearchDC->isRecord())
17500 SetMemberAccessSpecifier(New, PrevDecl, AS);
17501
17502 if (PrevDecl)
17503 CheckRedeclarationInModule(New, PrevDecl);
17504
17505 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
17506 New->startDefinition();
17507
17508 ProcessDeclAttributeList(S, New, Attrs);
17509 AddPragmaAttributes(S, New);
17510
17511 // If this has an identifier, add it to the scope stack.
17512 if (TUK == TUK_Friend) {
17513 // We might be replacing an existing declaration in the lookup tables;
17514 // if so, borrow its access specifier.
17515 if (PrevDecl)
17516 New->setAccess(PrevDecl->getAccess());
17517
17518 DeclContext *DC = New->getDeclContext()->getRedeclContext();
17519 DC->makeDeclVisibleInContext(New);
17520 if (Name) // can be null along some error paths
17521 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17522 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17523 } else if (Name) {
17524 S = getNonFieldDeclScope(S);
17525 PushOnScopeChains(New, S, true);
17526 } else {
17527 CurContext->addDecl(New);
17528 }
17529
17530 // If this is the C FILE type, notify the AST context.
17531 if (IdentifierInfo *II = New->getIdentifier())
17532 if (!New->isInvalidDecl() &&
17533 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
17534 II->isStr("FILE"))
17535 Context.setFILEDecl(New);
17536
17537 if (PrevDecl)
17538 mergeDeclAttributes(New, PrevDecl);
17539
17540 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
17541 inferGslOwnerPointerAttribute(CXXRD);
17542
17543 // If there's a #pragma GCC visibility in scope, set the visibility of this
17544 // record.
17545 AddPushedVisibilityAttribute(New);
17546
17547 if (isMemberSpecialization && !New->isInvalidDecl())
17548 CompleteMemberSpecialization(New, Previous);
17549
17550 OwnedDecl = true;
17551 // In C++, don't return an invalid declaration. We can't recover well from
17552 // the cases where we make the type anonymous.
17553 if (Invalid && getLangOpts().CPlusPlus) {
17554 if (New->isBeingDefined())
17555 if (auto RD = dyn_cast<RecordDecl>(New))
17556 RD->completeDefinition();
17557 return true;
17558 } else if (SkipBody && SkipBody->ShouldSkip) {
17559 return SkipBody->Previous;
17560 } else {
17561 return New;
17562 }
17563 }
17564
ActOnTagStartDefinition(Scope * S,Decl * TagD)17565 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
17566 AdjustDeclIfTemplate(TagD);
17567 TagDecl *Tag = cast<TagDecl>(TagD);
17568
17569 // Enter the tag context.
17570 PushDeclContext(S, Tag);
17571
17572 ActOnDocumentableDecl(TagD);
17573
17574 // If there's a #pragma GCC visibility in scope, set the visibility of this
17575 // record.
17576 AddPushedVisibilityAttribute(Tag);
17577 }
17578
ActOnDuplicateDefinition(Decl * Prev,SkipBodyInfo & SkipBody)17579 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
17580 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17581 return false;
17582
17583 // Make the previous decl visible.
17584 makeMergedDefinitionVisible(SkipBody.Previous);
17585 return true;
17586 }
17587
ActOnObjCContainerStartDefinition(ObjCContainerDecl * IDecl)17588 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
17589 assert(IDecl->getLexicalParent() == CurContext &&
17590 "The next DeclContext should be lexically contained in the current one.");
17591 CurContext = IDecl;
17592 }
17593
ActOnStartCXXMemberDeclarations(Scope * S,Decl * TagD,SourceLocation FinalLoc,bool IsFinalSpelledSealed,bool IsAbstract,SourceLocation LBraceLoc)17594 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
17595 SourceLocation FinalLoc,
17596 bool IsFinalSpelledSealed,
17597 bool IsAbstract,
17598 SourceLocation LBraceLoc) {
17599 AdjustDeclIfTemplate(TagD);
17600 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17601
17602 FieldCollector->StartClass();
17603
17604 if (!Record->getIdentifier())
17605 return;
17606
17607 if (IsAbstract)
17608 Record->markAbstract();
17609
17610 if (FinalLoc.isValid()) {
17611 Record->addAttr(FinalAttr::Create(
17612 Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
17613 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
17614 }
17615 // C++ [class]p2:
17616 // [...] The class-name is also inserted into the scope of the
17617 // class itself; this is known as the injected-class-name. For
17618 // purposes of access checking, the injected-class-name is treated
17619 // as if it were a public member name.
17620 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17621 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17622 Record->getLocation(), Record->getIdentifier(),
17623 /*PrevDecl=*/nullptr,
17624 /*DelayTypeCreation=*/true);
17625 Context.getTypeDeclType(InjectedClassName, Record);
17626 InjectedClassName->setImplicit();
17627 InjectedClassName->setAccess(AS_public);
17628 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17629 InjectedClassName->setDescribedClassTemplate(Template);
17630 PushOnScopeChains(InjectedClassName, S);
17631 assert(InjectedClassName->isInjectedClassName() &&
17632 "Broken injected-class-name");
17633 }
17634
ActOnTagFinishDefinition(Scope * S,Decl * TagD,SourceRange BraceRange)17635 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17636 SourceRange BraceRange) {
17637 AdjustDeclIfTemplate(TagD);
17638 TagDecl *Tag = cast<TagDecl>(TagD);
17639 Tag->setBraceRange(BraceRange);
17640
17641 // Make sure we "complete" the definition even it is invalid.
17642 if (Tag->isBeingDefined()) {
17643 assert(Tag->isInvalidDecl() && "We should already have completed it");
17644 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17645 RD->completeDefinition();
17646 }
17647
17648 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17649 FieldCollector->FinishClass();
17650 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17651 auto *Def = RD->getDefinition();
17652 assert(Def && "The record is expected to have a completed definition");
17653 unsigned NumInitMethods = 0;
17654 for (auto *Method : Def->methods()) {
17655 if (!Method->getIdentifier())
17656 continue;
17657 if (Method->getName() == "__init")
17658 NumInitMethods++;
17659 }
17660 if (NumInitMethods > 1 || !Def->hasInitMethod())
17661 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17662 }
17663 }
17664
17665 // Exit this scope of this tag's definition.
17666 PopDeclContext();
17667
17668 if (getCurLexicalContext()->isObjCContainer() &&
17669 Tag->getDeclContext()->isFileContext())
17670 Tag->setTopLevelDeclInObjCContainer();
17671
17672 // Notify the consumer that we've defined a tag.
17673 if (!Tag->isInvalidDecl())
17674 Consumer.HandleTagDeclDefinition(Tag);
17675
17676 // Clangs implementation of #pragma align(packed) differs in bitfield layout
17677 // from XLs and instead matches the XL #pragma pack(1) behavior.
17678 if (Context.getTargetInfo().getTriple().isOSAIX() &&
17679 AlignPackStack.hasValue()) {
17680 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17681 // Only diagnose #pragma align(packed).
17682 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17683 return;
17684 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17685 if (!RD)
17686 return;
17687 // Only warn if there is at least 1 bitfield member.
17688 if (llvm::any_of(RD->fields(),
17689 [](const FieldDecl *FD) { return FD->isBitField(); }))
17690 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17691 }
17692 }
17693
ActOnObjCContainerFinishDefinition()17694 void Sema::ActOnObjCContainerFinishDefinition() {
17695 // Exit this scope of this interface definition.
17696 PopDeclContext();
17697 }
17698
ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl * ObjCCtx)17699 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17700 assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17701 OriginalLexicalContext = ObjCCtx;
17702 ActOnObjCContainerFinishDefinition();
17703 }
17704
ActOnObjCReenterContainerContext(ObjCContainerDecl * ObjCCtx)17705 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17706 ActOnObjCContainerStartDefinition(ObjCCtx);
17707 OriginalLexicalContext = nullptr;
17708 }
17709
ActOnTagDefinitionError(Scope * S,Decl * TagD)17710 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17711 AdjustDeclIfTemplate(TagD);
17712 TagDecl *Tag = cast<TagDecl>(TagD);
17713 Tag->setInvalidDecl();
17714
17715 // Make sure we "complete" the definition even it is invalid.
17716 if (Tag->isBeingDefined()) {
17717 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17718 RD->completeDefinition();
17719 }
17720
17721 // We're undoing ActOnTagStartDefinition here, not
17722 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17723 // the FieldCollector.
17724
17725 PopDeclContext();
17726 }
17727
17728 // Note that FieldName may be null for anonymous bitfields.
VerifyBitField(SourceLocation FieldLoc,IdentifierInfo * FieldName,QualType FieldTy,bool IsMsStruct,Expr * BitWidth)17729 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17730 IdentifierInfo *FieldName, QualType FieldTy,
17731 bool IsMsStruct, Expr *BitWidth) {
17732 assert(BitWidth);
17733 if (BitWidth->containsErrors())
17734 return ExprError();
17735
17736 // C99 6.7.2.1p4 - verify the field type.
17737 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17738 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17739 // Handle incomplete and sizeless types with a specific error.
17740 if (RequireCompleteSizedType(FieldLoc, FieldTy,
17741 diag::err_field_incomplete_or_sizeless))
17742 return ExprError();
17743 if (FieldName)
17744 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17745 << FieldName << FieldTy << BitWidth->getSourceRange();
17746 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17747 << FieldTy << BitWidth->getSourceRange();
17748 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17749 UPPC_BitFieldWidth))
17750 return ExprError();
17751
17752 // If the bit-width is type- or value-dependent, don't try to check
17753 // it now.
17754 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17755 return BitWidth;
17756
17757 llvm::APSInt Value;
17758 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17759 if (ICE.isInvalid())
17760 return ICE;
17761 BitWidth = ICE.get();
17762
17763 // Zero-width bitfield is ok for anonymous field.
17764 if (Value == 0 && FieldName)
17765 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17766
17767 if (Value.isSigned() && Value.isNegative()) {
17768 if (FieldName)
17769 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17770 << FieldName << toString(Value, 10);
17771 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17772 << toString(Value, 10);
17773 }
17774
17775 // The size of the bit-field must not exceed our maximum permitted object
17776 // size.
17777 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17778 return Diag(FieldLoc, diag::err_bitfield_too_wide)
17779 << !FieldName << FieldName << toString(Value, 10);
17780 }
17781
17782 if (!FieldTy->isDependentType()) {
17783 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17784 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17785 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17786
17787 // Over-wide bitfields are an error in C or when using the MSVC bitfield
17788 // ABI.
17789 bool CStdConstraintViolation =
17790 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17791 bool MSBitfieldViolation =
17792 Value.ugt(TypeStorageSize) &&
17793 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17794 if (CStdConstraintViolation || MSBitfieldViolation) {
17795 unsigned DiagWidth =
17796 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17797 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17798 << (bool)FieldName << FieldName << toString(Value, 10)
17799 << !CStdConstraintViolation << DiagWidth;
17800 }
17801
17802 // Warn on types where the user might conceivably expect to get all
17803 // specified bits as value bits: that's all integral types other than
17804 // 'bool'.
17805 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17806 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17807 << FieldName << toString(Value, 10)
17808 << (unsigned)TypeWidth;
17809 }
17810 }
17811
17812 return BitWidth;
17813 }
17814
17815 /// ActOnField - Each field of a C struct/union is passed into this in order
17816 /// to create a FieldDecl object for it.
ActOnField(Scope * S,Decl * TagD,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth)17817 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17818 Declarator &D, Expr *BitfieldWidth) {
17819 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17820 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17821 /*InitStyle=*/ICIS_NoInit, AS_public);
17822 return Res;
17823 }
17824
17825 /// HandleField - Analyze a field of a C struct or a C++ data member.
17826 ///
HandleField(Scope * S,RecordDecl * Record,SourceLocation DeclStart,Declarator & D,Expr * BitWidth,InClassInitStyle InitStyle,AccessSpecifier AS)17827 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17828 SourceLocation DeclStart,
17829 Declarator &D, Expr *BitWidth,
17830 InClassInitStyle InitStyle,
17831 AccessSpecifier AS) {
17832 if (D.isDecompositionDeclarator()) {
17833 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17834 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17835 << Decomp.getSourceRange();
17836 return nullptr;
17837 }
17838
17839 IdentifierInfo *II = D.getIdentifier();
17840 SourceLocation Loc = DeclStart;
17841 if (II) Loc = D.getIdentifierLoc();
17842
17843 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17844 QualType T = TInfo->getType();
17845 if (getLangOpts().CPlusPlus) {
17846 CheckExtraCXXDefaultArguments(D);
17847
17848 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17849 UPPC_DataMemberType)) {
17850 D.setInvalidType();
17851 T = Context.IntTy;
17852 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17853 }
17854 }
17855
17856 DiagnoseFunctionSpecifiers(D.getDeclSpec());
17857
17858 if (D.getDeclSpec().isInlineSpecified())
17859 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17860 << getLangOpts().CPlusPlus17;
17861 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17862 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17863 diag::err_invalid_thread)
17864 << DeclSpec::getSpecifierName(TSCS);
17865
17866 // Check to see if this name was declared as a member previously
17867 NamedDecl *PrevDecl = nullptr;
17868 LookupResult Previous(*this, II, Loc, LookupMemberName,
17869 ForVisibleRedeclaration);
17870 LookupName(Previous, S);
17871 switch (Previous.getResultKind()) {
17872 case LookupResult::Found:
17873 case LookupResult::FoundUnresolvedValue:
17874 PrevDecl = Previous.getAsSingle<NamedDecl>();
17875 break;
17876
17877 case LookupResult::FoundOverloaded:
17878 PrevDecl = Previous.getRepresentativeDecl();
17879 break;
17880
17881 case LookupResult::NotFound:
17882 case LookupResult::NotFoundInCurrentInstantiation:
17883 case LookupResult::Ambiguous:
17884 break;
17885 }
17886 Previous.suppressDiagnostics();
17887
17888 if (PrevDecl && PrevDecl->isTemplateParameter()) {
17889 // Maybe we will complain about the shadowed template parameter.
17890 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17891 // Just pretend that we didn't see the previous declaration.
17892 PrevDecl = nullptr;
17893 }
17894
17895 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17896 PrevDecl = nullptr;
17897
17898 bool Mutable
17899 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17900 SourceLocation TSSL = D.getBeginLoc();
17901 FieldDecl *NewFD
17902 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17903 TSSL, AS, PrevDecl, &D);
17904
17905 if (NewFD->isInvalidDecl())
17906 Record->setInvalidDecl();
17907
17908 if (D.getDeclSpec().isModulePrivateSpecified())
17909 NewFD->setModulePrivate();
17910
17911 if (NewFD->isInvalidDecl() && PrevDecl) {
17912 // Don't introduce NewFD into scope; there's already something
17913 // with the same name in the same scope.
17914 } else if (II) {
17915 PushOnScopeChains(NewFD, S);
17916 } else
17917 Record->addDecl(NewFD);
17918
17919 return NewFD;
17920 }
17921
17922 /// Build a new FieldDecl and check its well-formedness.
17923 ///
17924 /// This routine builds a new FieldDecl given the fields name, type,
17925 /// record, etc. \p PrevDecl should refer to any previous declaration
17926 /// with the same name and in the same scope as the field to be
17927 /// created.
17928 ///
17929 /// \returns a new FieldDecl.
17930 ///
17931 /// \todo The Declarator argument is a hack. It will be removed once
CheckFieldDecl(DeclarationName Name,QualType T,TypeSourceInfo * TInfo,RecordDecl * Record,SourceLocation Loc,bool Mutable,Expr * BitWidth,InClassInitStyle InitStyle,SourceLocation TSSL,AccessSpecifier AS,NamedDecl * PrevDecl,Declarator * D)17932 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17933 TypeSourceInfo *TInfo,
17934 RecordDecl *Record, SourceLocation Loc,
17935 bool Mutable, Expr *BitWidth,
17936 InClassInitStyle InitStyle,
17937 SourceLocation TSSL,
17938 AccessSpecifier AS, NamedDecl *PrevDecl,
17939 Declarator *D) {
17940 IdentifierInfo *II = Name.getAsIdentifierInfo();
17941 bool InvalidDecl = false;
17942 if (D) InvalidDecl = D->isInvalidType();
17943
17944 // If we receive a broken type, recover by assuming 'int' and
17945 // marking this declaration as invalid.
17946 if (T.isNull() || T->containsErrors()) {
17947 InvalidDecl = true;
17948 T = Context.IntTy;
17949 }
17950
17951 QualType EltTy = Context.getBaseElementType(T);
17952 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17953 if (RequireCompleteSizedType(Loc, EltTy,
17954 diag::err_field_incomplete_or_sizeless)) {
17955 // Fields of incomplete type force their record to be invalid.
17956 Record->setInvalidDecl();
17957 InvalidDecl = true;
17958 } else {
17959 NamedDecl *Def;
17960 EltTy->isIncompleteType(&Def);
17961 if (Def && Def->isInvalidDecl()) {
17962 Record->setInvalidDecl();
17963 InvalidDecl = true;
17964 }
17965 }
17966 }
17967
17968 // TR 18037 does not allow fields to be declared with address space
17969 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17970 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17971 Diag(Loc, diag::err_field_with_address_space);
17972 Record->setInvalidDecl();
17973 InvalidDecl = true;
17974 }
17975
17976 if (LangOpts.OpenCL) {
17977 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17978 // used as structure or union field: image, sampler, event or block types.
17979 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17980 T->isBlockPointerType()) {
17981 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17982 Record->setInvalidDecl();
17983 InvalidDecl = true;
17984 }
17985 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17986 // is enabled.
17987 if (BitWidth && !getOpenCLOptions().isAvailableOption(
17988 "__cl_clang_bitfields", LangOpts)) {
17989 Diag(Loc, diag::err_opencl_bitfields);
17990 InvalidDecl = true;
17991 }
17992 }
17993
17994 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17995 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17996 T.hasQualifiers()) {
17997 InvalidDecl = true;
17998 Diag(Loc, diag::err_anon_bitfield_qualifiers);
17999 }
18000
18001 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18002 // than a variably modified type.
18003 if (!InvalidDecl && T->isVariablyModifiedType()) {
18004 if (!tryToFixVariablyModifiedVarType(
18005 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18006 InvalidDecl = true;
18007 }
18008
18009 // Fields can not have abstract class types
18010 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18011 diag::err_abstract_type_in_decl,
18012 AbstractFieldType))
18013 InvalidDecl = true;
18014
18015 if (InvalidDecl)
18016 BitWidth = nullptr;
18017 // If this is declared as a bit-field, check the bit-field.
18018 if (BitWidth) {
18019 BitWidth =
18020 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18021 if (!BitWidth) {
18022 InvalidDecl = true;
18023 BitWidth = nullptr;
18024 }
18025 }
18026
18027 // Check that 'mutable' is consistent with the type of the declaration.
18028 if (!InvalidDecl && Mutable) {
18029 unsigned DiagID = 0;
18030 if (T->isReferenceType())
18031 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18032 : diag::err_mutable_reference;
18033 else if (T.isConstQualified())
18034 DiagID = diag::err_mutable_const;
18035
18036 if (DiagID) {
18037 SourceLocation ErrLoc = Loc;
18038 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18039 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18040 Diag(ErrLoc, DiagID);
18041 if (DiagID != diag::ext_mutable_reference) {
18042 Mutable = false;
18043 InvalidDecl = true;
18044 }
18045 }
18046 }
18047
18048 // C++11 [class.union]p8 (DR1460):
18049 // At most one variant member of a union may have a
18050 // brace-or-equal-initializer.
18051 if (InitStyle != ICIS_NoInit)
18052 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18053
18054 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18055 BitWidth, Mutable, InitStyle);
18056 if (InvalidDecl)
18057 NewFD->setInvalidDecl();
18058
18059 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
18060 Diag(Loc, diag::err_duplicate_member) << II;
18061 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18062 NewFD->setInvalidDecl();
18063 }
18064
18065 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18066 if (Record->isUnion()) {
18067 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18068 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18069 if (RDecl->getDefinition()) {
18070 // C++ [class.union]p1: An object of a class with a non-trivial
18071 // constructor, a non-trivial copy constructor, a non-trivial
18072 // destructor, or a non-trivial copy assignment operator
18073 // cannot be a member of a union, nor can an array of such
18074 // objects.
18075 if (CheckNontrivialField(NewFD))
18076 NewFD->setInvalidDecl();
18077 }
18078 }
18079
18080 // C++ [class.union]p1: If a union contains a member of reference type,
18081 // the program is ill-formed, except when compiling with MSVC extensions
18082 // enabled.
18083 if (EltTy->isReferenceType()) {
18084 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18085 diag::ext_union_member_of_reference_type :
18086 diag::err_union_member_of_reference_type)
18087 << NewFD->getDeclName() << EltTy;
18088 if (!getLangOpts().MicrosoftExt)
18089 NewFD->setInvalidDecl();
18090 }
18091 }
18092 }
18093
18094 // FIXME: We need to pass in the attributes given an AST
18095 // representation, not a parser representation.
18096 if (D) {
18097 // FIXME: The current scope is almost... but not entirely... correct here.
18098 ProcessDeclAttributes(getCurScope(), NewFD, *D);
18099
18100 if (NewFD->hasAttrs())
18101 CheckAlignasUnderalignment(NewFD);
18102 }
18103
18104 // In auto-retain/release, infer strong retension for fields of
18105 // retainable type.
18106 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18107 NewFD->setInvalidDecl();
18108
18109 if (T.isObjCGCWeak())
18110 Diag(Loc, diag::warn_attribute_weak_on_field);
18111
18112 // PPC MMA non-pointer types are not allowed as field types.
18113 if (Context.getTargetInfo().getTriple().isPPC64() &&
18114 CheckPPCMMAType(T, NewFD->getLocation()))
18115 NewFD->setInvalidDecl();
18116
18117 NewFD->setAccess(AS);
18118 return NewFD;
18119 }
18120
CheckNontrivialField(FieldDecl * FD)18121 bool Sema::CheckNontrivialField(FieldDecl *FD) {
18122 assert(FD);
18123 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18124
18125 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18126 return false;
18127
18128 QualType EltTy = Context.getBaseElementType(FD->getType());
18129 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18130 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18131 if (RDecl->getDefinition()) {
18132 // We check for copy constructors before constructors
18133 // because otherwise we'll never get complaints about
18134 // copy constructors.
18135
18136 CXXSpecialMember member = CXXInvalid;
18137 // We're required to check for any non-trivial constructors. Since the
18138 // implicit default constructor is suppressed if there are any
18139 // user-declared constructors, we just need to check that there is a
18140 // trivial default constructor and a trivial copy constructor. (We don't
18141 // worry about move constructors here, since this is a C++98 check.)
18142 if (RDecl->hasNonTrivialCopyConstructor())
18143 member = CXXCopyConstructor;
18144 else if (!RDecl->hasTrivialDefaultConstructor())
18145 member = CXXDefaultConstructor;
18146 else if (RDecl->hasNonTrivialCopyAssignment())
18147 member = CXXCopyAssignment;
18148 else if (RDecl->hasNonTrivialDestructor())
18149 member = CXXDestructor;
18150
18151 if (member != CXXInvalid) {
18152 if (!getLangOpts().CPlusPlus11 &&
18153 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18154 // Objective-C++ ARC: it is an error to have a non-trivial field of
18155 // a union. However, system headers in Objective-C programs
18156 // occasionally have Objective-C lifetime objects within unions,
18157 // and rather than cause the program to fail, we make those
18158 // members unavailable.
18159 SourceLocation Loc = FD->getLocation();
18160 if (getSourceManager().isInSystemHeader(Loc)) {
18161 if (!FD->hasAttr<UnavailableAttr>())
18162 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18163 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18164 return false;
18165 }
18166 }
18167
18168 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
18169 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
18170 diag::err_illegal_union_or_anon_struct_member)
18171 << FD->getParent()->isUnion() << FD->getDeclName() << member;
18172 DiagnoseNontrivial(RDecl, member);
18173 return !getLangOpts().CPlusPlus11;
18174 }
18175 }
18176 }
18177
18178 return false;
18179 }
18180
18181 /// TranslateIvarVisibility - Translate visibility from a token ID to an
18182 /// AST enum value.
18183 static ObjCIvarDecl::AccessControl
TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)18184 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
18185 switch (ivarVisibility) {
18186 default: llvm_unreachable("Unknown visitibility kind");
18187 case tok::objc_private: return ObjCIvarDecl::Private;
18188 case tok::objc_public: return ObjCIvarDecl::Public;
18189 case tok::objc_protected: return ObjCIvarDecl::Protected;
18190 case tok::objc_package: return ObjCIvarDecl::Package;
18191 }
18192 }
18193
18194 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
18195 /// in order to create an IvarDecl object for it.
ActOnIvar(Scope * S,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth,tok::ObjCKeywordKind Visibility)18196 Decl *Sema::ActOnIvar(Scope *S,
18197 SourceLocation DeclStart,
18198 Declarator &D, Expr *BitfieldWidth,
18199 tok::ObjCKeywordKind Visibility) {
18200
18201 IdentifierInfo *II = D.getIdentifier();
18202 Expr *BitWidth = (Expr*)BitfieldWidth;
18203 SourceLocation Loc = DeclStart;
18204 if (II) Loc = D.getIdentifierLoc();
18205
18206 // FIXME: Unnamed fields can be handled in various different ways, for
18207 // example, unnamed unions inject all members into the struct namespace!
18208
18209 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18210 QualType T = TInfo->getType();
18211
18212 if (BitWidth) {
18213 // 6.7.2.1p3, 6.7.2.1p4
18214 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
18215 if (!BitWidth)
18216 D.setInvalidType();
18217 } else {
18218 // Not a bitfield.
18219
18220 // validate II.
18221
18222 }
18223 if (T->isReferenceType()) {
18224 Diag(Loc, diag::err_ivar_reference_type);
18225 D.setInvalidType();
18226 }
18227 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18228 // than a variably modified type.
18229 else if (T->isVariablyModifiedType()) {
18230 if (!tryToFixVariablyModifiedVarType(
18231 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18232 D.setInvalidType();
18233 }
18234
18235 // Get the visibility (access control) for this ivar.
18236 ObjCIvarDecl::AccessControl ac =
18237 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
18238 : ObjCIvarDecl::None;
18239 // Must set ivar's DeclContext to its enclosing interface.
18240 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
18241 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18242 return nullptr;
18243 ObjCContainerDecl *EnclosingContext;
18244 if (ObjCImplementationDecl *IMPDecl =
18245 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18246 if (LangOpts.ObjCRuntime.isFragile()) {
18247 // Case of ivar declared in an implementation. Context is that of its class.
18248 EnclosingContext = IMPDecl->getClassInterface();
18249 assert(EnclosingContext && "Implementation has no class interface!");
18250 }
18251 else
18252 EnclosingContext = EnclosingDecl;
18253 } else {
18254 if (ObjCCategoryDecl *CDecl =
18255 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18256 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
18257 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
18258 return nullptr;
18259 }
18260 }
18261 EnclosingContext = EnclosingDecl;
18262 }
18263
18264 // Construct the decl.
18265 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
18266 DeclStart, Loc, II, T,
18267 TInfo, ac, (Expr *)BitfieldWidth);
18268
18269 if (II) {
18270 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
18271 ForVisibleRedeclaration);
18272 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
18273 && !isa<TagDecl>(PrevDecl)) {
18274 Diag(Loc, diag::err_duplicate_member) << II;
18275 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18276 NewID->setInvalidDecl();
18277 }
18278 }
18279
18280 // Process attributes attached to the ivar.
18281 ProcessDeclAttributes(S, NewID, D);
18282
18283 if (D.isInvalidType())
18284 NewID->setInvalidDecl();
18285
18286 // In ARC, infer 'retaining' for ivars of retainable type.
18287 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
18288 NewID->setInvalidDecl();
18289
18290 if (D.getDeclSpec().isModulePrivateSpecified())
18291 NewID->setModulePrivate();
18292
18293 if (II) {
18294 // FIXME: When interfaces are DeclContexts, we'll need to add
18295 // these to the interface.
18296 S->AddDecl(NewID);
18297 IdResolver.AddDecl(NewID);
18298 }
18299
18300 if (LangOpts.ObjCRuntime.isNonFragile() &&
18301 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
18302 Diag(Loc, diag::warn_ivars_in_interface);
18303
18304 return NewID;
18305 }
18306
18307 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18308 /// class and class extensions. For every class \@interface and class
18309 /// extension \@interface, if the last ivar is a bitfield of any type,
18310 /// then add an implicit `char :0` ivar to the end of that interface.
ActOnLastBitfield(SourceLocation DeclLoc,SmallVectorImpl<Decl * > & AllIvarDecls)18311 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
18312 SmallVectorImpl<Decl *> &AllIvarDecls) {
18313 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18314 return;
18315
18316 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18317 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18318
18319 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18320 return;
18321 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18322 if (!ID) {
18323 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18324 if (!CD->IsClassExtension())
18325 return;
18326 }
18327 // No need to add this to end of @implementation.
18328 else
18329 return;
18330 }
18331 // All conditions are met. Add a new bitfield to the tail end of ivars.
18332 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18333 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18334
18335 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18336 DeclLoc, DeclLoc, nullptr,
18337 Context.CharTy,
18338 Context.getTrivialTypeSourceInfo(Context.CharTy,
18339 DeclLoc),
18340 ObjCIvarDecl::Private, BW,
18341 true);
18342 AllIvarDecls.push_back(Ivar);
18343 }
18344
18345 /// [class.dtor]p4:
18346 /// At the end of the definition of a class, overload resolution is
18347 /// performed among the prospective destructors declared in that class with
18348 /// an empty argument list to select the destructor for the class, also
18349 /// known as the selected destructor.
18350 ///
18351 /// We do the overload resolution here, then mark the selected constructor in the AST.
18352 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
ComputeSelectedDestructor(Sema & S,CXXRecordDecl * Record)18353 static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
18354 if (!Record->hasUserDeclaredDestructor()) {
18355 return;
18356 }
18357
18358 SourceLocation Loc = Record->getLocation();
18359 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
18360
18361 for (auto *Decl : Record->decls()) {
18362 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18363 if (DD->isInvalidDecl())
18364 continue;
18365 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18366 OCS);
18367 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18368 }
18369 }
18370
18371 if (OCS.empty()) {
18372 return;
18373 }
18374 OverloadCandidateSet::iterator Best;
18375 unsigned Msg = 0;
18376 OverloadCandidateDisplayKind DisplayKind;
18377
18378 switch (OCS.BestViableFunction(S, Loc, Best)) {
18379 case OR_Success:
18380 case OR_Deleted:
18381 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18382 break;
18383
18384 case OR_Ambiguous:
18385 Msg = diag::err_ambiguous_destructor;
18386 DisplayKind = OCD_AmbiguousCandidates;
18387 break;
18388
18389 case OR_No_Viable_Function:
18390 Msg = diag::err_no_viable_destructor;
18391 DisplayKind = OCD_AllCandidates;
18392 break;
18393 }
18394
18395 if (Msg) {
18396 // OpenCL have got their own thing going with destructors. It's slightly broken,
18397 // but we allow it.
18398 if (!S.LangOpts.OpenCL) {
18399 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18400 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18401 Record->setInvalidDecl();
18402 }
18403 // It's a bit hacky: At this point we've raised an error but we want the
18404 // rest of the compiler to continue somehow working. However almost
18405 // everything we'll try to do with the class will depend on there being a
18406 // destructor. So let's pretend the first one is selected and hope for the
18407 // best.
18408 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18409 }
18410 }
18411
18412 /// [class.mem.special]p5
18413 /// Two special member functions are of the same kind if:
18414 /// - they are both default constructors,
18415 /// - they are both copy or move constructors with the same first parameter
18416 /// type, or
18417 /// - they are both copy or move assignment operators with the same first
18418 /// parameter type and the same cv-qualifiers and ref-qualifier, if any.
AreSpecialMemberFunctionsSameKind(ASTContext & Context,CXXMethodDecl * M1,CXXMethodDecl * M2,Sema::CXXSpecialMember CSM)18419 static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
18420 CXXMethodDecl *M1,
18421 CXXMethodDecl *M2,
18422 Sema::CXXSpecialMember CSM) {
18423 // We don't want to compare templates to non-templates: See
18424 // https://github.com/llvm/llvm-project/issues/59206
18425 if (CSM == Sema::CXXDefaultConstructor)
18426 return bool(M1->getDescribedFunctionTemplate()) ==
18427 bool(M2->getDescribedFunctionTemplate());
18428 if (!Context.hasSameType(M1->getParamDecl(0)->getType(),
18429 M2->getParamDecl(0)->getType()))
18430 return false;
18431 if (!Context.hasSameType(M1->getThisType(), M2->getThisType()))
18432 return false;
18433
18434 return true;
18435 }
18436
18437 /// [class.mem.special]p6:
18438 /// An eligible special member function is a special member function for which:
18439 /// - the function is not deleted,
18440 /// - the associated constraints, if any, are satisfied, and
18441 /// - no special member function of the same kind whose associated constraints
18442 /// [CWG2595], if any, are satisfied is more constrained.
SetEligibleMethods(Sema & S,CXXRecordDecl * Record,ArrayRef<CXXMethodDecl * > Methods,Sema::CXXSpecialMember CSM)18443 static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
18444 ArrayRef<CXXMethodDecl *> Methods,
18445 Sema::CXXSpecialMember CSM) {
18446 SmallVector<bool, 4> SatisfactionStatus;
18447
18448 for (CXXMethodDecl *Method : Methods) {
18449 const Expr *Constraints = Method->getTrailingRequiresClause();
18450 if (!Constraints)
18451 SatisfactionStatus.push_back(true);
18452 else {
18453 ConstraintSatisfaction Satisfaction;
18454 if (S.CheckFunctionConstraints(Method, Satisfaction))
18455 SatisfactionStatus.push_back(false);
18456 else
18457 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18458 }
18459 }
18460
18461 for (size_t i = 0; i < Methods.size(); i++) {
18462 if (!SatisfactionStatus[i])
18463 continue;
18464 CXXMethodDecl *Method = Methods[i];
18465 CXXMethodDecl *OrigMethod = Method;
18466 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18467 OrigMethod = cast<CXXMethodDecl>(MF);
18468
18469 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18470 bool AnotherMethodIsMoreConstrained = false;
18471 for (size_t j = 0; j < Methods.size(); j++) {
18472 if (i == j || !SatisfactionStatus[j])
18473 continue;
18474 CXXMethodDecl *OtherMethod = Methods[j];
18475 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18476 OtherMethod = cast<CXXMethodDecl>(MF);
18477
18478 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18479 CSM))
18480 continue;
18481
18482 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18483 if (!OtherConstraints)
18484 continue;
18485 if (!Constraints) {
18486 AnotherMethodIsMoreConstrained = true;
18487 break;
18488 }
18489 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18490 {Constraints},
18491 AnotherMethodIsMoreConstrained)) {
18492 // There was an error with the constraints comparison. Exit the loop
18493 // and don't consider this function eligible.
18494 AnotherMethodIsMoreConstrained = true;
18495 }
18496 if (AnotherMethodIsMoreConstrained)
18497 break;
18498 }
18499 // FIXME: Do not consider deleted methods as eligible after implementing
18500 // DR1734 and DR1496.
18501 if (!AnotherMethodIsMoreConstrained) {
18502 Method->setIneligibleOrNotSelected(false);
18503 Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM);
18504 }
18505 }
18506 }
18507
ComputeSpecialMemberFunctionsEligiblity(Sema & S,CXXRecordDecl * Record)18508 static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
18509 CXXRecordDecl *Record) {
18510 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18511 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18512 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18513 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18514 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18515
18516 for (auto *Decl : Record->decls()) {
18517 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18518 if (!MD) {
18519 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18520 if (FTD)
18521 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18522 }
18523 if (!MD)
18524 continue;
18525 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18526 if (CD->isInvalidDecl())
18527 continue;
18528 if (CD->isDefaultConstructor())
18529 DefaultConstructors.push_back(MD);
18530 else if (CD->isCopyConstructor())
18531 CopyConstructors.push_back(MD);
18532 else if (CD->isMoveConstructor())
18533 MoveConstructors.push_back(MD);
18534 } else if (MD->isCopyAssignmentOperator()) {
18535 CopyAssignmentOperators.push_back(MD);
18536 } else if (MD->isMoveAssignmentOperator()) {
18537 MoveAssignmentOperators.push_back(MD);
18538 }
18539 }
18540
18541 SetEligibleMethods(S, Record, DefaultConstructors,
18542 Sema::CXXDefaultConstructor);
18543 SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor);
18544 SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor);
18545 SetEligibleMethods(S, Record, CopyAssignmentOperators,
18546 Sema::CXXCopyAssignment);
18547 SetEligibleMethods(S, Record, MoveAssignmentOperators,
18548 Sema::CXXMoveAssignment);
18549 }
18550
ActOnFields(Scope * S,SourceLocation RecLoc,Decl * EnclosingDecl,ArrayRef<Decl * > Fields,SourceLocation LBrac,SourceLocation RBrac,const ParsedAttributesView & Attrs)18551 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18552 ArrayRef<Decl *> Fields, SourceLocation LBrac,
18553 SourceLocation RBrac,
18554 const ParsedAttributesView &Attrs) {
18555 assert(EnclosingDecl && "missing record or interface decl");
18556
18557 // If this is an Objective-C @implementation or category and we have
18558 // new fields here we should reset the layout of the interface since
18559 // it will now change.
18560 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
18561 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18562 switch (DC->getKind()) {
18563 default: break;
18564 case Decl::ObjCCategory:
18565 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18566 break;
18567 case Decl::ObjCImplementation:
18568 Context.
18569 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18570 break;
18571 }
18572 }
18573
18574 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18575 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18576
18577 // Start counting up the number of named members; make sure to include
18578 // members of anonymous structs and unions in the total.
18579 unsigned NumNamedMembers = 0;
18580 if (Record) {
18581 for (const auto *I : Record->decls()) {
18582 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
18583 if (IFD->getDeclName())
18584 ++NumNamedMembers;
18585 }
18586 }
18587
18588 // Verify that all the fields are okay.
18589 SmallVector<FieldDecl*, 32> RecFields;
18590
18591 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
18592 i != end; ++i) {
18593 FieldDecl *FD = cast<FieldDecl>(*i);
18594
18595 // Get the type for the field.
18596 const Type *FDTy = FD->getType().getTypePtr();
18597
18598 if (!FD->isAnonymousStructOrUnion()) {
18599 // Remember all fields written by the user.
18600 RecFields.push_back(FD);
18601 }
18602
18603 // If the field is already invalid for some reason, don't emit more
18604 // diagnostics about it.
18605 if (FD->isInvalidDecl()) {
18606 EnclosingDecl->setInvalidDecl();
18607 continue;
18608 }
18609
18610 // C99 6.7.2.1p2:
18611 // A structure or union shall not contain a member with
18612 // incomplete or function type (hence, a structure shall not
18613 // contain an instance of itself, but may contain a pointer to
18614 // an instance of itself), except that the last member of a
18615 // structure with more than one named member may have incomplete
18616 // array type; such a structure (and any union containing,
18617 // possibly recursively, a member that is such a structure)
18618 // shall not be a member of a structure or an element of an
18619 // array.
18620 bool IsLastField = (i + 1 == Fields.end());
18621 if (FDTy->isFunctionType()) {
18622 // Field declared as a function.
18623 Diag(FD->getLocation(), diag::err_field_declared_as_function)
18624 << FD->getDeclName();
18625 FD->setInvalidDecl();
18626 EnclosingDecl->setInvalidDecl();
18627 continue;
18628 } else if (FDTy->isIncompleteArrayType() &&
18629 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
18630 if (Record) {
18631 // Flexible array member.
18632 // Microsoft and g++ is more permissive regarding flexible array.
18633 // It will accept flexible array in union and also
18634 // as the sole element of a struct/class.
18635 unsigned DiagID = 0;
18636 if (!Record->isUnion() && !IsLastField) {
18637 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
18638 << FD->getDeclName() << FD->getType() << Record->getTagKind();
18639 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
18640 FD->setInvalidDecl();
18641 EnclosingDecl->setInvalidDecl();
18642 continue;
18643 } else if (Record->isUnion())
18644 DiagID = getLangOpts().MicrosoftExt
18645 ? diag::ext_flexible_array_union_ms
18646 : getLangOpts().CPlusPlus
18647 ? diag::ext_flexible_array_union_gnu
18648 : diag::err_flexible_array_union;
18649 else if (NumNamedMembers < 1)
18650 DiagID = getLangOpts().MicrosoftExt
18651 ? diag::ext_flexible_array_empty_aggregate_ms
18652 : getLangOpts().CPlusPlus
18653 ? diag::ext_flexible_array_empty_aggregate_gnu
18654 : diag::err_flexible_array_empty_aggregate;
18655
18656 if (DiagID)
18657 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
18658 << Record->getTagKind();
18659 // While the layout of types that contain virtual bases is not specified
18660 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18661 // virtual bases after the derived members. This would make a flexible
18662 // array member declared at the end of an object not adjacent to the end
18663 // of the type.
18664 if (CXXRecord && CXXRecord->getNumVBases() != 0)
18665 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
18666 << FD->getDeclName() << Record->getTagKind();
18667 if (!getLangOpts().C99)
18668 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
18669 << FD->getDeclName() << Record->getTagKind();
18670
18671 // If the element type has a non-trivial destructor, we would not
18672 // implicitly destroy the elements, so disallow it for now.
18673 //
18674 // FIXME: GCC allows this. We should probably either implicitly delete
18675 // the destructor of the containing class, or just allow this.
18676 QualType BaseElem = Context.getBaseElementType(FD->getType());
18677 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18678 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18679 << FD->getDeclName() << FD->getType();
18680 FD->setInvalidDecl();
18681 EnclosingDecl->setInvalidDecl();
18682 continue;
18683 }
18684 // Okay, we have a legal flexible array member at the end of the struct.
18685 Record->setHasFlexibleArrayMember(true);
18686 } else {
18687 // In ObjCContainerDecl ivars with incomplete array type are accepted,
18688 // unless they are followed by another ivar. That check is done
18689 // elsewhere, after synthesized ivars are known.
18690 }
18691 } else if (!FDTy->isDependentType() &&
18692 RequireCompleteSizedType(
18693 FD->getLocation(), FD->getType(),
18694 diag::err_field_incomplete_or_sizeless)) {
18695 // Incomplete type
18696 FD->setInvalidDecl();
18697 EnclosingDecl->setInvalidDecl();
18698 continue;
18699 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18700 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18701 // A type which contains a flexible array member is considered to be a
18702 // flexible array member.
18703 Record->setHasFlexibleArrayMember(true);
18704 if (!Record->isUnion()) {
18705 // If this is a struct/class and this is not the last element, reject
18706 // it. Note that GCC supports variable sized arrays in the middle of
18707 // structures.
18708 if (!IsLastField)
18709 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18710 << FD->getDeclName() << FD->getType();
18711 else {
18712 // We support flexible arrays at the end of structs in
18713 // other structs as an extension.
18714 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18715 << FD->getDeclName();
18716 }
18717 }
18718 }
18719 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18720 RequireNonAbstractType(FD->getLocation(), FD->getType(),
18721 diag::err_abstract_type_in_decl,
18722 AbstractIvarType)) {
18723 // Ivars can not have abstract class types
18724 FD->setInvalidDecl();
18725 }
18726 if (Record && FDTTy->getDecl()->hasObjectMember())
18727 Record->setHasObjectMember(true);
18728 if (Record && FDTTy->getDecl()->hasVolatileMember())
18729 Record->setHasVolatileMember(true);
18730 } else if (FDTy->isObjCObjectType()) {
18731 /// A field cannot be an Objective-c object
18732 Diag(FD->getLocation(), diag::err_statically_allocated_object)
18733 << FixItHint::CreateInsertion(FD->getLocation(), "*");
18734 QualType T = Context.getObjCObjectPointerType(FD->getType());
18735 FD->setType(T);
18736 } else if (Record && Record->isUnion() &&
18737 FD->getType().hasNonTrivialObjCLifetime() &&
18738 getSourceManager().isInSystemHeader(FD->getLocation()) &&
18739 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
18740 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
18741 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
18742 // For backward compatibility, fields of C unions declared in system
18743 // headers that have non-trivial ObjC ownership qualifications are marked
18744 // as unavailable unless the qualifier is explicit and __strong. This can
18745 // break ABI compatibility between programs compiled with ARC and MRR, but
18746 // is a better option than rejecting programs using those unions under
18747 // ARC.
18748 FD->addAttr(UnavailableAttr::CreateImplicit(
18749 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18750 FD->getLocation()));
18751 } else if (getLangOpts().ObjC &&
18752 getLangOpts().getGC() != LangOptions::NonGC && Record &&
18753 !Record->hasObjectMember()) {
18754 if (FD->getType()->isObjCObjectPointerType() ||
18755 FD->getType().isObjCGCStrong())
18756 Record->setHasObjectMember(true);
18757 else if (Context.getAsArrayType(FD->getType())) {
18758 QualType BaseType = Context.getBaseElementType(FD->getType());
18759 if (BaseType->isRecordType() &&
18760 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18761 Record->setHasObjectMember(true);
18762 else if (BaseType->isObjCObjectPointerType() ||
18763 BaseType.isObjCGCStrong())
18764 Record->setHasObjectMember(true);
18765 }
18766 }
18767
18768 if (Record && !getLangOpts().CPlusPlus &&
18769 !shouldIgnoreForRecordTriviality(FD)) {
18770 QualType FT = FD->getType();
18771 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
18772 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
18773 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18774 Record->isUnion())
18775 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18776 }
18777 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
18778 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
18779 Record->setNonTrivialToPrimitiveCopy(true);
18780 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18781 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
18782 }
18783 if (FT.isDestructedType()) {
18784 Record->setNonTrivialToPrimitiveDestroy(true);
18785 Record->setParamDestroyedInCallee(true);
18786 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18787 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
18788 }
18789
18790 if (const auto *RT = FT->getAs<RecordType>()) {
18791 if (RT->getDecl()->getArgPassingRestrictions() ==
18792 RecordDecl::APK_CanNeverPassInRegs)
18793 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18794 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18795 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18796 }
18797
18798 if (Record && FD->getType().isVolatileQualified())
18799 Record->setHasVolatileMember(true);
18800 // Keep track of the number of named members.
18801 if (FD->getIdentifier())
18802 ++NumNamedMembers;
18803 }
18804
18805 // Okay, we successfully defined 'Record'.
18806 if (Record) {
18807 bool Completed = false;
18808 if (CXXRecord) {
18809 if (!CXXRecord->isInvalidDecl()) {
18810 // Set access bits correctly on the directly-declared conversions.
18811 for (CXXRecordDecl::conversion_iterator
18812 I = CXXRecord->conversion_begin(),
18813 E = CXXRecord->conversion_end(); I != E; ++I)
18814 I.setAccess((*I)->getAccess());
18815 }
18816
18817 // Add any implicitly-declared members to this class.
18818 AddImplicitlyDeclaredMembersToClass(CXXRecord);
18819
18820 if (!CXXRecord->isDependentType()) {
18821 if (!CXXRecord->isInvalidDecl()) {
18822 // If we have virtual base classes, we may end up finding multiple
18823 // final overriders for a given virtual function. Check for this
18824 // problem now.
18825 if (CXXRecord->getNumVBases()) {
18826 CXXFinalOverriderMap FinalOverriders;
18827 CXXRecord->getFinalOverriders(FinalOverriders);
18828
18829 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18830 MEnd = FinalOverriders.end();
18831 M != MEnd; ++M) {
18832 for (OverridingMethods::iterator SO = M->second.begin(),
18833 SOEnd = M->second.end();
18834 SO != SOEnd; ++SO) {
18835 assert(SO->second.size() > 0 &&
18836 "Virtual function without overriding functions?");
18837 if (SO->second.size() == 1)
18838 continue;
18839
18840 // C++ [class.virtual]p2:
18841 // In a derived class, if a virtual member function of a base
18842 // class subobject has more than one final overrider the
18843 // program is ill-formed.
18844 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18845 << (const NamedDecl *)M->first << Record;
18846 Diag(M->first->getLocation(),
18847 diag::note_overridden_virtual_function);
18848 for (OverridingMethods::overriding_iterator
18849 OM = SO->second.begin(),
18850 OMEnd = SO->second.end();
18851 OM != OMEnd; ++OM)
18852 Diag(OM->Method->getLocation(), diag::note_final_overrider)
18853 << (const NamedDecl *)M->first << OM->Method->getParent();
18854
18855 Record->setInvalidDecl();
18856 }
18857 }
18858 CXXRecord->completeDefinition(&FinalOverriders);
18859 Completed = true;
18860 }
18861 }
18862 ComputeSelectedDestructor(*this, CXXRecord);
18863 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
18864 }
18865 }
18866
18867 if (!Completed)
18868 Record->completeDefinition();
18869
18870 // Handle attributes before checking the layout.
18871 ProcessDeclAttributeList(S, Record, Attrs);
18872
18873 // Check to see if a FieldDecl is a pointer to a function.
18874 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
18875 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
18876 if (!FD) {
18877 // Check whether this is a forward declaration that was inserted by
18878 // Clang. This happens when a non-forward declared / defined type is
18879 // used, e.g.:
18880 //
18881 // struct foo {
18882 // struct bar *(*f)();
18883 // struct bar *(*g)();
18884 // };
18885 //
18886 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
18887 // incomplete definition.
18888 if (const auto *TD = dyn_cast<TagDecl>(D))
18889 return !TD->isCompleteDefinition();
18890 return false;
18891 }
18892 QualType FieldType = FD->getType().getDesugaredType(Context);
18893 if (isa<PointerType>(FieldType)) {
18894 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
18895 return PointeeType.getDesugaredType(Context)->isFunctionType();
18896 }
18897 return false;
18898 };
18899
18900 // Maybe randomize the record's decls. We automatically randomize a record
18901 // of function pointers, unless it has the "no_randomize_layout" attribute.
18902 if (!getLangOpts().CPlusPlus &&
18903 (Record->hasAttr<RandomizeLayoutAttr>() ||
18904 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
18905 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
18906 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18907 !Record->isRandomized()) {
18908 SmallVector<Decl *, 32> NewDeclOrdering;
18909 if (randstruct::randomizeStructureLayout(Context, Record,
18910 NewDeclOrdering))
18911 Record->reorderDecls(NewDeclOrdering);
18912 }
18913
18914 // We may have deferred checking for a deleted destructor. Check now.
18915 if (CXXRecord) {
18916 auto *Dtor = CXXRecord->getDestructor();
18917 if (Dtor && Dtor->isImplicit() &&
18918 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18919 CXXRecord->setImplicitDestructorIsDeleted();
18920 SetDeclDeleted(Dtor, CXXRecord->getLocation());
18921 }
18922 }
18923
18924 if (Record->hasAttrs()) {
18925 CheckAlignasUnderalignment(Record);
18926
18927 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18928 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18929 IA->getRange(), IA->getBestCase(),
18930 IA->getInheritanceModel());
18931 }
18932
18933 // Check if the structure/union declaration is a type that can have zero
18934 // size in C. For C this is a language extension, for C++ it may cause
18935 // compatibility problems.
18936 bool CheckForZeroSize;
18937 if (!getLangOpts().CPlusPlus) {
18938 CheckForZeroSize = true;
18939 } else {
18940 // For C++ filter out types that cannot be referenced in C code.
18941 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18942 CheckForZeroSize =
18943 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18944 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18945 CXXRecord->isCLike();
18946 }
18947 if (CheckForZeroSize) {
18948 bool ZeroSize = true;
18949 bool IsEmpty = true;
18950 unsigned NonBitFields = 0;
18951 for (RecordDecl::field_iterator I = Record->field_begin(),
18952 E = Record->field_end();
18953 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18954 IsEmpty = false;
18955 if (I->isUnnamedBitfield()) {
18956 if (!I->isZeroLengthBitField(Context))
18957 ZeroSize = false;
18958 } else {
18959 ++NonBitFields;
18960 QualType FieldType = I->getType();
18961 if (FieldType->isIncompleteType() ||
18962 !Context.getTypeSizeInChars(FieldType).isZero())
18963 ZeroSize = false;
18964 }
18965 }
18966
18967 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18968 // allowed in C++, but warn if its declaration is inside
18969 // extern "C" block.
18970 if (ZeroSize) {
18971 Diag(RecLoc, getLangOpts().CPlusPlus ?
18972 diag::warn_zero_size_struct_union_in_extern_c :
18973 diag::warn_zero_size_struct_union_compat)
18974 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18975 }
18976
18977 // Structs without named members are extension in C (C99 6.7.2.1p7),
18978 // but are accepted by GCC.
18979 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18980 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18981 diag::ext_no_named_members_in_struct_union)
18982 << Record->isUnion();
18983 }
18984 }
18985 } else {
18986 ObjCIvarDecl **ClsFields =
18987 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18988 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18989 ID->setEndOfDefinitionLoc(RBrac);
18990 // Add ivar's to class's DeclContext.
18991 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18992 ClsFields[i]->setLexicalDeclContext(ID);
18993 ID->addDecl(ClsFields[i]);
18994 }
18995 // Must enforce the rule that ivars in the base classes may not be
18996 // duplicates.
18997 if (ID->getSuperClass())
18998 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18999 } else if (ObjCImplementationDecl *IMPDecl =
19000 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19001 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19002 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19003 // Ivar declared in @implementation never belongs to the implementation.
19004 // Only it is in implementation's lexical context.
19005 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19006 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19007 IMPDecl->setIvarLBraceLoc(LBrac);
19008 IMPDecl->setIvarRBraceLoc(RBrac);
19009 } else if (ObjCCategoryDecl *CDecl =
19010 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19011 // case of ivars in class extension; all other cases have been
19012 // reported as errors elsewhere.
19013 // FIXME. Class extension does not have a LocEnd field.
19014 // CDecl->setLocEnd(RBrac);
19015 // Add ivar's to class extension's DeclContext.
19016 // Diagnose redeclaration of private ivars.
19017 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19018 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19019 if (IDecl) {
19020 if (const ObjCIvarDecl *ClsIvar =
19021 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19022 Diag(ClsFields[i]->getLocation(),
19023 diag::err_duplicate_ivar_declaration);
19024 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19025 continue;
19026 }
19027 for (const auto *Ext : IDecl->known_extensions()) {
19028 if (const ObjCIvarDecl *ClsExtIvar
19029 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19030 Diag(ClsFields[i]->getLocation(),
19031 diag::err_duplicate_ivar_declaration);
19032 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19033 continue;
19034 }
19035 }
19036 }
19037 ClsFields[i]->setLexicalDeclContext(CDecl);
19038 CDecl->addDecl(ClsFields[i]);
19039 }
19040 CDecl->setIvarLBraceLoc(LBrac);
19041 CDecl->setIvarRBraceLoc(RBrac);
19042 }
19043 }
19044 }
19045
19046 /// Determine whether the given integral value is representable within
19047 /// the given type T.
isRepresentableIntegerValue(ASTContext & Context,llvm::APSInt & Value,QualType T)19048 static bool isRepresentableIntegerValue(ASTContext &Context,
19049 llvm::APSInt &Value,
19050 QualType T) {
19051 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19052 "Integral type required!");
19053 unsigned BitWidth = Context.getIntWidth(T);
19054
19055 if (Value.isUnsigned() || Value.isNonNegative()) {
19056 if (T->isSignedIntegerOrEnumerationType())
19057 --BitWidth;
19058 return Value.getActiveBits() <= BitWidth;
19059 }
19060 return Value.getMinSignedBits() <= BitWidth;
19061 }
19062
19063 // Given an integral type, return the next larger integral type
19064 // (or a NULL type of no such type exists).
getNextLargerIntegralType(ASTContext & Context,QualType T)19065 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19066 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19067 // enum checking below.
19068 assert((T->isIntegralType(Context) ||
19069 T->isEnumeralType()) && "Integral type required!");
19070 const unsigned NumTypes = 4;
19071 QualType SignedIntegralTypes[NumTypes] = {
19072 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19073 };
19074 QualType UnsignedIntegralTypes[NumTypes] = {
19075 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19076 Context.UnsignedLongLongTy
19077 };
19078
19079 unsigned BitWidth = Context.getTypeSize(T);
19080 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19081 : UnsignedIntegralTypes;
19082 for (unsigned I = 0; I != NumTypes; ++I)
19083 if (Context.getTypeSize(Types[I]) > BitWidth)
19084 return Types[I];
19085
19086 return QualType();
19087 }
19088
CheckEnumConstant(EnumDecl * Enum,EnumConstantDecl * LastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,Expr * Val)19089 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19090 EnumConstantDecl *LastEnumConst,
19091 SourceLocation IdLoc,
19092 IdentifierInfo *Id,
19093 Expr *Val) {
19094 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19095 llvm::APSInt EnumVal(IntWidth);
19096 QualType EltTy;
19097
19098 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
19099 Val = nullptr;
19100
19101 if (Val)
19102 Val = DefaultLvalueConversion(Val).get();
19103
19104 if (Val) {
19105 if (Enum->isDependentType() || Val->isTypeDependent() ||
19106 Val->containsErrors())
19107 EltTy = Context.DependentTy;
19108 else {
19109 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19110 // underlying type, but do allow it in all other contexts.
19111 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19112 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19113 // constant-expression in the enumerator-definition shall be a converted
19114 // constant expression of the underlying type.
19115 EltTy = Enum->getIntegerType();
19116 ExprResult Converted =
19117 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19118 CCEK_Enumerator);
19119 if (Converted.isInvalid())
19120 Val = nullptr;
19121 else
19122 Val = Converted.get();
19123 } else if (!Val->isValueDependent() &&
19124 !(Val =
19125 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
19126 .get())) {
19127 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19128 } else {
19129 if (Enum->isComplete()) {
19130 EltTy = Enum->getIntegerType();
19131
19132 // In Obj-C and Microsoft mode, require the enumeration value to be
19133 // representable in the underlying type of the enumeration. In C++11,
19134 // we perform a non-narrowing conversion as part of converted constant
19135 // expression checking.
19136 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19137 if (Context.getTargetInfo()
19138 .getTriple()
19139 .isWindowsMSVCEnvironment()) {
19140 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19141 } else {
19142 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19143 }
19144 }
19145
19146 // Cast to the underlying type.
19147 Val = ImpCastExprToType(Val, EltTy,
19148 EltTy->isBooleanType() ? CK_IntegralToBoolean
19149 : CK_IntegralCast)
19150 .get();
19151 } else if (getLangOpts().CPlusPlus) {
19152 // C++11 [dcl.enum]p5:
19153 // If the underlying type is not fixed, the type of each enumerator
19154 // is the type of its initializing value:
19155 // - If an initializer is specified for an enumerator, the
19156 // initializing value has the same type as the expression.
19157 EltTy = Val->getType();
19158 } else {
19159 // C99 6.7.2.2p2:
19160 // The expression that defines the value of an enumeration constant
19161 // shall be an integer constant expression that has a value
19162 // representable as an int.
19163
19164 // Complain if the value is not representable in an int.
19165 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
19166 Diag(IdLoc, diag::ext_enum_value_not_int)
19167 << toString(EnumVal, 10) << Val->getSourceRange()
19168 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19169 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19170 // Force the type of the expression to 'int'.
19171 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19172 }
19173 EltTy = Val->getType();
19174 }
19175 }
19176 }
19177 }
19178
19179 if (!Val) {
19180 if (Enum->isDependentType())
19181 EltTy = Context.DependentTy;
19182 else if (!LastEnumConst) {
19183 // C++0x [dcl.enum]p5:
19184 // If the underlying type is not fixed, the type of each enumerator
19185 // is the type of its initializing value:
19186 // - If no initializer is specified for the first enumerator, the
19187 // initializing value has an unspecified integral type.
19188 //
19189 // GCC uses 'int' for its unspecified integral type, as does
19190 // C99 6.7.2.2p3.
19191 if (Enum->isFixed()) {
19192 EltTy = Enum->getIntegerType();
19193 }
19194 else {
19195 EltTy = Context.IntTy;
19196 }
19197 } else {
19198 // Assign the last value + 1.
19199 EnumVal = LastEnumConst->getInitVal();
19200 ++EnumVal;
19201 EltTy = LastEnumConst->getType();
19202
19203 // Check for overflow on increment.
19204 if (EnumVal < LastEnumConst->getInitVal()) {
19205 // C++0x [dcl.enum]p5:
19206 // If the underlying type is not fixed, the type of each enumerator
19207 // is the type of its initializing value:
19208 //
19209 // - Otherwise the type of the initializing value is the same as
19210 // the type of the initializing value of the preceding enumerator
19211 // unless the incremented value is not representable in that type,
19212 // in which case the type is an unspecified integral type
19213 // sufficient to contain the incremented value. If no such type
19214 // exists, the program is ill-formed.
19215 QualType T = getNextLargerIntegralType(Context, EltTy);
19216 if (T.isNull() || Enum->isFixed()) {
19217 // There is no integral type larger enough to represent this
19218 // value. Complain, then allow the value to wrap around.
19219 EnumVal = LastEnumConst->getInitVal();
19220 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19221 ++EnumVal;
19222 if (Enum->isFixed())
19223 // When the underlying type is fixed, this is ill-formed.
19224 Diag(IdLoc, diag::err_enumerator_wrapped)
19225 << toString(EnumVal, 10)
19226 << EltTy;
19227 else
19228 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19229 << toString(EnumVal, 10);
19230 } else {
19231 EltTy = T;
19232 }
19233
19234 // Retrieve the last enumerator's value, extent that type to the
19235 // type that is supposed to be large enough to represent the incremented
19236 // value, then increment.
19237 EnumVal = LastEnumConst->getInitVal();
19238 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19239 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19240 ++EnumVal;
19241
19242 // If we're not in C++, diagnose the overflow of enumerator values,
19243 // which in C99 means that the enumerator value is not representable in
19244 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19245 // permits enumerator values that are representable in some larger
19246 // integral type.
19247 if (!getLangOpts().CPlusPlus && !T.isNull())
19248 Diag(IdLoc, diag::warn_enum_value_overflow);
19249 } else if (!getLangOpts().CPlusPlus &&
19250 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19251 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19252 Diag(IdLoc, diag::ext_enum_value_not_int)
19253 << toString(EnumVal, 10) << 1;
19254 }
19255 }
19256 }
19257
19258 if (!EltTy->isDependentType()) {
19259 // Make the enumerator value match the signedness and size of the
19260 // enumerator's type.
19261 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19262 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19263 }
19264
19265 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19266 Val, EnumVal);
19267 }
19268
shouldSkipAnonEnumBody(Scope * S,IdentifierInfo * II,SourceLocation IILoc)19269 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
19270 SourceLocation IILoc) {
19271 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19272 !getLangOpts().CPlusPlus)
19273 return SkipBodyInfo();
19274
19275 // We have an anonymous enum definition. Look up the first enumerator to
19276 // determine if we should merge the definition with an existing one and
19277 // skip the body.
19278 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19279 forRedeclarationInCurContext());
19280 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19281 if (!PrevECD)
19282 return SkipBodyInfo();
19283
19284 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19285 NamedDecl *Hidden;
19286 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19287 SkipBodyInfo Skip;
19288 Skip.Previous = Hidden;
19289 return Skip;
19290 }
19291
19292 return SkipBodyInfo();
19293 }
19294
ActOnEnumConstant(Scope * S,Decl * theEnumDecl,Decl * lastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,const ParsedAttributesView & Attrs,SourceLocation EqualLoc,Expr * Val)19295 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19296 SourceLocation IdLoc, IdentifierInfo *Id,
19297 const ParsedAttributesView &Attrs,
19298 SourceLocation EqualLoc, Expr *Val) {
19299 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19300 EnumConstantDecl *LastEnumConst =
19301 cast_or_null<EnumConstantDecl>(lastEnumConst);
19302
19303 // The scope passed in may not be a decl scope. Zip up the scope tree until
19304 // we find one that is.
19305 S = getNonFieldDeclScope(S);
19306
19307 // Verify that there isn't already something declared with this name in this
19308 // scope.
19309 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
19310 LookupName(R, S);
19311 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19312
19313 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19314 // Maybe we will complain about the shadowed template parameter.
19315 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19316 // Just pretend that we didn't see the previous declaration.
19317 PrevDecl = nullptr;
19318 }
19319
19320 // C++ [class.mem]p15:
19321 // If T is the name of a class, then each of the following shall have a name
19322 // different from T:
19323 // - every enumerator of every member of class T that is an unscoped
19324 // enumerated type
19325 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19326 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
19327 DeclarationNameInfo(Id, IdLoc));
19328
19329 EnumConstantDecl *New =
19330 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19331 if (!New)
19332 return nullptr;
19333
19334 if (PrevDecl) {
19335 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19336 // Check for other kinds of shadowing not already handled.
19337 CheckShadow(New, PrevDecl, R);
19338 }
19339
19340 // When in C++, we may get a TagDecl with the same name; in this case the
19341 // enum constant will 'hide' the tag.
19342 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19343 "Received TagDecl when not in C++!");
19344 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19345 if (isa<EnumConstantDecl>(PrevDecl))
19346 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19347 else
19348 Diag(IdLoc, diag::err_redefinition) << Id;
19349 notePreviousDefinition(PrevDecl, IdLoc);
19350 return nullptr;
19351 }
19352 }
19353
19354 // Process attributes.
19355 ProcessDeclAttributeList(S, New, Attrs);
19356 AddPragmaAttributes(S, New);
19357
19358 // Register this decl in the current scope stack.
19359 New->setAccess(TheEnumDecl->getAccess());
19360 PushOnScopeChains(New, S);
19361
19362 ActOnDocumentableDecl(New);
19363
19364 return New;
19365 }
19366
19367 // Returns true when the enum initial expression does not trigger the
19368 // duplicate enum warning. A few common cases are exempted as follows:
19369 // Element2 = Element1
19370 // Element2 = Element1 + 1
19371 // Element2 = Element1 - 1
19372 // Where Element2 and Element1 are from the same enum.
ValidDuplicateEnum(EnumConstantDecl * ECD,EnumDecl * Enum)19373 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
19374 Expr *InitExpr = ECD->getInitExpr();
19375 if (!InitExpr)
19376 return true;
19377 InitExpr = InitExpr->IgnoreImpCasts();
19378
19379 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19380 if (!BO->isAdditiveOp())
19381 return true;
19382 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19383 if (!IL)
19384 return true;
19385 if (IL->getValue() != 1)
19386 return true;
19387
19388 InitExpr = BO->getLHS();
19389 }
19390
19391 // This checks if the elements are from the same enum.
19392 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19393 if (!DRE)
19394 return true;
19395
19396 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19397 if (!EnumConstant)
19398 return true;
19399
19400 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19401 Enum)
19402 return true;
19403
19404 return false;
19405 }
19406
19407 // Emits a warning when an element is implicitly set a value that
19408 // a previous element has already been set to.
CheckForDuplicateEnumValues(Sema & S,ArrayRef<Decl * > Elements,EnumDecl * Enum,QualType EnumType)19409 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
19410 EnumDecl *Enum, QualType EnumType) {
19411 // Avoid anonymous enums
19412 if (!Enum->getIdentifier())
19413 return;
19414
19415 // Only check for small enums.
19416 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19417 return;
19418
19419 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19420 return;
19421
19422 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19423 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19424
19425 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19426
19427 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19428 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19429
19430 // Use int64_t as a key to avoid needing special handling for map keys.
19431 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19432 llvm::APSInt Val = D->getInitVal();
19433 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19434 };
19435
19436 DuplicatesVector DupVector;
19437 ValueToVectorMap EnumMap;
19438
19439 // Populate the EnumMap with all values represented by enum constants without
19440 // an initializer.
19441 for (auto *Element : Elements) {
19442 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19443
19444 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19445 // this constant. Skip this enum since it may be ill-formed.
19446 if (!ECD) {
19447 return;
19448 }
19449
19450 // Constants with initalizers are handled in the next loop.
19451 if (ECD->getInitExpr())
19452 continue;
19453
19454 // Duplicate values are handled in the next loop.
19455 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19456 }
19457
19458 if (EnumMap.size() == 0)
19459 return;
19460
19461 // Create vectors for any values that has duplicates.
19462 for (auto *Element : Elements) {
19463 // The last loop returned if any constant was null.
19464 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19465 if (!ValidDuplicateEnum(ECD, Enum))
19466 continue;
19467
19468 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19469 if (Iter == EnumMap.end())
19470 continue;
19471
19472 DeclOrVector& Entry = Iter->second;
19473 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19474 // Ensure constants are different.
19475 if (D == ECD)
19476 continue;
19477
19478 // Create new vector and push values onto it.
19479 auto Vec = std::make_unique<ECDVector>();
19480 Vec->push_back(D);
19481 Vec->push_back(ECD);
19482
19483 // Update entry to point to the duplicates vector.
19484 Entry = Vec.get();
19485
19486 // Store the vector somewhere we can consult later for quick emission of
19487 // diagnostics.
19488 DupVector.emplace_back(std::move(Vec));
19489 continue;
19490 }
19491
19492 ECDVector *Vec = Entry.get<ECDVector*>();
19493 // Make sure constants are not added more than once.
19494 if (*Vec->begin() == ECD)
19495 continue;
19496
19497 Vec->push_back(ECD);
19498 }
19499
19500 // Emit diagnostics.
19501 for (const auto &Vec : DupVector) {
19502 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19503
19504 // Emit warning for one enum constant.
19505 auto *FirstECD = Vec->front();
19506 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19507 << FirstECD << toString(FirstECD->getInitVal(), 10)
19508 << FirstECD->getSourceRange();
19509
19510 // Emit one note for each of the remaining enum constants with
19511 // the same value.
19512 for (auto *ECD : llvm::drop_begin(*Vec))
19513 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19514 << ECD << toString(ECD->getInitVal(), 10)
19515 << ECD->getSourceRange();
19516 }
19517 }
19518
IsValueInFlagEnum(const EnumDecl * ED,const llvm::APInt & Val,bool AllowMask) const19519 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19520 bool AllowMask) const {
19521 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19522 assert(ED->isCompleteDefinition() && "expected enum definition");
19523
19524 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19525 llvm::APInt &FlagBits = R.first->second;
19526
19527 if (R.second) {
19528 for (auto *E : ED->enumerators()) {
19529 const auto &EVal = E->getInitVal();
19530 // Only single-bit enumerators introduce new flag values.
19531 if (EVal.isPowerOf2())
19532 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19533 }
19534 }
19535
19536 // A value is in a flag enum if either its bits are a subset of the enum's
19537 // flag bits (the first condition) or we are allowing masks and the same is
19538 // true of its complement (the second condition). When masks are allowed, we
19539 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19540 //
19541 // While it's true that any value could be used as a mask, the assumption is
19542 // that a mask will have all of the insignificant bits set. Anything else is
19543 // likely a logic error.
19544 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19545 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
19546 }
19547
ActOnEnumBody(SourceLocation EnumLoc,SourceRange BraceRange,Decl * EnumDeclX,ArrayRef<Decl * > Elements,Scope * S,const ParsedAttributesView & Attrs)19548 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
19549 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19550 const ParsedAttributesView &Attrs) {
19551 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19552 QualType EnumType = Context.getTypeDeclType(Enum);
19553
19554 ProcessDeclAttributeList(S, Enum, Attrs);
19555
19556 if (Enum->isDependentType()) {
19557 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19558 EnumConstantDecl *ECD =
19559 cast_or_null<EnumConstantDecl>(Elements[i]);
19560 if (!ECD) continue;
19561
19562 ECD->setType(EnumType);
19563 }
19564
19565 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
19566 return;
19567 }
19568
19569 // TODO: If the result value doesn't fit in an int, it must be a long or long
19570 // long value. ISO C does not support this, but GCC does as an extension,
19571 // emit a warning.
19572 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19573 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
19574 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
19575
19576 // Verify that all the values are okay, compute the size of the values, and
19577 // reverse the list.
19578 unsigned NumNegativeBits = 0;
19579 unsigned NumPositiveBits = 0;
19580
19581 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19582 EnumConstantDecl *ECD =
19583 cast_or_null<EnumConstantDecl>(Elements[i]);
19584 if (!ECD) continue; // Already issued a diagnostic.
19585
19586 const llvm::APSInt &InitVal = ECD->getInitVal();
19587
19588 // Keep track of the size of positive and negative values.
19589 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
19590 // If the enumerator is zero that should still be counted as a positive
19591 // bit since we need a bit to store the value zero.
19592 unsigned ActiveBits = InitVal.getActiveBits();
19593 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
19594 } else {
19595 NumNegativeBits = std::max(NumNegativeBits,
19596 (unsigned)InitVal.getMinSignedBits());
19597 }
19598 }
19599
19600 // If we have an empty set of enumerators we still need one bit.
19601 // From [dcl.enum]p8
19602 // If the enumerator-list is empty, the values of the enumeration are as if
19603 // the enumeration had a single enumerator with value 0
19604 if (!NumPositiveBits && !NumNegativeBits)
19605 NumPositiveBits = 1;
19606
19607 // Figure out the type that should be used for this enum.
19608 QualType BestType;
19609 unsigned BestWidth;
19610
19611 // C++0x N3000 [conv.prom]p3:
19612 // An rvalue of an unscoped enumeration type whose underlying
19613 // type is not fixed can be converted to an rvalue of the first
19614 // of the following types that can represent all the values of
19615 // the enumeration: int, unsigned int, long int, unsigned long
19616 // int, long long int, or unsigned long long int.
19617 // C99 6.4.4.3p2:
19618 // An identifier declared as an enumeration constant has type int.
19619 // The C99 rule is modified by a gcc extension
19620 QualType BestPromotionType;
19621
19622 bool Packed = Enum->hasAttr<PackedAttr>();
19623 // -fshort-enums is the equivalent to specifying the packed attribute on all
19624 // enum definitions.
19625 if (LangOpts.ShortEnums)
19626 Packed = true;
19627
19628 // If the enum already has a type because it is fixed or dictated by the
19629 // target, promote that type instead of analyzing the enumerators.
19630 if (Enum->isComplete()) {
19631 BestType = Enum->getIntegerType();
19632 if (Context.isPromotableIntegerType(BestType))
19633 BestPromotionType = Context.getPromotedIntegerType(BestType);
19634 else
19635 BestPromotionType = BestType;
19636
19637 BestWidth = Context.getIntWidth(BestType);
19638 }
19639 else if (NumNegativeBits) {
19640 // If there is a negative value, figure out the smallest integer type (of
19641 // int/long/longlong) that fits.
19642 // If it's packed, check also if it fits a char or a short.
19643 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
19644 BestType = Context.SignedCharTy;
19645 BestWidth = CharWidth;
19646 } else if (Packed && NumNegativeBits <= ShortWidth &&
19647 NumPositiveBits < ShortWidth) {
19648 BestType = Context.ShortTy;
19649 BestWidth = ShortWidth;
19650 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
19651 BestType = Context.IntTy;
19652 BestWidth = IntWidth;
19653 } else {
19654 BestWidth = Context.getTargetInfo().getLongWidth();
19655
19656 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
19657 BestType = Context.LongTy;
19658 } else {
19659 BestWidth = Context.getTargetInfo().getLongLongWidth();
19660
19661 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
19662 Diag(Enum->getLocation(), diag::ext_enum_too_large);
19663 BestType = Context.LongLongTy;
19664 }
19665 }
19666 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
19667 } else {
19668 // If there is no negative value, figure out the smallest type that fits
19669 // all of the enumerator values.
19670 // If it's packed, check also if it fits a char or a short.
19671 if (Packed && NumPositiveBits <= CharWidth) {
19672 BestType = Context.UnsignedCharTy;
19673 BestPromotionType = Context.IntTy;
19674 BestWidth = CharWidth;
19675 } else if (Packed && NumPositiveBits <= ShortWidth) {
19676 BestType = Context.UnsignedShortTy;
19677 BestPromotionType = Context.IntTy;
19678 BestWidth = ShortWidth;
19679 } else if (NumPositiveBits <= IntWidth) {
19680 BestType = Context.UnsignedIntTy;
19681 BestWidth = IntWidth;
19682 BestPromotionType
19683 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19684 ? Context.UnsignedIntTy : Context.IntTy;
19685 } else if (NumPositiveBits <=
19686 (BestWidth = Context.getTargetInfo().getLongWidth())) {
19687 BestType = Context.UnsignedLongTy;
19688 BestPromotionType
19689 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19690 ? Context.UnsignedLongTy : Context.LongTy;
19691 } else {
19692 BestWidth = Context.getTargetInfo().getLongLongWidth();
19693 assert(NumPositiveBits <= BestWidth &&
19694 "How could an initializer get larger than ULL?");
19695 BestType = Context.UnsignedLongLongTy;
19696 BestPromotionType
19697 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19698 ? Context.UnsignedLongLongTy : Context.LongLongTy;
19699 }
19700 }
19701
19702 // Loop over all of the enumerator constants, changing their types to match
19703 // the type of the enum if needed.
19704 for (auto *D : Elements) {
19705 auto *ECD = cast_or_null<EnumConstantDecl>(D);
19706 if (!ECD) continue; // Already issued a diagnostic.
19707
19708 // Standard C says the enumerators have int type, but we allow, as an
19709 // extension, the enumerators to be larger than int size. If each
19710 // enumerator value fits in an int, type it as an int, otherwise type it the
19711 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
19712 // that X has type 'int', not 'unsigned'.
19713
19714 // Determine whether the value fits into an int.
19715 llvm::APSInt InitVal = ECD->getInitVal();
19716
19717 // If it fits into an integer type, force it. Otherwise force it to match
19718 // the enum decl type.
19719 QualType NewTy;
19720 unsigned NewWidth;
19721 bool NewSign;
19722 if (!getLangOpts().CPlusPlus &&
19723 !Enum->isFixed() &&
19724 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
19725 NewTy = Context.IntTy;
19726 NewWidth = IntWidth;
19727 NewSign = true;
19728 } else if (ECD->getType() == BestType) {
19729 // Already the right type!
19730 if (getLangOpts().CPlusPlus)
19731 // C++ [dcl.enum]p4: Following the closing brace of an
19732 // enum-specifier, each enumerator has the type of its
19733 // enumeration.
19734 ECD->setType(EnumType);
19735 continue;
19736 } else {
19737 NewTy = BestType;
19738 NewWidth = BestWidth;
19739 NewSign = BestType->isSignedIntegerOrEnumerationType();
19740 }
19741
19742 // Adjust the APSInt value.
19743 InitVal = InitVal.extOrTrunc(NewWidth);
19744 InitVal.setIsSigned(NewSign);
19745 ECD->setInitVal(InitVal);
19746
19747 // Adjust the Expr initializer and type.
19748 if (ECD->getInitExpr() &&
19749 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
19750 ECD->setInitExpr(ImplicitCastExpr::Create(
19751 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
19752 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
19753 if (getLangOpts().CPlusPlus)
19754 // C++ [dcl.enum]p4: Following the closing brace of an
19755 // enum-specifier, each enumerator has the type of its
19756 // enumeration.
19757 ECD->setType(EnumType);
19758 else
19759 ECD->setType(NewTy);
19760 }
19761
19762 Enum->completeDefinition(BestType, BestPromotionType,
19763 NumPositiveBits, NumNegativeBits);
19764
19765 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
19766
19767 if (Enum->isClosedFlag()) {
19768 for (Decl *D : Elements) {
19769 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
19770 if (!ECD) continue; // Already issued a diagnostic.
19771
19772 llvm::APSInt InitVal = ECD->getInitVal();
19773 if (InitVal != 0 && !InitVal.isPowerOf2() &&
19774 !IsValueInFlagEnum(Enum, InitVal, true))
19775 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
19776 << ECD << Enum;
19777 }
19778 }
19779
19780 // Now that the enum type is defined, ensure it's not been underaligned.
19781 if (Enum->hasAttrs())
19782 CheckAlignasUnderalignment(Enum);
19783 }
19784
ActOnFileScopeAsmDecl(Expr * expr,SourceLocation StartLoc,SourceLocation EndLoc)19785 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
19786 SourceLocation StartLoc,
19787 SourceLocation EndLoc) {
19788 StringLiteral *AsmString = cast<StringLiteral>(expr);
19789
19790 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
19791 AsmString, StartLoc,
19792 EndLoc);
19793 CurContext->addDecl(New);
19794 return New;
19795 }
19796
ActOnTopLevelStmtDecl(Stmt * Statement)19797 Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) {
19798 auto *New = TopLevelStmtDecl::Create(Context, Statement);
19799 Context.getTranslationUnitDecl()->addDecl(New);
19800 return New;
19801 }
19802
ActOnPragmaRedefineExtname(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)19803 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
19804 IdentifierInfo* AliasName,
19805 SourceLocation PragmaLoc,
19806 SourceLocation NameLoc,
19807 SourceLocation AliasNameLoc) {
19808 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19809 LookupOrdinaryName);
19810 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19811 AttributeCommonInfo::AS_Pragma);
19812 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19813 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19814
19815 // If a declaration that:
19816 // 1) declares a function or a variable
19817 // 2) has external linkage
19818 // already exists, add a label attribute to it.
19819 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19820 if (isDeclExternC(PrevDecl))
19821 PrevDecl->addAttr(Attr);
19822 else
19823 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19824 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19825 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
19826 } else
19827 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19828 }
19829
ActOnPragmaWeakID(IdentifierInfo * Name,SourceLocation PragmaLoc,SourceLocation NameLoc)19830 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19831 SourceLocation PragmaLoc,
19832 SourceLocation NameLoc) {
19833 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19834
19835 if (PrevDecl) {
19836 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
19837 } else {
19838 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19839 }
19840 }
19841
ActOnPragmaWeakAlias(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)19842 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
19843 IdentifierInfo* AliasName,
19844 SourceLocation PragmaLoc,
19845 SourceLocation NameLoc,
19846 SourceLocation AliasNameLoc) {
19847 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
19848 LookupOrdinaryName);
19849 WeakInfo W = WeakInfo(Name, NameLoc);
19850
19851 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19852 if (!PrevDecl->hasAttr<AliasAttr>())
19853 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
19854 DeclApplyPragmaWeak(TUScope, ND, W);
19855 } else {
19856 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
19857 }
19858 }
19859
getObjCDeclContext() const19860 ObjCContainerDecl *Sema::getObjCDeclContext() const {
19861 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19862 }
19863
getEmissionStatus(FunctionDecl * FD,bool Final)19864 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
19865 bool Final) {
19866 assert(FD && "Expected non-null FunctionDecl");
19867
19868 // SYCL functions can be template, so we check if they have appropriate
19869 // attribute prior to checking if it is a template.
19870 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19871 return FunctionEmissionStatus::Emitted;
19872
19873 // Templates are emitted when they're instantiated.
19874 if (FD->isDependentContext())
19875 return FunctionEmissionStatus::TemplateDiscarded;
19876
19877 // Check whether this function is an externally visible definition.
19878 auto IsEmittedForExternalSymbol = [this, FD]() {
19879 // We have to check the GVA linkage of the function's *definition* -- if we
19880 // only have a declaration, we don't know whether or not the function will
19881 // be emitted, because (say) the definition could include "inline".
19882 FunctionDecl *Def = FD->getDefinition();
19883
19884 return Def && !isDiscardableGVALinkage(
19885 getASTContext().GetGVALinkageForFunction(Def));
19886 };
19887
19888 if (LangOpts.OpenMPIsDevice) {
19889 // In OpenMP device mode we will not emit host only functions, or functions
19890 // we don't need due to their linkage.
19891 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19892 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19893 // DevTy may be changed later by
19894 // #pragma omp declare target to(*) device_type(*).
19895 // Therefore DevTy having no value does not imply host. The emission status
19896 // will be checked again at the end of compilation unit with Final = true.
19897 if (DevTy)
19898 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19899 return FunctionEmissionStatus::OMPDiscarded;
19900 // If we have an explicit value for the device type, or we are in a target
19901 // declare context, we need to emit all extern and used symbols.
19902 if (isInOpenMPDeclareTargetContext() || DevTy)
19903 if (IsEmittedForExternalSymbol())
19904 return FunctionEmissionStatus::Emitted;
19905 // Device mode only emits what it must, if it wasn't tagged yet and needed,
19906 // we'll omit it.
19907 if (Final)
19908 return FunctionEmissionStatus::OMPDiscarded;
19909 } else if (LangOpts.OpenMP > 45) {
19910 // In OpenMP host compilation prior to 5.0 everything was an emitted host
19911 // function. In 5.0, no_host was introduced which might cause a function to
19912 // be ommitted.
19913 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19914 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19915 if (DevTy)
19916 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19917 return FunctionEmissionStatus::OMPDiscarded;
19918 }
19919
19920 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19921 return FunctionEmissionStatus::Emitted;
19922
19923 if (LangOpts.CUDA) {
19924 // When compiling for device, host functions are never emitted. Similarly,
19925 // when compiling for host, device and global functions are never emitted.
19926 // (Technically, we do emit a host-side stub for global functions, but this
19927 // doesn't count for our purposes here.)
19928 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19929 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19930 return FunctionEmissionStatus::CUDADiscarded;
19931 if (!LangOpts.CUDAIsDevice &&
19932 (T == Sema::CFT_Device || T == Sema::CFT_Global))
19933 return FunctionEmissionStatus::CUDADiscarded;
19934
19935 if (IsEmittedForExternalSymbol())
19936 return FunctionEmissionStatus::Emitted;
19937 }
19938
19939 // Otherwise, the function is known-emitted if it's in our set of
19940 // known-emitted functions.
19941 return FunctionEmissionStatus::Unknown;
19942 }
19943
shouldIgnoreInHostDeviceCheck(FunctionDecl * Callee)19944 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19945 // Host-side references to a __global__ function refer to the stub, so the
19946 // function itself is never emitted and therefore should not be marked.
19947 // If we have host fn calls kernel fn calls host+device, the HD function
19948 // does not get instantiated on the host. We model this by omitting at the
19949 // call to the kernel from the callgraph. This ensures that, when compiling
19950 // for host, only HD functions actually called from the host get marked as
19951 // known-emitted.
19952 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19953 IdentifyCUDATarget(Callee) == CFT_Global;
19954 }
19955