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/ExprCXX.h"
25 #include "clang/AST/NonTrivialTypeVisitor.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50
51 using namespace clang;
52 using namespace sema;
53
ConvertDeclToDeclGroup(Decl * Ptr,Decl * OwnedType)54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55 if (OwnedType) {
56 Decl *Group[2] = { OwnedType, Ptr };
57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58 }
59
60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62
63 namespace {
64
65 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
66 public:
TypeNameValidatorCCC(bool AllowInvalid,bool WantClass=false,bool AllowTemplates=false,bool AllowNonTemplates=true)67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68 bool AllowTemplates = false,
69 bool AllowNonTemplates = true)
70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72 WantExpressionKeywords = false;
73 WantCXXNamedCasts = false;
74 WantRemainingKeywords = false;
75 }
76
ValidateCandidate(const TypoCorrection & candidate)77 bool ValidateCandidate(const TypoCorrection &candidate) override {
78 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79 if (!AllowInvalidDecl && ND->isInvalidDecl())
80 return false;
81
82 if (getAsTypeTemplateDecl(ND))
83 return AllowTemplates;
84
85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86 if (!IsType)
87 return false;
88
89 if (AllowNonTemplates)
90 return true;
91
92 // An injected-class-name of a class template (specialization) is valid
93 // as a template or as a non-template.
94 if (AllowTemplates) {
95 auto *RD = dyn_cast<CXXRecordDecl>(ND);
96 if (!RD || !RD->isInjectedClassName())
97 return false;
98 RD = cast<CXXRecordDecl>(RD->getDeclContext());
99 return RD->getDescribedClassTemplate() ||
100 isa<ClassTemplateSpecializationDecl>(RD);
101 }
102
103 return false;
104 }
105
106 return !WantClassName && candidate.isKeyword();
107 }
108
clone()109 std::unique_ptr<CorrectionCandidateCallback> clone() override {
110 return llvm::make_unique<TypeNameValidatorCCC>(*this);
111 }
112
113 private:
114 bool AllowInvalidDecl;
115 bool WantClassName;
116 bool AllowTemplates;
117 bool AllowNonTemplates;
118 };
119
120 } // end anonymous namespace
121
122 /// Determine whether the token kind starts a simple-type-specifier.
isSimpleTypeSpecifier(tok::TokenKind Kind) const123 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
124 switch (Kind) {
125 // FIXME: Take into account the current language when deciding whether a
126 // token kind is a valid type specifier
127 case tok::kw_short:
128 case tok::kw_long:
129 case tok::kw___int64:
130 case tok::kw___int128:
131 case tok::kw_signed:
132 case tok::kw_unsigned:
133 case tok::kw_void:
134 case tok::kw_char:
135 case tok::kw_int:
136 case tok::kw_half:
137 case tok::kw_float:
138 case tok::kw_double:
139 case tok::kw__Float16:
140 case tok::kw___float128:
141 case tok::kw_wchar_t:
142 case tok::kw_bool:
143 case tok::kw___underlying_type:
144 case tok::kw___auto_type:
145 return true;
146
147 case tok::annot_typename:
148 case tok::kw_char16_t:
149 case tok::kw_char32_t:
150 case tok::kw_typeof:
151 case tok::annot_decltype:
152 case tok::kw_decltype:
153 return getLangOpts().CPlusPlus;
154
155 case tok::kw_char8_t:
156 return getLangOpts().Char8;
157
158 default:
159 break;
160 }
161
162 return false;
163 }
164
165 namespace {
166 enum class UnqualifiedTypeNameLookupResult {
167 NotFound,
168 FoundNonType,
169 FoundType
170 };
171 } // end anonymous namespace
172
173 /// Tries to perform unqualified lookup of the type decls in bases for
174 /// dependent class.
175 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
176 /// type decl, \a FoundType if only type decls are found.
177 static UnqualifiedTypeNameLookupResult
lookupUnqualifiedTypeNameInBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc,const CXXRecordDecl * RD)178 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
179 SourceLocation NameLoc,
180 const CXXRecordDecl *RD) {
181 if (!RD->hasDefinition())
182 return UnqualifiedTypeNameLookupResult::NotFound;
183 // Look for type decls in base classes.
184 UnqualifiedTypeNameLookupResult FoundTypeDecl =
185 UnqualifiedTypeNameLookupResult::NotFound;
186 for (const auto &Base : RD->bases()) {
187 const CXXRecordDecl *BaseRD = nullptr;
188 if (auto *BaseTT = Base.getType()->getAs<TagType>())
189 BaseRD = BaseTT->getAsCXXRecordDecl();
190 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
191 // Look for type decls in dependent base classes that have known primary
192 // templates.
193 if (!TST || !TST->isDependentType())
194 continue;
195 auto *TD = TST->getTemplateName().getAsTemplateDecl();
196 if (!TD)
197 continue;
198 if (auto *BasePrimaryTemplate =
199 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
200 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
201 BaseRD = BasePrimaryTemplate;
202 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
203 if (const ClassTemplatePartialSpecializationDecl *PS =
204 CTD->findPartialSpecialization(Base.getType()))
205 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
206 BaseRD = PS;
207 }
208 }
209 }
210 if (BaseRD) {
211 for (NamedDecl *ND : BaseRD->lookup(&II)) {
212 if (!isa<TypeDecl>(ND))
213 return UnqualifiedTypeNameLookupResult::FoundNonType;
214 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215 }
216 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
217 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
218 case UnqualifiedTypeNameLookupResult::FoundNonType:
219 return UnqualifiedTypeNameLookupResult::FoundNonType;
220 case UnqualifiedTypeNameLookupResult::FoundType:
221 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
222 break;
223 case UnqualifiedTypeNameLookupResult::NotFound:
224 break;
225 }
226 }
227 }
228 }
229
230 return FoundTypeDecl;
231 }
232
recoverFromTypeInKnownDependentBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc)233 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
234 const IdentifierInfo &II,
235 SourceLocation NameLoc) {
236 // Lookup in the parent class template context, if any.
237 const CXXRecordDecl *RD = nullptr;
238 UnqualifiedTypeNameLookupResult FoundTypeDecl =
239 UnqualifiedTypeNameLookupResult::NotFound;
240 for (DeclContext *DC = S.CurContext;
241 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
242 DC = DC->getParent()) {
243 // Look for type decls in dependent base classes that have known primary
244 // templates.
245 RD = dyn_cast<CXXRecordDecl>(DC);
246 if (RD && RD->getDescribedClassTemplate())
247 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
248 }
249 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
250 return nullptr;
251
252 // We found some types in dependent base classes. Recover as if the user
253 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
254 // lookup during template instantiation.
255 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
256
257 ASTContext &Context = S.Context;
258 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
259 cast<Type>(Context.getRecordType(RD)));
260 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
261
262 CXXScopeSpec SS;
263 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
264
265 TypeLocBuilder Builder;
266 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
267 DepTL.setNameLoc(NameLoc);
268 DepTL.setElaboratedKeywordLoc(SourceLocation());
269 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
270 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
271 }
272
273 /// If the identifier refers to a type name within this scope,
274 /// return the declaration of that type.
275 ///
276 /// This routine performs ordinary name lookup of the identifier II
277 /// within the given scope, with optional C++ scope specifier SS, to
278 /// determine whether the name refers to a type. If so, returns an
279 /// opaque pointer (actually a QualType) corresponding to that
280 /// 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,IdentifierInfo ** CorrectedII)281 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
282 Scope *S, CXXScopeSpec *SS,
283 bool isClassName, bool HasTrailingDot,
284 ParsedType ObjectTypePtr,
285 bool IsCtorOrDtorName,
286 bool WantNontrivialTypeSourceInfo,
287 bool IsClassTemplateDeductionContext,
288 IdentifierInfo **CorrectedII) {
289 // FIXME: Consider allowing this outside C++1z mode as an extension.
290 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
291 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
292 !isClassName && !HasTrailingDot;
293
294 // Determine where we will perform name lookup.
295 DeclContext *LookupCtx = nullptr;
296 if (ObjectTypePtr) {
297 QualType ObjectType = ObjectTypePtr.get();
298 if (ObjectType->isRecordType())
299 LookupCtx = computeDeclContext(ObjectType);
300 } else if (SS && SS->isNotEmpty()) {
301 LookupCtx = computeDeclContext(*SS, false);
302
303 if (!LookupCtx) {
304 if (isDependentScopeSpecifier(*SS)) {
305 // C++ [temp.res]p3:
306 // A qualified-id that refers to a type and in which the
307 // nested-name-specifier depends on a template-parameter (14.6.2)
308 // shall be prefixed by the keyword typename to indicate that the
309 // qualified-id denotes a type, forming an
310 // elaborated-type-specifier (7.1.5.3).
311 //
312 // We therefore do not perform any name lookup if the result would
313 // refer to a member of an unknown specialization.
314 if (!isClassName && !IsCtorOrDtorName)
315 return nullptr;
316
317 // We know from the grammar that this name refers to a type,
318 // so build a dependent node to describe the type.
319 if (WantNontrivialTypeSourceInfo)
320 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
321
322 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
323 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
324 II, NameLoc);
325 return ParsedType::make(T);
326 }
327
328 return nullptr;
329 }
330
331 if (!LookupCtx->isDependentContext() &&
332 RequireCompleteDeclContext(*SS, LookupCtx))
333 return nullptr;
334 }
335
336 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
337 // lookup for class-names.
338 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
339 LookupOrdinaryName;
340 LookupResult Result(*this, &II, NameLoc, Kind);
341 if (LookupCtx) {
342 // Perform "qualified" name lookup into the declaration context we
343 // computed, which is either the type of the base of a member access
344 // expression or the declaration context associated with a prior
345 // nested-name-specifier.
346 LookupQualifiedName(Result, LookupCtx);
347
348 if (ObjectTypePtr && Result.empty()) {
349 // C++ [basic.lookup.classref]p3:
350 // If the unqualified-id is ~type-name, the type-name is looked up
351 // in the context of the entire postfix-expression. If the type T of
352 // the object expression is of a class type C, the type-name is also
353 // looked up in the scope of class C. At least one of the lookups shall
354 // find a name that refers to (possibly cv-qualified) T.
355 LookupName(Result, S);
356 }
357 } else {
358 // Perform unqualified name lookup.
359 LookupName(Result, S);
360
361 // For unqualified lookup in a class template in MSVC mode, look into
362 // dependent base classes where the primary class template is known.
363 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
364 if (ParsedType TypeInBase =
365 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
366 return TypeInBase;
367 }
368 }
369
370 NamedDecl *IIDecl = nullptr;
371 switch (Result.getResultKind()) {
372 case LookupResult::NotFound:
373 case LookupResult::NotFoundInCurrentInstantiation:
374 if (CorrectedII) {
375 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
376 AllowDeducedTemplate);
377 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
378 S, SS, CCC, CTK_ErrorRecovery);
379 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
380 TemplateTy Template;
381 bool MemberOfUnknownSpecialization;
382 UnqualifiedId TemplateName;
383 TemplateName.setIdentifier(NewII, NameLoc);
384 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
385 CXXScopeSpec NewSS, *NewSSPtr = SS;
386 if (SS && NNS) {
387 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
388 NewSSPtr = &NewSS;
389 }
390 if (Correction && (NNS || NewII != &II) &&
391 // Ignore a correction to a template type as the to-be-corrected
392 // identifier is not a template (typo correction for template names
393 // is handled elsewhere).
394 !(getLangOpts().CPlusPlus && NewSSPtr &&
395 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
396 Template, MemberOfUnknownSpecialization))) {
397 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
398 isClassName, HasTrailingDot, ObjectTypePtr,
399 IsCtorOrDtorName,
400 WantNontrivialTypeSourceInfo,
401 IsClassTemplateDeductionContext);
402 if (Ty) {
403 diagnoseTypo(Correction,
404 PDiag(diag::err_unknown_type_or_class_name_suggest)
405 << Result.getLookupName() << isClassName);
406 if (SS && NNS)
407 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
408 *CorrectedII = NewII;
409 return Ty;
410 }
411 }
412 }
413 // If typo correction failed or was not performed, fall through
414 LLVM_FALLTHROUGH;
415 case LookupResult::FoundOverloaded:
416 case LookupResult::FoundUnresolvedValue:
417 Result.suppressDiagnostics();
418 return nullptr;
419
420 case LookupResult::Ambiguous:
421 // Recover from type-hiding ambiguities by hiding the type. We'll
422 // do the lookup again when looking for an object, and we can
423 // diagnose the error then. If we don't do this, then the error
424 // about hiding the type will be immediately followed by an error
425 // that only makes sense if the identifier was treated like a type.
426 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
427 Result.suppressDiagnostics();
428 return nullptr;
429 }
430
431 // Look to see if we have a type anywhere in the list of results.
432 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
433 Res != ResEnd; ++Res) {
434 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
435 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
436 if (!IIDecl ||
437 (*Res)->getLocation().getRawEncoding() <
438 IIDecl->getLocation().getRawEncoding())
439 IIDecl = *Res;
440 }
441 }
442
443 if (!IIDecl) {
444 // None of the entities we found is a type, so there is no way
445 // to even assume that the result is a type. In this case, don't
446 // complain about the ambiguity. The parser will either try to
447 // perform this lookup again (e.g., as an object name), which
448 // will produce the ambiguity, or will complain that it expected
449 // a type name.
450 Result.suppressDiagnostics();
451 return nullptr;
452 }
453
454 // We found a type within the ambiguous lookup; diagnose the
455 // ambiguity and then return that type. This might be the right
456 // answer, or it might not be, but it suppresses any attempt to
457 // perform the name lookup again.
458 break;
459
460 case LookupResult::Found:
461 IIDecl = Result.getFoundDecl();
462 break;
463 }
464
465 assert(IIDecl && "Didn't find decl");
466
467 QualType T;
468 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
469 // C++ [class.qual]p2: A lookup that would find the injected-class-name
470 // instead names the constructors of the class, except when naming a class.
471 // This is ill-formed when we're not actually forming a ctor or dtor name.
472 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
473 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
474 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
475 FoundRD->isInjectedClassName() &&
476 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
477 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
478 << &II << /*Type*/1;
479
480 DiagnoseUseOfDecl(IIDecl, NameLoc);
481
482 T = Context.getTypeDeclType(TD);
483 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
484 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
485 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
486 if (!HasTrailingDot)
487 T = Context.getObjCInterfaceType(IDecl);
488 } else if (AllowDeducedTemplate) {
489 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
490 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
491 QualType(), false);
492 }
493
494 if (T.isNull()) {
495 // If it's not plausibly a type, suppress diagnostics.
496 Result.suppressDiagnostics();
497 return nullptr;
498 }
499
500 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
501 // constructor or destructor name (in such a case, the scope specifier
502 // will be attached to the enclosing Expr or Decl node).
503 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
504 !isa<ObjCInterfaceDecl>(IIDecl)) {
505 if (WantNontrivialTypeSourceInfo) {
506 // Construct a type with type-source information.
507 TypeLocBuilder Builder;
508 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
509
510 T = getElaboratedType(ETK_None, *SS, T);
511 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
512 ElabTL.setElaboratedKeywordLoc(SourceLocation());
513 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
514 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
515 } else {
516 T = getElaboratedType(ETK_None, *SS, T);
517 }
518 }
519
520 return ParsedType::make(T);
521 }
522
523 // Builds a fake NNS for the given decl context.
524 static NestedNameSpecifier *
synthesizeCurrentNestedNameSpecifier(ASTContext & Context,DeclContext * DC)525 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
526 for (;; DC = DC->getLookupParent()) {
527 DC = DC->getPrimaryContext();
528 auto *ND = dyn_cast<NamespaceDecl>(DC);
529 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
530 return NestedNameSpecifier::Create(Context, nullptr, ND);
531 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
532 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
533 RD->getTypeForDecl());
534 else if (isa<TranslationUnitDecl>(DC))
535 return NestedNameSpecifier::GlobalSpecifier(Context);
536 }
537 llvm_unreachable("something isn't in TU scope?");
538 }
539
540 /// Find the parent class with dependent bases of the innermost enclosing method
541 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
542 /// up allowing unqualified dependent type names at class-level, which MSVC
543 /// correctly rejects.
544 static const CXXRecordDecl *
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext * DC)545 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
546 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
547 DC = DC->getPrimaryContext();
548 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
549 if (MD->getParent()->hasAnyDependentBases())
550 return MD->getParent();
551 }
552 return nullptr;
553 }
554
ActOnMSVCUnknownTypeName(const IdentifierInfo & II,SourceLocation NameLoc,bool IsTemplateTypeArg)555 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
556 SourceLocation NameLoc,
557 bool IsTemplateTypeArg) {
558 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
559
560 NestedNameSpecifier *NNS = nullptr;
561 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
562 // If we weren't able to parse a default template argument, delay lookup
563 // until instantiation time by making a non-dependent DependentTypeName. We
564 // pretend we saw a NestedNameSpecifier referring to the current scope, and
565 // lookup is retried.
566 // FIXME: This hurts our diagnostic quality, since we get errors like "no
567 // type named 'Foo' in 'current_namespace'" when the user didn't write any
568 // name specifiers.
569 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
570 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
571 } else if (const CXXRecordDecl *RD =
572 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
573 // Build a DependentNameType that will perform lookup into RD at
574 // instantiation time.
575 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
576 RD->getTypeForDecl());
577
578 // Diagnose that this identifier was undeclared, and retry the lookup during
579 // template instantiation.
580 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
581 << RD;
582 } else {
583 // This is not a situation that we should recover from.
584 return ParsedType();
585 }
586
587 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
588
589 // Build type location information. We synthesized the qualifier, so we have
590 // to build a fake NestedNameSpecifierLoc.
591 NestedNameSpecifierLocBuilder NNSLocBuilder;
592 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
593 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
594
595 TypeLocBuilder Builder;
596 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
597 DepTL.setNameLoc(NameLoc);
598 DepTL.setElaboratedKeywordLoc(SourceLocation());
599 DepTL.setQualifierLoc(QualifierLoc);
600 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
601 }
602
603 /// isTagName() - This method is called *for error recovery purposes only*
604 /// to determine if the specified name is a valid tag name ("struct foo"). If
605 /// so, this returns the TST for the tag corresponding to it (TST_enum,
606 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
607 /// cases in C where the user forgot to specify the tag.
isTagName(IdentifierInfo & II,Scope * S)608 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
609 // Do a tag name lookup in this scope.
610 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
611 LookupName(R, S, false);
612 R.suppressDiagnostics();
613 if (R.getResultKind() == LookupResult::Found)
614 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
615 switch (TD->getTagKind()) {
616 case TTK_Struct: return DeclSpec::TST_struct;
617 case TTK_Interface: return DeclSpec::TST_interface;
618 case TTK_Union: return DeclSpec::TST_union;
619 case TTK_Class: return DeclSpec::TST_class;
620 case TTK_Enum: return DeclSpec::TST_enum;
621 }
622 }
623
624 return DeclSpec::TST_unspecified;
625 }
626
627 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
628 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
629 /// then downgrade the missing typename error to a warning.
630 /// This is needed for MSVC compatibility; Example:
631 /// @code
632 /// template<class T> class A {
633 /// public:
634 /// typedef int TYPE;
635 /// };
636 /// template<class T> class B : public A<T> {
637 /// public:
638 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
639 /// };
640 /// @endcode
isMicrosoftMissingTypename(const CXXScopeSpec * SS,Scope * S)641 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
642 if (CurContext->isRecord()) {
643 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
644 return true;
645
646 const Type *Ty = SS->getScopeRep()->getAsType();
647
648 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
649 for (const auto &Base : RD->bases())
650 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
651 return true;
652 return S->isFunctionPrototypeScope();
653 }
654 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
655 }
656
DiagnoseUnknownTypeName(IdentifierInfo * & II,SourceLocation IILoc,Scope * S,CXXScopeSpec * SS,ParsedType & SuggestedType,bool IsTemplateName)657 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
658 SourceLocation IILoc,
659 Scope *S,
660 CXXScopeSpec *SS,
661 ParsedType &SuggestedType,
662 bool IsTemplateName) {
663 // Don't report typename errors for editor placeholders.
664 if (II->isEditorPlaceholder())
665 return;
666 // We don't have anything to suggest (yet).
667 SuggestedType = nullptr;
668
669 // There may have been a typo in the name of the type. Look up typo
670 // results, in case we have something that we can suggest.
671 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
672 /*AllowTemplates=*/IsTemplateName,
673 /*AllowNonTemplates=*/!IsTemplateName);
674 if (TypoCorrection Corrected =
675 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
676 CCC, CTK_ErrorRecovery)) {
677 // FIXME: Support error recovery for the template-name case.
678 bool CanRecover = !IsTemplateName;
679 if (Corrected.isKeyword()) {
680 // We corrected to a keyword.
681 diagnoseTypo(Corrected,
682 PDiag(IsTemplateName ? diag::err_no_template_suggest
683 : diag::err_unknown_typename_suggest)
684 << II);
685 II = Corrected.getCorrectionAsIdentifierInfo();
686 } else {
687 // We found a similarly-named type or interface; suggest that.
688 if (!SS || !SS->isSet()) {
689 diagnoseTypo(Corrected,
690 PDiag(IsTemplateName ? diag::err_no_template_suggest
691 : diag::err_unknown_typename_suggest)
692 << II, CanRecover);
693 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
694 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
695 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
696 II->getName().equals(CorrectedStr);
697 diagnoseTypo(Corrected,
698 PDiag(IsTemplateName
699 ? diag::err_no_member_template_suggest
700 : diag::err_unknown_nested_typename_suggest)
701 << II << DC << DroppedSpecifier << SS->getRange(),
702 CanRecover);
703 } else {
704 llvm_unreachable("could not have corrected a typo here");
705 }
706
707 if (!CanRecover)
708 return;
709
710 CXXScopeSpec tmpSS;
711 if (Corrected.getCorrectionSpecifier())
712 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
713 SourceRange(IILoc));
714 // FIXME: Support class template argument deduction here.
715 SuggestedType =
716 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
717 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
718 /*IsCtorOrDtorName=*/false,
719 /*WantNontrivialTypeSourceInfo=*/true);
720 }
721 return;
722 }
723
724 if (getLangOpts().CPlusPlus && !IsTemplateName) {
725 // See if II is a class template that the user forgot to pass arguments to.
726 UnqualifiedId Name;
727 Name.setIdentifier(II, IILoc);
728 CXXScopeSpec EmptySS;
729 TemplateTy TemplateResult;
730 bool MemberOfUnknownSpecialization;
731 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
732 Name, nullptr, true, TemplateResult,
733 MemberOfUnknownSpecialization) == TNK_Type_template) {
734 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
735 return;
736 }
737 }
738
739 // FIXME: Should we move the logic that tries to recover from a missing tag
740 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
741
742 if (!SS || (!SS->isSet() && !SS->isInvalid()))
743 Diag(IILoc, IsTemplateName ? diag::err_no_template
744 : diag::err_unknown_typename)
745 << II;
746 else if (DeclContext *DC = computeDeclContext(*SS, false))
747 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
748 : diag::err_typename_nested_not_found)
749 << II << DC << SS->getRange();
750 else if (isDependentScopeSpecifier(*SS)) {
751 unsigned DiagID = diag::err_typename_missing;
752 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
753 DiagID = diag::ext_typename_missing;
754
755 Diag(SS->getRange().getBegin(), DiagID)
756 << SS->getScopeRep() << II->getName()
757 << SourceRange(SS->getRange().getBegin(), IILoc)
758 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
759 SuggestedType = ActOnTypenameType(S, SourceLocation(),
760 *SS, *II, IILoc).get();
761 } else {
762 assert(SS && SS->isInvalid() &&
763 "Invalid scope specifier has already been diagnosed");
764 }
765 }
766
767 /// Determine whether the given result set contains either a type name
768 /// or
isResultTypeOrTemplate(LookupResult & R,const Token & NextToken)769 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
770 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
771 NextToken.is(tok::less);
772
773 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
774 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
775 return true;
776
777 if (CheckTemplate && isa<TemplateDecl>(*I))
778 return true;
779 }
780
781 return false;
782 }
783
isTagTypeWithMissingTag(Sema & SemaRef,LookupResult & Result,Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc)784 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
785 Scope *S, CXXScopeSpec &SS,
786 IdentifierInfo *&Name,
787 SourceLocation NameLoc) {
788 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
789 SemaRef.LookupParsedName(R, S, &SS);
790 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
791 StringRef FixItTagName;
792 switch (Tag->getTagKind()) {
793 case TTK_Class:
794 FixItTagName = "class ";
795 break;
796
797 case TTK_Enum:
798 FixItTagName = "enum ";
799 break;
800
801 case TTK_Struct:
802 FixItTagName = "struct ";
803 break;
804
805 case TTK_Interface:
806 FixItTagName = "__interface ";
807 break;
808
809 case TTK_Union:
810 FixItTagName = "union ";
811 break;
812 }
813
814 StringRef TagName = FixItTagName.drop_back();
815 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
816 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
817 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
818
819 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
820 I != IEnd; ++I)
821 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
822 << Name << TagName;
823
824 // Replace lookup results with just the tag decl.
825 Result.clear(Sema::LookupTagName);
826 SemaRef.LookupParsedName(Result, S, &SS);
827 return true;
828 }
829
830 return false;
831 }
832
833 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
buildNestedType(Sema & S,CXXScopeSpec & SS,QualType T,SourceLocation NameLoc)834 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
835 QualType T, SourceLocation NameLoc) {
836 ASTContext &Context = S.Context;
837
838 TypeLocBuilder Builder;
839 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
840
841 T = S.getElaboratedType(ETK_None, SS, T);
842 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
843 ElabTL.setElaboratedKeywordLoc(SourceLocation());
844 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
845 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
846 }
847
848 Sema::NameClassification
ClassifyName(Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc,const Token & NextToken,bool IsAddressOfOperand,CorrectionCandidateCallback * CCC)849 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
850 SourceLocation NameLoc, const Token &NextToken,
851 bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) {
852 DeclarationNameInfo NameInfo(Name, NameLoc);
853 ObjCMethodDecl *CurMethod = getCurMethodDecl();
854
855 if (NextToken.is(tok::coloncolon)) {
856 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
857 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
858 } else if (getLangOpts().CPlusPlus && SS.isSet() &&
859 isCurrentClassName(*Name, S, &SS)) {
860 // Per [class.qual]p2, this names the constructors of SS, not the
861 // injected-class-name. We don't have a classification for that.
862 // There's not much point caching this result, since the parser
863 // will reject it later.
864 return NameClassification::Unknown();
865 }
866
867 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868 LookupParsedName(Result, S, &SS, !CurMethod);
869
870 // For unqualified lookup in a class template in MSVC mode, look into
871 // dependent base classes where the primary class template is known.
872 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873 if (ParsedType TypeInBase =
874 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875 return TypeInBase;
876 }
877
878 // Perform lookup for Objective-C instance variables (including automatically
879 // synthesized instance variables), if we're in an Objective-C method.
880 // FIXME: This lookup really, really needs to be folded in to the normal
881 // unqualified lookup mechanism.
882 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
884 if (E.get() || E.isInvalid())
885 return E;
886 }
887
888 bool SecondTry = false;
889 bool IsFilteredTemplateName = false;
890
891 Corrected:
892 switch (Result.getResultKind()) {
893 case LookupResult::NotFound:
894 // If an unqualified-id is followed by a '(', then we have a function
895 // call.
896 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
897 // In C++, this is an ADL-only call.
898 // FIXME: Reference?
899 if (getLangOpts().CPlusPlus)
900 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901
902 // C90 6.3.2.2:
903 // If the expression that precedes the parenthesized argument list in a
904 // function call consists solely of an identifier, and if no
905 // declaration is visible for this identifier, the identifier is
906 // implicitly declared exactly as if, in the innermost block containing
907 // the function call, the declaration
908 //
909 // extern int identifier ();
910 //
911 // appeared.
912 //
913 // We also allow this in C99 as an extension.
914 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915 Result.addDecl(D);
916 Result.resolveKind();
917 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918 }
919 }
920
921 if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
922 // In C++20 onwards, this could be an ADL-only call to a function
923 // template, and we're required to assume that this is a template name.
924 //
925 // FIXME: Find a way to still do typo correction in this case.
926 TemplateName Template =
927 Context.getAssumedTemplateName(NameInfo.getName());
928 return NameClassification::UndeclaredTemplate(Template);
929 }
930
931 // In C, we first see whether there is a tag type by the same name, in
932 // which case it's likely that the user just forgot to write "enum",
933 // "struct", or "union".
934 if (!getLangOpts().CPlusPlus && !SecondTry &&
935 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
936 break;
937 }
938
939 // Perform typo correction to determine if there is another name that is
940 // close to this name.
941 if (!SecondTry && CCC) {
942 SecondTry = true;
943 if (TypoCorrection Corrected =
944 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
945 &SS, *CCC, CTK_ErrorRecovery)) {
946 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
947 unsigned QualifiedDiag = diag::err_no_member_suggest;
948
949 NamedDecl *FirstDecl = Corrected.getFoundDecl();
950 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
951 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
952 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
953 UnqualifiedDiag = diag::err_no_template_suggest;
954 QualifiedDiag = diag::err_no_member_template_suggest;
955 } else if (UnderlyingFirstDecl &&
956 (isa<TypeDecl>(UnderlyingFirstDecl) ||
957 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
958 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
959 UnqualifiedDiag = diag::err_unknown_typename_suggest;
960 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
961 }
962
963 if (SS.isEmpty()) {
964 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
965 } else {// FIXME: is this even reachable? Test it.
966 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
967 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
968 Name->getName().equals(CorrectedStr);
969 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
970 << Name << computeDeclContext(SS, false)
971 << DroppedSpecifier << SS.getRange());
972 }
973
974 // Update the name, so that the caller has the new name.
975 Name = Corrected.getCorrectionAsIdentifierInfo();
976
977 // Typo correction corrected to a keyword.
978 if (Corrected.isKeyword())
979 return Name;
980
981 // Also update the LookupResult...
982 // FIXME: This should probably go away at some point
983 Result.clear();
984 Result.setLookupName(Corrected.getCorrection());
985 if (FirstDecl)
986 Result.addDecl(FirstDecl);
987
988 // If we found an Objective-C instance variable, let
989 // LookupInObjCMethod build the appropriate expression to
990 // reference the ivar.
991 // FIXME: This is a gross hack.
992 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
993 Result.clear();
994 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
995 return E;
996 }
997
998 goto Corrected;
999 }
1000 }
1001
1002 // We failed to correct; just fall through and let the parser deal with it.
1003 Result.suppressDiagnostics();
1004 return NameClassification::Unknown();
1005
1006 case LookupResult::NotFoundInCurrentInstantiation: {
1007 // We performed name lookup into the current instantiation, and there were
1008 // dependent bases, so we treat this result the same way as any other
1009 // dependent nested-name-specifier.
1010
1011 // C++ [temp.res]p2:
1012 // A name used in a template declaration or definition and that is
1013 // dependent on a template-parameter is assumed not to name a type
1014 // unless the applicable name lookup finds a type name or the name is
1015 // qualified by the keyword typename.
1016 //
1017 // FIXME: If the next token is '<', we might want to ask the parser to
1018 // perform some heroics to see if we actually have a
1019 // template-argument-list, which would indicate a missing 'template'
1020 // keyword here.
1021 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1022 NameInfo, IsAddressOfOperand,
1023 /*TemplateArgs=*/nullptr);
1024 }
1025
1026 case LookupResult::Found:
1027 case LookupResult::FoundOverloaded:
1028 case LookupResult::FoundUnresolvedValue:
1029 break;
1030
1031 case LookupResult::Ambiguous:
1032 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1033 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1034 /*AllowDependent=*/false)) {
1035 // C++ [temp.local]p3:
1036 // A lookup that finds an injected-class-name (10.2) can result in an
1037 // ambiguity in certain cases (for example, if it is found in more than
1038 // one base class). If all of the injected-class-names that are found
1039 // refer to specializations of the same class template, and if the name
1040 // is followed by a template-argument-list, the reference refers to the
1041 // class template itself and not a specialization thereof, and is not
1042 // ambiguous.
1043 //
1044 // This filtering can make an ambiguous result into an unambiguous one,
1045 // so try again after filtering out template names.
1046 FilterAcceptableTemplateNames(Result);
1047 if (!Result.isAmbiguous()) {
1048 IsFilteredTemplateName = true;
1049 break;
1050 }
1051 }
1052
1053 // Diagnose the ambiguity and return an error.
1054 return NameClassification::Error();
1055 }
1056
1057 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1058 (IsFilteredTemplateName ||
1059 hasAnyAcceptableTemplateNames(
1060 Result, /*AllowFunctionTemplates=*/true,
1061 /*AllowDependent=*/false,
1062 /*AllowNonTemplateFunctions*/ !SS.isSet() &&
1063 getLangOpts().CPlusPlus2a))) {
1064 // C++ [temp.names]p3:
1065 // After name lookup (3.4) finds that a name is a template-name or that
1066 // an operator-function-id or a literal- operator-id refers to a set of
1067 // overloaded functions any member of which is a function template if
1068 // this is followed by a <, the < is always taken as the delimiter of a
1069 // template-argument-list and never as the less-than operator.
1070 // C++2a [temp.names]p2:
1071 // A name is also considered to refer to a template if it is an
1072 // unqualified-id followed by a < and name lookup finds either one
1073 // or more functions or finds nothing.
1074 if (!IsFilteredTemplateName)
1075 FilterAcceptableTemplateNames(Result);
1076
1077 bool IsFunctionTemplate;
1078 bool IsVarTemplate;
1079 TemplateName Template;
1080 if (Result.end() - Result.begin() > 1) {
1081 IsFunctionTemplate = true;
1082 Template = Context.getOverloadedTemplateName(Result.begin(),
1083 Result.end());
1084 } else if (!Result.empty()) {
1085 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1086 *Result.begin(), /*AllowFunctionTemplates=*/true,
1087 /*AllowDependent=*/false));
1088 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1089 IsVarTemplate = isa<VarTemplateDecl>(TD);
1090
1091 if (SS.isSet() && !SS.isInvalid())
1092 Template =
1093 Context.getQualifiedTemplateName(SS.getScopeRep(),
1094 /*TemplateKeyword=*/false, TD);
1095 else
1096 Template = TemplateName(TD);
1097 } else {
1098 // All results were non-template functions. This is a function template
1099 // name.
1100 IsFunctionTemplate = true;
1101 Template = Context.getAssumedTemplateName(NameInfo.getName());
1102 }
1103
1104 if (IsFunctionTemplate) {
1105 // Function templates always go through overload resolution, at which
1106 // point we'll perform the various checks (e.g., accessibility) we need
1107 // to based on which function we selected.
1108 Result.suppressDiagnostics();
1109
1110 return NameClassification::FunctionTemplate(Template);
1111 }
1112
1113 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1114 : NameClassification::TypeTemplate(Template);
1115 }
1116
1117 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1118 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1119 DiagnoseUseOfDecl(Type, NameLoc);
1120 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1121 QualType T = Context.getTypeDeclType(Type);
1122 if (SS.isNotEmpty())
1123 return buildNestedType(*this, SS, T, NameLoc);
1124 return ParsedType::make(T);
1125 }
1126
1127 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1128 if (!Class) {
1129 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1130 if (ObjCCompatibleAliasDecl *Alias =
1131 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1132 Class = Alias->getClassInterface();
1133 }
1134
1135 if (Class) {
1136 DiagnoseUseOfDecl(Class, NameLoc);
1137
1138 if (NextToken.is(tok::period)) {
1139 // Interface. <something> is parsed as a property reference expression.
1140 // Just return "unknown" as a fall-through for now.
1141 Result.suppressDiagnostics();
1142 return NameClassification::Unknown();
1143 }
1144
1145 QualType T = Context.getObjCInterfaceType(Class);
1146 return ParsedType::make(T);
1147 }
1148
1149 // We can have a type template here if we're classifying a template argument.
1150 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1151 !isa<VarTemplateDecl>(FirstDecl))
1152 return NameClassification::TypeTemplate(
1153 TemplateName(cast<TemplateDecl>(FirstDecl)));
1154
1155 // Check for a tag type hidden by a non-type decl in a few cases where it
1156 // seems likely a type is wanted instead of the non-type that was found.
1157 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1158 if ((NextToken.is(tok::identifier) ||
1159 (NextIsOp &&
1160 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1161 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1162 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1163 DiagnoseUseOfDecl(Type, NameLoc);
1164 QualType T = Context.getTypeDeclType(Type);
1165 if (SS.isNotEmpty())
1166 return buildNestedType(*this, SS, T, NameLoc);
1167 return ParsedType::make(T);
1168 }
1169
1170 if (FirstDecl->isCXXClassMember())
1171 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1172 nullptr, S);
1173
1174 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1175 return BuildDeclarationNameExpr(SS, Result, ADL);
1176 }
1177
1178 Sema::TemplateNameKindForDiagnostics
getTemplateNameKindForDiagnostics(TemplateName Name)1179 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1180 auto *TD = Name.getAsTemplateDecl();
1181 if (!TD)
1182 return TemplateNameKindForDiagnostics::DependentTemplate;
1183 if (isa<ClassTemplateDecl>(TD))
1184 return TemplateNameKindForDiagnostics::ClassTemplate;
1185 if (isa<FunctionTemplateDecl>(TD))
1186 return TemplateNameKindForDiagnostics::FunctionTemplate;
1187 if (isa<VarTemplateDecl>(TD))
1188 return TemplateNameKindForDiagnostics::VarTemplate;
1189 if (isa<TypeAliasTemplateDecl>(TD))
1190 return TemplateNameKindForDiagnostics::AliasTemplate;
1191 if (isa<TemplateTemplateParmDecl>(TD))
1192 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1193 if (isa<ConceptDecl>(TD))
1194 return TemplateNameKindForDiagnostics::Concept;
1195 return TemplateNameKindForDiagnostics::DependentTemplate;
1196 }
1197
1198 // Determines the context to return to after temporarily entering a
1199 // context. This depends in an unnecessarily complicated way on the
1200 // exact ordering of callbacks from the parser.
getContainingDC(DeclContext * DC)1201 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1202
1203 // Functions defined inline within classes aren't parsed until we've
1204 // finished parsing the top-level class, so the top-level class is
1205 // the context we'll need to return to.
1206 // A Lambda call operator whose parent is a class must not be treated
1207 // as an inline member function. A Lambda can be used legally
1208 // either as an in-class member initializer or a default argument. These
1209 // are parsed once the class has been marked complete and so the containing
1210 // context would be the nested class (when the lambda is defined in one);
1211 // If the class is not complete, then the lambda is being used in an
1212 // ill-formed fashion (such as to specify the width of a bit-field, or
1213 // in an array-bound) - in which case we still want to return the
1214 // lexically containing DC (which could be a nested class).
1215 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1216 DC = DC->getLexicalParent();
1217
1218 // A function not defined within a class will always return to its
1219 // lexical context.
1220 if (!isa<CXXRecordDecl>(DC))
1221 return DC;
1222
1223 // A C++ inline method/friend is parsed *after* the topmost class
1224 // it was declared in is fully parsed ("complete"); the topmost
1225 // class is the context we need to return to.
1226 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1227 DC = RD;
1228
1229 // Return the declaration context of the topmost class the inline method is
1230 // declared in.
1231 return DC;
1232 }
1233
1234 return DC->getLexicalParent();
1235 }
1236
PushDeclContext(Scope * S,DeclContext * DC)1237 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1238 assert(getContainingDC(DC) == CurContext &&
1239 "The next DeclContext should be lexically contained in the current one.");
1240 CurContext = DC;
1241 S->setEntity(DC);
1242 }
1243
PopDeclContext()1244 void Sema::PopDeclContext() {
1245 assert(CurContext && "DeclContext imbalance!");
1246
1247 CurContext = getContainingDC(CurContext);
1248 assert(CurContext && "Popped translation unit!");
1249 }
1250
ActOnTagStartSkippedDefinition(Scope * S,Decl * D)1251 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1252 Decl *D) {
1253 // Unlike PushDeclContext, the context to which we return is not necessarily
1254 // the containing DC of TD, because the new context will be some pre-existing
1255 // TagDecl definition instead of a fresh one.
1256 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1257 CurContext = cast<TagDecl>(D)->getDefinition();
1258 assert(CurContext && "skipping definition of undefined tag");
1259 // Start lookups from the parent of the current context; we don't want to look
1260 // into the pre-existing complete definition.
1261 S->setEntity(CurContext->getLookupParent());
1262 return Result;
1263 }
1264
ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)1265 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1266 CurContext = static_cast<decltype(CurContext)>(Context);
1267 }
1268
1269 /// EnterDeclaratorContext - Used when we must lookup names in the context
1270 /// of a declarator's nested name specifier.
1271 ///
EnterDeclaratorContext(Scope * S,DeclContext * DC)1272 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1273 // C++0x [basic.lookup.unqual]p13:
1274 // A name used in the definition of a static data member of class
1275 // X (after the qualified-id of the static member) is looked up as
1276 // if the name was used in a member function of X.
1277 // C++0x [basic.lookup.unqual]p14:
1278 // If a variable member of a namespace is defined outside of the
1279 // scope of its namespace then any name used in the definition of
1280 // the variable member (after the declarator-id) is looked up as
1281 // if the definition of the variable member occurred in its
1282 // namespace.
1283 // Both of these imply that we should push a scope whose context
1284 // is the semantic context of the declaration. We can't use
1285 // PushDeclContext here because that context is not necessarily
1286 // lexically contained in the current context. Fortunately,
1287 // the containing scope should have the appropriate information.
1288
1289 assert(!S->getEntity() && "scope already has entity");
1290
1291 #ifndef NDEBUG
1292 Scope *Ancestor = S->getParent();
1293 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1294 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1295 #endif
1296
1297 CurContext = DC;
1298 S->setEntity(DC);
1299 }
1300
ExitDeclaratorContext(Scope * S)1301 void Sema::ExitDeclaratorContext(Scope *S) {
1302 assert(S->getEntity() == CurContext && "Context imbalance!");
1303
1304 // Switch back to the lexical context. The safety of this is
1305 // enforced by an assert in EnterDeclaratorContext.
1306 Scope *Ancestor = S->getParent();
1307 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1308 CurContext = Ancestor->getEntity();
1309
1310 // We don't need to do anything with the scope, which is going to
1311 // disappear.
1312 }
1313
ActOnReenterFunctionContext(Scope * S,Decl * D)1314 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1315 // We assume that the caller has already called
1316 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1317 FunctionDecl *FD = D->getAsFunction();
1318 if (!FD)
1319 return;
1320
1321 // Same implementation as PushDeclContext, but enters the context
1322 // from the lexical parent, rather than the top-level class.
1323 assert(CurContext == FD->getLexicalParent() &&
1324 "The next DeclContext should be lexically contained in the current one.");
1325 CurContext = FD;
1326 S->setEntity(CurContext);
1327
1328 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1329 ParmVarDecl *Param = FD->getParamDecl(P);
1330 // If the parameter has an identifier, then add it to the scope
1331 if (Param->getIdentifier()) {
1332 S->AddDecl(Param);
1333 IdResolver.AddDecl(Param);
1334 }
1335 }
1336 }
1337
ActOnExitFunctionContext()1338 void Sema::ActOnExitFunctionContext() {
1339 // Same implementation as PopDeclContext, but returns to the lexical parent,
1340 // rather than the top-level class.
1341 assert(CurContext && "DeclContext imbalance!");
1342 CurContext = CurContext->getLexicalParent();
1343 assert(CurContext && "Popped translation unit!");
1344 }
1345
1346 /// Determine whether we allow overloading of the function
1347 /// PrevDecl with another declaration.
1348 ///
1349 /// This routine determines whether overloading is possible, not
1350 /// whether some new function is actually an overload. It will return
1351 /// true in C++ (where we can always provide overloads) or, as an
1352 /// extension, in C when the previous function is already an
1353 /// overloaded function declaration or has the "overloadable"
1354 /// attribute.
AllowOverloadingOfFunction(LookupResult & Previous,ASTContext & Context,const FunctionDecl * New)1355 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1356 ASTContext &Context,
1357 const FunctionDecl *New) {
1358 if (Context.getLangOpts().CPlusPlus)
1359 return true;
1360
1361 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1362 return true;
1363
1364 return Previous.getResultKind() == LookupResult::Found &&
1365 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1366 New->hasAttr<OverloadableAttr>());
1367 }
1368
1369 /// Add this decl to the scope shadowed decl chains.
PushOnScopeChains(NamedDecl * D,Scope * S,bool AddToContext)1370 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1371 // Move up the scope chain until we find the nearest enclosing
1372 // non-transparent context. The declaration will be introduced into this
1373 // scope.
1374 while (S->getEntity() && S->getEntity()->isTransparentContext())
1375 S = S->getParent();
1376
1377 // Add scoped declarations into their context, so that they can be
1378 // found later. Declarations without a context won't be inserted
1379 // into any context.
1380 if (AddToContext)
1381 CurContext->addDecl(D);
1382
1383 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1384 // are function-local declarations.
1385 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1386 !D->getDeclContext()->getRedeclContext()->Equals(
1387 D->getLexicalDeclContext()->getRedeclContext()) &&
1388 !D->getLexicalDeclContext()->isFunctionOrMethod())
1389 return;
1390
1391 // Template instantiations should also not be pushed into scope.
1392 if (isa<FunctionDecl>(D) &&
1393 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1394 return;
1395
1396 // If this replaces anything in the current scope,
1397 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1398 IEnd = IdResolver.end();
1399 for (; I != IEnd; ++I) {
1400 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1401 S->RemoveDecl(*I);
1402 IdResolver.RemoveDecl(*I);
1403
1404 // Should only need to replace one decl.
1405 break;
1406 }
1407 }
1408
1409 S->AddDecl(D);
1410
1411 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1412 // Implicitly-generated labels may end up getting generated in an order that
1413 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1414 // the label at the appropriate place in the identifier chain.
1415 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1416 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1417 if (IDC == CurContext) {
1418 if (!S->isDeclScope(*I))
1419 continue;
1420 } else if (IDC->Encloses(CurContext))
1421 break;
1422 }
1423
1424 IdResolver.InsertDeclAfter(I, D);
1425 } else {
1426 IdResolver.AddDecl(D);
1427 }
1428 }
1429
isDeclInScope(NamedDecl * D,DeclContext * Ctx,Scope * S,bool AllowInlineNamespace)1430 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1431 bool AllowInlineNamespace) {
1432 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1433 }
1434
getScopeForDeclContext(Scope * S,DeclContext * DC)1435 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1436 DeclContext *TargetDC = DC->getPrimaryContext();
1437 do {
1438 if (DeclContext *ScopeDC = S->getEntity())
1439 if (ScopeDC->getPrimaryContext() == TargetDC)
1440 return S;
1441 } while ((S = S->getParent()));
1442
1443 return nullptr;
1444 }
1445
1446 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1447 DeclContext*,
1448 ASTContext&);
1449
1450 /// Filters out lookup results that don't fall within the given scope
1451 /// as determined by isDeclInScope.
FilterLookupForScope(LookupResult & R,DeclContext * Ctx,Scope * S,bool ConsiderLinkage,bool AllowInlineNamespace)1452 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1453 bool ConsiderLinkage,
1454 bool AllowInlineNamespace) {
1455 LookupResult::Filter F = R.makeFilter();
1456 while (F.hasNext()) {
1457 NamedDecl *D = F.next();
1458
1459 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1460 continue;
1461
1462 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1463 continue;
1464
1465 F.erase();
1466 }
1467
1468 F.done();
1469 }
1470
1471 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1472 /// have compatible owning modules.
CheckRedeclarationModuleOwnership(NamedDecl * New,NamedDecl * Old)1473 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1474 // FIXME: The Modules TS is not clear about how friend declarations are
1475 // to be treated. It's not meaningful to have different owning modules for
1476 // linkage in redeclarations of the same entity, so for now allow the
1477 // redeclaration and change the owning modules to match.
1478 if (New->getFriendObjectKind() &&
1479 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1480 New->setLocalOwningModule(Old->getOwningModule());
1481 makeMergedDefinitionVisible(New);
1482 return false;
1483 }
1484
1485 Module *NewM = New->getOwningModule();
1486 Module *OldM = Old->getOwningModule();
1487
1488 if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1489 NewM = NewM->Parent;
1490 if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1491 OldM = OldM->Parent;
1492
1493 if (NewM == OldM)
1494 return false;
1495
1496 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1497 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1498 if (NewIsModuleInterface || OldIsModuleInterface) {
1499 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1500 // if a declaration of D [...] appears in the purview of a module, all
1501 // other such declarations shall appear in the purview of the same module
1502 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1503 << New
1504 << NewIsModuleInterface
1505 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1506 << OldIsModuleInterface
1507 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1508 Diag(Old->getLocation(), diag::note_previous_declaration);
1509 New->setInvalidDecl();
1510 return true;
1511 }
1512
1513 return false;
1514 }
1515
isUsingDecl(NamedDecl * D)1516 static bool isUsingDecl(NamedDecl *D) {
1517 return isa<UsingShadowDecl>(D) ||
1518 isa<UnresolvedUsingTypenameDecl>(D) ||
1519 isa<UnresolvedUsingValueDecl>(D);
1520 }
1521
1522 /// Removes using shadow declarations from the lookup results.
RemoveUsingDecls(LookupResult & R)1523 static void RemoveUsingDecls(LookupResult &R) {
1524 LookupResult::Filter F = R.makeFilter();
1525 while (F.hasNext())
1526 if (isUsingDecl(F.next()))
1527 F.erase();
1528
1529 F.done();
1530 }
1531
1532 /// Check for this common pattern:
1533 /// @code
1534 /// class S {
1535 /// S(const S&); // DO NOT IMPLEMENT
1536 /// void operator=(const S&); // DO NOT IMPLEMENT
1537 /// };
1538 /// @endcode
IsDisallowedCopyOrAssign(const CXXMethodDecl * D)1539 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1540 // FIXME: Should check for private access too but access is set after we get
1541 // the decl here.
1542 if (D->doesThisDeclarationHaveABody())
1543 return false;
1544
1545 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1546 return CD->isCopyConstructor();
1547 return D->isCopyAssignmentOperator();
1548 }
1549
1550 // We need this to handle
1551 //
1552 // typedef struct {
1553 // void *foo() { return 0; }
1554 // } A;
1555 //
1556 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1557 // for example. If 'A', foo will have external linkage. If we have '*A',
1558 // foo will have no linkage. Since we can't know until we get to the end
1559 // of the typedef, this function finds out if D might have non-external linkage.
1560 // Callers should verify at the end of the TU if it D has external linkage or
1561 // not.
mightHaveNonExternalLinkage(const DeclaratorDecl * D)1562 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1563 const DeclContext *DC = D->getDeclContext();
1564 while (!DC->isTranslationUnit()) {
1565 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1566 if (!RD->hasNameForLinkage())
1567 return true;
1568 }
1569 DC = DC->getParent();
1570 }
1571
1572 return !D->isExternallyVisible();
1573 }
1574
1575 // FIXME: This needs to be refactored; some other isInMainFile users want
1576 // these semantics.
isMainFileLoc(const Sema & S,SourceLocation Loc)1577 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1578 if (S.TUKind != TU_Complete)
1579 return false;
1580 return S.SourceMgr.isInMainFile(Loc);
1581 }
1582
ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl * D) const1583 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1584 assert(D);
1585
1586 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1587 return false;
1588
1589 // Ignore all entities declared within templates, and out-of-line definitions
1590 // of members of class templates.
1591 if (D->getDeclContext()->isDependentContext() ||
1592 D->getLexicalDeclContext()->isDependentContext())
1593 return false;
1594
1595 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1596 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1597 return false;
1598 // A non-out-of-line declaration of a member specialization was implicitly
1599 // instantiated; it's the out-of-line declaration that we're interested in.
1600 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1601 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1602 return false;
1603
1604 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1605 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1606 return false;
1607 } else {
1608 // 'static inline' functions are defined in headers; don't warn.
1609 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1610 return false;
1611 }
1612
1613 if (FD->doesThisDeclarationHaveABody() &&
1614 Context.DeclMustBeEmitted(FD))
1615 return false;
1616 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1617 // Constants and utility variables are defined in headers with internal
1618 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1619 // like "inline".)
1620 if (!isMainFileLoc(*this, VD->getLocation()))
1621 return false;
1622
1623 if (Context.DeclMustBeEmitted(VD))
1624 return false;
1625
1626 if (VD->isStaticDataMember() &&
1627 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1628 return false;
1629 if (VD->isStaticDataMember() &&
1630 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1631 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1632 return false;
1633
1634 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1635 return false;
1636 } else {
1637 return false;
1638 }
1639
1640 // Only warn for unused decls internal to the translation unit.
1641 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1642 // for inline functions defined in the main source file, for instance.
1643 return mightHaveNonExternalLinkage(D);
1644 }
1645
MarkUnusedFileScopedDecl(const DeclaratorDecl * D)1646 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1647 if (!D)
1648 return;
1649
1650 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1651 const FunctionDecl *First = FD->getFirstDecl();
1652 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1653 return; // First should already be in the vector.
1654 }
1655
1656 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1657 const VarDecl *First = VD->getFirstDecl();
1658 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1659 return; // First should already be in the vector.
1660 }
1661
1662 if (ShouldWarnIfUnusedFileScopedDecl(D))
1663 UnusedFileScopedDecls.push_back(D);
1664 }
1665
ShouldDiagnoseUnusedDecl(const NamedDecl * D)1666 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1667 if (D->isInvalidDecl())
1668 return false;
1669
1670 bool Referenced = false;
1671 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1672 // For a decomposition declaration, warn if none of the bindings are
1673 // referenced, instead of if the variable itself is referenced (which
1674 // it is, by the bindings' expressions).
1675 for (auto *BD : DD->bindings()) {
1676 if (BD->isReferenced()) {
1677 Referenced = true;
1678 break;
1679 }
1680 }
1681 } else if (!D->getDeclName()) {
1682 return false;
1683 } else if (D->isReferenced() || D->isUsed()) {
1684 Referenced = true;
1685 }
1686
1687 if (Referenced || D->hasAttr<UnusedAttr>() ||
1688 D->hasAttr<ObjCPreciseLifetimeAttr>())
1689 return false;
1690
1691 if (isa<LabelDecl>(D))
1692 return true;
1693
1694 // Except for labels, we only care about unused decls that are local to
1695 // functions.
1696 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1697 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1698 // For dependent types, the diagnostic is deferred.
1699 WithinFunction =
1700 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1701 if (!WithinFunction)
1702 return false;
1703
1704 if (isa<TypedefNameDecl>(D))
1705 return true;
1706
1707 // White-list anything that isn't a local variable.
1708 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1709 return false;
1710
1711 // Types of valid local variables should be complete, so this should succeed.
1712 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1713
1714 // White-list anything with an __attribute__((unused)) type.
1715 const auto *Ty = VD->getType().getTypePtr();
1716
1717 // Only look at the outermost level of typedef.
1718 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1719 if (TT->getDecl()->hasAttr<UnusedAttr>())
1720 return false;
1721 }
1722
1723 // If we failed to complete the type for some reason, or if the type is
1724 // dependent, don't diagnose the variable.
1725 if (Ty->isIncompleteType() || Ty->isDependentType())
1726 return false;
1727
1728 // Look at the element type to ensure that the warning behaviour is
1729 // consistent for both scalars and arrays.
1730 Ty = Ty->getBaseElementTypeUnsafe();
1731
1732 if (const TagType *TT = Ty->getAs<TagType>()) {
1733 const TagDecl *Tag = TT->getDecl();
1734 if (Tag->hasAttr<UnusedAttr>())
1735 return false;
1736
1737 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1738 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1739 return false;
1740
1741 if (const Expr *Init = VD->getInit()) {
1742 if (const ExprWithCleanups *Cleanups =
1743 dyn_cast<ExprWithCleanups>(Init))
1744 Init = Cleanups->getSubExpr();
1745 const CXXConstructExpr *Construct =
1746 dyn_cast<CXXConstructExpr>(Init);
1747 if (Construct && !Construct->isElidable()) {
1748 CXXConstructorDecl *CD = Construct->getConstructor();
1749 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1750 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1751 return false;
1752 }
1753 }
1754 }
1755 }
1756
1757 // TODO: __attribute__((unused)) templates?
1758 }
1759
1760 return true;
1761 }
1762
GenerateFixForUnusedDecl(const NamedDecl * D,ASTContext & Ctx,FixItHint & Hint)1763 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1764 FixItHint &Hint) {
1765 if (isa<LabelDecl>(D)) {
1766 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1767 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1768 true);
1769 if (AfterColon.isInvalid())
1770 return;
1771 Hint = FixItHint::CreateRemoval(
1772 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1773 }
1774 }
1775
DiagnoseUnusedNestedTypedefs(const RecordDecl * D)1776 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1777 if (D->getTypeForDecl()->isDependentType())
1778 return;
1779
1780 for (auto *TmpD : D->decls()) {
1781 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1782 DiagnoseUnusedDecl(T);
1783 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1784 DiagnoseUnusedNestedTypedefs(R);
1785 }
1786 }
1787
1788 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1789 /// unless they are marked attr(unused).
DiagnoseUnusedDecl(const NamedDecl * D)1790 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1791 if (!ShouldDiagnoseUnusedDecl(D))
1792 return;
1793
1794 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1795 // typedefs can be referenced later on, so the diagnostics are emitted
1796 // at end-of-translation-unit.
1797 UnusedLocalTypedefNameCandidates.insert(TD);
1798 return;
1799 }
1800
1801 FixItHint Hint;
1802 GenerateFixForUnusedDecl(D, Context, Hint);
1803
1804 unsigned DiagID;
1805 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1806 DiagID = diag::warn_unused_exception_param;
1807 else if (isa<LabelDecl>(D))
1808 DiagID = diag::warn_unused_label;
1809 else
1810 DiagID = diag::warn_unused_variable;
1811
1812 Diag(D->getLocation(), DiagID) << D << Hint;
1813 }
1814
CheckPoppedLabel(LabelDecl * L,Sema & S)1815 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1816 // Verify that we have no forward references left. If so, there was a goto
1817 // or address of a label taken, but no definition of it. Label fwd
1818 // definitions are indicated with a null substmt which is also not a resolved
1819 // MS inline assembly label name.
1820 bool Diagnose = false;
1821 if (L->isMSAsmLabel())
1822 Diagnose = !L->isResolvedMSAsmLabel();
1823 else
1824 Diagnose = L->getStmt() == nullptr;
1825 if (Diagnose)
1826 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1827 }
1828
ActOnPopScope(SourceLocation Loc,Scope * S)1829 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1830 S->mergeNRVOIntoParent();
1831
1832 if (S->decl_empty()) return;
1833 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1834 "Scope shouldn't contain decls!");
1835
1836 for (auto *TmpD : S->decls()) {
1837 assert(TmpD && "This decl didn't get pushed??");
1838
1839 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1840 NamedDecl *D = cast<NamedDecl>(TmpD);
1841
1842 // Diagnose unused variables in this scope.
1843 if (!S->hasUnrecoverableErrorOccurred()) {
1844 DiagnoseUnusedDecl(D);
1845 if (const auto *RD = dyn_cast<RecordDecl>(D))
1846 DiagnoseUnusedNestedTypedefs(RD);
1847 }
1848
1849 if (!D->getDeclName()) continue;
1850
1851 // If this was a forward reference to a label, verify it was defined.
1852 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1853 CheckPoppedLabel(LD, *this);
1854
1855 // Remove this name from our lexical scope, and warn on it if we haven't
1856 // already.
1857 IdResolver.RemoveDecl(D);
1858 auto ShadowI = ShadowingDecls.find(D);
1859 if (ShadowI != ShadowingDecls.end()) {
1860 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1861 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1862 << D << FD << FD->getParent();
1863 Diag(FD->getLocation(), diag::note_previous_declaration);
1864 }
1865 ShadowingDecls.erase(ShadowI);
1866 }
1867 }
1868 }
1869
1870 /// Look for an Objective-C class in the translation unit.
1871 ///
1872 /// \param Id The name of the Objective-C class we're looking for. If
1873 /// typo-correction fixes this name, the Id will be updated
1874 /// to the fixed name.
1875 ///
1876 /// \param IdLoc The location of the name in the translation unit.
1877 ///
1878 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1879 /// if there is no class with the given name.
1880 ///
1881 /// \returns The declaration of the named Objective-C class, or NULL if the
1882 /// class could not be found.
getObjCInterfaceDecl(IdentifierInfo * & Id,SourceLocation IdLoc,bool DoTypoCorrection)1883 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1884 SourceLocation IdLoc,
1885 bool DoTypoCorrection) {
1886 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1887 // creation from this context.
1888 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1889
1890 if (!IDecl && DoTypoCorrection) {
1891 // Perform typo correction at the given location, but only if we
1892 // find an Objective-C class name.
1893 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1894 if (TypoCorrection C =
1895 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1896 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1897 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1898 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1899 Id = IDecl->getIdentifier();
1900 }
1901 }
1902 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1903 // This routine must always return a class definition, if any.
1904 if (Def && Def->getDefinition())
1905 Def = Def->getDefinition();
1906 return Def;
1907 }
1908
1909 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1910 /// from S, where a non-field would be declared. This routine copes
1911 /// with the difference between C and C++ scoping rules in structs and
1912 /// unions. For example, the following code is well-formed in C but
1913 /// ill-formed in C++:
1914 /// @code
1915 /// struct S6 {
1916 /// enum { BAR } e;
1917 /// };
1918 ///
1919 /// void test_S6() {
1920 /// struct S6 a;
1921 /// a.e = BAR;
1922 /// }
1923 /// @endcode
1924 /// For the declaration of BAR, this routine will return a different
1925 /// scope. The scope S will be the scope of the unnamed enumeration
1926 /// within S6. In C++, this routine will return the scope associated
1927 /// with S6, because the enumeration's scope is a transparent
1928 /// context but structures can contain non-field names. In C, this
1929 /// routine will return the translation unit scope, since the
1930 /// enumeration's scope is a transparent context and structures cannot
1931 /// contain non-field names.
getNonFieldDeclScope(Scope * S)1932 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1933 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1934 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1935 (S->isClassScope() && !getLangOpts().CPlusPlus))
1936 S = S->getParent();
1937 return S;
1938 }
1939
1940 /// Looks up the declaration of "struct objc_super" and
1941 /// saves it for later use in building builtin declaration of
1942 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1943 /// pre-existing declaration exists no action takes place.
LookupPredefedObjCSuperType(Sema & ThisSema,Scope * S,IdentifierInfo * II)1944 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1945 IdentifierInfo *II) {
1946 if (!II->isStr("objc_msgSendSuper"))
1947 return;
1948 ASTContext &Context = ThisSema.Context;
1949
1950 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1951 SourceLocation(), Sema::LookupTagName);
1952 ThisSema.LookupName(Result, S);
1953 if (Result.getResultKind() == LookupResult::Found)
1954 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1955 Context.setObjCSuperType(Context.getTagDeclType(TD));
1956 }
1957
getHeaderName(Builtin::Context & BuiltinInfo,unsigned ID,ASTContext::GetBuiltinTypeError Error)1958 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
1959 ASTContext::GetBuiltinTypeError Error) {
1960 switch (Error) {
1961 case ASTContext::GE_None:
1962 return "";
1963 case ASTContext::GE_Missing_type:
1964 return BuiltinInfo.getHeaderName(ID);
1965 case ASTContext::GE_Missing_stdio:
1966 return "stdio.h";
1967 case ASTContext::GE_Missing_setjmp:
1968 return "setjmp.h";
1969 case ASTContext::GE_Missing_ucontext:
1970 return "ucontext.h";
1971 }
1972 llvm_unreachable("unhandled error kind");
1973 }
1974
1975 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1976 /// file scope. lazily create a decl for it. ForRedeclaration is true
1977 /// if we're creating this built-in in anticipation of redeclaring the
1978 /// built-in.
LazilyCreateBuiltin(IdentifierInfo * II,unsigned ID,Scope * S,bool ForRedeclaration,SourceLocation Loc)1979 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1980 Scope *S, bool ForRedeclaration,
1981 SourceLocation Loc) {
1982 LookupPredefedObjCSuperType(*this, S, II);
1983
1984 ASTContext::GetBuiltinTypeError Error;
1985 QualType R = Context.GetBuiltinType(ID, Error);
1986 if (Error) {
1987 if (!ForRedeclaration)
1988 return nullptr;
1989
1990 // If we have a builtin without an associated type we should not emit a
1991 // warning when we were not able to find a type for it.
1992 if (Error == ASTContext::GE_Missing_type)
1993 return nullptr;
1994
1995 // If we could not find a type for setjmp it is because the jmp_buf type was
1996 // not defined prior to the setjmp declaration.
1997 if (Error == ASTContext::GE_Missing_setjmp) {
1998 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
1999 << Context.BuiltinInfo.getName(ID);
2000 return nullptr;
2001 }
2002
2003 // Generally, we emit a warning that the declaration requires the
2004 // appropriate header.
2005 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2006 << getHeaderName(Context.BuiltinInfo, ID, Error)
2007 << Context.BuiltinInfo.getName(ID);
2008 return nullptr;
2009 }
2010
2011 if (!ForRedeclaration &&
2012 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2013 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2014 Diag(Loc, diag::ext_implicit_lib_function_decl)
2015 << Context.BuiltinInfo.getName(ID) << R;
2016 if (Context.BuiltinInfo.getHeaderName(ID) &&
2017 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2018 Diag(Loc, diag::note_include_header_or_declare)
2019 << Context.BuiltinInfo.getHeaderName(ID)
2020 << Context.BuiltinInfo.getName(ID);
2021 }
2022
2023 if (R.isNull())
2024 return nullptr;
2025
2026 DeclContext *Parent = Context.getTranslationUnitDecl();
2027 if (getLangOpts().CPlusPlus) {
2028 LinkageSpecDecl *CLinkageDecl =
2029 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2030 LinkageSpecDecl::lang_c, false);
2031 CLinkageDecl->setImplicit();
2032 Parent->addDecl(CLinkageDecl);
2033 Parent = CLinkageDecl;
2034 }
2035
2036 FunctionDecl *New = FunctionDecl::Create(Context,
2037 Parent,
2038 Loc, Loc, II, R, /*TInfo=*/nullptr,
2039 SC_Extern,
2040 false,
2041 R->isFunctionProtoType());
2042 New->setImplicit();
2043
2044 // Create Decl objects for each parameter, adding them to the
2045 // FunctionDecl.
2046 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2047 SmallVector<ParmVarDecl*, 16> Params;
2048 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2049 ParmVarDecl *parm =
2050 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2051 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2052 SC_None, nullptr);
2053 parm->setScopeInfo(0, i);
2054 Params.push_back(parm);
2055 }
2056 New->setParams(Params);
2057 }
2058
2059 AddKnownFunctionAttributes(New);
2060 RegisterLocallyScopedExternCDecl(New, S);
2061
2062 // TUScope is the translation-unit scope to insert this function into.
2063 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2064 // relate Scopes to DeclContexts, and probably eliminate CurContext
2065 // entirely, but we're not there yet.
2066 DeclContext *SavedContext = CurContext;
2067 CurContext = Parent;
2068 PushOnScopeChains(New, TUScope);
2069 CurContext = SavedContext;
2070 return New;
2071 }
2072
2073 /// Typedef declarations don't have linkage, but they still denote the same
2074 /// entity if their types are the same.
2075 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2076 /// isSameEntity.
filterNonConflictingPreviousTypedefDecls(Sema & S,TypedefNameDecl * Decl,LookupResult & Previous)2077 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2078 TypedefNameDecl *Decl,
2079 LookupResult &Previous) {
2080 // This is only interesting when modules are enabled.
2081 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2082 return;
2083
2084 // Empty sets are uninteresting.
2085 if (Previous.empty())
2086 return;
2087
2088 LookupResult::Filter Filter = Previous.makeFilter();
2089 while (Filter.hasNext()) {
2090 NamedDecl *Old = Filter.next();
2091
2092 // Non-hidden declarations are never ignored.
2093 if (S.isVisible(Old))
2094 continue;
2095
2096 // Declarations of the same entity are not ignored, even if they have
2097 // different linkages.
2098 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2099 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2100 Decl->getUnderlyingType()))
2101 continue;
2102
2103 // If both declarations give a tag declaration a typedef name for linkage
2104 // purposes, then they declare the same entity.
2105 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2106 Decl->getAnonDeclWithTypedefName())
2107 continue;
2108 }
2109
2110 Filter.erase();
2111 }
2112
2113 Filter.done();
2114 }
2115
isIncompatibleTypedef(TypeDecl * Old,TypedefNameDecl * New)2116 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2117 QualType OldType;
2118 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2119 OldType = OldTypedef->getUnderlyingType();
2120 else
2121 OldType = Context.getTypeDeclType(Old);
2122 QualType NewType = New->getUnderlyingType();
2123
2124 if (NewType->isVariablyModifiedType()) {
2125 // Must not redefine a typedef with a variably-modified type.
2126 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2127 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2128 << Kind << NewType;
2129 if (Old->getLocation().isValid())
2130 notePreviousDefinition(Old, New->getLocation());
2131 New->setInvalidDecl();
2132 return true;
2133 }
2134
2135 if (OldType != NewType &&
2136 !OldType->isDependentType() &&
2137 !NewType->isDependentType() &&
2138 !Context.hasSameType(OldType, NewType)) {
2139 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2140 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2141 << Kind << NewType << OldType;
2142 if (Old->getLocation().isValid())
2143 notePreviousDefinition(Old, New->getLocation());
2144 New->setInvalidDecl();
2145 return true;
2146 }
2147 return false;
2148 }
2149
2150 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2151 /// same name and scope as a previous declaration 'Old'. Figure out
2152 /// how to resolve this situation, merging decls or emitting
2153 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2154 ///
MergeTypedefNameDecl(Scope * S,TypedefNameDecl * New,LookupResult & OldDecls)2155 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2156 LookupResult &OldDecls) {
2157 // If the new decl is known invalid already, don't bother doing any
2158 // merging checks.
2159 if (New->isInvalidDecl()) return;
2160
2161 // Allow multiple definitions for ObjC built-in typedefs.
2162 // FIXME: Verify the underlying types are equivalent!
2163 if (getLangOpts().ObjC) {
2164 const IdentifierInfo *TypeID = New->getIdentifier();
2165 switch (TypeID->getLength()) {
2166 default: break;
2167 case 2:
2168 {
2169 if (!TypeID->isStr("id"))
2170 break;
2171 QualType T = New->getUnderlyingType();
2172 if (!T->isPointerType())
2173 break;
2174 if (!T->isVoidPointerType()) {
2175 QualType PT = T->getAs<PointerType>()->getPointeeType();
2176 if (!PT->isStructureType())
2177 break;
2178 }
2179 Context.setObjCIdRedefinitionType(T);
2180 // Install the built-in type for 'id', ignoring the current definition.
2181 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2182 return;
2183 }
2184 case 5:
2185 if (!TypeID->isStr("Class"))
2186 break;
2187 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2188 // Install the built-in type for 'Class', ignoring the current definition.
2189 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2190 return;
2191 case 3:
2192 if (!TypeID->isStr("SEL"))
2193 break;
2194 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2195 // Install the built-in type for 'SEL', ignoring the current definition.
2196 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2197 return;
2198 }
2199 // Fall through - the typedef name was not a builtin type.
2200 }
2201
2202 // Verify the old decl was also a type.
2203 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2204 if (!Old) {
2205 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2206 << New->getDeclName();
2207
2208 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2209 if (OldD->getLocation().isValid())
2210 notePreviousDefinition(OldD, New->getLocation());
2211
2212 return New->setInvalidDecl();
2213 }
2214
2215 // If the old declaration is invalid, just give up here.
2216 if (Old->isInvalidDecl())
2217 return New->setInvalidDecl();
2218
2219 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2220 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2221 auto *NewTag = New->getAnonDeclWithTypedefName();
2222 NamedDecl *Hidden = nullptr;
2223 if (OldTag && NewTag &&
2224 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2225 !hasVisibleDefinition(OldTag, &Hidden)) {
2226 // There is a definition of this tag, but it is not visible. Use it
2227 // instead of our tag.
2228 New->setTypeForDecl(OldTD->getTypeForDecl());
2229 if (OldTD->isModed())
2230 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2231 OldTD->getUnderlyingType());
2232 else
2233 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2234
2235 // Make the old tag definition visible.
2236 makeMergedDefinitionVisible(Hidden);
2237
2238 // If this was an unscoped enumeration, yank all of its enumerators
2239 // out of the scope.
2240 if (isa<EnumDecl>(NewTag)) {
2241 Scope *EnumScope = getNonFieldDeclScope(S);
2242 for (auto *D : NewTag->decls()) {
2243 auto *ED = cast<EnumConstantDecl>(D);
2244 assert(EnumScope->isDeclScope(ED));
2245 EnumScope->RemoveDecl(ED);
2246 IdResolver.RemoveDecl(ED);
2247 ED->getLexicalDeclContext()->removeDecl(ED);
2248 }
2249 }
2250 }
2251 }
2252
2253 // If the typedef types are not identical, reject them in all languages and
2254 // with any extensions enabled.
2255 if (isIncompatibleTypedef(Old, New))
2256 return;
2257
2258 // The types match. Link up the redeclaration chain and merge attributes if
2259 // the old declaration was a typedef.
2260 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2261 New->setPreviousDecl(Typedef);
2262 mergeDeclAttributes(New, Old);
2263 }
2264
2265 if (getLangOpts().MicrosoftExt)
2266 return;
2267
2268 if (getLangOpts().CPlusPlus) {
2269 // C++ [dcl.typedef]p2:
2270 // In a given non-class scope, a typedef specifier can be used to
2271 // redefine the name of any type declared in that scope to refer
2272 // to the type to which it already refers.
2273 if (!isa<CXXRecordDecl>(CurContext))
2274 return;
2275
2276 // C++0x [dcl.typedef]p4:
2277 // In a given class scope, a typedef specifier can be used to redefine
2278 // any class-name declared in that scope that is not also a typedef-name
2279 // to refer to the type to which it already refers.
2280 //
2281 // This wording came in via DR424, which was a correction to the
2282 // wording in DR56, which accidentally banned code like:
2283 //
2284 // struct S {
2285 // typedef struct A { } A;
2286 // };
2287 //
2288 // in the C++03 standard. We implement the C++0x semantics, which
2289 // allow the above but disallow
2290 //
2291 // struct S {
2292 // typedef int I;
2293 // typedef int I;
2294 // };
2295 //
2296 // since that was the intent of DR56.
2297 if (!isa<TypedefNameDecl>(Old))
2298 return;
2299
2300 Diag(New->getLocation(), diag::err_redefinition)
2301 << New->getDeclName();
2302 notePreviousDefinition(Old, New->getLocation());
2303 return New->setInvalidDecl();
2304 }
2305
2306 // Modules always permit redefinition of typedefs, as does C11.
2307 if (getLangOpts().Modules || getLangOpts().C11)
2308 return;
2309
2310 // If we have a redefinition of a typedef in C, emit a warning. This warning
2311 // is normally mapped to an error, but can be controlled with
2312 // -Wtypedef-redefinition. If either the original or the redefinition is
2313 // in a system header, don't emit this for compatibility with GCC.
2314 if (getDiagnostics().getSuppressSystemWarnings() &&
2315 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2316 (Old->isImplicit() ||
2317 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2318 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2319 return;
2320
2321 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2322 << New->getDeclName();
2323 notePreviousDefinition(Old, New->getLocation());
2324 }
2325
2326 /// DeclhasAttr - returns true if decl Declaration already has the target
2327 /// attribute.
DeclHasAttr(const Decl * D,const Attr * A)2328 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2329 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2330 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2331 for (const auto *i : D->attrs())
2332 if (i->getKind() == A->getKind()) {
2333 if (Ann) {
2334 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2335 return true;
2336 continue;
2337 }
2338 // FIXME: Don't hardcode this check
2339 if (OA && isa<OwnershipAttr>(i))
2340 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2341 return true;
2342 }
2343
2344 return false;
2345 }
2346
isAttributeTargetADefinition(Decl * D)2347 static bool isAttributeTargetADefinition(Decl *D) {
2348 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2349 return VD->isThisDeclarationADefinition();
2350 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2351 return TD->isCompleteDefinition() || TD->isBeingDefined();
2352 return true;
2353 }
2354
2355 /// Merge alignment attributes from \p Old to \p New, taking into account the
2356 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2357 ///
2358 /// \return \c true if any attributes were added to \p New.
mergeAlignedAttrs(Sema & S,NamedDecl * New,Decl * Old)2359 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2360 // Look for alignas attributes on Old, and pick out whichever attribute
2361 // specifies the strictest alignment requirement.
2362 AlignedAttr *OldAlignasAttr = nullptr;
2363 AlignedAttr *OldStrictestAlignAttr = nullptr;
2364 unsigned OldAlign = 0;
2365 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2366 // FIXME: We have no way of representing inherited dependent alignments
2367 // in a case like:
2368 // template<int A, int B> struct alignas(A) X;
2369 // template<int A, int B> struct alignas(B) X {};
2370 // For now, we just ignore any alignas attributes which are not on the
2371 // definition in such a case.
2372 if (I->isAlignmentDependent())
2373 return false;
2374
2375 if (I->isAlignas())
2376 OldAlignasAttr = I;
2377
2378 unsigned Align = I->getAlignment(S.Context);
2379 if (Align > OldAlign) {
2380 OldAlign = Align;
2381 OldStrictestAlignAttr = I;
2382 }
2383 }
2384
2385 // Look for alignas attributes on New.
2386 AlignedAttr *NewAlignasAttr = nullptr;
2387 unsigned NewAlign = 0;
2388 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2389 if (I->isAlignmentDependent())
2390 return false;
2391
2392 if (I->isAlignas())
2393 NewAlignasAttr = I;
2394
2395 unsigned Align = I->getAlignment(S.Context);
2396 if (Align > NewAlign)
2397 NewAlign = Align;
2398 }
2399
2400 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2401 // Both declarations have 'alignas' attributes. We require them to match.
2402 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2403 // fall short. (If two declarations both have alignas, they must both match
2404 // every definition, and so must match each other if there is a definition.)
2405
2406 // If either declaration only contains 'alignas(0)' specifiers, then it
2407 // specifies the natural alignment for the type.
2408 if (OldAlign == 0 || NewAlign == 0) {
2409 QualType Ty;
2410 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2411 Ty = VD->getType();
2412 else
2413 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2414
2415 if (OldAlign == 0)
2416 OldAlign = S.Context.getTypeAlign(Ty);
2417 if (NewAlign == 0)
2418 NewAlign = S.Context.getTypeAlign(Ty);
2419 }
2420
2421 if (OldAlign != NewAlign) {
2422 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2423 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2424 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2425 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2426 }
2427 }
2428
2429 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2430 // C++11 [dcl.align]p6:
2431 // if any declaration of an entity has an alignment-specifier,
2432 // every defining declaration of that entity shall specify an
2433 // equivalent alignment.
2434 // C11 6.7.5/7:
2435 // If the definition of an object does not have an alignment
2436 // specifier, any other declaration of that object shall also
2437 // have no alignment specifier.
2438 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2439 << OldAlignasAttr;
2440 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2441 << OldAlignasAttr;
2442 }
2443
2444 bool AnyAdded = false;
2445
2446 // Ensure we have an attribute representing the strictest alignment.
2447 if (OldAlign > NewAlign) {
2448 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2449 Clone->setInherited(true);
2450 New->addAttr(Clone);
2451 AnyAdded = true;
2452 }
2453
2454 // Ensure we have an alignas attribute if the old declaration had one.
2455 if (OldAlignasAttr && !NewAlignasAttr &&
2456 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2457 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2458 Clone->setInherited(true);
2459 New->addAttr(Clone);
2460 AnyAdded = true;
2461 }
2462
2463 return AnyAdded;
2464 }
2465
mergeDeclAttribute(Sema & S,NamedDecl * D,const InheritableAttr * Attr,Sema::AvailabilityMergeKind AMK)2466 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2467 const InheritableAttr *Attr,
2468 Sema::AvailabilityMergeKind AMK) {
2469 // This function copies an attribute Attr from a previous declaration to the
2470 // new declaration D if the new declaration doesn't itself have that attribute
2471 // yet or if that attribute allows duplicates.
2472 // If you're adding a new attribute that requires logic different from
2473 // "use explicit attribute on decl if present, else use attribute from
2474 // previous decl", for example if the attribute needs to be consistent
2475 // between redeclarations, you need to call a custom merge function here.
2476 InheritableAttr *NewAttr = nullptr;
2477 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2478 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2479 NewAttr = S.mergeAvailabilityAttr(
2480 D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
2481 AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
2482 AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
2483 AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
2484 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2485 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2486 AttrSpellingListIndex);
2487 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2488 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2489 AttrSpellingListIndex);
2490 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2491 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2492 AttrSpellingListIndex);
2493 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2494 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2495 AttrSpellingListIndex);
2496 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2497 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2498 FA->getFormatIdx(), FA->getFirstArg(),
2499 AttrSpellingListIndex);
2500 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2501 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2502 AttrSpellingListIndex);
2503 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2504 NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2505 AttrSpellingListIndex);
2506 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2507 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2508 AttrSpellingListIndex,
2509 IA->getSemanticSpelling());
2510 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2511 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2512 &S.Context.Idents.get(AA->getSpelling()),
2513 AttrSpellingListIndex);
2514 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2515 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2516 isa<CUDAGlobalAttr>(Attr))) {
2517 // CUDA target attributes are part of function signature for
2518 // overloading purposes and must not be merged.
2519 return false;
2520 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2521 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2522 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2523 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2524 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2525 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2526 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2527 NewAttr = S.mergeCommonAttr(D, *CommonA);
2528 else if (isa<AlignedAttr>(Attr))
2529 // AlignedAttrs are handled separately, because we need to handle all
2530 // such attributes on a declaration at the same time.
2531 NewAttr = nullptr;
2532 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2533 (AMK == Sema::AMK_Override ||
2534 AMK == Sema::AMK_ProtocolImplementation))
2535 NewAttr = nullptr;
2536 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2537 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2538 UA->getGuid());
2539 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2540 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2541 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2542 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2543 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2544 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2545
2546 if (NewAttr) {
2547 NewAttr->setInherited(true);
2548 D->addAttr(NewAttr);
2549 if (isa<MSInheritanceAttr>(NewAttr))
2550 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2551 return true;
2552 }
2553
2554 return false;
2555 }
2556
getDefinition(const Decl * D)2557 static const NamedDecl *getDefinition(const Decl *D) {
2558 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2559 return TD->getDefinition();
2560 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2561 const VarDecl *Def = VD->getDefinition();
2562 if (Def)
2563 return Def;
2564 return VD->getActingDefinition();
2565 }
2566 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2567 return FD->getDefinition();
2568 return nullptr;
2569 }
2570
hasAttribute(const Decl * D,attr::Kind Kind)2571 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2572 for (const auto *Attribute : D->attrs())
2573 if (Attribute->getKind() == Kind)
2574 return true;
2575 return false;
2576 }
2577
2578 /// checkNewAttributesAfterDef - If we already have a definition, check that
2579 /// there are no new attributes in this declaration.
checkNewAttributesAfterDef(Sema & S,Decl * New,const Decl * Old)2580 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2581 if (!New->hasAttrs())
2582 return;
2583
2584 const NamedDecl *Def = getDefinition(Old);
2585 if (!Def || Def == New)
2586 return;
2587
2588 AttrVec &NewAttributes = New->getAttrs();
2589 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2590 const Attr *NewAttribute = NewAttributes[I];
2591
2592 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2593 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2594 Sema::SkipBodyInfo SkipBody;
2595 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2596
2597 // If we're skipping this definition, drop the "alias" attribute.
2598 if (SkipBody.ShouldSkip) {
2599 NewAttributes.erase(NewAttributes.begin() + I);
2600 --E;
2601 continue;
2602 }
2603 } else {
2604 VarDecl *VD = cast<VarDecl>(New);
2605 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2606 VarDecl::TentativeDefinition
2607 ? diag::err_alias_after_tentative
2608 : diag::err_redefinition;
2609 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2610 if (Diag == diag::err_redefinition)
2611 S.notePreviousDefinition(Def, VD->getLocation());
2612 else
2613 S.Diag(Def->getLocation(), diag::note_previous_definition);
2614 VD->setInvalidDecl();
2615 }
2616 ++I;
2617 continue;
2618 }
2619
2620 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2621 // Tentative definitions are only interesting for the alias check above.
2622 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2623 ++I;
2624 continue;
2625 }
2626 }
2627
2628 if (hasAttribute(Def, NewAttribute->getKind())) {
2629 ++I;
2630 continue; // regular attr merging will take care of validating this.
2631 }
2632
2633 if (isa<C11NoReturnAttr>(NewAttribute)) {
2634 // C's _Noreturn is allowed to be added to a function after it is defined.
2635 ++I;
2636 continue;
2637 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2638 if (AA->isAlignas()) {
2639 // C++11 [dcl.align]p6:
2640 // if any declaration of an entity has an alignment-specifier,
2641 // every defining declaration of that entity shall specify an
2642 // equivalent alignment.
2643 // C11 6.7.5/7:
2644 // If the definition of an object does not have an alignment
2645 // specifier, any other declaration of that object shall also
2646 // have no alignment specifier.
2647 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2648 << AA;
2649 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2650 << AA;
2651 NewAttributes.erase(NewAttributes.begin() + I);
2652 --E;
2653 continue;
2654 }
2655 }
2656
2657 S.Diag(NewAttribute->getLocation(),
2658 diag::warn_attribute_precede_definition);
2659 S.Diag(Def->getLocation(), diag::note_previous_definition);
2660 NewAttributes.erase(NewAttributes.begin() + I);
2661 --E;
2662 }
2663 }
2664
2665 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
mergeDeclAttributes(NamedDecl * New,Decl * Old,AvailabilityMergeKind AMK)2666 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2667 AvailabilityMergeKind AMK) {
2668 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2669 UsedAttr *NewAttr = OldAttr->clone(Context);
2670 NewAttr->setInherited(true);
2671 New->addAttr(NewAttr);
2672 }
2673
2674 if (!Old->hasAttrs() && !New->hasAttrs())
2675 return;
2676
2677 // Attributes declared post-definition are currently ignored.
2678 checkNewAttributesAfterDef(*this, New, Old);
2679
2680 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2681 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2682 if (OldA->getLabel() != NewA->getLabel()) {
2683 // This redeclaration changes __asm__ label.
2684 Diag(New->getLocation(), diag::err_different_asm_label);
2685 Diag(OldA->getLocation(), diag::note_previous_declaration);
2686 }
2687 } else if (Old->isUsed()) {
2688 // This redeclaration adds an __asm__ label to a declaration that has
2689 // already been ODR-used.
2690 Diag(New->getLocation(), diag::err_late_asm_label_name)
2691 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2692 }
2693 }
2694
2695 // Re-declaration cannot add abi_tag's.
2696 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2697 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2698 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2699 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2700 NewTag) == OldAbiTagAttr->tags_end()) {
2701 Diag(NewAbiTagAttr->getLocation(),
2702 diag::err_new_abi_tag_on_redeclaration)
2703 << NewTag;
2704 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2705 }
2706 }
2707 } else {
2708 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2709 Diag(Old->getLocation(), diag::note_previous_declaration);
2710 }
2711 }
2712
2713 // This redeclaration adds a section attribute.
2714 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2715 if (auto *VD = dyn_cast<VarDecl>(New)) {
2716 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2717 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2718 Diag(Old->getLocation(), diag::note_previous_declaration);
2719 }
2720 }
2721 }
2722
2723 // Redeclaration adds code-seg attribute.
2724 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2725 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2726 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2727 Diag(New->getLocation(), diag::warn_mismatched_section)
2728 << 0 /*codeseg*/;
2729 Diag(Old->getLocation(), diag::note_previous_declaration);
2730 }
2731
2732 if (!Old->hasAttrs())
2733 return;
2734
2735 bool foundAny = New->hasAttrs();
2736
2737 // Ensure that any moving of objects within the allocated map is done before
2738 // we process them.
2739 if (!foundAny) New->setAttrs(AttrVec());
2740
2741 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2742 // Ignore deprecated/unavailable/availability attributes if requested.
2743 AvailabilityMergeKind LocalAMK = AMK_None;
2744 if (isa<DeprecatedAttr>(I) ||
2745 isa<UnavailableAttr>(I) ||
2746 isa<AvailabilityAttr>(I)) {
2747 switch (AMK) {
2748 case AMK_None:
2749 continue;
2750
2751 case AMK_Redeclaration:
2752 case AMK_Override:
2753 case AMK_ProtocolImplementation:
2754 LocalAMK = AMK;
2755 break;
2756 }
2757 }
2758
2759 // Already handled.
2760 if (isa<UsedAttr>(I))
2761 continue;
2762
2763 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2764 foundAny = true;
2765 }
2766
2767 if (mergeAlignedAttrs(*this, New, Old))
2768 foundAny = true;
2769
2770 if (!foundAny) New->dropAttrs();
2771 }
2772
2773 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2774 /// to the new one.
mergeParamDeclAttributes(ParmVarDecl * newDecl,const ParmVarDecl * oldDecl,Sema & S)2775 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2776 const ParmVarDecl *oldDecl,
2777 Sema &S) {
2778 // C++11 [dcl.attr.depend]p2:
2779 // The first declaration of a function shall specify the
2780 // carries_dependency attribute for its declarator-id if any declaration
2781 // of the function specifies the carries_dependency attribute.
2782 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2783 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2784 S.Diag(CDA->getLocation(),
2785 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2786 // Find the first declaration of the parameter.
2787 // FIXME: Should we build redeclaration chains for function parameters?
2788 const FunctionDecl *FirstFD =
2789 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2790 const ParmVarDecl *FirstVD =
2791 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2792 S.Diag(FirstVD->getLocation(),
2793 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2794 }
2795
2796 if (!oldDecl->hasAttrs())
2797 return;
2798
2799 bool foundAny = newDecl->hasAttrs();
2800
2801 // Ensure that any moving of objects within the allocated map is
2802 // done before we process them.
2803 if (!foundAny) newDecl->setAttrs(AttrVec());
2804
2805 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2806 if (!DeclHasAttr(newDecl, I)) {
2807 InheritableAttr *newAttr =
2808 cast<InheritableParamAttr>(I->clone(S.Context));
2809 newAttr->setInherited(true);
2810 newDecl->addAttr(newAttr);
2811 foundAny = true;
2812 }
2813 }
2814
2815 if (!foundAny) newDecl->dropAttrs();
2816 }
2817
mergeParamDeclTypes(ParmVarDecl * NewParam,const ParmVarDecl * OldParam,Sema & S)2818 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2819 const ParmVarDecl *OldParam,
2820 Sema &S) {
2821 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2822 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2823 if (*Oldnullability != *Newnullability) {
2824 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2825 << DiagNullabilityKind(
2826 *Newnullability,
2827 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2828 != 0))
2829 << DiagNullabilityKind(
2830 *Oldnullability,
2831 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2832 != 0));
2833 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2834 }
2835 } else {
2836 QualType NewT = NewParam->getType();
2837 NewT = S.Context.getAttributedType(
2838 AttributedType::getNullabilityAttrKind(*Oldnullability),
2839 NewT, NewT);
2840 NewParam->setType(NewT);
2841 }
2842 }
2843 }
2844
2845 namespace {
2846
2847 /// Used in MergeFunctionDecl to keep track of function parameters in
2848 /// C.
2849 struct GNUCompatibleParamWarning {
2850 ParmVarDecl *OldParm;
2851 ParmVarDecl *NewParm;
2852 QualType PromotedType;
2853 };
2854
2855 } // end anonymous namespace
2856
2857 /// getSpecialMember - get the special member enum for a method.
getSpecialMember(const CXXMethodDecl * MD)2858 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2859 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2860 if (Ctor->isDefaultConstructor())
2861 return Sema::CXXDefaultConstructor;
2862
2863 if (Ctor->isCopyConstructor())
2864 return Sema::CXXCopyConstructor;
2865
2866 if (Ctor->isMoveConstructor())
2867 return Sema::CXXMoveConstructor;
2868 } else if (isa<CXXDestructorDecl>(MD)) {
2869 return Sema::CXXDestructor;
2870 } else if (MD->isCopyAssignmentOperator()) {
2871 return Sema::CXXCopyAssignment;
2872 } else if (MD->isMoveAssignmentOperator()) {
2873 return Sema::CXXMoveAssignment;
2874 }
2875
2876 return Sema::CXXInvalid;
2877 }
2878
2879 // Determine whether the previous declaration was a definition, implicit
2880 // declaration, or a declaration.
2881 template <typename T>
2882 static std::pair<diag::kind, SourceLocation>
getNoteDiagForInvalidRedeclaration(const T * Old,const T * New)2883 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2884 diag::kind PrevDiag;
2885 SourceLocation OldLocation = Old->getLocation();
2886 if (Old->isThisDeclarationADefinition())
2887 PrevDiag = diag::note_previous_definition;
2888 else if (Old->isImplicit()) {
2889 PrevDiag = diag::note_previous_implicit_declaration;
2890 if (OldLocation.isInvalid())
2891 OldLocation = New->getLocation();
2892 } else
2893 PrevDiag = diag::note_previous_declaration;
2894 return std::make_pair(PrevDiag, OldLocation);
2895 }
2896
2897 /// canRedefineFunction - checks if a function can be redefined. Currently,
2898 /// only extern inline functions can be redefined, and even then only in
2899 /// GNU89 mode.
canRedefineFunction(const FunctionDecl * FD,const LangOptions & LangOpts)2900 static bool canRedefineFunction(const FunctionDecl *FD,
2901 const LangOptions& LangOpts) {
2902 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2903 !LangOpts.CPlusPlus &&
2904 FD->isInlineSpecified() &&
2905 FD->getStorageClass() == SC_Extern);
2906 }
2907
getCallingConvAttributedType(QualType T) const2908 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2909 const AttributedType *AT = T->getAs<AttributedType>();
2910 while (AT && !AT->isCallingConv())
2911 AT = AT->getModifiedType()->getAs<AttributedType>();
2912 return AT;
2913 }
2914
2915 template <typename T>
haveIncompatibleLanguageLinkages(const T * Old,const T * New)2916 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2917 const DeclContext *DC = Old->getDeclContext();
2918 if (DC->isRecord())
2919 return false;
2920
2921 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2922 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2923 return true;
2924 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2925 return true;
2926 return false;
2927 }
2928
isExternC(T * D)2929 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
isExternC(VarTemplateDecl *)2930 static bool isExternC(VarTemplateDecl *) { return false; }
2931
2932 /// Check whether a redeclaration of an entity introduced by a
2933 /// using-declaration is valid, given that we know it's not an overload
2934 /// (nor a hidden tag declaration).
2935 template<typename ExpectedDecl>
checkUsingShadowRedecl(Sema & S,UsingShadowDecl * OldS,ExpectedDecl * New)2936 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2937 ExpectedDecl *New) {
2938 // C++11 [basic.scope.declarative]p4:
2939 // Given a set of declarations in a single declarative region, each of
2940 // which specifies the same unqualified name,
2941 // -- they shall all refer to the same entity, or all refer to functions
2942 // and function templates; or
2943 // -- exactly one declaration shall declare a class name or enumeration
2944 // name that is not a typedef name and the other declarations shall all
2945 // refer to the same variable or enumerator, or all refer to functions
2946 // and function templates; in this case the class name or enumeration
2947 // name is hidden (3.3.10).
2948
2949 // C++11 [namespace.udecl]p14:
2950 // If a function declaration in namespace scope or block scope has the
2951 // same name and the same parameter-type-list as a function introduced
2952 // by a using-declaration, and the declarations do not declare the same
2953 // function, the program is ill-formed.
2954
2955 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2956 if (Old &&
2957 !Old->getDeclContext()->getRedeclContext()->Equals(
2958 New->getDeclContext()->getRedeclContext()) &&
2959 !(isExternC(Old) && isExternC(New)))
2960 Old = nullptr;
2961
2962 if (!Old) {
2963 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2964 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2965 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2966 return true;
2967 }
2968 return false;
2969 }
2970
hasIdenticalPassObjectSizeAttrs(const FunctionDecl * A,const FunctionDecl * B)2971 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2972 const FunctionDecl *B) {
2973 assert(A->getNumParams() == B->getNumParams());
2974
2975 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2976 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2977 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2978 if (AttrA == AttrB)
2979 return true;
2980 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
2981 AttrA->isDynamic() == AttrB->isDynamic();
2982 };
2983
2984 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2985 }
2986
2987 /// If necessary, adjust the semantic declaration context for a qualified
2988 /// declaration to name the correct inline namespace within the qualifier.
adjustDeclContextForDeclaratorDecl(DeclaratorDecl * NewD,DeclaratorDecl * OldD)2989 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2990 DeclaratorDecl *OldD) {
2991 // The only case where we need to update the DeclContext is when
2992 // redeclaration lookup for a qualified name finds a declaration
2993 // in an inline namespace within the context named by the qualifier:
2994 //
2995 // inline namespace N { int f(); }
2996 // int ::f(); // Sema DC needs adjusting from :: to N::.
2997 //
2998 // For unqualified declarations, the semantic context *can* change
2999 // along the redeclaration chain (for local extern declarations,
3000 // extern "C" declarations, and friend declarations in particular).
3001 if (!NewD->getQualifier())
3002 return;
3003
3004 // NewD is probably already in the right context.
3005 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3006 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3007 if (NamedDC->Equals(SemaDC))
3008 return;
3009
3010 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3011 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3012 "unexpected context for redeclaration");
3013
3014 auto *LexDC = NewD->getLexicalDeclContext();
3015 auto FixSemaDC = [=](NamedDecl *D) {
3016 if (!D)
3017 return;
3018 D->setDeclContext(SemaDC);
3019 D->setLexicalDeclContext(LexDC);
3020 };
3021
3022 FixSemaDC(NewD);
3023 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3024 FixSemaDC(FD->getDescribedFunctionTemplate());
3025 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3026 FixSemaDC(VD->getDescribedVarTemplate());
3027 }
3028
3029 /// MergeFunctionDecl - We just parsed a function 'New' from
3030 /// declarator D which has the same name and scope as a previous
3031 /// declaration 'Old'. Figure out how to resolve this situation,
3032 /// merging decls or emitting diagnostics as appropriate.
3033 ///
3034 /// In C++, New and Old must be declarations that are not
3035 /// overloaded. Use IsOverload to determine whether New and Old are
3036 /// overloaded, and to select the Old declaration that New should be
3037 /// merged with.
3038 ///
3039 /// Returns true if there was an error, false otherwise.
MergeFunctionDecl(FunctionDecl * New,NamedDecl * & OldD,Scope * S,bool MergeTypeWithOld)3040 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3041 Scope *S, bool MergeTypeWithOld) {
3042 // Verify the old decl was also a function.
3043 FunctionDecl *Old = OldD->getAsFunction();
3044 if (!Old) {
3045 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3046 if (New->getFriendObjectKind()) {
3047 Diag(New->getLocation(), diag::err_using_decl_friend);
3048 Diag(Shadow->getTargetDecl()->getLocation(),
3049 diag::note_using_decl_target);
3050 Diag(Shadow->getUsingDecl()->getLocation(),
3051 diag::note_using_decl) << 0;
3052 return true;
3053 }
3054
3055 // Check whether the two declarations might declare the same function.
3056 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3057 return true;
3058 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3059 } else {
3060 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3061 << New->getDeclName();
3062 notePreviousDefinition(OldD, New->getLocation());
3063 return true;
3064 }
3065 }
3066
3067 // If the old declaration is invalid, just give up here.
3068 if (Old->isInvalidDecl())
3069 return true;
3070
3071 // Disallow redeclaration of some builtins.
3072 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3073 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3074 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3075 << Old << Old->getType();
3076 return true;
3077 }
3078
3079 diag::kind PrevDiag;
3080 SourceLocation OldLocation;
3081 std::tie(PrevDiag, OldLocation) =
3082 getNoteDiagForInvalidRedeclaration(Old, New);
3083
3084 // Don't complain about this if we're in GNU89 mode and the old function
3085 // is an extern inline function.
3086 // Don't complain about specializations. They are not supposed to have
3087 // storage classes.
3088 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3089 New->getStorageClass() == SC_Static &&
3090 Old->hasExternalFormalLinkage() &&
3091 !New->getTemplateSpecializationInfo() &&
3092 !canRedefineFunction(Old, getLangOpts())) {
3093 if (getLangOpts().MicrosoftExt) {
3094 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3095 Diag(OldLocation, PrevDiag);
3096 } else {
3097 Diag(New->getLocation(), diag::err_static_non_static) << New;
3098 Diag(OldLocation, PrevDiag);
3099 return true;
3100 }
3101 }
3102
3103 if (New->hasAttr<InternalLinkageAttr>() &&
3104 !Old->hasAttr<InternalLinkageAttr>()) {
3105 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3106 << New->getDeclName();
3107 notePreviousDefinition(Old, New->getLocation());
3108 New->dropAttr<InternalLinkageAttr>();
3109 }
3110
3111 if (CheckRedeclarationModuleOwnership(New, Old))
3112 return true;
3113
3114 if (!getLangOpts().CPlusPlus) {
3115 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3116 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3117 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3118 << New << OldOvl;
3119
3120 // Try our best to find a decl that actually has the overloadable
3121 // attribute for the note. In most cases (e.g. programs with only one
3122 // broken declaration/definition), this won't matter.
3123 //
3124 // FIXME: We could do this if we juggled some extra state in
3125 // OverloadableAttr, rather than just removing it.
3126 const Decl *DiagOld = Old;
3127 if (OldOvl) {
3128 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3129 const auto *A = D->getAttr<OverloadableAttr>();
3130 return A && !A->isImplicit();
3131 });
3132 // If we've implicitly added *all* of the overloadable attrs to this
3133 // chain, emitting a "previous redecl" note is pointless.
3134 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3135 }
3136
3137 if (DiagOld)
3138 Diag(DiagOld->getLocation(),
3139 diag::note_attribute_overloadable_prev_overload)
3140 << OldOvl;
3141
3142 if (OldOvl)
3143 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3144 else
3145 New->dropAttr<OverloadableAttr>();
3146 }
3147 }
3148
3149 // If a function is first declared with a calling convention, but is later
3150 // declared or defined without one, all following decls assume the calling
3151 // convention of the first.
3152 //
3153 // It's OK if a function is first declared without a calling convention,
3154 // but is later declared or defined with the default calling convention.
3155 //
3156 // To test if either decl has an explicit calling convention, we look for
3157 // AttributedType sugar nodes on the type as written. If they are missing or
3158 // were canonicalized away, we assume the calling convention was implicit.
3159 //
3160 // Note also that we DO NOT return at this point, because we still have
3161 // other tests to run.
3162 QualType OldQType = Context.getCanonicalType(Old->getType());
3163 QualType NewQType = Context.getCanonicalType(New->getType());
3164 const FunctionType *OldType = cast<FunctionType>(OldQType);
3165 const FunctionType *NewType = cast<FunctionType>(NewQType);
3166 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3167 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3168 bool RequiresAdjustment = false;
3169
3170 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3171 FunctionDecl *First = Old->getFirstDecl();
3172 const FunctionType *FT =
3173 First->getType().getCanonicalType()->castAs<FunctionType>();
3174 FunctionType::ExtInfo FI = FT->getExtInfo();
3175 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3176 if (!NewCCExplicit) {
3177 // Inherit the CC from the previous declaration if it was specified
3178 // there but not here.
3179 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3180 RequiresAdjustment = true;
3181 } else if (New->getBuiltinID()) {
3182 // Calling Conventions on a Builtin aren't really useful and setting a
3183 // default calling convention and cdecl'ing some builtin redeclarations is
3184 // common, so warn and ignore the calling convention on the redeclaration.
3185 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3186 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3187 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3188 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3189 RequiresAdjustment = true;
3190 } else {
3191 // Calling conventions aren't compatible, so complain.
3192 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3193 Diag(New->getLocation(), diag::err_cconv_change)
3194 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3195 << !FirstCCExplicit
3196 << (!FirstCCExplicit ? "" :
3197 FunctionType::getNameForCallConv(FI.getCC()));
3198
3199 // Put the note on the first decl, since it is the one that matters.
3200 Diag(First->getLocation(), diag::note_previous_declaration);
3201 return true;
3202 }
3203 }
3204
3205 // FIXME: diagnose the other way around?
3206 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3207 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3208 RequiresAdjustment = true;
3209 }
3210
3211 // Merge regparm attribute.
3212 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3213 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3214 if (NewTypeInfo.getHasRegParm()) {
3215 Diag(New->getLocation(), diag::err_regparm_mismatch)
3216 << NewType->getRegParmType()
3217 << OldType->getRegParmType();
3218 Diag(OldLocation, diag::note_previous_declaration);
3219 return true;
3220 }
3221
3222 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3223 RequiresAdjustment = true;
3224 }
3225
3226 // Merge ns_returns_retained attribute.
3227 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3228 if (NewTypeInfo.getProducesResult()) {
3229 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3230 << "'ns_returns_retained'";
3231 Diag(OldLocation, diag::note_previous_declaration);
3232 return true;
3233 }
3234
3235 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3236 RequiresAdjustment = true;
3237 }
3238
3239 if (OldTypeInfo.getNoCallerSavedRegs() !=
3240 NewTypeInfo.getNoCallerSavedRegs()) {
3241 if (NewTypeInfo.getNoCallerSavedRegs()) {
3242 AnyX86NoCallerSavedRegistersAttr *Attr =
3243 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3244 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3245 Diag(OldLocation, diag::note_previous_declaration);
3246 return true;
3247 }
3248
3249 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3250 RequiresAdjustment = true;
3251 }
3252
3253 if (RequiresAdjustment) {
3254 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3255 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3256 New->setType(QualType(AdjustedType, 0));
3257 NewQType = Context.getCanonicalType(New->getType());
3258 }
3259
3260 // If this redeclaration makes the function inline, we may need to add it to
3261 // UndefinedButUsed.
3262 if (!Old->isInlined() && New->isInlined() &&
3263 !New->hasAttr<GNUInlineAttr>() &&
3264 !getLangOpts().GNUInline &&
3265 Old->isUsed(false) &&
3266 !Old->isDefined() && !New->isThisDeclarationADefinition())
3267 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3268 SourceLocation()));
3269
3270 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3271 // about it.
3272 if (New->hasAttr<GNUInlineAttr>() &&
3273 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3274 UndefinedButUsed.erase(Old->getCanonicalDecl());
3275 }
3276
3277 // If pass_object_size params don't match up perfectly, this isn't a valid
3278 // redeclaration.
3279 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3280 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3281 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3282 << New->getDeclName();
3283 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3284 return true;
3285 }
3286
3287 if (getLangOpts().CPlusPlus) {
3288 // C++1z [over.load]p2
3289 // Certain function declarations cannot be overloaded:
3290 // -- Function declarations that differ only in the return type,
3291 // the exception specification, or both cannot be overloaded.
3292
3293 // Check the exception specifications match. This may recompute the type of
3294 // both Old and New if it resolved exception specifications, so grab the
3295 // types again after this. Because this updates the type, we do this before
3296 // any of the other checks below, which may update the "de facto" NewQType
3297 // but do not necessarily update the type of New.
3298 if (CheckEquivalentExceptionSpec(Old, New))
3299 return true;
3300 OldQType = Context.getCanonicalType(Old->getType());
3301 NewQType = Context.getCanonicalType(New->getType());
3302
3303 // Go back to the type source info to compare the declared return types,
3304 // per C++1y [dcl.type.auto]p13:
3305 // Redeclarations or specializations of a function or function template
3306 // with a declared return type that uses a placeholder type shall also
3307 // use that placeholder, not a deduced type.
3308 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3309 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3310 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3311 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3312 OldDeclaredReturnType)) {
3313 QualType ResQT;
3314 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3315 OldDeclaredReturnType->isObjCObjectPointerType())
3316 // FIXME: This does the wrong thing for a deduced return type.
3317 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3318 if (ResQT.isNull()) {
3319 if (New->isCXXClassMember() && New->isOutOfLine())
3320 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3321 << New << New->getReturnTypeSourceRange();
3322 else
3323 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3324 << New->getReturnTypeSourceRange();
3325 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3326 << Old->getReturnTypeSourceRange();
3327 return true;
3328 }
3329 else
3330 NewQType = ResQT;
3331 }
3332
3333 QualType OldReturnType = OldType->getReturnType();
3334 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3335 if (OldReturnType != NewReturnType) {
3336 // If this function has a deduced return type and has already been
3337 // defined, copy the deduced value from the old declaration.
3338 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3339 if (OldAT && OldAT->isDeduced()) {
3340 New->setType(
3341 SubstAutoType(New->getType(),
3342 OldAT->isDependentType() ? Context.DependentTy
3343 : OldAT->getDeducedType()));
3344 NewQType = Context.getCanonicalType(
3345 SubstAutoType(NewQType,
3346 OldAT->isDependentType() ? Context.DependentTy
3347 : OldAT->getDeducedType()));
3348 }
3349 }
3350
3351 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3352 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3353 if (OldMethod && NewMethod) {
3354 // Preserve triviality.
3355 NewMethod->setTrivial(OldMethod->isTrivial());
3356
3357 // MSVC allows explicit template specialization at class scope:
3358 // 2 CXXMethodDecls referring to the same function will be injected.
3359 // We don't want a redeclaration error.
3360 bool IsClassScopeExplicitSpecialization =
3361 OldMethod->isFunctionTemplateSpecialization() &&
3362 NewMethod->isFunctionTemplateSpecialization();
3363 bool isFriend = NewMethod->getFriendObjectKind();
3364
3365 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3366 !IsClassScopeExplicitSpecialization) {
3367 // -- Member function declarations with the same name and the
3368 // same parameter types cannot be overloaded if any of them
3369 // is a static member function declaration.
3370 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3371 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3372 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3373 return true;
3374 }
3375
3376 // C++ [class.mem]p1:
3377 // [...] A member shall not be declared twice in the
3378 // member-specification, except that a nested class or member
3379 // class template can be declared and then later defined.
3380 if (!inTemplateInstantiation()) {
3381 unsigned NewDiag;
3382 if (isa<CXXConstructorDecl>(OldMethod))
3383 NewDiag = diag::err_constructor_redeclared;
3384 else if (isa<CXXDestructorDecl>(NewMethod))
3385 NewDiag = diag::err_destructor_redeclared;
3386 else if (isa<CXXConversionDecl>(NewMethod))
3387 NewDiag = diag::err_conv_function_redeclared;
3388 else
3389 NewDiag = diag::err_member_redeclared;
3390
3391 Diag(New->getLocation(), NewDiag);
3392 } else {
3393 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3394 << New << New->getType();
3395 }
3396 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3397 return true;
3398
3399 // Complain if this is an explicit declaration of a special
3400 // member that was initially declared implicitly.
3401 //
3402 // As an exception, it's okay to befriend such methods in order
3403 // to permit the implicit constructor/destructor/operator calls.
3404 } else if (OldMethod->isImplicit()) {
3405 if (isFriend) {
3406 NewMethod->setImplicit();
3407 } else {
3408 Diag(NewMethod->getLocation(),
3409 diag::err_definition_of_implicitly_declared_member)
3410 << New << getSpecialMember(OldMethod);
3411 return true;
3412 }
3413 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3414 Diag(NewMethod->getLocation(),
3415 diag::err_definition_of_explicitly_defaulted_member)
3416 << getSpecialMember(OldMethod);
3417 return true;
3418 }
3419 }
3420
3421 // C++11 [dcl.attr.noreturn]p1:
3422 // The first declaration of a function shall specify the noreturn
3423 // attribute if any declaration of that function specifies the noreturn
3424 // attribute.
3425 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3426 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3427 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3428 Diag(Old->getFirstDecl()->getLocation(),
3429 diag::note_noreturn_missing_first_decl);
3430 }
3431
3432 // C++11 [dcl.attr.depend]p2:
3433 // The first declaration of a function shall specify the
3434 // carries_dependency attribute for its declarator-id if any declaration
3435 // of the function specifies the carries_dependency attribute.
3436 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3437 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3438 Diag(CDA->getLocation(),
3439 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3440 Diag(Old->getFirstDecl()->getLocation(),
3441 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3442 }
3443
3444 // (C++98 8.3.5p3):
3445 // All declarations for a function shall agree exactly in both the
3446 // return type and the parameter-type-list.
3447 // We also want to respect all the extended bits except noreturn.
3448
3449 // noreturn should now match unless the old type info didn't have it.
3450 QualType OldQTypeForComparison = OldQType;
3451 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3452 auto *OldType = OldQType->castAs<FunctionProtoType>();
3453 const FunctionType *OldTypeForComparison
3454 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3455 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3456 assert(OldQTypeForComparison.isCanonical());
3457 }
3458
3459 if (haveIncompatibleLanguageLinkages(Old, New)) {
3460 // As a special case, retain the language linkage from previous
3461 // declarations of a friend function as an extension.
3462 //
3463 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3464 // and is useful because there's otherwise no way to specify language
3465 // linkage within class scope.
3466 //
3467 // Check cautiously as the friend object kind isn't yet complete.
3468 if (New->getFriendObjectKind() != Decl::FOK_None) {
3469 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3470 Diag(OldLocation, PrevDiag);
3471 } else {
3472 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3473 Diag(OldLocation, PrevDiag);
3474 return true;
3475 }
3476 }
3477
3478 // If the function types are compatible, merge the declarations. Ignore the
3479 // exception specifier because it was already checked above in
3480 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3481 // about incompatible types under -fms-compatibility.
3482 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3483 NewQType))
3484 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3485
3486 // If the types are imprecise (due to dependent constructs in friends or
3487 // local extern declarations), it's OK if they differ. We'll check again
3488 // during instantiation.
3489 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3490 return false;
3491
3492 // Fall through for conflicting redeclarations and redefinitions.
3493 }
3494
3495 // C: Function types need to be compatible, not identical. This handles
3496 // duplicate function decls like "void f(int); void f(enum X);" properly.
3497 if (!getLangOpts().CPlusPlus &&
3498 Context.typesAreCompatible(OldQType, NewQType)) {
3499 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3500 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3501 const FunctionProtoType *OldProto = nullptr;
3502 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3503 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3504 // The old declaration provided a function prototype, but the
3505 // new declaration does not. Merge in the prototype.
3506 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3507 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3508 NewQType =
3509 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3510 OldProto->getExtProtoInfo());
3511 New->setType(NewQType);
3512 New->setHasInheritedPrototype();
3513
3514 // Synthesize parameters with the same types.
3515 SmallVector<ParmVarDecl*, 16> Params;
3516 for (const auto &ParamType : OldProto->param_types()) {
3517 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3518 SourceLocation(), nullptr,
3519 ParamType, /*TInfo=*/nullptr,
3520 SC_None, nullptr);
3521 Param->setScopeInfo(0, Params.size());
3522 Param->setImplicit();
3523 Params.push_back(Param);
3524 }
3525
3526 New->setParams(Params);
3527 }
3528
3529 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3530 }
3531
3532 // GNU C permits a K&R definition to follow a prototype declaration
3533 // if the declared types of the parameters in the K&R definition
3534 // match the types in the prototype declaration, even when the
3535 // promoted types of the parameters from the K&R definition differ
3536 // from the types in the prototype. GCC then keeps the types from
3537 // the prototype.
3538 //
3539 // If a variadic prototype is followed by a non-variadic K&R definition,
3540 // the K&R definition becomes variadic. This is sort of an edge case, but
3541 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3542 // C99 6.9.1p8.
3543 if (!getLangOpts().CPlusPlus &&
3544 Old->hasPrototype() && !New->hasPrototype() &&
3545 New->getType()->getAs<FunctionProtoType>() &&
3546 Old->getNumParams() == New->getNumParams()) {
3547 SmallVector<QualType, 16> ArgTypes;
3548 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3549 const FunctionProtoType *OldProto
3550 = Old->getType()->getAs<FunctionProtoType>();
3551 const FunctionProtoType *NewProto
3552 = New->getType()->getAs<FunctionProtoType>();
3553
3554 // Determine whether this is the GNU C extension.
3555 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3556 NewProto->getReturnType());
3557 bool LooseCompatible = !MergedReturn.isNull();
3558 for (unsigned Idx = 0, End = Old->getNumParams();
3559 LooseCompatible && Idx != End; ++Idx) {
3560 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3561 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3562 if (Context.typesAreCompatible(OldParm->getType(),
3563 NewProto->getParamType(Idx))) {
3564 ArgTypes.push_back(NewParm->getType());
3565 } else if (Context.typesAreCompatible(OldParm->getType(),
3566 NewParm->getType(),
3567 /*CompareUnqualified=*/true)) {
3568 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3569 NewProto->getParamType(Idx) };
3570 Warnings.push_back(Warn);
3571 ArgTypes.push_back(NewParm->getType());
3572 } else
3573 LooseCompatible = false;
3574 }
3575
3576 if (LooseCompatible) {
3577 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3578 Diag(Warnings[Warn].NewParm->getLocation(),
3579 diag::ext_param_promoted_not_compatible_with_prototype)
3580 << Warnings[Warn].PromotedType
3581 << Warnings[Warn].OldParm->getType();
3582 if (Warnings[Warn].OldParm->getLocation().isValid())
3583 Diag(Warnings[Warn].OldParm->getLocation(),
3584 diag::note_previous_declaration);
3585 }
3586
3587 if (MergeTypeWithOld)
3588 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3589 OldProto->getExtProtoInfo()));
3590 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3591 }
3592
3593 // Fall through to diagnose conflicting types.
3594 }
3595
3596 // A function that has already been declared has been redeclared or
3597 // defined with a different type; show an appropriate diagnostic.
3598
3599 // If the previous declaration was an implicitly-generated builtin
3600 // declaration, then at the very least we should use a specialized note.
3601 unsigned BuiltinID;
3602 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3603 // If it's actually a library-defined builtin function like 'malloc'
3604 // or 'printf', just warn about the incompatible redeclaration.
3605 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3606 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3607 Diag(OldLocation, diag::note_previous_builtin_declaration)
3608 << Old << Old->getType();
3609
3610 // If this is a global redeclaration, just forget hereafter
3611 // about the "builtin-ness" of the function.
3612 //
3613 // Doing this for local extern declarations is problematic. If
3614 // the builtin declaration remains visible, a second invalid
3615 // local declaration will produce a hard error; if it doesn't
3616 // remain visible, a single bogus local redeclaration (which is
3617 // actually only a warning) could break all the downstream code.
3618 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3619 New->getIdentifier()->revertBuiltin();
3620
3621 return false;
3622 }
3623
3624 PrevDiag = diag::note_previous_builtin_declaration;
3625 }
3626
3627 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3628 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3629 return true;
3630 }
3631
3632 /// Completes the merge of two function declarations that are
3633 /// known to be compatible.
3634 ///
3635 /// This routine handles the merging of attributes and other
3636 /// properties of function declarations from the old declaration to
3637 /// the new declaration, once we know that New is in fact a
3638 /// redeclaration of Old.
3639 ///
3640 /// \returns false
MergeCompatibleFunctionDecls(FunctionDecl * New,FunctionDecl * Old,Scope * S,bool MergeTypeWithOld)3641 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3642 Scope *S, bool MergeTypeWithOld) {
3643 // Merge the attributes
3644 mergeDeclAttributes(New, Old);
3645
3646 // Merge "pure" flag.
3647 if (Old->isPure())
3648 New->setPure();
3649
3650 // Merge "used" flag.
3651 if (Old->getMostRecentDecl()->isUsed(false))
3652 New->setIsUsed();
3653
3654 // Merge attributes from the parameters. These can mismatch with K&R
3655 // declarations.
3656 if (New->getNumParams() == Old->getNumParams())
3657 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3658 ParmVarDecl *NewParam = New->getParamDecl(i);
3659 ParmVarDecl *OldParam = Old->getParamDecl(i);
3660 mergeParamDeclAttributes(NewParam, OldParam, *this);
3661 mergeParamDeclTypes(NewParam, OldParam, *this);
3662 }
3663
3664 if (getLangOpts().CPlusPlus)
3665 return MergeCXXFunctionDecl(New, Old, S);
3666
3667 // Merge the function types so the we get the composite types for the return
3668 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3669 // was visible.
3670 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3671 if (!Merged.isNull() && MergeTypeWithOld)
3672 New->setType(Merged);
3673
3674 return false;
3675 }
3676
mergeObjCMethodDecls(ObjCMethodDecl * newMethod,ObjCMethodDecl * oldMethod)3677 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3678 ObjCMethodDecl *oldMethod) {
3679 // Merge the attributes, including deprecated/unavailable
3680 AvailabilityMergeKind MergeKind =
3681 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3682 ? AMK_ProtocolImplementation
3683 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3684 : AMK_Override;
3685
3686 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3687
3688 // Merge attributes from the parameters.
3689 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3690 oe = oldMethod->param_end();
3691 for (ObjCMethodDecl::param_iterator
3692 ni = newMethod->param_begin(), ne = newMethod->param_end();
3693 ni != ne && oi != oe; ++ni, ++oi)
3694 mergeParamDeclAttributes(*ni, *oi, *this);
3695
3696 CheckObjCMethodOverride(newMethod, oldMethod);
3697 }
3698
diagnoseVarDeclTypeMismatch(Sema & S,VarDecl * New,VarDecl * Old)3699 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3700 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3701
3702 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3703 ? diag::err_redefinition_different_type
3704 : diag::err_redeclaration_different_type)
3705 << New->getDeclName() << New->getType() << Old->getType();
3706
3707 diag::kind PrevDiag;
3708 SourceLocation OldLocation;
3709 std::tie(PrevDiag, OldLocation)
3710 = getNoteDiagForInvalidRedeclaration(Old, New);
3711 S.Diag(OldLocation, PrevDiag);
3712 New->setInvalidDecl();
3713 }
3714
3715 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3716 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3717 /// emitting diagnostics as appropriate.
3718 ///
3719 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3720 /// to here in AddInitializerToDecl. We can't check them before the initializer
3721 /// is attached.
MergeVarDeclTypes(VarDecl * New,VarDecl * Old,bool MergeTypeWithOld)3722 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3723 bool MergeTypeWithOld) {
3724 if (New->isInvalidDecl() || Old->isInvalidDecl())
3725 return;
3726
3727 QualType MergedT;
3728 if (getLangOpts().CPlusPlus) {
3729 if (New->getType()->isUndeducedType()) {
3730 // We don't know what the new type is until the initializer is attached.
3731 return;
3732 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3733 // These could still be something that needs exception specs checked.
3734 return MergeVarDeclExceptionSpecs(New, Old);
3735 }
3736 // C++ [basic.link]p10:
3737 // [...] the types specified by all declarations referring to a given
3738 // object or function shall be identical, except that declarations for an
3739 // array object can specify array types that differ by the presence or
3740 // absence of a major array bound (8.3.4).
3741 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3742 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3743 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3744
3745 // We are merging a variable declaration New into Old. If it has an array
3746 // bound, and that bound differs from Old's bound, we should diagnose the
3747 // mismatch.
3748 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3749 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3750 PrevVD = PrevVD->getPreviousDecl()) {
3751 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3752 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3753 continue;
3754
3755 if (!Context.hasSameType(NewArray, PrevVDTy))
3756 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3757 }
3758 }
3759
3760 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3761 if (Context.hasSameType(OldArray->getElementType(),
3762 NewArray->getElementType()))
3763 MergedT = New->getType();
3764 }
3765 // FIXME: Check visibility. New is hidden but has a complete type. If New
3766 // has no array bound, it should not inherit one from Old, if Old is not
3767 // visible.
3768 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3769 if (Context.hasSameType(OldArray->getElementType(),
3770 NewArray->getElementType()))
3771 MergedT = Old->getType();
3772 }
3773 }
3774 else if (New->getType()->isObjCObjectPointerType() &&
3775 Old->getType()->isObjCObjectPointerType()) {
3776 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3777 Old->getType());
3778 }
3779 } else {
3780 // C 6.2.7p2:
3781 // All declarations that refer to the same object or function shall have
3782 // compatible type.
3783 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3784 }
3785 if (MergedT.isNull()) {
3786 // It's OK if we couldn't merge types if either type is dependent, for a
3787 // block-scope variable. In other cases (static data members of class
3788 // templates, variable templates, ...), we require the types to be
3789 // equivalent.
3790 // FIXME: The C++ standard doesn't say anything about this.
3791 if ((New->getType()->isDependentType() ||
3792 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3793 // If the old type was dependent, we can't merge with it, so the new type
3794 // becomes dependent for now. We'll reproduce the original type when we
3795 // instantiate the TypeSourceInfo for the variable.
3796 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3797 New->setType(Context.DependentTy);
3798 return;
3799 }
3800 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3801 }
3802
3803 // Don't actually update the type on the new declaration if the old
3804 // declaration was an extern declaration in a different scope.
3805 if (MergeTypeWithOld)
3806 New->setType(MergedT);
3807 }
3808
mergeTypeWithPrevious(Sema & S,VarDecl * NewVD,VarDecl * OldVD,LookupResult & Previous)3809 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3810 LookupResult &Previous) {
3811 // C11 6.2.7p4:
3812 // For an identifier with internal or external linkage declared
3813 // in a scope in which a prior declaration of that identifier is
3814 // visible, if the prior declaration specifies internal or
3815 // external linkage, the type of the identifier at the later
3816 // declaration becomes the composite type.
3817 //
3818 // If the variable isn't visible, we do not merge with its type.
3819 if (Previous.isShadowed())
3820 return false;
3821
3822 if (S.getLangOpts().CPlusPlus) {
3823 // C++11 [dcl.array]p3:
3824 // If there is a preceding declaration of the entity in the same
3825 // scope in which the bound was specified, an omitted array bound
3826 // is taken to be the same as in that earlier declaration.
3827 return NewVD->isPreviousDeclInSameBlockScope() ||
3828 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3829 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3830 } else {
3831 // If the old declaration was function-local, don't merge with its
3832 // type unless we're in the same function.
3833 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3834 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3835 }
3836 }
3837
3838 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3839 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3840 /// situation, merging decls or emitting diagnostics as appropriate.
3841 ///
3842 /// Tentative definition rules (C99 6.9.2p2) are checked by
3843 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3844 /// definitions here, since the initializer hasn't been attached.
3845 ///
MergeVarDecl(VarDecl * New,LookupResult & Previous)3846 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3847 // If the new decl is already invalid, don't do any other checking.
3848 if (New->isInvalidDecl())
3849 return;
3850
3851 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3852 return;
3853
3854 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3855
3856 // Verify the old decl was also a variable or variable template.
3857 VarDecl *Old = nullptr;
3858 VarTemplateDecl *OldTemplate = nullptr;
3859 if (Previous.isSingleResult()) {
3860 if (NewTemplate) {
3861 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3862 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3863
3864 if (auto *Shadow =
3865 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3866 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3867 return New->setInvalidDecl();
3868 } else {
3869 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3870
3871 if (auto *Shadow =
3872 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3873 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3874 return New->setInvalidDecl();
3875 }
3876 }
3877 if (!Old) {
3878 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3879 << New->getDeclName();
3880 notePreviousDefinition(Previous.getRepresentativeDecl(),
3881 New->getLocation());
3882 return New->setInvalidDecl();
3883 }
3884
3885 // Ensure the template parameters are compatible.
3886 if (NewTemplate &&
3887 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3888 OldTemplate->getTemplateParameters(),
3889 /*Complain=*/true, TPL_TemplateMatch))
3890 return New->setInvalidDecl();
3891
3892 // C++ [class.mem]p1:
3893 // A member shall not be declared twice in the member-specification [...]
3894 //
3895 // Here, we need only consider static data members.
3896 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3897 Diag(New->getLocation(), diag::err_duplicate_member)
3898 << New->getIdentifier();
3899 Diag(Old->getLocation(), diag::note_previous_declaration);
3900 New->setInvalidDecl();
3901 }
3902
3903 mergeDeclAttributes(New, Old);
3904 // Warn if an already-declared variable is made a weak_import in a subsequent
3905 // declaration
3906 if (New->hasAttr<WeakImportAttr>() &&
3907 Old->getStorageClass() == SC_None &&
3908 !Old->hasAttr<WeakImportAttr>()) {
3909 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3910 notePreviousDefinition(Old, New->getLocation());
3911 // Remove weak_import attribute on new declaration.
3912 New->dropAttr<WeakImportAttr>();
3913 }
3914
3915 if (New->hasAttr<InternalLinkageAttr>() &&
3916 !Old->hasAttr<InternalLinkageAttr>()) {
3917 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3918 << New->getDeclName();
3919 notePreviousDefinition(Old, New->getLocation());
3920 New->dropAttr<InternalLinkageAttr>();
3921 }
3922
3923 // Merge the types.
3924 VarDecl *MostRecent = Old->getMostRecentDecl();
3925 if (MostRecent != Old) {
3926 MergeVarDeclTypes(New, MostRecent,
3927 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3928 if (New->isInvalidDecl())
3929 return;
3930 }
3931
3932 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3933 if (New->isInvalidDecl())
3934 return;
3935
3936 diag::kind PrevDiag;
3937 SourceLocation OldLocation;
3938 std::tie(PrevDiag, OldLocation) =
3939 getNoteDiagForInvalidRedeclaration(Old, New);
3940
3941 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3942 if (New->getStorageClass() == SC_Static &&
3943 !New->isStaticDataMember() &&
3944 Old->hasExternalFormalLinkage()) {
3945 if (getLangOpts().MicrosoftExt) {
3946 Diag(New->getLocation(), diag::ext_static_non_static)
3947 << New->getDeclName();
3948 Diag(OldLocation, PrevDiag);
3949 } else {
3950 Diag(New->getLocation(), diag::err_static_non_static)
3951 << New->getDeclName();
3952 Diag(OldLocation, PrevDiag);
3953 return New->setInvalidDecl();
3954 }
3955 }
3956 // C99 6.2.2p4:
3957 // For an identifier declared with the storage-class specifier
3958 // extern in a scope in which a prior declaration of that
3959 // identifier is visible,23) if the prior declaration specifies
3960 // internal or external linkage, the linkage of the identifier at
3961 // the later declaration is the same as the linkage specified at
3962 // the prior declaration. If no prior declaration is visible, or
3963 // if the prior declaration specifies no linkage, then the
3964 // identifier has external linkage.
3965 if (New->hasExternalStorage() && Old->hasLinkage())
3966 /* Okay */;
3967 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3968 !New->isStaticDataMember() &&
3969 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3970 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3971 Diag(OldLocation, PrevDiag);
3972 return New->setInvalidDecl();
3973 }
3974
3975 // Check if extern is followed by non-extern and vice-versa.
3976 if (New->hasExternalStorage() &&
3977 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3978 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3979 Diag(OldLocation, PrevDiag);
3980 return New->setInvalidDecl();
3981 }
3982 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3983 !New->hasExternalStorage()) {
3984 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3985 Diag(OldLocation, PrevDiag);
3986 return New->setInvalidDecl();
3987 }
3988
3989 if (CheckRedeclarationModuleOwnership(New, Old))
3990 return;
3991
3992 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3993
3994 // FIXME: The test for external storage here seems wrong? We still
3995 // need to check for mismatches.
3996 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3997 // Don't complain about out-of-line definitions of static members.
3998 !(Old->getLexicalDeclContext()->isRecord() &&
3999 !New->getLexicalDeclContext()->isRecord())) {
4000 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4001 Diag(OldLocation, PrevDiag);
4002 return New->setInvalidDecl();
4003 }
4004
4005 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4006 if (VarDecl *Def = Old->getDefinition()) {
4007 // C++1z [dcl.fcn.spec]p4:
4008 // If the definition of a variable appears in a translation unit before
4009 // its first declaration as inline, the program is ill-formed.
4010 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4011 Diag(Def->getLocation(), diag::note_previous_definition);
4012 }
4013 }
4014
4015 // If this redeclaration makes the variable inline, we may need to add it to
4016 // UndefinedButUsed.
4017 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4018 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4019 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4020 SourceLocation()));
4021
4022 if (New->getTLSKind() != Old->getTLSKind()) {
4023 if (!Old->getTLSKind()) {
4024 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4025 Diag(OldLocation, PrevDiag);
4026 } else if (!New->getTLSKind()) {
4027 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4028 Diag(OldLocation, PrevDiag);
4029 } else {
4030 // Do not allow redeclaration to change the variable between requiring
4031 // static and dynamic initialization.
4032 // FIXME: GCC allows this, but uses the TLS keyword on the first
4033 // declaration to determine the kind. Do we need to be compatible here?
4034 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4035 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4036 Diag(OldLocation, PrevDiag);
4037 }
4038 }
4039
4040 // C++ doesn't have tentative definitions, so go right ahead and check here.
4041 if (getLangOpts().CPlusPlus &&
4042 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4043 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4044 Old->getCanonicalDecl()->isConstexpr()) {
4045 // This definition won't be a definition any more once it's been merged.
4046 Diag(New->getLocation(),
4047 diag::warn_deprecated_redundant_constexpr_static_def);
4048 } else if (VarDecl *Def = Old->getDefinition()) {
4049 if (checkVarDeclRedefinition(Def, New))
4050 return;
4051 }
4052 }
4053
4054 if (haveIncompatibleLanguageLinkages(Old, New)) {
4055 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4056 Diag(OldLocation, PrevDiag);
4057 New->setInvalidDecl();
4058 return;
4059 }
4060
4061 // Merge "used" flag.
4062 if (Old->getMostRecentDecl()->isUsed(false))
4063 New->setIsUsed();
4064
4065 // Keep a chain of previous declarations.
4066 New->setPreviousDecl(Old);
4067 if (NewTemplate)
4068 NewTemplate->setPreviousDecl(OldTemplate);
4069 adjustDeclContextForDeclaratorDecl(New, Old);
4070
4071 // Inherit access appropriately.
4072 New->setAccess(Old->getAccess());
4073 if (NewTemplate)
4074 NewTemplate->setAccess(New->getAccess());
4075
4076 if (Old->isInline())
4077 New->setImplicitlyInline();
4078 }
4079
notePreviousDefinition(const NamedDecl * Old,SourceLocation New)4080 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4081 SourceManager &SrcMgr = getSourceManager();
4082 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4083 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4084 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4085 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4086 auto &HSI = PP.getHeaderSearchInfo();
4087 StringRef HdrFilename =
4088 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4089
4090 auto noteFromModuleOrInclude = [&](Module *Mod,
4091 SourceLocation IncLoc) -> bool {
4092 // Redefinition errors with modules are common with non modular mapped
4093 // headers, example: a non-modular header H in module A that also gets
4094 // included directly in a TU. Pointing twice to the same header/definition
4095 // is confusing, try to get better diagnostics when modules is on.
4096 if (IncLoc.isValid()) {
4097 if (Mod) {
4098 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4099 << HdrFilename.str() << Mod->getFullModuleName();
4100 if (!Mod->DefinitionLoc.isInvalid())
4101 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4102 << Mod->getFullModuleName();
4103 } else {
4104 Diag(IncLoc, diag::note_redefinition_include_same_file)
4105 << HdrFilename.str();
4106 }
4107 return true;
4108 }
4109
4110 return false;
4111 };
4112
4113 // Is it the same file and same offset? Provide more information on why
4114 // this leads to a redefinition error.
4115 bool EmittedDiag = false;
4116 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4117 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4118 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4119 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4120 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4121
4122 // If the header has no guards, emit a note suggesting one.
4123 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4124 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4125
4126 if (EmittedDiag)
4127 return;
4128 }
4129
4130 // Redefinition coming from different files or couldn't do better above.
4131 if (Old->getLocation().isValid())
4132 Diag(Old->getLocation(), diag::note_previous_definition);
4133 }
4134
4135 /// We've just determined that \p Old and \p New both appear to be definitions
4136 /// of the same variable. Either diagnose or fix the problem.
checkVarDeclRedefinition(VarDecl * Old,VarDecl * New)4137 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4138 if (!hasVisibleDefinition(Old) &&
4139 (New->getFormalLinkage() == InternalLinkage ||
4140 New->isInline() ||
4141 New->getDescribedVarTemplate() ||
4142 New->getNumTemplateParameterLists() ||
4143 New->getDeclContext()->isDependentContext())) {
4144 // The previous definition is hidden, and multiple definitions are
4145 // permitted (in separate TUs). Demote this to a declaration.
4146 New->demoteThisDefinitionToDeclaration();
4147
4148 // Make the canonical definition visible.
4149 if (auto *OldTD = Old->getDescribedVarTemplate())
4150 makeMergedDefinitionVisible(OldTD);
4151 makeMergedDefinitionVisible(Old);
4152 return false;
4153 } else {
4154 Diag(New->getLocation(), diag::err_redefinition) << New;
4155 notePreviousDefinition(Old, New->getLocation());
4156 New->setInvalidDecl();
4157 return true;
4158 }
4159 }
4160
4161 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4162 /// no declarator (e.g. "struct foo;") is parsed.
4163 Decl *
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,RecordDecl * & AnonRecord)4164 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4165 RecordDecl *&AnonRecord) {
4166 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4167 AnonRecord);
4168 }
4169
4170 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4171 // disambiguate entities defined in different scopes.
4172 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4173 // compatibility.
4174 // We will pick our mangling number depending on which version of MSVC is being
4175 // targeted.
getMSManglingNumber(const LangOptions & LO,Scope * S)4176 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4177 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4178 ? S->getMSCurManglingNumber()
4179 : S->getMSLastManglingNumber();
4180 }
4181
handleTagNumbering(const TagDecl * Tag,Scope * TagScope)4182 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4183 if (!Context.getLangOpts().CPlusPlus)
4184 return;
4185
4186 if (isa<CXXRecordDecl>(Tag->getParent())) {
4187 // If this tag is the direct child of a class, number it if
4188 // it is anonymous.
4189 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4190 return;
4191 MangleNumberingContext &MCtx =
4192 Context.getManglingNumberContext(Tag->getParent());
4193 Context.setManglingNumber(
4194 Tag, MCtx.getManglingNumber(
4195 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4196 return;
4197 }
4198
4199 // If this tag isn't a direct child of a class, number it if it is local.
4200 Decl *ManglingContextDecl;
4201 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4202 Tag->getDeclContext(), ManglingContextDecl)) {
4203 Context.setManglingNumber(
4204 Tag, MCtx->getManglingNumber(
4205 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4206 }
4207 }
4208
setTagNameForLinkagePurposes(TagDecl * TagFromDeclSpec,TypedefNameDecl * NewTD)4209 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4210 TypedefNameDecl *NewTD) {
4211 if (TagFromDeclSpec->isInvalidDecl())
4212 return;
4213
4214 // Do nothing if the tag already has a name for linkage purposes.
4215 if (TagFromDeclSpec->hasNameForLinkage())
4216 return;
4217
4218 // A well-formed anonymous tag must always be a TUK_Definition.
4219 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4220
4221 // The type must match the tag exactly; no qualifiers allowed.
4222 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4223 Context.getTagDeclType(TagFromDeclSpec))) {
4224 if (getLangOpts().CPlusPlus)
4225 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4226 return;
4227 }
4228
4229 // If we've already computed linkage for the anonymous tag, then
4230 // adding a typedef name for the anonymous decl can change that
4231 // linkage, which might be a serious problem. Diagnose this as
4232 // unsupported and ignore the typedef name. TODO: we should
4233 // pursue this as a language defect and establish a formal rule
4234 // for how to handle it.
4235 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4236 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4237
4238 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4239 tagLoc = getLocForEndOfToken(tagLoc);
4240
4241 llvm::SmallString<40> textToInsert;
4242 textToInsert += ' ';
4243 textToInsert += NewTD->getIdentifier()->getName();
4244 Diag(tagLoc, diag::note_typedef_changes_linkage)
4245 << FixItHint::CreateInsertion(tagLoc, textToInsert);
4246 return;
4247 }
4248
4249 // Otherwise, set this is the anon-decl typedef for the tag.
4250 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4251 }
4252
GetDiagnosticTypeSpecifierID(DeclSpec::TST T)4253 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4254 switch (T) {
4255 case DeclSpec::TST_class:
4256 return 0;
4257 case DeclSpec::TST_struct:
4258 return 1;
4259 case DeclSpec::TST_interface:
4260 return 2;
4261 case DeclSpec::TST_union:
4262 return 3;
4263 case DeclSpec::TST_enum:
4264 return 4;
4265 default:
4266 llvm_unreachable("unexpected type specifier");
4267 }
4268 }
4269
4270 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4271 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4272 /// parameters to cope with template friend declarations.
4273 Decl *
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,MultiTemplateParamsArg TemplateParams,bool IsExplicitInstantiation,RecordDecl * & AnonRecord)4274 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4275 MultiTemplateParamsArg TemplateParams,
4276 bool IsExplicitInstantiation,
4277 RecordDecl *&AnonRecord) {
4278 Decl *TagD = nullptr;
4279 TagDecl *Tag = nullptr;
4280 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4281 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4282 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4283 DS.getTypeSpecType() == DeclSpec::TST_union ||
4284 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4285 TagD = DS.getRepAsDecl();
4286
4287 if (!TagD) // We probably had an error
4288 return nullptr;
4289
4290 // Note that the above type specs guarantee that the
4291 // type rep is a Decl, whereas in many of the others
4292 // it's a Type.
4293 if (isa<TagDecl>(TagD))
4294 Tag = cast<TagDecl>(TagD);
4295 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4296 Tag = CTD->getTemplatedDecl();
4297 }
4298
4299 if (Tag) {
4300 handleTagNumbering(Tag, S);
4301 Tag->setFreeStanding();
4302 if (Tag->isInvalidDecl())
4303 return Tag;
4304 }
4305
4306 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4307 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4308 // or incomplete types shall not be restrict-qualified."
4309 if (TypeQuals & DeclSpec::TQ_restrict)
4310 Diag(DS.getRestrictSpecLoc(),
4311 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4312 << DS.getSourceRange();
4313 }
4314
4315 if (DS.isInlineSpecified())
4316 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4317 << getLangOpts().CPlusPlus17;
4318
4319 if (DS.hasConstexprSpecifier()) {
4320 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4321 // and definitions of functions and variables.
4322 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4323 // the declaration of a function or function template
4324 bool IsConsteval = DS.getConstexprSpecifier() == CSK_consteval;
4325 if (Tag)
4326 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4327 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << IsConsteval;
4328 else
4329 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4330 << IsConsteval;
4331 // Don't emit warnings after this error.
4332 return TagD;
4333 }
4334
4335 DiagnoseFunctionSpecifiers(DS);
4336
4337 if (DS.isFriendSpecified()) {
4338 // If we're dealing with a decl but not a TagDecl, assume that
4339 // whatever routines created it handled the friendship aspect.
4340 if (TagD && !Tag)
4341 return nullptr;
4342 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4343 }
4344
4345 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4346 bool IsExplicitSpecialization =
4347 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4348 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4349 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4350 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4351 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4352 // nested-name-specifier unless it is an explicit instantiation
4353 // or an explicit specialization.
4354 //
4355 // FIXME: We allow class template partial specializations here too, per the
4356 // obvious intent of DR1819.
4357 //
4358 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4359 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4360 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4361 return nullptr;
4362 }
4363
4364 // Track whether this decl-specifier declares anything.
4365 bool DeclaresAnything = true;
4366
4367 // Handle anonymous struct definitions.
4368 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4369 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4370 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4371 if (getLangOpts().CPlusPlus ||
4372 Record->getDeclContext()->isRecord()) {
4373 // If CurContext is a DeclContext that can contain statements,
4374 // RecursiveASTVisitor won't visit the decls that
4375 // BuildAnonymousStructOrUnion() will put into CurContext.
4376 // Also store them here so that they can be part of the
4377 // DeclStmt that gets created in this case.
4378 // FIXME: Also return the IndirectFieldDecls created by
4379 // BuildAnonymousStructOr union, for the same reason?
4380 if (CurContext->isFunctionOrMethod())
4381 AnonRecord = Record;
4382 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4383 Context.getPrintingPolicy());
4384 }
4385
4386 DeclaresAnything = false;
4387 }
4388 }
4389
4390 // C11 6.7.2.1p2:
4391 // A struct-declaration that does not declare an anonymous structure or
4392 // anonymous union shall contain a struct-declarator-list.
4393 //
4394 // This rule also existed in C89 and C99; the grammar for struct-declaration
4395 // did not permit a struct-declaration without a struct-declarator-list.
4396 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4397 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4398 // Check for Microsoft C extension: anonymous struct/union member.
4399 // Handle 2 kinds of anonymous struct/union:
4400 // struct STRUCT;
4401 // union UNION;
4402 // and
4403 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4404 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4405 if ((Tag && Tag->getDeclName()) ||
4406 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4407 RecordDecl *Record = nullptr;
4408 if (Tag)
4409 Record = dyn_cast<RecordDecl>(Tag);
4410 else if (const RecordType *RT =
4411 DS.getRepAsType().get()->getAsStructureType())
4412 Record = RT->getDecl();
4413 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4414 Record = UT->getDecl();
4415
4416 if (Record && getLangOpts().MicrosoftExt) {
4417 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4418 << Record->isUnion() << DS.getSourceRange();
4419 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4420 }
4421
4422 DeclaresAnything = false;
4423 }
4424 }
4425
4426 // Skip all the checks below if we have a type error.
4427 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4428 (TagD && TagD->isInvalidDecl()))
4429 return TagD;
4430
4431 if (getLangOpts().CPlusPlus &&
4432 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4433 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4434 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4435 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4436 DeclaresAnything = false;
4437
4438 if (!DS.isMissingDeclaratorOk()) {
4439 // Customize diagnostic for a typedef missing a name.
4440 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4441 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4442 << DS.getSourceRange();
4443 else
4444 DeclaresAnything = false;
4445 }
4446
4447 if (DS.isModulePrivateSpecified() &&
4448 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4449 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4450 << Tag->getTagKind()
4451 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4452
4453 ActOnDocumentableDecl(TagD);
4454
4455 // C 6.7/2:
4456 // A declaration [...] shall declare at least a declarator [...], a tag,
4457 // or the members of an enumeration.
4458 // C++ [dcl.dcl]p3:
4459 // [If there are no declarators], and except for the declaration of an
4460 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4461 // names into the program, or shall redeclare a name introduced by a
4462 // previous declaration.
4463 if (!DeclaresAnything) {
4464 // In C, we allow this as a (popular) extension / bug. Don't bother
4465 // producing further diagnostics for redundant qualifiers after this.
4466 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4467 return TagD;
4468 }
4469
4470 // C++ [dcl.stc]p1:
4471 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4472 // init-declarator-list of the declaration shall not be empty.
4473 // C++ [dcl.fct.spec]p1:
4474 // If a cv-qualifier appears in a decl-specifier-seq, the
4475 // init-declarator-list of the declaration shall not be empty.
4476 //
4477 // Spurious qualifiers here appear to be valid in C.
4478 unsigned DiagID = diag::warn_standalone_specifier;
4479 if (getLangOpts().CPlusPlus)
4480 DiagID = diag::ext_standalone_specifier;
4481
4482 // Note that a linkage-specification sets a storage class, but
4483 // 'extern "C" struct foo;' is actually valid and not theoretically
4484 // useless.
4485 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4486 if (SCS == DeclSpec::SCS_mutable)
4487 // Since mutable is not a viable storage class specifier in C, there is
4488 // no reason to treat it as an extension. Instead, diagnose as an error.
4489 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4490 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4491 Diag(DS.getStorageClassSpecLoc(), DiagID)
4492 << DeclSpec::getSpecifierName(SCS);
4493 }
4494
4495 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4496 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4497 << DeclSpec::getSpecifierName(TSCS);
4498 if (DS.getTypeQualifiers()) {
4499 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4500 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4501 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4502 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4503 // Restrict is covered above.
4504 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4505 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4506 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4507 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4508 }
4509
4510 // Warn about ignored type attributes, for example:
4511 // __attribute__((aligned)) struct A;
4512 // Attributes should be placed after tag to apply to type declaration.
4513 if (!DS.getAttributes().empty()) {
4514 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4515 if (TypeSpecType == DeclSpec::TST_class ||
4516 TypeSpecType == DeclSpec::TST_struct ||
4517 TypeSpecType == DeclSpec::TST_interface ||
4518 TypeSpecType == DeclSpec::TST_union ||
4519 TypeSpecType == DeclSpec::TST_enum) {
4520 for (const ParsedAttr &AL : DS.getAttributes())
4521 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4522 << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4523 }
4524 }
4525
4526 return TagD;
4527 }
4528
4529 /// We are trying to inject an anonymous member into the given scope;
4530 /// check if there's an existing declaration that can't be overloaded.
4531 ///
4532 /// \return true if this is a forbidden redeclaration
CheckAnonMemberRedeclaration(Sema & SemaRef,Scope * S,DeclContext * Owner,DeclarationName Name,SourceLocation NameLoc,bool IsUnion)4533 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4534 Scope *S,
4535 DeclContext *Owner,
4536 DeclarationName Name,
4537 SourceLocation NameLoc,
4538 bool IsUnion) {
4539 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4540 Sema::ForVisibleRedeclaration);
4541 if (!SemaRef.LookupName(R, S)) return false;
4542
4543 // Pick a representative declaration.
4544 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4545 assert(PrevDecl && "Expected a non-null Decl");
4546
4547 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4548 return false;
4549
4550 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4551 << IsUnion << Name;
4552 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4553
4554 return true;
4555 }
4556
4557 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4558 /// anonymous struct or union AnonRecord into the owning context Owner
4559 /// and scope S. This routine will be invoked just after we realize
4560 /// that an unnamed union or struct is actually an anonymous union or
4561 /// struct, e.g.,
4562 ///
4563 /// @code
4564 /// union {
4565 /// int i;
4566 /// float f;
4567 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4568 /// // f into the surrounding scope.x
4569 /// @endcode
4570 ///
4571 /// This routine is recursive, injecting the names of nested anonymous
4572 /// structs/unions into the owning context and scope as well.
4573 static bool
InjectAnonymousStructOrUnionMembers(Sema & SemaRef,Scope * S,DeclContext * Owner,RecordDecl * AnonRecord,AccessSpecifier AS,SmallVectorImpl<NamedDecl * > & Chaining)4574 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4575 RecordDecl *AnonRecord, AccessSpecifier AS,
4576 SmallVectorImpl<NamedDecl *> &Chaining) {
4577 bool Invalid = false;
4578
4579 // Look every FieldDecl and IndirectFieldDecl with a name.
4580 for (auto *D : AnonRecord->decls()) {
4581 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4582 cast<NamedDecl>(D)->getDeclName()) {
4583 ValueDecl *VD = cast<ValueDecl>(D);
4584 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4585 VD->getLocation(),
4586 AnonRecord->isUnion())) {
4587 // C++ [class.union]p2:
4588 // The names of the members of an anonymous union shall be
4589 // distinct from the names of any other entity in the
4590 // scope in which the anonymous union is declared.
4591 Invalid = true;
4592 } else {
4593 // C++ [class.union]p2:
4594 // For the purpose of name lookup, after the anonymous union
4595 // definition, the members of the anonymous union are
4596 // considered to have been defined in the scope in which the
4597 // anonymous union is declared.
4598 unsigned OldChainingSize = Chaining.size();
4599 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4600 Chaining.append(IF->chain_begin(), IF->chain_end());
4601 else
4602 Chaining.push_back(VD);
4603
4604 assert(Chaining.size() >= 2);
4605 NamedDecl **NamedChain =
4606 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4607 for (unsigned i = 0; i < Chaining.size(); i++)
4608 NamedChain[i] = Chaining[i];
4609
4610 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4611 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4612 VD->getType(), {NamedChain, Chaining.size()});
4613
4614 for (const auto *Attr : VD->attrs())
4615 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4616
4617 IndirectField->setAccess(AS);
4618 IndirectField->setImplicit();
4619 SemaRef.PushOnScopeChains(IndirectField, S);
4620
4621 // That includes picking up the appropriate access specifier.
4622 if (AS != AS_none) IndirectField->setAccess(AS);
4623
4624 Chaining.resize(OldChainingSize);
4625 }
4626 }
4627 }
4628
4629 return Invalid;
4630 }
4631
4632 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4633 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4634 /// illegal input values are mapped to SC_None.
4635 static StorageClass
StorageClassSpecToVarDeclStorageClass(const DeclSpec & DS)4636 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4637 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4638 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4639 "Parser allowed 'typedef' as storage class VarDecl.");
4640 switch (StorageClassSpec) {
4641 case DeclSpec::SCS_unspecified: return SC_None;
4642 case DeclSpec::SCS_extern:
4643 if (DS.isExternInLinkageSpec())
4644 return SC_None;
4645 return SC_Extern;
4646 case DeclSpec::SCS_static: return SC_Static;
4647 case DeclSpec::SCS_auto: return SC_Auto;
4648 case DeclSpec::SCS_register: return SC_Register;
4649 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4650 // Illegal SCSs map to None: error reporting is up to the caller.
4651 case DeclSpec::SCS_mutable: // Fall through.
4652 case DeclSpec::SCS_typedef: return SC_None;
4653 }
4654 llvm_unreachable("unknown storage class specifier");
4655 }
4656
findDefaultInitializer(const CXXRecordDecl * Record)4657 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4658 assert(Record->hasInClassInitializer());
4659
4660 for (const auto *I : Record->decls()) {
4661 const auto *FD = dyn_cast<FieldDecl>(I);
4662 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4663 FD = IFD->getAnonField();
4664 if (FD && FD->hasInClassInitializer())
4665 return FD->getLocation();
4666 }
4667
4668 llvm_unreachable("couldn't find in-class initializer");
4669 }
4670
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,SourceLocation DefaultInitLoc)4671 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4672 SourceLocation DefaultInitLoc) {
4673 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4674 return;
4675
4676 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4677 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4678 }
4679
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,CXXRecordDecl * AnonUnion)4680 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4681 CXXRecordDecl *AnonUnion) {
4682 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4683 return;
4684
4685 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4686 }
4687
4688 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4689 /// anonymous structure or union. Anonymous unions are a C++ feature
4690 /// (C++ [class.union]) and a C11 feature; anonymous structures
4691 /// are a C11 feature and GNU C++ extension.
BuildAnonymousStructOrUnion(Scope * S,DeclSpec & DS,AccessSpecifier AS,RecordDecl * Record,const PrintingPolicy & Policy)4692 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4693 AccessSpecifier AS,
4694 RecordDecl *Record,
4695 const PrintingPolicy &Policy) {
4696 DeclContext *Owner = Record->getDeclContext();
4697
4698 // Diagnose whether this anonymous struct/union is an extension.
4699 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4700 Diag(Record->getLocation(), diag::ext_anonymous_union);
4701 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4702 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4703 else if (!Record->isUnion() && !getLangOpts().C11)
4704 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4705
4706 // C and C++ require different kinds of checks for anonymous
4707 // structs/unions.
4708 bool Invalid = false;
4709 if (getLangOpts().CPlusPlus) {
4710 const char *PrevSpec = nullptr;
4711 unsigned DiagID;
4712 if (Record->isUnion()) {
4713 // C++ [class.union]p6:
4714 // C++17 [class.union.anon]p2:
4715 // Anonymous unions declared in a named namespace or in the
4716 // global namespace shall be declared static.
4717 DeclContext *OwnerScope = Owner->getRedeclContext();
4718 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4719 (OwnerScope->isTranslationUnit() ||
4720 (OwnerScope->isNamespace() &&
4721 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4722 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4723 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4724
4725 // Recover by adding 'static'.
4726 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4727 PrevSpec, DiagID, Policy);
4728 }
4729 // C++ [class.union]p6:
4730 // A storage class is not allowed in a declaration of an
4731 // anonymous union in a class scope.
4732 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4733 isa<RecordDecl>(Owner)) {
4734 Diag(DS.getStorageClassSpecLoc(),
4735 diag::err_anonymous_union_with_storage_spec)
4736 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4737
4738 // Recover by removing the storage specifier.
4739 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4740 SourceLocation(),
4741 PrevSpec, DiagID, Context.getPrintingPolicy());
4742 }
4743 }
4744
4745 // Ignore const/volatile/restrict qualifiers.
4746 if (DS.getTypeQualifiers()) {
4747 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4748 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4749 << Record->isUnion() << "const"
4750 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4751 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4752 Diag(DS.getVolatileSpecLoc(),
4753 diag::ext_anonymous_struct_union_qualified)
4754 << Record->isUnion() << "volatile"
4755 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4756 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4757 Diag(DS.getRestrictSpecLoc(),
4758 diag::ext_anonymous_struct_union_qualified)
4759 << Record->isUnion() << "restrict"
4760 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4761 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4762 Diag(DS.getAtomicSpecLoc(),
4763 diag::ext_anonymous_struct_union_qualified)
4764 << Record->isUnion() << "_Atomic"
4765 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4766 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4767 Diag(DS.getUnalignedSpecLoc(),
4768 diag::ext_anonymous_struct_union_qualified)
4769 << Record->isUnion() << "__unaligned"
4770 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4771
4772 DS.ClearTypeQualifiers();
4773 }
4774
4775 // C++ [class.union]p2:
4776 // The member-specification of an anonymous union shall only
4777 // define non-static data members. [Note: nested types and
4778 // functions cannot be declared within an anonymous union. ]
4779 for (auto *Mem : Record->decls()) {
4780 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4781 // C++ [class.union]p3:
4782 // An anonymous union shall not have private or protected
4783 // members (clause 11).
4784 assert(FD->getAccess() != AS_none);
4785 if (FD->getAccess() != AS_public) {
4786 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4787 << Record->isUnion() << (FD->getAccess() == AS_protected);
4788 Invalid = true;
4789 }
4790
4791 // C++ [class.union]p1
4792 // An object of a class with a non-trivial constructor, a non-trivial
4793 // copy constructor, a non-trivial destructor, or a non-trivial copy
4794 // assignment operator cannot be a member of a union, nor can an
4795 // array of such objects.
4796 if (CheckNontrivialField(FD))
4797 Invalid = true;
4798 } else if (Mem->isImplicit()) {
4799 // Any implicit members are fine.
4800 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4801 // This is a type that showed up in an
4802 // elaborated-type-specifier inside the anonymous struct or
4803 // union, but which actually declares a type outside of the
4804 // anonymous struct or union. It's okay.
4805 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4806 if (!MemRecord->isAnonymousStructOrUnion() &&
4807 MemRecord->getDeclName()) {
4808 // Visual C++ allows type definition in anonymous struct or union.
4809 if (getLangOpts().MicrosoftExt)
4810 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4811 << Record->isUnion();
4812 else {
4813 // This is a nested type declaration.
4814 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4815 << Record->isUnion();
4816 Invalid = true;
4817 }
4818 } else {
4819 // This is an anonymous type definition within another anonymous type.
4820 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4821 // not part of standard C++.
4822 Diag(MemRecord->getLocation(),
4823 diag::ext_anonymous_record_with_anonymous_type)
4824 << Record->isUnion();
4825 }
4826 } else if (isa<AccessSpecDecl>(Mem)) {
4827 // Any access specifier is fine.
4828 } else if (isa<StaticAssertDecl>(Mem)) {
4829 // In C++1z, static_assert declarations are also fine.
4830 } else {
4831 // We have something that isn't a non-static data
4832 // member. Complain about it.
4833 unsigned DK = diag::err_anonymous_record_bad_member;
4834 if (isa<TypeDecl>(Mem))
4835 DK = diag::err_anonymous_record_with_type;
4836 else if (isa<FunctionDecl>(Mem))
4837 DK = diag::err_anonymous_record_with_function;
4838 else if (isa<VarDecl>(Mem))
4839 DK = diag::err_anonymous_record_with_static;
4840
4841 // Visual C++ allows type definition in anonymous struct or union.
4842 if (getLangOpts().MicrosoftExt &&
4843 DK == diag::err_anonymous_record_with_type)
4844 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4845 << Record->isUnion();
4846 else {
4847 Diag(Mem->getLocation(), DK) << Record->isUnion();
4848 Invalid = true;
4849 }
4850 }
4851 }
4852
4853 // C++11 [class.union]p8 (DR1460):
4854 // At most one variant member of a union may have a
4855 // brace-or-equal-initializer.
4856 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4857 Owner->isRecord())
4858 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4859 cast<CXXRecordDecl>(Record));
4860 }
4861
4862 if (!Record->isUnion() && !Owner->isRecord()) {
4863 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4864 << getLangOpts().CPlusPlus;
4865 Invalid = true;
4866 }
4867
4868 // C++ [dcl.dcl]p3:
4869 // [If there are no declarators], and except for the declaration of an
4870 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4871 // names into the program
4872 // C++ [class.mem]p2:
4873 // each such member-declaration shall either declare at least one member
4874 // name of the class or declare at least one unnamed bit-field
4875 //
4876 // For C this is an error even for a named struct, and is diagnosed elsewhere.
4877 if (getLangOpts().CPlusPlus && Record->field_empty())
4878 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4879
4880 // Mock up a declarator.
4881 Declarator Dc(DS, DeclaratorContext::MemberContext);
4882 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4883 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4884
4885 // Create a declaration for this anonymous struct/union.
4886 NamedDecl *Anon = nullptr;
4887 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4888 Anon = FieldDecl::Create(
4889 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4890 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4891 /*BitWidth=*/nullptr, /*Mutable=*/false,
4892 /*InitStyle=*/ICIS_NoInit);
4893 Anon->setAccess(AS);
4894 if (getLangOpts().CPlusPlus)
4895 FieldCollector->Add(cast<FieldDecl>(Anon));
4896 } else {
4897 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4898 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4899 if (SCSpec == DeclSpec::SCS_mutable) {
4900 // mutable can only appear on non-static class members, so it's always
4901 // an error here
4902 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4903 Invalid = true;
4904 SC = SC_None;
4905 }
4906
4907 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4908 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4909 Context.getTypeDeclType(Record), TInfo, SC);
4910
4911 // Default-initialize the implicit variable. This initialization will be
4912 // trivial in almost all cases, except if a union member has an in-class
4913 // initializer:
4914 // union { int n = 0; };
4915 ActOnUninitializedDecl(Anon);
4916 }
4917 Anon->setImplicit();
4918
4919 // Mark this as an anonymous struct/union type.
4920 Record->setAnonymousStructOrUnion(true);
4921
4922 // Add the anonymous struct/union object to the current
4923 // context. We'll be referencing this object when we refer to one of
4924 // its members.
4925 Owner->addDecl(Anon);
4926
4927 // Inject the members of the anonymous struct/union into the owning
4928 // context and into the identifier resolver chain for name lookup
4929 // purposes.
4930 SmallVector<NamedDecl*, 2> Chain;
4931 Chain.push_back(Anon);
4932
4933 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4934 Invalid = true;
4935
4936 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4937 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4938 Decl *ManglingContextDecl;
4939 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4940 NewVD->getDeclContext(), ManglingContextDecl)) {
4941 Context.setManglingNumber(
4942 NewVD, MCtx->getManglingNumber(
4943 NewVD, getMSManglingNumber(getLangOpts(), S)));
4944 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4945 }
4946 }
4947 }
4948
4949 if (Invalid)
4950 Anon->setInvalidDecl();
4951
4952 return Anon;
4953 }
4954
4955 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4956 /// Microsoft C anonymous structure.
4957 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4958 /// Example:
4959 ///
4960 /// struct A { int a; };
4961 /// struct B { struct A; int b; };
4962 ///
4963 /// void foo() {
4964 /// B var;
4965 /// var.a = 3;
4966 /// }
4967 ///
BuildMicrosoftCAnonymousStruct(Scope * S,DeclSpec & DS,RecordDecl * Record)4968 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4969 RecordDecl *Record) {
4970 assert(Record && "expected a record!");
4971
4972 // Mock up a declarator.
4973 Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4974 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4975 assert(TInfo && "couldn't build declarator info for anonymous struct");
4976
4977 auto *ParentDecl = cast<RecordDecl>(CurContext);
4978 QualType RecTy = Context.getTypeDeclType(Record);
4979
4980 // Create a declaration for this anonymous struct.
4981 NamedDecl *Anon =
4982 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4983 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4984 /*BitWidth=*/nullptr, /*Mutable=*/false,
4985 /*InitStyle=*/ICIS_NoInit);
4986 Anon->setImplicit();
4987
4988 // Add the anonymous struct object to the current context.
4989 CurContext->addDecl(Anon);
4990
4991 // Inject the members of the anonymous struct into the current
4992 // context and into the identifier resolver chain for name lookup
4993 // purposes.
4994 SmallVector<NamedDecl*, 2> Chain;
4995 Chain.push_back(Anon);
4996
4997 RecordDecl *RecordDef = Record->getDefinition();
4998 if (RequireCompleteType(Anon->getLocation(), RecTy,
4999 diag::err_field_incomplete) ||
5000 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5001 AS_none, Chain)) {
5002 Anon->setInvalidDecl();
5003 ParentDecl->setInvalidDecl();
5004 }
5005
5006 return Anon;
5007 }
5008
5009 /// GetNameForDeclarator - Determine the full declaration name for the
5010 /// given Declarator.
GetNameForDeclarator(Declarator & D)5011 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5012 return GetNameFromUnqualifiedId(D.getName());
5013 }
5014
5015 /// Retrieves the declaration name from a parsed unqualified-id.
5016 DeclarationNameInfo
GetNameFromUnqualifiedId(const UnqualifiedId & Name)5017 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5018 DeclarationNameInfo NameInfo;
5019 NameInfo.setLoc(Name.StartLocation);
5020
5021 switch (Name.getKind()) {
5022
5023 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5024 case UnqualifiedIdKind::IK_Identifier:
5025 NameInfo.setName(Name.Identifier);
5026 return NameInfo;
5027
5028 case UnqualifiedIdKind::IK_DeductionGuideName: {
5029 // C++ [temp.deduct.guide]p3:
5030 // The simple-template-id shall name a class template specialization.
5031 // The template-name shall be the same identifier as the template-name
5032 // of the simple-template-id.
5033 // These together intend to imply that the template-name shall name a
5034 // class template.
5035 // FIXME: template<typename T> struct X {};
5036 // template<typename T> using Y = X<T>;
5037 // Y(int) -> Y<int>;
5038 // satisfies these rules but does not name a class template.
5039 TemplateName TN = Name.TemplateName.get().get();
5040 auto *Template = TN.getAsTemplateDecl();
5041 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5042 Diag(Name.StartLocation,
5043 diag::err_deduction_guide_name_not_class_template)
5044 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5045 if (Template)
5046 Diag(Template->getLocation(), diag::note_template_decl_here);
5047 return DeclarationNameInfo();
5048 }
5049
5050 NameInfo.setName(
5051 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5052 return NameInfo;
5053 }
5054
5055 case UnqualifiedIdKind::IK_OperatorFunctionId:
5056 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5057 Name.OperatorFunctionId.Operator));
5058 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5059 = Name.OperatorFunctionId.SymbolLocations[0];
5060 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5061 = Name.EndLocation.getRawEncoding();
5062 return NameInfo;
5063
5064 case UnqualifiedIdKind::IK_LiteralOperatorId:
5065 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5066 Name.Identifier));
5067 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5068 return NameInfo;
5069
5070 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5071 TypeSourceInfo *TInfo;
5072 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5073 if (Ty.isNull())
5074 return DeclarationNameInfo();
5075 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5076 Context.getCanonicalType(Ty)));
5077 NameInfo.setNamedTypeInfo(TInfo);
5078 return NameInfo;
5079 }
5080
5081 case UnqualifiedIdKind::IK_ConstructorName: {
5082 TypeSourceInfo *TInfo;
5083 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5084 if (Ty.isNull())
5085 return DeclarationNameInfo();
5086 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5087 Context.getCanonicalType(Ty)));
5088 NameInfo.setNamedTypeInfo(TInfo);
5089 return NameInfo;
5090 }
5091
5092 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5093 // In well-formed code, we can only have a constructor
5094 // template-id that refers to the current context, so go there
5095 // to find the actual type being constructed.
5096 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5097 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5098 return DeclarationNameInfo();
5099
5100 // Determine the type of the class being constructed.
5101 QualType CurClassType = Context.getTypeDeclType(CurClass);
5102
5103 // FIXME: Check two things: that the template-id names the same type as
5104 // CurClassType, and that the template-id does not occur when the name
5105 // was qualified.
5106
5107 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5108 Context.getCanonicalType(CurClassType)));
5109 // FIXME: should we retrieve TypeSourceInfo?
5110 NameInfo.setNamedTypeInfo(nullptr);
5111 return NameInfo;
5112 }
5113
5114 case UnqualifiedIdKind::IK_DestructorName: {
5115 TypeSourceInfo *TInfo;
5116 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5117 if (Ty.isNull())
5118 return DeclarationNameInfo();
5119 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5120 Context.getCanonicalType(Ty)));
5121 NameInfo.setNamedTypeInfo(TInfo);
5122 return NameInfo;
5123 }
5124
5125 case UnqualifiedIdKind::IK_TemplateId: {
5126 TemplateName TName = Name.TemplateId->Template.get();
5127 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5128 return Context.getNameForTemplate(TName, TNameLoc);
5129 }
5130
5131 } // switch (Name.getKind())
5132
5133 llvm_unreachable("Unknown name kind");
5134 }
5135
getCoreType(QualType Ty)5136 static QualType getCoreType(QualType Ty) {
5137 do {
5138 if (Ty->isPointerType() || Ty->isReferenceType())
5139 Ty = Ty->getPointeeType();
5140 else if (Ty->isArrayType())
5141 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5142 else
5143 return Ty.withoutLocalFastQualifiers();
5144 } while (true);
5145 }
5146
5147 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5148 /// and Definition have "nearly" matching parameters. This heuristic is
5149 /// used to improve diagnostics in the case where an out-of-line function
5150 /// definition doesn't match any declaration within the class or namespace.
5151 /// Also sets Params to the list of indices to the parameters that differ
5152 /// between the declaration and the definition. If hasSimilarParameters
5153 /// returns true and Params is empty, then all of the parameters match.
hasSimilarParameters(ASTContext & Context,FunctionDecl * Declaration,FunctionDecl * Definition,SmallVectorImpl<unsigned> & Params)5154 static bool hasSimilarParameters(ASTContext &Context,
5155 FunctionDecl *Declaration,
5156 FunctionDecl *Definition,
5157 SmallVectorImpl<unsigned> &Params) {
5158 Params.clear();
5159 if (Declaration->param_size() != Definition->param_size())
5160 return false;
5161 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5162 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5163 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5164
5165 // The parameter types are identical
5166 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5167 continue;
5168
5169 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5170 QualType DefParamBaseTy = getCoreType(DefParamTy);
5171 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5172 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5173
5174 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5175 (DeclTyName && DeclTyName == DefTyName))
5176 Params.push_back(Idx);
5177 else // The two parameters aren't even close
5178 return false;
5179 }
5180
5181 return true;
5182 }
5183
5184 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5185 /// declarator needs to be rebuilt in the current instantiation.
5186 /// Any bits of declarator which appear before the name are valid for
5187 /// consideration here. That's specifically the type in the decl spec
5188 /// and the base type in any member-pointer chunks.
RebuildDeclaratorInCurrentInstantiation(Sema & S,Declarator & D,DeclarationName Name)5189 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5190 DeclarationName Name) {
5191 // The types we specifically need to rebuild are:
5192 // - typenames, typeofs, and decltypes
5193 // - types which will become injected class names
5194 // Of course, we also need to rebuild any type referencing such a
5195 // type. It's safest to just say "dependent", but we call out a
5196 // few cases here.
5197
5198 DeclSpec &DS = D.getMutableDeclSpec();
5199 switch (DS.getTypeSpecType()) {
5200 case DeclSpec::TST_typename:
5201 case DeclSpec::TST_typeofType:
5202 case DeclSpec::TST_underlyingType:
5203 case DeclSpec::TST_atomic: {
5204 // Grab the type from the parser.
5205 TypeSourceInfo *TSI = nullptr;
5206 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5207 if (T.isNull() || !T->isDependentType()) break;
5208
5209 // Make sure there's a type source info. This isn't really much
5210 // of a waste; most dependent types should have type source info
5211 // attached already.
5212 if (!TSI)
5213 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5214
5215 // Rebuild the type in the current instantiation.
5216 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5217 if (!TSI) return true;
5218
5219 // Store the new type back in the decl spec.
5220 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5221 DS.UpdateTypeRep(LocType);
5222 break;
5223 }
5224
5225 case DeclSpec::TST_decltype:
5226 case DeclSpec::TST_typeofExpr: {
5227 Expr *E = DS.getRepAsExpr();
5228 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5229 if (Result.isInvalid()) return true;
5230 DS.UpdateExprRep(Result.get());
5231 break;
5232 }
5233
5234 default:
5235 // Nothing to do for these decl specs.
5236 break;
5237 }
5238
5239 // It doesn't matter what order we do this in.
5240 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5241 DeclaratorChunk &Chunk = D.getTypeObject(I);
5242
5243 // The only type information in the declarator which can come
5244 // before the declaration name is the base type of a member
5245 // pointer.
5246 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5247 continue;
5248
5249 // Rebuild the scope specifier in-place.
5250 CXXScopeSpec &SS = Chunk.Mem.Scope();
5251 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5252 return true;
5253 }
5254
5255 return false;
5256 }
5257
ActOnDeclarator(Scope * S,Declarator & D)5258 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5259 D.setFunctionDefinitionKind(FDK_Declaration);
5260 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5261
5262 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5263 Dcl && Dcl->getDeclContext()->isFileContext())
5264 Dcl->setTopLevelDeclInObjCContainer();
5265
5266 if (getLangOpts().OpenCL)
5267 setCurrentOpenCLExtensionForDecl(Dcl);
5268
5269 return Dcl;
5270 }
5271
5272 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5273 /// If T is the name of a class, then each of the following shall have a
5274 /// name different from T:
5275 /// - every static data member of class T;
5276 /// - every member function of class T
5277 /// - every member of class T that is itself a type;
5278 /// \returns true if the declaration name violates these rules.
DiagnoseClassNameShadow(DeclContext * DC,DeclarationNameInfo NameInfo)5279 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5280 DeclarationNameInfo NameInfo) {
5281 DeclarationName Name = NameInfo.getName();
5282
5283 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5284 while (Record && Record->isAnonymousStructOrUnion())
5285 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5286 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5287 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5288 return true;
5289 }
5290
5291 return false;
5292 }
5293
5294 /// Diagnose a declaration whose declarator-id has the given
5295 /// nested-name-specifier.
5296 ///
5297 /// \param SS The nested-name-specifier of the declarator-id.
5298 ///
5299 /// \param DC The declaration context to which the nested-name-specifier
5300 /// resolves.
5301 ///
5302 /// \param Name The name of the entity being declared.
5303 ///
5304 /// \param Loc The location of the name of the entity being declared.
5305 ///
5306 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5307 /// we're declaring an explicit / partial specialization / instantiation.
5308 ///
5309 /// \returns true if we cannot safely recover from this error, false otherwise.
diagnoseQualifiedDeclaration(CXXScopeSpec & SS,DeclContext * DC,DeclarationName Name,SourceLocation Loc,bool IsTemplateId)5310 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5311 DeclarationName Name,
5312 SourceLocation Loc, bool IsTemplateId) {
5313 DeclContext *Cur = CurContext;
5314 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5315 Cur = Cur->getParent();
5316
5317 // If the user provided a superfluous scope specifier that refers back to the
5318 // class in which the entity is already declared, diagnose and ignore it.
5319 //
5320 // class X {
5321 // void X::f();
5322 // };
5323 //
5324 // Note, it was once ill-formed to give redundant qualification in all
5325 // contexts, but that rule was removed by DR482.
5326 if (Cur->Equals(DC)) {
5327 if (Cur->isRecord()) {
5328 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5329 : diag::err_member_extra_qualification)
5330 << Name << FixItHint::CreateRemoval(SS.getRange());
5331 SS.clear();
5332 } else {
5333 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5334 }
5335 return false;
5336 }
5337
5338 // Check whether the qualifying scope encloses the scope of the original
5339 // declaration. For a template-id, we perform the checks in
5340 // CheckTemplateSpecializationScope.
5341 if (!Cur->Encloses(DC) && !IsTemplateId) {
5342 if (Cur->isRecord())
5343 Diag(Loc, diag::err_member_qualification)
5344 << Name << SS.getRange();
5345 else if (isa<TranslationUnitDecl>(DC))
5346 Diag(Loc, diag::err_invalid_declarator_global_scope)
5347 << Name << SS.getRange();
5348 else if (isa<FunctionDecl>(Cur))
5349 Diag(Loc, diag::err_invalid_declarator_in_function)
5350 << Name << SS.getRange();
5351 else if (isa<BlockDecl>(Cur))
5352 Diag(Loc, diag::err_invalid_declarator_in_block)
5353 << Name << SS.getRange();
5354 else
5355 Diag(Loc, diag::err_invalid_declarator_scope)
5356 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5357
5358 return true;
5359 }
5360
5361 if (Cur->isRecord()) {
5362 // Cannot qualify members within a class.
5363 Diag(Loc, diag::err_member_qualification)
5364 << Name << SS.getRange();
5365 SS.clear();
5366
5367 // C++ constructors and destructors with incorrect scopes can break
5368 // our AST invariants by having the wrong underlying types. If
5369 // that's the case, then drop this declaration entirely.
5370 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5371 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5372 !Context.hasSameType(Name.getCXXNameType(),
5373 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5374 return true;
5375
5376 return false;
5377 }
5378
5379 // C++11 [dcl.meaning]p1:
5380 // [...] "The nested-name-specifier of the qualified declarator-id shall
5381 // not begin with a decltype-specifer"
5382 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5383 while (SpecLoc.getPrefix())
5384 SpecLoc = SpecLoc.getPrefix();
5385 if (dyn_cast_or_null<DecltypeType>(
5386 SpecLoc.getNestedNameSpecifier()->getAsType()))
5387 Diag(Loc, diag::err_decltype_in_declarator)
5388 << SpecLoc.getTypeLoc().getSourceRange();
5389
5390 return false;
5391 }
5392
HandleDeclarator(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParamLists)5393 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5394 MultiTemplateParamsArg TemplateParamLists) {
5395 // TODO: consider using NameInfo for diagnostic.
5396 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5397 DeclarationName Name = NameInfo.getName();
5398
5399 // All of these full declarators require an identifier. If it doesn't have
5400 // one, the ParsedFreeStandingDeclSpec action should be used.
5401 if (D.isDecompositionDeclarator()) {
5402 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5403 } else if (!Name) {
5404 if (!D.isInvalidType()) // Reject this if we think it is valid.
5405 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5406 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5407 return nullptr;
5408 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5409 return nullptr;
5410
5411 // The scope passed in may not be a decl scope. Zip up the scope tree until
5412 // we find one that is.
5413 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5414 (S->getFlags() & Scope::TemplateParamScope) != 0)
5415 S = S->getParent();
5416
5417 DeclContext *DC = CurContext;
5418 if (D.getCXXScopeSpec().isInvalid())
5419 D.setInvalidType();
5420 else if (D.getCXXScopeSpec().isSet()) {
5421 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5422 UPPC_DeclarationQualifier))
5423 return nullptr;
5424
5425 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5426 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5427 if (!DC || isa<EnumDecl>(DC)) {
5428 // If we could not compute the declaration context, it's because the
5429 // declaration context is dependent but does not refer to a class,
5430 // class template, or class template partial specialization. Complain
5431 // and return early, to avoid the coming semantic disaster.
5432 Diag(D.getIdentifierLoc(),
5433 diag::err_template_qualified_declarator_no_match)
5434 << D.getCXXScopeSpec().getScopeRep()
5435 << D.getCXXScopeSpec().getRange();
5436 return nullptr;
5437 }
5438 bool IsDependentContext = DC->isDependentContext();
5439
5440 if (!IsDependentContext &&
5441 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5442 return nullptr;
5443
5444 // If a class is incomplete, do not parse entities inside it.
5445 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5446 Diag(D.getIdentifierLoc(),
5447 diag::err_member_def_undefined_record)
5448 << Name << DC << D.getCXXScopeSpec().getRange();
5449 return nullptr;
5450 }
5451 if (!D.getDeclSpec().isFriendSpecified()) {
5452 if (diagnoseQualifiedDeclaration(
5453 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5454 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5455 if (DC->isRecord())
5456 return nullptr;
5457
5458 D.setInvalidType();
5459 }
5460 }
5461
5462 // Check whether we need to rebuild the type of the given
5463 // declaration in the current instantiation.
5464 if (EnteringContext && IsDependentContext &&
5465 TemplateParamLists.size() != 0) {
5466 ContextRAII SavedContext(*this, DC);
5467 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5468 D.setInvalidType();
5469 }
5470 }
5471
5472 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5473 QualType R = TInfo->getType();
5474
5475 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5476 UPPC_DeclarationType))
5477 D.setInvalidType();
5478
5479 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5480 forRedeclarationInCurContext());
5481
5482 // See if this is a redefinition of a variable in the same scope.
5483 if (!D.getCXXScopeSpec().isSet()) {
5484 bool IsLinkageLookup = false;
5485 bool CreateBuiltins = false;
5486
5487 // If the declaration we're planning to build will be a function
5488 // or object with linkage, then look for another declaration with
5489 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5490 //
5491 // If the declaration we're planning to build will be declared with
5492 // external linkage in the translation unit, create any builtin with
5493 // the same name.
5494 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5495 /* Do nothing*/;
5496 else if (CurContext->isFunctionOrMethod() &&
5497 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5498 R->isFunctionType())) {
5499 IsLinkageLookup = true;
5500 CreateBuiltins =
5501 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5502 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5503 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5504 CreateBuiltins = true;
5505
5506 if (IsLinkageLookup) {
5507 Previous.clear(LookupRedeclarationWithLinkage);
5508 Previous.setRedeclarationKind(ForExternalRedeclaration);
5509 }
5510
5511 LookupName(Previous, S, CreateBuiltins);
5512 } else { // Something like "int foo::x;"
5513 LookupQualifiedName(Previous, DC);
5514
5515 // C++ [dcl.meaning]p1:
5516 // When the declarator-id is qualified, the declaration shall refer to a
5517 // previously declared member of the class or namespace to which the
5518 // qualifier refers (or, in the case of a namespace, of an element of the
5519 // inline namespace set of that namespace (7.3.1)) or to a specialization
5520 // thereof; [...]
5521 //
5522 // Note that we already checked the context above, and that we do not have
5523 // enough information to make sure that Previous contains the declaration
5524 // we want to match. For example, given:
5525 //
5526 // class X {
5527 // void f();
5528 // void f(float);
5529 // };
5530 //
5531 // void X::f(int) { } // ill-formed
5532 //
5533 // In this case, Previous will point to the overload set
5534 // containing the two f's declared in X, but neither of them
5535 // matches.
5536
5537 // C++ [dcl.meaning]p1:
5538 // [...] the member shall not merely have been introduced by a
5539 // using-declaration in the scope of the class or namespace nominated by
5540 // the nested-name-specifier of the declarator-id.
5541 RemoveUsingDecls(Previous);
5542 }
5543
5544 if (Previous.isSingleResult() &&
5545 Previous.getFoundDecl()->isTemplateParameter()) {
5546 // Maybe we will complain about the shadowed template parameter.
5547 if (!D.isInvalidType())
5548 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5549 Previous.getFoundDecl());
5550
5551 // Just pretend that we didn't see the previous declaration.
5552 Previous.clear();
5553 }
5554
5555 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5556 // Forget that the previous declaration is the injected-class-name.
5557 Previous.clear();
5558
5559 // In C++, the previous declaration we find might be a tag type
5560 // (class or enum). In this case, the new declaration will hide the
5561 // tag type. Note that this applies to functions, function templates, and
5562 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5563 if (Previous.isSingleTagDecl() &&
5564 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5565 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5566 Previous.clear();
5567
5568 // Check that there are no default arguments other than in the parameters
5569 // of a function declaration (C++ only).
5570 if (getLangOpts().CPlusPlus)
5571 CheckExtraCXXDefaultArguments(D);
5572
5573 NamedDecl *New;
5574
5575 bool AddToScope = true;
5576 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5577 if (TemplateParamLists.size()) {
5578 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5579 return nullptr;
5580 }
5581
5582 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5583 } else if (R->isFunctionType()) {
5584 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5585 TemplateParamLists,
5586 AddToScope);
5587 } else {
5588 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5589 AddToScope);
5590 }
5591
5592 if (!New)
5593 return nullptr;
5594
5595 // If this has an identifier and is not a function template specialization,
5596 // add it to the scope stack.
5597 if (New->getDeclName() && AddToScope)
5598 PushOnScopeChains(New, S);
5599
5600 if (isInOpenMPDeclareTargetContext())
5601 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5602
5603 return New;
5604 }
5605
5606 /// Helper method to turn variable array types into constant array
5607 /// types in certain situations which would otherwise be errors (for
5608 /// GCC compatibility).
TryToFixInvalidVariablyModifiedType(QualType T,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)5609 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5610 ASTContext &Context,
5611 bool &SizeIsNegative,
5612 llvm::APSInt &Oversized) {
5613 // This method tries to turn a variable array into a constant
5614 // array even when the size isn't an ICE. This is necessary
5615 // for compatibility with code that depends on gcc's buggy
5616 // constant expression folding, like struct {char x[(int)(char*)2];}
5617 SizeIsNegative = false;
5618 Oversized = 0;
5619
5620 if (T->isDependentType())
5621 return QualType();
5622
5623 QualifierCollector Qs;
5624 const Type *Ty = Qs.strip(T);
5625
5626 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5627 QualType Pointee = PTy->getPointeeType();
5628 QualType FixedType =
5629 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5630 Oversized);
5631 if (FixedType.isNull()) return FixedType;
5632 FixedType = Context.getPointerType(FixedType);
5633 return Qs.apply(Context, FixedType);
5634 }
5635 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5636 QualType Inner = PTy->getInnerType();
5637 QualType FixedType =
5638 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5639 Oversized);
5640 if (FixedType.isNull()) return FixedType;
5641 FixedType = Context.getParenType(FixedType);
5642 return Qs.apply(Context, FixedType);
5643 }
5644
5645 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5646 if (!VLATy)
5647 return QualType();
5648 // FIXME: We should probably handle this case
5649 if (VLATy->getElementType()->isVariablyModifiedType())
5650 return QualType();
5651
5652 Expr::EvalResult Result;
5653 if (!VLATy->getSizeExpr() ||
5654 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5655 return QualType();
5656
5657 llvm::APSInt Res = Result.Val.getInt();
5658
5659 // Check whether the array size is negative.
5660 if (Res.isSigned() && Res.isNegative()) {
5661 SizeIsNegative = true;
5662 return QualType();
5663 }
5664
5665 // Check whether the array is too large to be addressed.
5666 unsigned ActiveSizeBits
5667 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5668 Res);
5669 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5670 Oversized = Res;
5671 return QualType();
5672 }
5673
5674 return Context.getConstantArrayType(VLATy->getElementType(),
5675 Res, ArrayType::Normal, 0);
5676 }
5677
5678 static void
FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL,TypeLoc DstTL)5679 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5680 SrcTL = SrcTL.getUnqualifiedLoc();
5681 DstTL = DstTL.getUnqualifiedLoc();
5682 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5683 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5684 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5685 DstPTL.getPointeeLoc());
5686 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5687 return;
5688 }
5689 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5690 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5691 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5692 DstPTL.getInnerLoc());
5693 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5694 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5695 return;
5696 }
5697 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5698 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5699 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5700 TypeLoc DstElemTL = DstATL.getElementLoc();
5701 DstElemTL.initializeFullCopy(SrcElemTL);
5702 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5703 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5704 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5705 }
5706
5707 /// Helper method to turn variable array types into constant array
5708 /// types in certain situations which would otherwise be errors (for
5709 /// GCC compatibility).
5710 static TypeSourceInfo*
TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo * TInfo,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)5711 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5712 ASTContext &Context,
5713 bool &SizeIsNegative,
5714 llvm::APSInt &Oversized) {
5715 QualType FixedTy
5716 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5717 SizeIsNegative, Oversized);
5718 if (FixedTy.isNull())
5719 return nullptr;
5720 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5721 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5722 FixedTInfo->getTypeLoc());
5723 return FixedTInfo;
5724 }
5725
5726 /// Register the given locally-scoped extern "C" declaration so
5727 /// that it can be found later for redeclarations. We include any extern "C"
5728 /// declaration that is not visible in the translation unit here, not just
5729 /// function-scope declarations.
5730 void
RegisterLocallyScopedExternCDecl(NamedDecl * ND,Scope * S)5731 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5732 if (!getLangOpts().CPlusPlus &&
5733 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5734 // Don't need to track declarations in the TU in C.
5735 return;
5736
5737 // Note that we have a locally-scoped external with this name.
5738 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5739 }
5740
findLocallyScopedExternCDecl(DeclarationName Name)5741 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5742 // FIXME: We can have multiple results via __attribute__((overloadable)).
5743 auto Result = Context.getExternCContextDecl()->lookup(Name);
5744 return Result.empty() ? nullptr : *Result.begin();
5745 }
5746
5747 /// Diagnose function specifiers on a declaration of an identifier that
5748 /// does not identify a function.
DiagnoseFunctionSpecifiers(const DeclSpec & DS)5749 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5750 // FIXME: We should probably indicate the identifier in question to avoid
5751 // confusion for constructs like "virtual int a(), b;"
5752 if (DS.isVirtualSpecified())
5753 Diag(DS.getVirtualSpecLoc(),
5754 diag::err_virtual_non_function);
5755
5756 if (DS.hasExplicitSpecifier())
5757 Diag(DS.getExplicitSpecLoc(),
5758 diag::err_explicit_non_function);
5759
5760 if (DS.isNoreturnSpecified())
5761 Diag(DS.getNoreturnSpecLoc(),
5762 diag::err_noreturn_non_function);
5763 }
5764
5765 NamedDecl*
ActOnTypedefDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous)5766 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5767 TypeSourceInfo *TInfo, LookupResult &Previous) {
5768 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5769 if (D.getCXXScopeSpec().isSet()) {
5770 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5771 << D.getCXXScopeSpec().getRange();
5772 D.setInvalidType();
5773 // Pretend we didn't see the scope specifier.
5774 DC = CurContext;
5775 Previous.clear();
5776 }
5777
5778 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5779
5780 if (D.getDeclSpec().isInlineSpecified())
5781 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5782 << getLangOpts().CPlusPlus17;
5783 if (D.getDeclSpec().hasConstexprSpecifier())
5784 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5785 << 1 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
5786
5787 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5788 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5789 Diag(D.getName().StartLocation,
5790 diag::err_deduction_guide_invalid_specifier)
5791 << "typedef";
5792 else
5793 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5794 << D.getName().getSourceRange();
5795 return nullptr;
5796 }
5797
5798 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5799 if (!NewTD) return nullptr;
5800
5801 // Handle attributes prior to checking for duplicates in MergeVarDecl
5802 ProcessDeclAttributes(S, NewTD, D);
5803
5804 CheckTypedefForVariablyModifiedType(S, NewTD);
5805
5806 bool Redeclaration = D.isRedeclaration();
5807 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5808 D.setRedeclaration(Redeclaration);
5809 return ND;
5810 }
5811
5812 void
CheckTypedefForVariablyModifiedType(Scope * S,TypedefNameDecl * NewTD)5813 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5814 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5815 // then it shall have block scope.
5816 // Note that variably modified types must be fixed before merging the decl so
5817 // that redeclarations will match.
5818 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5819 QualType T = TInfo->getType();
5820 if (T->isVariablyModifiedType()) {
5821 setFunctionHasBranchProtectedScope();
5822
5823 if (S->getFnParent() == nullptr) {
5824 bool SizeIsNegative;
5825 llvm::APSInt Oversized;
5826 TypeSourceInfo *FixedTInfo =
5827 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5828 SizeIsNegative,
5829 Oversized);
5830 if (FixedTInfo) {
5831 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5832 NewTD->setTypeSourceInfo(FixedTInfo);
5833 } else {
5834 if (SizeIsNegative)
5835 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5836 else if (T->isVariableArrayType())
5837 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5838 else if (Oversized.getBoolValue())
5839 Diag(NewTD->getLocation(), diag::err_array_too_large)
5840 << Oversized.toString(10);
5841 else
5842 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5843 NewTD->setInvalidDecl();
5844 }
5845 }
5846 }
5847 }
5848
5849 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5850 /// declares a typedef-name, either using the 'typedef' type specifier or via
5851 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5852 NamedDecl*
ActOnTypedefNameDecl(Scope * S,DeclContext * DC,TypedefNameDecl * NewTD,LookupResult & Previous,bool & Redeclaration)5853 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5854 LookupResult &Previous, bool &Redeclaration) {
5855
5856 // Find the shadowed declaration before filtering for scope.
5857 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5858
5859 // Merge the decl with the existing one if appropriate. If the decl is
5860 // in an outer scope, it isn't the same thing.
5861 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5862 /*AllowInlineNamespace*/false);
5863 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5864 if (!Previous.empty()) {
5865 Redeclaration = true;
5866 MergeTypedefNameDecl(S, NewTD, Previous);
5867 }
5868
5869 if (ShadowedDecl && !Redeclaration)
5870 CheckShadow(NewTD, ShadowedDecl, Previous);
5871
5872 // If this is the C FILE type, notify the AST context.
5873 if (IdentifierInfo *II = NewTD->getIdentifier())
5874 if (!NewTD->isInvalidDecl() &&
5875 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5876 if (II->isStr("FILE"))
5877 Context.setFILEDecl(NewTD);
5878 else if (II->isStr("jmp_buf"))
5879 Context.setjmp_bufDecl(NewTD);
5880 else if (II->isStr("sigjmp_buf"))
5881 Context.setsigjmp_bufDecl(NewTD);
5882 else if (II->isStr("ucontext_t"))
5883 Context.setucontext_tDecl(NewTD);
5884 }
5885
5886 return NewTD;
5887 }
5888
5889 /// Determines whether the given declaration is an out-of-scope
5890 /// previous declaration.
5891 ///
5892 /// This routine should be invoked when name lookup has found a
5893 /// previous declaration (PrevDecl) that is not in the scope where a
5894 /// new declaration by the same name is being introduced. If the new
5895 /// declaration occurs in a local scope, previous declarations with
5896 /// linkage may still be considered previous declarations (C99
5897 /// 6.2.2p4-5, C++ [basic.link]p6).
5898 ///
5899 /// \param PrevDecl the previous declaration found by name
5900 /// lookup
5901 ///
5902 /// \param DC the context in which the new declaration is being
5903 /// declared.
5904 ///
5905 /// \returns true if PrevDecl is an out-of-scope previous declaration
5906 /// for a new delcaration with the same name.
5907 static bool
isOutOfScopePreviousDeclaration(NamedDecl * PrevDecl,DeclContext * DC,ASTContext & Context)5908 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5909 ASTContext &Context) {
5910 if (!PrevDecl)
5911 return false;
5912
5913 if (!PrevDecl->hasLinkage())
5914 return false;
5915
5916 if (Context.getLangOpts().CPlusPlus) {
5917 // C++ [basic.link]p6:
5918 // If there is a visible declaration of an entity with linkage
5919 // having the same name and type, ignoring entities declared
5920 // outside the innermost enclosing namespace scope, the block
5921 // scope declaration declares that same entity and receives the
5922 // linkage of the previous declaration.
5923 DeclContext *OuterContext = DC->getRedeclContext();
5924 if (!OuterContext->isFunctionOrMethod())
5925 // This rule only applies to block-scope declarations.
5926 return false;
5927
5928 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5929 if (PrevOuterContext->isRecord())
5930 // We found a member function: ignore it.
5931 return false;
5932
5933 // Find the innermost enclosing namespace for the new and
5934 // previous declarations.
5935 OuterContext = OuterContext->getEnclosingNamespaceContext();
5936 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5937
5938 // The previous declaration is in a different namespace, so it
5939 // isn't the same function.
5940 if (!OuterContext->Equals(PrevOuterContext))
5941 return false;
5942 }
5943
5944 return true;
5945 }
5946
SetNestedNameSpecifier(Sema & S,DeclaratorDecl * DD,Declarator & D)5947 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
5948 CXXScopeSpec &SS = D.getCXXScopeSpec();
5949 if (!SS.isSet()) return;
5950 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
5951 }
5952
inferObjCARCLifetime(ValueDecl * decl)5953 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5954 QualType type = decl->getType();
5955 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5956 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5957 // Various kinds of declaration aren't allowed to be __autoreleasing.
5958 unsigned kind = -1U;
5959 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5960 if (var->hasAttr<BlocksAttr>())
5961 kind = 0; // __block
5962 else if (!var->hasLocalStorage())
5963 kind = 1; // global
5964 } else if (isa<ObjCIvarDecl>(decl)) {
5965 kind = 3; // ivar
5966 } else if (isa<FieldDecl>(decl)) {
5967 kind = 2; // field
5968 }
5969
5970 if (kind != -1U) {
5971 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5972 << kind;
5973 }
5974 } else if (lifetime == Qualifiers::OCL_None) {
5975 // Try to infer lifetime.
5976 if (!type->isObjCLifetimeType())
5977 return false;
5978
5979 lifetime = type->getObjCARCImplicitLifetime();
5980 type = Context.getLifetimeQualifiedType(type, lifetime);
5981 decl->setType(type);
5982 }
5983
5984 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5985 // Thread-local variables cannot have lifetime.
5986 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5987 var->getTLSKind()) {
5988 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5989 << var->getType();
5990 return true;
5991 }
5992 }
5993
5994 return false;
5995 }
5996
checkAttributesAfterMerging(Sema & S,NamedDecl & ND)5997 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5998 // Ensure that an auto decl is deduced otherwise the checks below might cache
5999 // the wrong linkage.
6000 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6001
6002 // 'weak' only applies to declarations with external linkage.
6003 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6004 if (!ND.isExternallyVisible()) {
6005 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6006 ND.dropAttr<WeakAttr>();
6007 }
6008 }
6009 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6010 if (ND.isExternallyVisible()) {
6011 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6012 ND.dropAttr<WeakRefAttr>();
6013 ND.dropAttr<AliasAttr>();
6014 }
6015 }
6016
6017 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6018 if (VD->hasInit()) {
6019 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6020 assert(VD->isThisDeclarationADefinition() &&
6021 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6022 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6023 VD->dropAttr<AliasAttr>();
6024 }
6025 }
6026 }
6027
6028 // 'selectany' only applies to externally visible variable declarations.
6029 // It does not apply to functions.
6030 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6031 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6032 S.Diag(Attr->getLocation(),
6033 diag::err_attribute_selectany_non_extern_data);
6034 ND.dropAttr<SelectAnyAttr>();
6035 }
6036 }
6037
6038 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6039 auto *VD = dyn_cast<VarDecl>(&ND);
6040 bool IsAnonymousNS = false;
6041 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6042 if (VD) {
6043 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6044 while (NS && !IsAnonymousNS) {
6045 IsAnonymousNS = NS->isAnonymousNamespace();
6046 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6047 }
6048 }
6049 // dll attributes require external linkage. Static locals may have external
6050 // linkage but still cannot be explicitly imported or exported.
6051 // In Microsoft mode, a variable defined in anonymous namespace must have
6052 // external linkage in order to be exported.
6053 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6054 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6055 (!AnonNSInMicrosoftMode &&
6056 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6057 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6058 << &ND << Attr;
6059 ND.setInvalidDecl();
6060 }
6061 }
6062
6063 // Virtual functions cannot be marked as 'notail'.
6064 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6065 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6066 if (MD->isVirtual()) {
6067 S.Diag(ND.getLocation(),
6068 diag::err_invalid_attribute_on_virtual_function)
6069 << Attr;
6070 ND.dropAttr<NotTailCalledAttr>();
6071 }
6072
6073 // Check the attributes on the function type, if any.
6074 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6075 // Don't declare this variable in the second operand of the for-statement;
6076 // GCC miscompiles that by ending its lifetime before evaluating the
6077 // third operand. See gcc.gnu.org/PR86769.
6078 AttributedTypeLoc ATL;
6079 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6080 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6081 TL = ATL.getModifiedLoc()) {
6082 // The [[lifetimebound]] attribute can be applied to the implicit object
6083 // parameter of a non-static member function (other than a ctor or dtor)
6084 // by applying it to the function type.
6085 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6086 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6087 if (!MD || MD->isStatic()) {
6088 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6089 << !MD << A->getRange();
6090 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6091 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6092 << isa<CXXDestructorDecl>(MD) << A->getRange();
6093 }
6094 }
6095 }
6096 }
6097 }
6098
checkDLLAttributeRedeclaration(Sema & S,NamedDecl * OldDecl,NamedDecl * NewDecl,bool IsSpecialization,bool IsDefinition)6099 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6100 NamedDecl *NewDecl,
6101 bool IsSpecialization,
6102 bool IsDefinition) {
6103 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6104 return;
6105
6106 bool IsTemplate = false;
6107 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6108 OldDecl = OldTD->getTemplatedDecl();
6109 IsTemplate = true;
6110 if (!IsSpecialization)
6111 IsDefinition = false;
6112 }
6113 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6114 NewDecl = NewTD->getTemplatedDecl();
6115 IsTemplate = true;
6116 }
6117
6118 if (!OldDecl || !NewDecl)
6119 return;
6120
6121 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6122 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6123 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6124 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6125
6126 // dllimport and dllexport are inheritable attributes so we have to exclude
6127 // inherited attribute instances.
6128 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6129 (NewExportAttr && !NewExportAttr->isInherited());
6130
6131 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6132 // the only exception being explicit specializations.
6133 // Implicitly generated declarations are also excluded for now because there
6134 // is no other way to switch these to use dllimport or dllexport.
6135 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6136
6137 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6138 // Allow with a warning for free functions and global variables.
6139 bool JustWarn = false;
6140 if (!OldDecl->isCXXClassMember()) {
6141 auto *VD = dyn_cast<VarDecl>(OldDecl);
6142 if (VD && !VD->getDescribedVarTemplate())
6143 JustWarn = true;
6144 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6145 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6146 JustWarn = true;
6147 }
6148
6149 // We cannot change a declaration that's been used because IR has already
6150 // been emitted. Dllimported functions will still work though (modulo
6151 // address equality) as they can use the thunk.
6152 if (OldDecl->isUsed())
6153 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6154 JustWarn = false;
6155
6156 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6157 : diag::err_attribute_dll_redeclaration;
6158 S.Diag(NewDecl->getLocation(), DiagID)
6159 << NewDecl
6160 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6161 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6162 if (!JustWarn) {
6163 NewDecl->setInvalidDecl();
6164 return;
6165 }
6166 }
6167
6168 // A redeclaration is not allowed to drop a dllimport attribute, the only
6169 // exceptions being inline function definitions (except for function
6170 // templates), local extern declarations, qualified friend declarations or
6171 // special MSVC extension: in the last case, the declaration is treated as if
6172 // it were marked dllexport.
6173 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6174 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6175 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6176 // Ignore static data because out-of-line definitions are diagnosed
6177 // separately.
6178 IsStaticDataMember = VD->isStaticDataMember();
6179 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6180 VarDecl::DeclarationOnly;
6181 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6182 IsInline = FD->isInlined();
6183 IsQualifiedFriend = FD->getQualifier() &&
6184 FD->getFriendObjectKind() == Decl::FOK_Declared;
6185 }
6186
6187 if (OldImportAttr && !HasNewAttr &&
6188 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6189 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6190 if (IsMicrosoft && IsDefinition) {
6191 S.Diag(NewDecl->getLocation(),
6192 diag::warn_redeclaration_without_import_attribute)
6193 << NewDecl;
6194 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6195 NewDecl->dropAttr<DLLImportAttr>();
6196 NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6197 NewImportAttr->getRange(), S.Context,
6198 NewImportAttr->getSpellingListIndex()));
6199 } else {
6200 S.Diag(NewDecl->getLocation(),
6201 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6202 << NewDecl << OldImportAttr;
6203 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6204 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6205 OldDecl->dropAttr<DLLImportAttr>();
6206 NewDecl->dropAttr<DLLImportAttr>();
6207 }
6208 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6209 // In MinGW, seeing a function declared inline drops the dllimport
6210 // attribute.
6211 OldDecl->dropAttr<DLLImportAttr>();
6212 NewDecl->dropAttr<DLLImportAttr>();
6213 S.Diag(NewDecl->getLocation(),
6214 diag::warn_dllimport_dropped_from_inline_function)
6215 << NewDecl << OldImportAttr;
6216 }
6217
6218 // A specialization of a class template member function is processed here
6219 // since it's a redeclaration. If the parent class is dllexport, the
6220 // specialization inherits that attribute. This doesn't happen automatically
6221 // since the parent class isn't instantiated until later.
6222 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6223 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6224 !NewImportAttr && !NewExportAttr) {
6225 if (const DLLExportAttr *ParentExportAttr =
6226 MD->getParent()->getAttr<DLLExportAttr>()) {
6227 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6228 NewAttr->setInherited(true);
6229 NewDecl->addAttr(NewAttr);
6230 }
6231 }
6232 }
6233 }
6234
6235 /// Given that we are within the definition of the given function,
6236 /// will that definition behave like C99's 'inline', where the
6237 /// definition is discarded except for optimization purposes?
isFunctionDefinitionDiscarded(Sema & S,FunctionDecl * FD)6238 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6239 // Try to avoid calling GetGVALinkageForFunction.
6240
6241 // All cases of this require the 'inline' keyword.
6242 if (!FD->isInlined()) return false;
6243
6244 // This is only possible in C++ with the gnu_inline attribute.
6245 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6246 return false;
6247
6248 // Okay, go ahead and call the relatively-more-expensive function.
6249 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6250 }
6251
6252 /// Determine whether a variable is extern "C" prior to attaching
6253 /// an initializer. We can't just call isExternC() here, because that
6254 /// will also compute and cache whether the declaration is externally
6255 /// visible, which might change when we attach the initializer.
6256 ///
6257 /// This can only be used if the declaration is known to not be a
6258 /// redeclaration of an internal linkage declaration.
6259 ///
6260 /// For instance:
6261 ///
6262 /// auto x = []{};
6263 ///
6264 /// Attaching the initializer here makes this declaration not externally
6265 /// visible, because its type has internal linkage.
6266 ///
6267 /// FIXME: This is a hack.
6268 template<typename T>
isIncompleteDeclExternC(Sema & S,const T * D)6269 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6270 if (S.getLangOpts().CPlusPlus) {
6271 // In C++, the overloadable attribute negates the effects of extern "C".
6272 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6273 return false;
6274
6275 // So do CUDA's host/device attributes.
6276 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6277 D->template hasAttr<CUDAHostAttr>()))
6278 return false;
6279 }
6280 return D->isExternC();
6281 }
6282
shouldConsiderLinkage(const VarDecl * VD)6283 static bool shouldConsiderLinkage(const VarDecl *VD) {
6284 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6285 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6286 isa<OMPDeclareMapperDecl>(DC))
6287 return VD->hasExternalStorage();
6288 if (DC->isFileContext())
6289 return true;
6290 if (DC->isRecord())
6291 return false;
6292 llvm_unreachable("Unexpected context");
6293 }
6294
shouldConsiderLinkage(const FunctionDecl * FD)6295 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6296 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6297 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6298 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6299 return true;
6300 if (DC->isRecord())
6301 return false;
6302 llvm_unreachable("Unexpected context");
6303 }
6304
hasParsedAttr(Scope * S,const Declarator & PD,ParsedAttr::Kind Kind)6305 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6306 ParsedAttr::Kind Kind) {
6307 // Check decl attributes on the DeclSpec.
6308 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6309 return true;
6310
6311 // Walk the declarator structure, checking decl attributes that were in a type
6312 // position to the decl itself.
6313 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6314 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6315 return true;
6316 }
6317
6318 // Finally, check attributes on the decl itself.
6319 return PD.getAttributes().hasAttribute(Kind);
6320 }
6321
6322 /// Adjust the \c DeclContext for a function or variable that might be a
6323 /// function-local external declaration.
adjustContextForLocalExternDecl(DeclContext * & DC)6324 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6325 if (!DC->isFunctionOrMethod())
6326 return false;
6327
6328 // If this is a local extern function or variable declared within a function
6329 // template, don't add it into the enclosing namespace scope until it is
6330 // instantiated; it might have a dependent type right now.
6331 if (DC->isDependentContext())
6332 return true;
6333
6334 // C++11 [basic.link]p7:
6335 // When a block scope declaration of an entity with linkage is not found to
6336 // refer to some other declaration, then that entity is a member of the
6337 // innermost enclosing namespace.
6338 //
6339 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6340 // semantically-enclosing namespace, not a lexically-enclosing one.
6341 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6342 DC = DC->getParent();
6343 return true;
6344 }
6345
6346 /// Returns true if given declaration has external C language linkage.
isDeclExternC(const Decl * D)6347 static bool isDeclExternC(const Decl *D) {
6348 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6349 return FD->isExternC();
6350 if (const auto *VD = dyn_cast<VarDecl>(D))
6351 return VD->isExternC();
6352
6353 llvm_unreachable("Unknown type of decl!");
6354 }
6355
ActOnVariableDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamLists,bool & AddToScope,ArrayRef<BindingDecl * > Bindings)6356 NamedDecl *Sema::ActOnVariableDeclarator(
6357 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6358 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6359 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6360 QualType R = TInfo->getType();
6361 DeclarationName Name = GetNameForDeclarator(D).getName();
6362
6363 IdentifierInfo *II = Name.getAsIdentifierInfo();
6364
6365 if (D.isDecompositionDeclarator()) {
6366 // Take the name of the first declarator as our name for diagnostic
6367 // purposes.
6368 auto &Decomp = D.getDecompositionDeclarator();
6369 if (!Decomp.bindings().empty()) {
6370 II = Decomp.bindings()[0].Name;
6371 Name = II;
6372 }
6373 } else if (!II) {
6374 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6375 return nullptr;
6376 }
6377
6378 if (getLangOpts().OpenCL) {
6379 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6380 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6381 // argument.
6382 if (R->isImageType() || R->isPipeType()) {
6383 Diag(D.getIdentifierLoc(),
6384 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6385 << R;
6386 D.setInvalidType();
6387 return nullptr;
6388 }
6389
6390 // OpenCL v1.2 s6.9.r:
6391 // The event type cannot be used to declare a program scope variable.
6392 // OpenCL v2.0 s6.9.q:
6393 // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6394 if (NULL == S->getParent()) {
6395 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6396 Diag(D.getIdentifierLoc(),
6397 diag::err_invalid_type_for_program_scope_var) << R;
6398 D.setInvalidType();
6399 return nullptr;
6400 }
6401 }
6402
6403 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6404 QualType NR = R;
6405 while (NR->isPointerType()) {
6406 if (NR->isFunctionPointerType()) {
6407 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6408 D.setInvalidType();
6409 break;
6410 }
6411 NR = NR->getPointeeType();
6412 }
6413
6414 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6415 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6416 // half array type (unless the cl_khr_fp16 extension is enabled).
6417 if (Context.getBaseElementType(R)->isHalfType()) {
6418 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6419 D.setInvalidType();
6420 }
6421 }
6422
6423 if (R->isSamplerT()) {
6424 // OpenCL v1.2 s6.9.b p4:
6425 // The sampler type cannot be used with the __local and __global address
6426 // space qualifiers.
6427 if (R.getAddressSpace() == LangAS::opencl_local ||
6428 R.getAddressSpace() == LangAS::opencl_global) {
6429 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6430 }
6431
6432 // OpenCL v1.2 s6.12.14.1:
6433 // A global sampler must be declared with either the constant address
6434 // space qualifier or with the const qualifier.
6435 if (DC->isTranslationUnit() &&
6436 !(R.getAddressSpace() == LangAS::opencl_constant ||
6437 R.isConstQualified())) {
6438 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6439 D.setInvalidType();
6440 }
6441 }
6442
6443 // OpenCL v1.2 s6.9.r:
6444 // The event type cannot be used with the __local, __constant and __global
6445 // address space qualifiers.
6446 if (R->isEventT()) {
6447 if (R.getAddressSpace() != LangAS::opencl_private) {
6448 Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6449 D.setInvalidType();
6450 }
6451 }
6452
6453 // C++ for OpenCL does not allow the thread_local storage qualifier.
6454 // OpenCL C does not support thread_local either, and
6455 // also reject all other thread storage class specifiers.
6456 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6457 if (TSC != TSCS_unspecified) {
6458 bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6459 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6460 diag::err_opencl_unknown_type_specifier)
6461 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6462 << DeclSpec::getSpecifierName(TSC) << 1;
6463 D.setInvalidType();
6464 return nullptr;
6465 }
6466 }
6467
6468 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6469 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6470
6471 // dllimport globals without explicit storage class are treated as extern. We
6472 // have to change the storage class this early to get the right DeclContext.
6473 if (SC == SC_None && !DC->isRecord() &&
6474 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6475 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6476 SC = SC_Extern;
6477
6478 DeclContext *OriginalDC = DC;
6479 bool IsLocalExternDecl = SC == SC_Extern &&
6480 adjustContextForLocalExternDecl(DC);
6481
6482 if (SCSpec == DeclSpec::SCS_mutable) {
6483 // mutable can only appear on non-static class members, so it's always
6484 // an error here
6485 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6486 D.setInvalidType();
6487 SC = SC_None;
6488 }
6489
6490 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6491 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6492 D.getDeclSpec().getStorageClassSpecLoc())) {
6493 // In C++11, the 'register' storage class specifier is deprecated.
6494 // Suppress the warning in system macros, it's used in macros in some
6495 // popular C system headers, such as in glibc's htonl() macro.
6496 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6497 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6498 : diag::warn_deprecated_register)
6499 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6500 }
6501
6502 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6503
6504 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6505 // C99 6.9p2: The storage-class specifiers auto and register shall not
6506 // appear in the declaration specifiers in an external declaration.
6507 // Global Register+Asm is a GNU extension we support.
6508 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6509 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6510 D.setInvalidType();
6511 }
6512 }
6513
6514 bool IsMemberSpecialization = false;
6515 bool IsVariableTemplateSpecialization = false;
6516 bool IsPartialSpecialization = false;
6517 bool IsVariableTemplate = false;
6518 VarDecl *NewVD = nullptr;
6519 VarTemplateDecl *NewTemplate = nullptr;
6520 TemplateParameterList *TemplateParams = nullptr;
6521 if (!getLangOpts().CPlusPlus) {
6522 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6523 II, R, TInfo, SC);
6524
6525 if (R->getContainedDeducedType())
6526 ParsingInitForAutoVars.insert(NewVD);
6527
6528 if (D.isInvalidType())
6529 NewVD->setInvalidDecl();
6530
6531 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6532 NewVD->hasLocalStorage())
6533 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6534 NTCUC_AutoVar, NTCUK_Destruct);
6535 } else {
6536 bool Invalid = false;
6537
6538 if (DC->isRecord() && !CurContext->isRecord()) {
6539 // This is an out-of-line definition of a static data member.
6540 switch (SC) {
6541 case SC_None:
6542 break;
6543 case SC_Static:
6544 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6545 diag::err_static_out_of_line)
6546 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6547 break;
6548 case SC_Auto:
6549 case SC_Register:
6550 case SC_Extern:
6551 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6552 // to names of variables declared in a block or to function parameters.
6553 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6554 // of class members
6555
6556 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6557 diag::err_storage_class_for_static_member)
6558 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6559 break;
6560 case SC_PrivateExtern:
6561 llvm_unreachable("C storage class in c++!");
6562 }
6563 }
6564
6565 if (SC == SC_Static && CurContext->isRecord()) {
6566 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6567 if (RD->isLocalClass())
6568 Diag(D.getIdentifierLoc(),
6569 diag::err_static_data_member_not_allowed_in_local_class)
6570 << Name << RD->getDeclName();
6571
6572 // C++98 [class.union]p1: If a union contains a static data member,
6573 // the program is ill-formed. C++11 drops this restriction.
6574 if (RD->isUnion())
6575 Diag(D.getIdentifierLoc(),
6576 getLangOpts().CPlusPlus11
6577 ? diag::warn_cxx98_compat_static_data_member_in_union
6578 : diag::ext_static_data_member_in_union) << Name;
6579 // We conservatively disallow static data members in anonymous structs.
6580 else if (!RD->getDeclName())
6581 Diag(D.getIdentifierLoc(),
6582 diag::err_static_data_member_not_allowed_in_anon_struct)
6583 << Name << RD->isUnion();
6584 }
6585 }
6586
6587 // Match up the template parameter lists with the scope specifier, then
6588 // determine whether we have a template or a template specialization.
6589 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6590 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6591 D.getCXXScopeSpec(),
6592 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6593 ? D.getName().TemplateId
6594 : nullptr,
6595 TemplateParamLists,
6596 /*never a friend*/ false, IsMemberSpecialization, Invalid);
6597
6598 if (TemplateParams) {
6599 if (!TemplateParams->size() &&
6600 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6601 // There is an extraneous 'template<>' for this variable. Complain
6602 // about it, but allow the declaration of the variable.
6603 Diag(TemplateParams->getTemplateLoc(),
6604 diag::err_template_variable_noparams)
6605 << II
6606 << SourceRange(TemplateParams->getTemplateLoc(),
6607 TemplateParams->getRAngleLoc());
6608 TemplateParams = nullptr;
6609 } else {
6610 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6611 // This is an explicit specialization or a partial specialization.
6612 // FIXME: Check that we can declare a specialization here.
6613 IsVariableTemplateSpecialization = true;
6614 IsPartialSpecialization = TemplateParams->size() > 0;
6615 } else { // if (TemplateParams->size() > 0)
6616 // This is a template declaration.
6617 IsVariableTemplate = true;
6618
6619 // Check that we can declare a template here.
6620 if (CheckTemplateDeclScope(S, TemplateParams))
6621 return nullptr;
6622
6623 // Only C++1y supports variable templates (N3651).
6624 Diag(D.getIdentifierLoc(),
6625 getLangOpts().CPlusPlus14
6626 ? diag::warn_cxx11_compat_variable_template
6627 : diag::ext_variable_template);
6628 }
6629 }
6630 } else {
6631 assert((Invalid ||
6632 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6633 "should have a 'template<>' for this decl");
6634 }
6635
6636 if (IsVariableTemplateSpecialization) {
6637 SourceLocation TemplateKWLoc =
6638 TemplateParamLists.size() > 0
6639 ? TemplateParamLists[0]->getTemplateLoc()
6640 : SourceLocation();
6641 DeclResult Res = ActOnVarTemplateSpecialization(
6642 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6643 IsPartialSpecialization);
6644 if (Res.isInvalid())
6645 return nullptr;
6646 NewVD = cast<VarDecl>(Res.get());
6647 AddToScope = false;
6648 } else if (D.isDecompositionDeclarator()) {
6649 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6650 D.getIdentifierLoc(), R, TInfo, SC,
6651 Bindings);
6652 } else
6653 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6654 D.getIdentifierLoc(), II, R, TInfo, SC);
6655
6656 // If this is supposed to be a variable template, create it as such.
6657 if (IsVariableTemplate) {
6658 NewTemplate =
6659 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6660 TemplateParams, NewVD);
6661 NewVD->setDescribedVarTemplate(NewTemplate);
6662 }
6663
6664 // If this decl has an auto type in need of deduction, make a note of the
6665 // Decl so we can diagnose uses of it in its own initializer.
6666 if (R->getContainedDeducedType())
6667 ParsingInitForAutoVars.insert(NewVD);
6668
6669 if (D.isInvalidType() || Invalid) {
6670 NewVD->setInvalidDecl();
6671 if (NewTemplate)
6672 NewTemplate->setInvalidDecl();
6673 }
6674
6675 SetNestedNameSpecifier(*this, NewVD, D);
6676
6677 // If we have any template parameter lists that don't directly belong to
6678 // the variable (matching the scope specifier), store them.
6679 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6680 if (TemplateParamLists.size() > VDTemplateParamLists)
6681 NewVD->setTemplateParameterListsInfo(
6682 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6683
6684 if (D.getDeclSpec().hasConstexprSpecifier()) {
6685 NewVD->setConstexpr(true);
6686 // C++1z [dcl.spec.constexpr]p1:
6687 // A static data member declared with the constexpr specifier is
6688 // implicitly an inline variable.
6689 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6690 NewVD->setImplicitlyInline();
6691 if (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval)
6692 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6693 diag::err_constexpr_wrong_decl_kind)
6694 << /*consteval*/ 1;
6695 }
6696 }
6697
6698 if (D.getDeclSpec().isInlineSpecified()) {
6699 if (!getLangOpts().CPlusPlus) {
6700 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6701 << 0;
6702 } else if (CurContext->isFunctionOrMethod()) {
6703 // 'inline' is not allowed on block scope variable declaration.
6704 Diag(D.getDeclSpec().getInlineSpecLoc(),
6705 diag::err_inline_declaration_block_scope) << Name
6706 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6707 } else {
6708 Diag(D.getDeclSpec().getInlineSpecLoc(),
6709 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6710 : diag::ext_inline_variable);
6711 NewVD->setInlineSpecified();
6712 }
6713 }
6714
6715 // Set the lexical context. If the declarator has a C++ scope specifier, the
6716 // lexical context will be different from the semantic context.
6717 NewVD->setLexicalDeclContext(CurContext);
6718 if (NewTemplate)
6719 NewTemplate->setLexicalDeclContext(CurContext);
6720
6721 if (IsLocalExternDecl) {
6722 if (D.isDecompositionDeclarator())
6723 for (auto *B : Bindings)
6724 B->setLocalExternDecl();
6725 else
6726 NewVD->setLocalExternDecl();
6727 }
6728
6729 bool EmitTLSUnsupportedError = false;
6730 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6731 // C++11 [dcl.stc]p4:
6732 // When thread_local is applied to a variable of block scope the
6733 // storage-class-specifier static is implied if it does not appear
6734 // explicitly.
6735 // Core issue: 'static' is not implied if the variable is declared
6736 // 'extern'.
6737 if (NewVD->hasLocalStorage() &&
6738 (SCSpec != DeclSpec::SCS_unspecified ||
6739 TSCS != DeclSpec::TSCS_thread_local ||
6740 !DC->isFunctionOrMethod()))
6741 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6742 diag::err_thread_non_global)
6743 << DeclSpec::getSpecifierName(TSCS);
6744 else if (!Context.getTargetInfo().isTLSSupported()) {
6745 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6746 // Postpone error emission until we've collected attributes required to
6747 // figure out whether it's a host or device variable and whether the
6748 // error should be ignored.
6749 EmitTLSUnsupportedError = true;
6750 // We still need to mark the variable as TLS so it shows up in AST with
6751 // proper storage class for other tools to use even if we're not going
6752 // to emit any code for it.
6753 NewVD->setTSCSpec(TSCS);
6754 } else
6755 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6756 diag::err_thread_unsupported);
6757 } else
6758 NewVD->setTSCSpec(TSCS);
6759 }
6760
6761 // C99 6.7.4p3
6762 // An inline definition of a function with external linkage shall
6763 // not contain a definition of a modifiable object with static or
6764 // thread storage duration...
6765 // We only apply this when the function is required to be defined
6766 // elsewhere, i.e. when the function is not 'extern inline'. Note
6767 // that a local variable with thread storage duration still has to
6768 // be marked 'static'. Also note that it's possible to get these
6769 // semantics in C++ using __attribute__((gnu_inline)).
6770 if (SC == SC_Static && S->getFnParent() != nullptr &&
6771 !NewVD->getType().isConstQualified()) {
6772 FunctionDecl *CurFD = getCurFunctionDecl();
6773 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6774 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6775 diag::warn_static_local_in_extern_inline);
6776 MaybeSuggestAddingStaticToDecl(CurFD);
6777 }
6778 }
6779
6780 if (D.getDeclSpec().isModulePrivateSpecified()) {
6781 if (IsVariableTemplateSpecialization)
6782 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6783 << (IsPartialSpecialization ? 1 : 0)
6784 << FixItHint::CreateRemoval(
6785 D.getDeclSpec().getModulePrivateSpecLoc());
6786 else if (IsMemberSpecialization)
6787 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6788 << 2
6789 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6790 else if (NewVD->hasLocalStorage())
6791 Diag(NewVD->getLocation(), diag::err_module_private_local)
6792 << 0 << NewVD->getDeclName()
6793 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6794 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6795 else {
6796 NewVD->setModulePrivate();
6797 if (NewTemplate)
6798 NewTemplate->setModulePrivate();
6799 for (auto *B : Bindings)
6800 B->setModulePrivate();
6801 }
6802 }
6803
6804 // Handle attributes prior to checking for duplicates in MergeVarDecl
6805 ProcessDeclAttributes(S, NewVD, D);
6806
6807 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6808 if (EmitTLSUnsupportedError &&
6809 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6810 (getLangOpts().OpenMPIsDevice &&
6811 NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6812 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6813 diag::err_thread_unsupported);
6814 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6815 // storage [duration]."
6816 if (SC == SC_None && S->getFnParent() != nullptr &&
6817 (NewVD->hasAttr<CUDASharedAttr>() ||
6818 NewVD->hasAttr<CUDAConstantAttr>())) {
6819 NewVD->setStorageClass(SC_Static);
6820 }
6821 }
6822
6823 // Ensure that dllimport globals without explicit storage class are treated as
6824 // extern. The storage class is set above using parsed attributes. Now we can
6825 // check the VarDecl itself.
6826 assert(!NewVD->hasAttr<DLLImportAttr>() ||
6827 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6828 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6829
6830 // In auto-retain/release, infer strong retension for variables of
6831 // retainable type.
6832 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6833 NewVD->setInvalidDecl();
6834
6835 // Handle GNU asm-label extension (encoded as an attribute).
6836 if (Expr *E = (Expr*)D.getAsmLabel()) {
6837 // The parser guarantees this is a string.
6838 StringLiteral *SE = cast<StringLiteral>(E);
6839 StringRef Label = SE->getString();
6840 if (S->getFnParent() != nullptr) {
6841 switch (SC) {
6842 case SC_None:
6843 case SC_Auto:
6844 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6845 break;
6846 case SC_Register:
6847 // Local Named register
6848 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6849 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6850 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6851 break;
6852 case SC_Static:
6853 case SC_Extern:
6854 case SC_PrivateExtern:
6855 break;
6856 }
6857 } else if (SC == SC_Register) {
6858 // Global Named register
6859 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6860 const auto &TI = Context.getTargetInfo();
6861 bool HasSizeMismatch;
6862
6863 if (!TI.isValidGCCRegisterName(Label))
6864 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6865 else if (!TI.validateGlobalRegisterVariable(Label,
6866 Context.getTypeSize(R),
6867 HasSizeMismatch))
6868 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6869 else if (HasSizeMismatch)
6870 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6871 }
6872
6873 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6874 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6875 NewVD->setInvalidDecl(true);
6876 }
6877 }
6878
6879 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6880 Context, Label, 0));
6881 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6882 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6883 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6884 if (I != ExtnameUndeclaredIdentifiers.end()) {
6885 if (isDeclExternC(NewVD)) {
6886 NewVD->addAttr(I->second);
6887 ExtnameUndeclaredIdentifiers.erase(I);
6888 } else
6889 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6890 << /*Variable*/1 << NewVD;
6891 }
6892 }
6893
6894 // Find the shadowed declaration before filtering for scope.
6895 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6896 ? getShadowedDeclaration(NewVD, Previous)
6897 : nullptr;
6898
6899 // Don't consider existing declarations that are in a different
6900 // scope and are out-of-semantic-context declarations (if the new
6901 // declaration has linkage).
6902 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6903 D.getCXXScopeSpec().isNotEmpty() ||
6904 IsMemberSpecialization ||
6905 IsVariableTemplateSpecialization);
6906
6907 // Check whether the previous declaration is in the same block scope. This
6908 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6909 if (getLangOpts().CPlusPlus &&
6910 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6911 NewVD->setPreviousDeclInSameBlockScope(
6912 Previous.isSingleResult() && !Previous.isShadowed() &&
6913 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6914
6915 if (!getLangOpts().CPlusPlus) {
6916 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6917 } else {
6918 // If this is an explicit specialization of a static data member, check it.
6919 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6920 CheckMemberSpecialization(NewVD, Previous))
6921 NewVD->setInvalidDecl();
6922
6923 // Merge the decl with the existing one if appropriate.
6924 if (!Previous.empty()) {
6925 if (Previous.isSingleResult() &&
6926 isa<FieldDecl>(Previous.getFoundDecl()) &&
6927 D.getCXXScopeSpec().isSet()) {
6928 // The user tried to define a non-static data member
6929 // out-of-line (C++ [dcl.meaning]p1).
6930 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6931 << D.getCXXScopeSpec().getRange();
6932 Previous.clear();
6933 NewVD->setInvalidDecl();
6934 }
6935 } else if (D.getCXXScopeSpec().isSet()) {
6936 // No previous declaration in the qualifying scope.
6937 Diag(D.getIdentifierLoc(), diag::err_no_member)
6938 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6939 << D.getCXXScopeSpec().getRange();
6940 NewVD->setInvalidDecl();
6941 }
6942
6943 if (!IsVariableTemplateSpecialization)
6944 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6945
6946 if (NewTemplate) {
6947 VarTemplateDecl *PrevVarTemplate =
6948 NewVD->getPreviousDecl()
6949 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6950 : nullptr;
6951
6952 // Check the template parameter list of this declaration, possibly
6953 // merging in the template parameter list from the previous variable
6954 // template declaration.
6955 if (CheckTemplateParameterList(
6956 TemplateParams,
6957 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6958 : nullptr,
6959 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6960 DC->isDependentContext())
6961 ? TPC_ClassTemplateMember
6962 : TPC_VarTemplate))
6963 NewVD->setInvalidDecl();
6964
6965 // If we are providing an explicit specialization of a static variable
6966 // template, make a note of that.
6967 if (PrevVarTemplate &&
6968 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6969 PrevVarTemplate->setMemberSpecialization();
6970 }
6971 }
6972
6973 // Diagnose shadowed variables iff this isn't a redeclaration.
6974 if (ShadowedDecl && !D.isRedeclaration())
6975 CheckShadow(NewVD, ShadowedDecl, Previous);
6976
6977 ProcessPragmaWeak(S, NewVD);
6978
6979 // If this is the first declaration of an extern C variable, update
6980 // the map of such variables.
6981 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6982 isIncompleteDeclExternC(*this, NewVD))
6983 RegisterLocallyScopedExternCDecl(NewVD, S);
6984
6985 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6986 Decl *ManglingContextDecl;
6987 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6988 NewVD->getDeclContext(), ManglingContextDecl)) {
6989 Context.setManglingNumber(
6990 NewVD, MCtx->getManglingNumber(
6991 NewVD, getMSManglingNumber(getLangOpts(), S)));
6992 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6993 }
6994 }
6995
6996 // Special handling of variable named 'main'.
6997 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6998 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6999 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7000
7001 // C++ [basic.start.main]p3
7002 // A program that declares a variable main at global scope is ill-formed.
7003 if (getLangOpts().CPlusPlus)
7004 Diag(D.getBeginLoc(), diag::err_main_global_variable);
7005
7006 // In C, and external-linkage variable named main results in undefined
7007 // behavior.
7008 else if (NewVD->hasExternalFormalLinkage())
7009 Diag(D.getBeginLoc(), diag::warn_main_redefined);
7010 }
7011
7012 if (D.isRedeclaration() && !Previous.empty()) {
7013 NamedDecl *Prev = Previous.getRepresentativeDecl();
7014 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7015 D.isFunctionDefinition());
7016 }
7017
7018 if (NewTemplate) {
7019 if (NewVD->isInvalidDecl())
7020 NewTemplate->setInvalidDecl();
7021 ActOnDocumentableDecl(NewTemplate);
7022 return NewTemplate;
7023 }
7024
7025 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7026 CompleteMemberSpecialization(NewVD, Previous);
7027
7028 return NewVD;
7029 }
7030
7031 /// Enum describing the %select options in diag::warn_decl_shadow.
7032 enum ShadowedDeclKind {
7033 SDK_Local,
7034 SDK_Global,
7035 SDK_StaticMember,
7036 SDK_Field,
7037 SDK_Typedef,
7038 SDK_Using
7039 };
7040
7041 /// Determine what kind of declaration we're shadowing.
computeShadowedDeclKind(const NamedDecl * ShadowedDecl,const DeclContext * OldDC)7042 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7043 const DeclContext *OldDC) {
7044 if (isa<TypeAliasDecl>(ShadowedDecl))
7045 return SDK_Using;
7046 else if (isa<TypedefDecl>(ShadowedDecl))
7047 return SDK_Typedef;
7048 else if (isa<RecordDecl>(OldDC))
7049 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7050
7051 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7052 }
7053
7054 /// Return the location of the capture if the given lambda captures the given
7055 /// variable \p VD, or an invalid source location otherwise.
getCaptureLocation(const LambdaScopeInfo * LSI,const VarDecl * VD)7056 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7057 const VarDecl *VD) {
7058 for (const Capture &Capture : LSI->Captures) {
7059 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7060 return Capture.getLocation();
7061 }
7062 return SourceLocation();
7063 }
7064
shouldWarnIfShadowedDecl(const DiagnosticsEngine & Diags,const LookupResult & R)7065 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7066 const LookupResult &R) {
7067 // Only diagnose if we're shadowing an unambiguous field or variable.
7068 if (R.getResultKind() != LookupResult::Found)
7069 return false;
7070
7071 // Return false if warning is ignored.
7072 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7073 }
7074
7075 /// Return the declaration shadowed by the given variable \p D, or null
7076 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
getShadowedDeclaration(const VarDecl * D,const LookupResult & R)7077 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7078 const LookupResult &R) {
7079 if (!shouldWarnIfShadowedDecl(Diags, R))
7080 return nullptr;
7081
7082 // Don't diagnose declarations at file scope.
7083 if (D->hasGlobalStorage())
7084 return nullptr;
7085
7086 NamedDecl *ShadowedDecl = R.getFoundDecl();
7087 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7088 ? ShadowedDecl
7089 : nullptr;
7090 }
7091
7092 /// Return the declaration shadowed by the given typedef \p D, or null
7093 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
getShadowedDeclaration(const TypedefNameDecl * D,const LookupResult & R)7094 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7095 const LookupResult &R) {
7096 // Don't warn if typedef declaration is part of a class
7097 if (D->getDeclContext()->isRecord())
7098 return nullptr;
7099
7100 if (!shouldWarnIfShadowedDecl(Diags, R))
7101 return nullptr;
7102
7103 NamedDecl *ShadowedDecl = R.getFoundDecl();
7104 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7105 }
7106
7107 /// Diagnose variable or built-in function shadowing. Implements
7108 /// -Wshadow.
7109 ///
7110 /// This method is called whenever a VarDecl is added to a "useful"
7111 /// scope.
7112 ///
7113 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7114 /// \param R the lookup of the name
7115 ///
CheckShadow(NamedDecl * D,NamedDecl * ShadowedDecl,const LookupResult & R)7116 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7117 const LookupResult &R) {
7118 DeclContext *NewDC = D->getDeclContext();
7119
7120 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7121 // Fields are not shadowed by variables in C++ static methods.
7122 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7123 if (MD->isStatic())
7124 return;
7125
7126 // Fields shadowed by constructor parameters are a special case. Usually
7127 // the constructor initializes the field with the parameter.
7128 if (isa<CXXConstructorDecl>(NewDC))
7129 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7130 // Remember that this was shadowed so we can either warn about its
7131 // modification or its existence depending on warning settings.
7132 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7133 return;
7134 }
7135 }
7136
7137 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7138 if (shadowedVar->isExternC()) {
7139 // For shadowing external vars, make sure that we point to the global
7140 // declaration, not a locally scoped extern declaration.
7141 for (auto I : shadowedVar->redecls())
7142 if (I->isFileVarDecl()) {
7143 ShadowedDecl = I;
7144 break;
7145 }
7146 }
7147
7148 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7149
7150 unsigned WarningDiag = diag::warn_decl_shadow;
7151 SourceLocation CaptureLoc;
7152 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7153 isa<CXXMethodDecl>(NewDC)) {
7154 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7155 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7156 if (RD->getLambdaCaptureDefault() == LCD_None) {
7157 // Try to avoid warnings for lambdas with an explicit capture list.
7158 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7159 // Warn only when the lambda captures the shadowed decl explicitly.
7160 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7161 if (CaptureLoc.isInvalid())
7162 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7163 } else {
7164 // Remember that this was shadowed so we can avoid the warning if the
7165 // shadowed decl isn't captured and the warning settings allow it.
7166 cast<LambdaScopeInfo>(getCurFunction())
7167 ->ShadowingDecls.push_back(
7168 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7169 return;
7170 }
7171 }
7172
7173 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7174 // A variable can't shadow a local variable in an enclosing scope, if
7175 // they are separated by a non-capturing declaration context.
7176 for (DeclContext *ParentDC = NewDC;
7177 ParentDC && !ParentDC->Equals(OldDC);
7178 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7179 // Only block literals, captured statements, and lambda expressions
7180 // can capture; other scopes don't.
7181 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7182 !isLambdaCallOperator(ParentDC)) {
7183 return;
7184 }
7185 }
7186 }
7187 }
7188 }
7189
7190 // Only warn about certain kinds of shadowing for class members.
7191 if (NewDC && NewDC->isRecord()) {
7192 // In particular, don't warn about shadowing non-class members.
7193 if (!OldDC->isRecord())
7194 return;
7195
7196 // TODO: should we warn about static data members shadowing
7197 // static data members from base classes?
7198
7199 // TODO: don't diagnose for inaccessible shadowed members.
7200 // This is hard to do perfectly because we might friend the
7201 // shadowing context, but that's just a false negative.
7202 }
7203
7204
7205 DeclarationName Name = R.getLookupName();
7206
7207 // Emit warning and note.
7208 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7209 return;
7210 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7211 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7212 if (!CaptureLoc.isInvalid())
7213 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7214 << Name << /*explicitly*/ 1;
7215 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7216 }
7217
7218 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7219 /// when these variables are captured by the lambda.
DiagnoseShadowingLambdaDecls(const LambdaScopeInfo * LSI)7220 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7221 for (const auto &Shadow : LSI->ShadowingDecls) {
7222 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7223 // Try to avoid the warning when the shadowed decl isn't captured.
7224 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7225 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7226 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7227 ? diag::warn_decl_shadow_uncaptured_local
7228 : diag::warn_decl_shadow)
7229 << Shadow.VD->getDeclName()
7230 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7231 if (!CaptureLoc.isInvalid())
7232 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7233 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7234 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7235 }
7236 }
7237
7238 /// Check -Wshadow without the advantage of a previous lookup.
CheckShadow(Scope * S,VarDecl * D)7239 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7240 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7241 return;
7242
7243 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7244 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7245 LookupName(R, S);
7246 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7247 CheckShadow(D, ShadowedDecl, R);
7248 }
7249
7250 /// Check if 'E', which is an expression that is about to be modified, refers
7251 /// to a constructor parameter that shadows a field.
CheckShadowingDeclModification(Expr * E,SourceLocation Loc)7252 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7253 // Quickly ignore expressions that can't be shadowing ctor parameters.
7254 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7255 return;
7256 E = E->IgnoreParenImpCasts();
7257 auto *DRE = dyn_cast<DeclRefExpr>(E);
7258 if (!DRE)
7259 return;
7260 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7261 auto I = ShadowingDecls.find(D);
7262 if (I == ShadowingDecls.end())
7263 return;
7264 const NamedDecl *ShadowedDecl = I->second;
7265 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7266 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7267 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7268 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7269
7270 // Avoid issuing multiple warnings about the same decl.
7271 ShadowingDecls.erase(I);
7272 }
7273
7274 /// Check for conflict between this global or extern "C" declaration and
7275 /// previous global or extern "C" declarations. This is only used in C++.
7276 template<typename T>
checkGlobalOrExternCConflict(Sema & S,const T * ND,bool IsGlobal,LookupResult & Previous)7277 static bool checkGlobalOrExternCConflict(
7278 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7279 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7280 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7281
7282 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7283 // The common case: this global doesn't conflict with any extern "C"
7284 // declaration.
7285 return false;
7286 }
7287
7288 if (Prev) {
7289 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7290 // Both the old and new declarations have C language linkage. This is a
7291 // redeclaration.
7292 Previous.clear();
7293 Previous.addDecl(Prev);
7294 return true;
7295 }
7296
7297 // This is a global, non-extern "C" declaration, and there is a previous
7298 // non-global extern "C" declaration. Diagnose if this is a variable
7299 // declaration.
7300 if (!isa<VarDecl>(ND))
7301 return false;
7302 } else {
7303 // The declaration is extern "C". Check for any declaration in the
7304 // translation unit which might conflict.
7305 if (IsGlobal) {
7306 // We have already performed the lookup into the translation unit.
7307 IsGlobal = false;
7308 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7309 I != E; ++I) {
7310 if (isa<VarDecl>(*I)) {
7311 Prev = *I;
7312 break;
7313 }
7314 }
7315 } else {
7316 DeclContext::lookup_result R =
7317 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7318 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7319 I != E; ++I) {
7320 if (isa<VarDecl>(*I)) {
7321 Prev = *I;
7322 break;
7323 }
7324 // FIXME: If we have any other entity with this name in global scope,
7325 // the declaration is ill-formed, but that is a defect: it breaks the
7326 // 'stat' hack, for instance. Only variables can have mangled name
7327 // clashes with extern "C" declarations, so only they deserve a
7328 // diagnostic.
7329 }
7330 }
7331
7332 if (!Prev)
7333 return false;
7334 }
7335
7336 // Use the first declaration's location to ensure we point at something which
7337 // is lexically inside an extern "C" linkage-spec.
7338 assert(Prev && "should have found a previous declaration to diagnose");
7339 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7340 Prev = FD->getFirstDecl();
7341 else
7342 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7343
7344 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7345 << IsGlobal << ND;
7346 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7347 << IsGlobal;
7348 return false;
7349 }
7350
7351 /// Apply special rules for handling extern "C" declarations. Returns \c true
7352 /// if we have found that this is a redeclaration of some prior entity.
7353 ///
7354 /// Per C++ [dcl.link]p6:
7355 /// Two declarations [for a function or variable] with C language linkage
7356 /// with the same name that appear in different scopes refer to the same
7357 /// [entity]. An entity with C language linkage shall not be declared with
7358 /// the same name as an entity in global scope.
7359 template<typename T>
checkForConflictWithNonVisibleExternC(Sema & S,const T * ND,LookupResult & Previous)7360 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7361 LookupResult &Previous) {
7362 if (!S.getLangOpts().CPlusPlus) {
7363 // In C, when declaring a global variable, look for a corresponding 'extern'
7364 // variable declared in function scope. We don't need this in C++, because
7365 // we find local extern decls in the surrounding file-scope DeclContext.
7366 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7367 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7368 Previous.clear();
7369 Previous.addDecl(Prev);
7370 return true;
7371 }
7372 }
7373 return false;
7374 }
7375
7376 // A declaration in the translation unit can conflict with an extern "C"
7377 // declaration.
7378 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7379 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7380
7381 // An extern "C" declaration can conflict with a declaration in the
7382 // translation unit or can be a redeclaration of an extern "C" declaration
7383 // in another scope.
7384 if (isIncompleteDeclExternC(S,ND))
7385 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7386
7387 // Neither global nor extern "C": nothing to do.
7388 return false;
7389 }
7390
CheckVariableDeclarationType(VarDecl * NewVD)7391 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7392 // If the decl is already known invalid, don't check it.
7393 if (NewVD->isInvalidDecl())
7394 return;
7395
7396 QualType T = NewVD->getType();
7397
7398 // Defer checking an 'auto' type until its initializer is attached.
7399 if (T->isUndeducedType())
7400 return;
7401
7402 if (NewVD->hasAttrs())
7403 CheckAlignasUnderalignment(NewVD);
7404
7405 if (T->isObjCObjectType()) {
7406 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7407 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7408 T = Context.getObjCObjectPointerType(T);
7409 NewVD->setType(T);
7410 }
7411
7412 // Emit an error if an address space was applied to decl with local storage.
7413 // This includes arrays of objects with address space qualifiers, but not
7414 // automatic variables that point to other address spaces.
7415 // ISO/IEC TR 18037 S5.1.2
7416 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7417 T.getAddressSpace() != LangAS::Default) {
7418 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7419 NewVD->setInvalidDecl();
7420 return;
7421 }
7422
7423 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7424 // scope.
7425 if (getLangOpts().OpenCLVersion == 120 &&
7426 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7427 NewVD->isStaticLocal()) {
7428 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7429 NewVD->setInvalidDecl();
7430 return;
7431 }
7432
7433 if (getLangOpts().OpenCL) {
7434 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7435 if (NewVD->hasAttr<BlocksAttr>()) {
7436 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7437 return;
7438 }
7439
7440 if (T->isBlockPointerType()) {
7441 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7442 // can't use 'extern' storage class.
7443 if (!T.isConstQualified()) {
7444 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7445 << 0 /*const*/;
7446 NewVD->setInvalidDecl();
7447 return;
7448 }
7449 if (NewVD->hasExternalStorage()) {
7450 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7451 NewVD->setInvalidDecl();
7452 return;
7453 }
7454 }
7455 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7456 // __constant address space.
7457 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7458 // variables inside a function can also be declared in the global
7459 // address space.
7460 // C++ for OpenCL inherits rule from OpenCL C v2.0.
7461 // FIXME: Adding local AS in C++ for OpenCL might make sense.
7462 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7463 NewVD->hasExternalStorage()) {
7464 if (!T->isSamplerT() &&
7465 !(T.getAddressSpace() == LangAS::opencl_constant ||
7466 (T.getAddressSpace() == LangAS::opencl_global &&
7467 (getLangOpts().OpenCLVersion == 200 ||
7468 getLangOpts().OpenCLCPlusPlus)))) {
7469 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7470 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7471 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7472 << Scope << "global or constant";
7473 else
7474 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7475 << Scope << "constant";
7476 NewVD->setInvalidDecl();
7477 return;
7478 }
7479 } else {
7480 if (T.getAddressSpace() == LangAS::opencl_global) {
7481 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7482 << 1 /*is any function*/ << "global";
7483 NewVD->setInvalidDecl();
7484 return;
7485 }
7486 if (T.getAddressSpace() == LangAS::opencl_constant ||
7487 T.getAddressSpace() == LangAS::opencl_local) {
7488 FunctionDecl *FD = getCurFunctionDecl();
7489 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7490 // in functions.
7491 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7492 if (T.getAddressSpace() == LangAS::opencl_constant)
7493 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7494 << 0 /*non-kernel only*/ << "constant";
7495 else
7496 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7497 << 0 /*non-kernel only*/ << "local";
7498 NewVD->setInvalidDecl();
7499 return;
7500 }
7501 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7502 // in the outermost scope of a kernel function.
7503 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7504 if (!getCurScope()->isFunctionScope()) {
7505 if (T.getAddressSpace() == LangAS::opencl_constant)
7506 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7507 << "constant";
7508 else
7509 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7510 << "local";
7511 NewVD->setInvalidDecl();
7512 return;
7513 }
7514 }
7515 } else if (T.getAddressSpace() != LangAS::opencl_private &&
7516 // If we are parsing a template we didn't deduce an addr
7517 // space yet.
7518 T.getAddressSpace() != LangAS::Default) {
7519 // Do not allow other address spaces on automatic variable.
7520 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7521 NewVD->setInvalidDecl();
7522 return;
7523 }
7524 }
7525 }
7526
7527 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7528 && !NewVD->hasAttr<BlocksAttr>()) {
7529 if (getLangOpts().getGC() != LangOptions::NonGC)
7530 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7531 else {
7532 assert(!getLangOpts().ObjCAutoRefCount);
7533 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7534 }
7535 }
7536
7537 bool isVM = T->isVariablyModifiedType();
7538 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7539 NewVD->hasAttr<BlocksAttr>())
7540 setFunctionHasBranchProtectedScope();
7541
7542 if ((isVM && NewVD->hasLinkage()) ||
7543 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7544 bool SizeIsNegative;
7545 llvm::APSInt Oversized;
7546 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7547 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7548 QualType FixedT;
7549 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
7550 FixedT = FixedTInfo->getType();
7551 else if (FixedTInfo) {
7552 // Type and type-as-written are canonically different. We need to fix up
7553 // both types separately.
7554 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7555 Oversized);
7556 }
7557 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7558 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7559 // FIXME: This won't give the correct result for
7560 // int a[10][n];
7561 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7562
7563 if (NewVD->isFileVarDecl())
7564 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7565 << SizeRange;
7566 else if (NewVD->isStaticLocal())
7567 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7568 << SizeRange;
7569 else
7570 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7571 << SizeRange;
7572 NewVD->setInvalidDecl();
7573 return;
7574 }
7575
7576 if (!FixedTInfo) {
7577 if (NewVD->isFileVarDecl())
7578 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7579 else
7580 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7581 NewVD->setInvalidDecl();
7582 return;
7583 }
7584
7585 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7586 NewVD->setType(FixedT);
7587 NewVD->setTypeSourceInfo(FixedTInfo);
7588 }
7589
7590 if (T->isVoidType()) {
7591 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7592 // of objects and functions.
7593 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7594 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7595 << T;
7596 NewVD->setInvalidDecl();
7597 return;
7598 }
7599 }
7600
7601 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7602 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7603 NewVD->setInvalidDecl();
7604 return;
7605 }
7606
7607 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7608 Diag(NewVD->getLocation(), diag::err_block_on_vm);
7609 NewVD->setInvalidDecl();
7610 return;
7611 }
7612
7613 if (NewVD->isConstexpr() && !T->isDependentType() &&
7614 RequireLiteralType(NewVD->getLocation(), T,
7615 diag::err_constexpr_var_non_literal)) {
7616 NewVD->setInvalidDecl();
7617 return;
7618 }
7619 }
7620
7621 /// Perform semantic checking on a newly-created variable
7622 /// declaration.
7623 ///
7624 /// This routine performs all of the type-checking required for a
7625 /// variable declaration once it has been built. It is used both to
7626 /// check variables after they have been parsed and their declarators
7627 /// have been translated into a declaration, and to check variables
7628 /// that have been instantiated from a template.
7629 ///
7630 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7631 ///
7632 /// Returns true if the variable declaration is a redeclaration.
CheckVariableDeclaration(VarDecl * NewVD,LookupResult & Previous)7633 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7634 CheckVariableDeclarationType(NewVD);
7635
7636 // If the decl is already known invalid, don't check it.
7637 if (NewVD->isInvalidDecl())
7638 return false;
7639
7640 // If we did not find anything by this name, look for a non-visible
7641 // extern "C" declaration with the same name.
7642 if (Previous.empty() &&
7643 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7644 Previous.setShadowed();
7645
7646 if (!Previous.empty()) {
7647 MergeVarDecl(NewVD, Previous);
7648 return true;
7649 }
7650 return false;
7651 }
7652
7653 namespace {
7654 struct FindOverriddenMethod {
7655 Sema *S;
7656 CXXMethodDecl *Method;
7657
7658 /// Member lookup function that determines whether a given C++
7659 /// method overrides a method in a base class, to be used with
7660 /// CXXRecordDecl::lookupInBases().
operator ()__anon63d8c17d0811::FindOverriddenMethod7661 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7662 RecordDecl *BaseRecord =
7663 Specifier->getType()->getAs<RecordType>()->getDecl();
7664
7665 DeclarationName Name = Method->getDeclName();
7666
7667 // FIXME: Do we care about other names here too?
7668 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7669 // We really want to find the base class destructor here.
7670 QualType T = S->Context.getTypeDeclType(BaseRecord);
7671 CanQualType CT = S->Context.getCanonicalType(T);
7672
7673 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7674 }
7675
7676 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7677 Path.Decls = Path.Decls.slice(1)) {
7678 NamedDecl *D = Path.Decls.front();
7679 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7680 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7681 return true;
7682 }
7683 }
7684
7685 return false;
7686 }
7687 };
7688
7689 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7690 } // end anonymous namespace
7691
7692 /// Report an error regarding overriding, along with any relevant
7693 /// overridden methods.
7694 ///
7695 /// \param DiagID the primary error to report.
7696 /// \param MD the overriding method.
7697 /// \param OEK which overrides to include as notes.
ReportOverrides(Sema & S,unsigned DiagID,const CXXMethodDecl * MD,OverrideErrorKind OEK=OEK_All)7698 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7699 OverrideErrorKind OEK = OEK_All) {
7700 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7701 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7702 // This check (& the OEK parameter) could be replaced by a predicate, but
7703 // without lambdas that would be overkill. This is still nicer than writing
7704 // out the diag loop 3 times.
7705 if ((OEK == OEK_All) ||
7706 (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7707 (OEK == OEK_Deleted && O->isDeleted()))
7708 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7709 }
7710 }
7711
7712 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7713 /// and if so, check that it's a valid override and remember it.
AddOverriddenMethods(CXXRecordDecl * DC,CXXMethodDecl * MD)7714 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7715 // Look for methods in base classes that this method might override.
7716 CXXBasePaths Paths;
7717 FindOverriddenMethod FOM;
7718 FOM.Method = MD;
7719 FOM.S = this;
7720 bool hasDeletedOverridenMethods = false;
7721 bool hasNonDeletedOverridenMethods = false;
7722 bool AddedAny = false;
7723 if (DC->lookupInBases(FOM, Paths)) {
7724 for (auto *I : Paths.found_decls()) {
7725 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7726 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7727 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7728 !CheckOverridingFunctionAttributes(MD, OldMD) &&
7729 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7730 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7731 hasDeletedOverridenMethods |= OldMD->isDeleted();
7732 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7733 AddedAny = true;
7734 }
7735 }
7736 }
7737 }
7738
7739 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7740 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7741 }
7742 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7743 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7744 }
7745
7746 return AddedAny;
7747 }
7748
7749 namespace {
7750 // Struct for holding all of the extra arguments needed by
7751 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7752 struct ActOnFDArgs {
7753 Scope *S;
7754 Declarator &D;
7755 MultiTemplateParamsArg TemplateParamLists;
7756 bool AddToScope;
7757 };
7758 } // end anonymous namespace
7759
7760 namespace {
7761
7762 // Callback to only accept typo corrections that have a non-zero edit distance.
7763 // Also only accept corrections that have the same parent decl.
7764 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7765 public:
DifferentNameValidatorCCC(ASTContext & Context,FunctionDecl * TypoFD,CXXRecordDecl * Parent)7766 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7767 CXXRecordDecl *Parent)
7768 : Context(Context), OriginalFD(TypoFD),
7769 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7770
ValidateCandidate(const TypoCorrection & candidate)7771 bool ValidateCandidate(const TypoCorrection &candidate) override {
7772 if (candidate.getEditDistance() == 0)
7773 return false;
7774
7775 SmallVector<unsigned, 1> MismatchedParams;
7776 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7777 CDeclEnd = candidate.end();
7778 CDecl != CDeclEnd; ++CDecl) {
7779 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7780
7781 if (FD && !FD->hasBody() &&
7782 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7783 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7784 CXXRecordDecl *Parent = MD->getParent();
7785 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7786 return true;
7787 } else if (!ExpectedParent) {
7788 return true;
7789 }
7790 }
7791 }
7792
7793 return false;
7794 }
7795
clone()7796 std::unique_ptr<CorrectionCandidateCallback> clone() override {
7797 return llvm::make_unique<DifferentNameValidatorCCC>(*this);
7798 }
7799
7800 private:
7801 ASTContext &Context;
7802 FunctionDecl *OriginalFD;
7803 CXXRecordDecl *ExpectedParent;
7804 };
7805
7806 } // end anonymous namespace
7807
MarkTypoCorrectedFunctionDefinition(const NamedDecl * F)7808 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7809 TypoCorrectedFunctionDefinitions.insert(F);
7810 }
7811
7812 /// Generate diagnostics for an invalid function redeclaration.
7813 ///
7814 /// This routine handles generating the diagnostic messages for an invalid
7815 /// function redeclaration, including finding possible similar declarations
7816 /// or performing typo correction if there are no previous declarations with
7817 /// the same name.
7818 ///
7819 /// Returns a NamedDecl iff typo correction was performed and substituting in
7820 /// the new declaration name does not cause new errors.
DiagnoseInvalidRedeclaration(Sema & SemaRef,LookupResult & Previous,FunctionDecl * NewFD,ActOnFDArgs & ExtraArgs,bool IsLocalFriend,Scope * S)7821 static NamedDecl *DiagnoseInvalidRedeclaration(
7822 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7823 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7824 DeclarationName Name = NewFD->getDeclName();
7825 DeclContext *NewDC = NewFD->getDeclContext();
7826 SmallVector<unsigned, 1> MismatchedParams;
7827 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7828 TypoCorrection Correction;
7829 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7830 unsigned DiagMsg =
7831 IsLocalFriend ? diag::err_no_matching_local_friend :
7832 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7833 diag::err_member_decl_does_not_match;
7834 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7835 IsLocalFriend ? Sema::LookupLocalFriendName
7836 : Sema::LookupOrdinaryName,
7837 Sema::ForVisibleRedeclaration);
7838
7839 NewFD->setInvalidDecl();
7840 if (IsLocalFriend)
7841 SemaRef.LookupName(Prev, S);
7842 else
7843 SemaRef.LookupQualifiedName(Prev, NewDC);
7844 assert(!Prev.isAmbiguous() &&
7845 "Cannot have an ambiguity in previous-declaration lookup");
7846 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7847 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
7848 MD ? MD->getParent() : nullptr);
7849 if (!Prev.empty()) {
7850 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7851 Func != FuncEnd; ++Func) {
7852 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7853 if (FD &&
7854 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7855 // Add 1 to the index so that 0 can mean the mismatch didn't
7856 // involve a parameter
7857 unsigned ParamNum =
7858 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7859 NearMatches.push_back(std::make_pair(FD, ParamNum));
7860 }
7861 }
7862 // If the qualified name lookup yielded nothing, try typo correction
7863 } else if ((Correction = SemaRef.CorrectTypo(
7864 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7865 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
7866 IsLocalFriend ? nullptr : NewDC))) {
7867 // Set up everything for the call to ActOnFunctionDeclarator
7868 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7869 ExtraArgs.D.getIdentifierLoc());
7870 Previous.clear();
7871 Previous.setLookupName(Correction.getCorrection());
7872 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7873 CDeclEnd = Correction.end();
7874 CDecl != CDeclEnd; ++CDecl) {
7875 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7876 if (FD && !FD->hasBody() &&
7877 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7878 Previous.addDecl(FD);
7879 }
7880 }
7881 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7882
7883 NamedDecl *Result;
7884 // Retry building the function declaration with the new previous
7885 // declarations, and with errors suppressed.
7886 {
7887 // Trap errors.
7888 Sema::SFINAETrap Trap(SemaRef);
7889
7890 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7891 // pieces need to verify the typo-corrected C++ declaration and hopefully
7892 // eliminate the need for the parameter pack ExtraArgs.
7893 Result = SemaRef.ActOnFunctionDeclarator(
7894 ExtraArgs.S, ExtraArgs.D,
7895 Correction.getCorrectionDecl()->getDeclContext(),
7896 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7897 ExtraArgs.AddToScope);
7898
7899 if (Trap.hasErrorOccurred())
7900 Result = nullptr;
7901 }
7902
7903 if (Result) {
7904 // Determine which correction we picked.
7905 Decl *Canonical = Result->getCanonicalDecl();
7906 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7907 I != E; ++I)
7908 if ((*I)->getCanonicalDecl() == Canonical)
7909 Correction.setCorrectionDecl(*I);
7910
7911 // Let Sema know about the correction.
7912 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7913 SemaRef.diagnoseTypo(
7914 Correction,
7915 SemaRef.PDiag(IsLocalFriend
7916 ? diag::err_no_matching_local_friend_suggest
7917 : diag::err_member_decl_does_not_match_suggest)
7918 << Name << NewDC << IsDefinition);
7919 return Result;
7920 }
7921
7922 // Pretend the typo correction never occurred
7923 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7924 ExtraArgs.D.getIdentifierLoc());
7925 ExtraArgs.D.setRedeclaration(wasRedeclaration);
7926 Previous.clear();
7927 Previous.setLookupName(Name);
7928 }
7929
7930 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7931 << Name << NewDC << IsDefinition << NewFD->getLocation();
7932
7933 bool NewFDisConst = false;
7934 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7935 NewFDisConst = NewMD->isConst();
7936
7937 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7938 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7939 NearMatch != NearMatchEnd; ++NearMatch) {
7940 FunctionDecl *FD = NearMatch->first;
7941 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7942 bool FDisConst = MD && MD->isConst();
7943 bool IsMember = MD || !IsLocalFriend;
7944
7945 // FIXME: These notes are poorly worded for the local friend case.
7946 if (unsigned Idx = NearMatch->second) {
7947 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7948 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7949 if (Loc.isInvalid()) Loc = FD->getLocation();
7950 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7951 : diag::note_local_decl_close_param_match)
7952 << Idx << FDParam->getType()
7953 << NewFD->getParamDecl(Idx - 1)->getType();
7954 } else if (FDisConst != NewFDisConst) {
7955 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7956 << NewFDisConst << FD->getSourceRange().getEnd();
7957 } else
7958 SemaRef.Diag(FD->getLocation(),
7959 IsMember ? diag::note_member_def_close_match
7960 : diag::note_local_decl_close_match);
7961 }
7962 return nullptr;
7963 }
7964
getFunctionStorageClass(Sema & SemaRef,Declarator & D)7965 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7966 switch (D.getDeclSpec().getStorageClassSpec()) {
7967 default: llvm_unreachable("Unknown storage class!");
7968 case DeclSpec::SCS_auto:
7969 case DeclSpec::SCS_register:
7970 case DeclSpec::SCS_mutable:
7971 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7972 diag::err_typecheck_sclass_func);
7973 D.getMutableDeclSpec().ClearStorageClassSpecs();
7974 D.setInvalidType();
7975 break;
7976 case DeclSpec::SCS_unspecified: break;
7977 case DeclSpec::SCS_extern:
7978 if (D.getDeclSpec().isExternInLinkageSpec())
7979 return SC_None;
7980 return SC_Extern;
7981 case DeclSpec::SCS_static: {
7982 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7983 // C99 6.7.1p5:
7984 // The declaration of an identifier for a function that has
7985 // block scope shall have no explicit storage-class specifier
7986 // other than extern
7987 // See also (C++ [dcl.stc]p4).
7988 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7989 diag::err_static_block_func);
7990 break;
7991 } else
7992 return SC_Static;
7993 }
7994 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7995 }
7996
7997 // No explicit storage class has already been returned
7998 return SC_None;
7999 }
8000
CreateNewFunctionDecl(Sema & SemaRef,Declarator & D,DeclContext * DC,QualType & R,TypeSourceInfo * TInfo,StorageClass SC,bool & IsVirtualOkay)8001 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8002 DeclContext *DC, QualType &R,
8003 TypeSourceInfo *TInfo,
8004 StorageClass SC,
8005 bool &IsVirtualOkay) {
8006 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8007 DeclarationName Name = NameInfo.getName();
8008
8009 FunctionDecl *NewFD = nullptr;
8010 bool isInline = D.getDeclSpec().isInlineSpecified();
8011
8012 if (!SemaRef.getLangOpts().CPlusPlus) {
8013 // Determine whether the function was written with a
8014 // prototype. This true when:
8015 // - there is a prototype in the declarator, or
8016 // - the type R of the function is some kind of typedef or other non-
8017 // attributed reference to a type name (which eventually refers to a
8018 // function type).
8019 bool HasPrototype =
8020 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8021 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8022
8023 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8024 R, TInfo, SC, isInline, HasPrototype,
8025 CSK_unspecified);
8026 if (D.isInvalidType())
8027 NewFD->setInvalidDecl();
8028
8029 return NewFD;
8030 }
8031
8032 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8033 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8034 // Check that the return type is not an abstract class type.
8035 // For record types, this is done by the AbstractClassUsageDiagnoser once
8036 // the class has been completely parsed.
8037 if (!DC->isRecord() &&
8038 SemaRef.RequireNonAbstractType(
8039 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
8040 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8041 D.setInvalidType();
8042
8043 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8044 // This is a C++ constructor declaration.
8045 assert(DC->isRecord() &&
8046 "Constructors can only be declared in a member context");
8047
8048 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8049 return CXXConstructorDecl::Create(
8050 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8051 TInfo, ExplicitSpecifier, isInline,
8052 /*isImplicitlyDeclared=*/false, ConstexprKind);
8053
8054 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8055 // This is a C++ destructor declaration.
8056 if (DC->isRecord()) {
8057 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8058 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8059 CXXDestructorDecl *NewDD =
8060 CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
8061 NameInfo, R, TInfo, isInline,
8062 /*isImplicitlyDeclared=*/false);
8063
8064 // If the destructor needs an implicit exception specification, set it
8065 // now. FIXME: It'd be nice to be able to create the right type to start
8066 // with, but the type needs to reference the destructor declaration.
8067 if (SemaRef.getLangOpts().CPlusPlus11)
8068 SemaRef.AdjustDestructorExceptionSpec(NewDD);
8069
8070 IsVirtualOkay = true;
8071 return NewDD;
8072
8073 } else {
8074 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8075 D.setInvalidType();
8076
8077 // Create a FunctionDecl to satisfy the function definition parsing
8078 // code path.
8079 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8080 D.getIdentifierLoc(), Name, R, TInfo, SC,
8081 isInline,
8082 /*hasPrototype=*/true, ConstexprKind);
8083 }
8084
8085 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8086 if (!DC->isRecord()) {
8087 SemaRef.Diag(D.getIdentifierLoc(),
8088 diag::err_conv_function_not_member);
8089 return nullptr;
8090 }
8091
8092 SemaRef.CheckConversionDeclarator(D, R, SC);
8093 IsVirtualOkay = true;
8094 return CXXConversionDecl::Create(
8095 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8096 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8097
8098 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8099 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8100
8101 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8102 ExplicitSpecifier, NameInfo, R, TInfo,
8103 D.getEndLoc());
8104 } else if (DC->isRecord()) {
8105 // If the name of the function is the same as the name of the record,
8106 // then this must be an invalid constructor that has a return type.
8107 // (The parser checks for a return type and makes the declarator a
8108 // constructor if it has no return type).
8109 if (Name.getAsIdentifierInfo() &&
8110 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8111 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8112 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8113 << SourceRange(D.getIdentifierLoc());
8114 return nullptr;
8115 }
8116
8117 // This is a C++ method declaration.
8118 CXXMethodDecl *Ret = CXXMethodDecl::Create(
8119 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8120 TInfo, SC, isInline, ConstexprKind, SourceLocation());
8121 IsVirtualOkay = !Ret->isStatic();
8122 return Ret;
8123 } else {
8124 bool isFriend =
8125 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8126 if (!isFriend && SemaRef.CurContext->isRecord())
8127 return nullptr;
8128
8129 // Determine whether the function was written with a
8130 // prototype. This true when:
8131 // - we're in C++ (where every function has a prototype),
8132 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8133 R, TInfo, SC, isInline, true /*HasPrototype*/,
8134 ConstexprKind);
8135 }
8136 }
8137
8138 enum OpenCLParamType {
8139 ValidKernelParam,
8140 PtrPtrKernelParam,
8141 PtrKernelParam,
8142 InvalidAddrSpacePtrKernelParam,
8143 InvalidKernelParam,
8144 RecordKernelParam
8145 };
8146
isOpenCLSizeDependentType(ASTContext & C,QualType Ty)8147 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8148 // Size dependent types are just typedefs to normal integer types
8149 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8150 // integers other than by their names.
8151 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8152
8153 // Remove typedefs one by one until we reach a typedef
8154 // for a size dependent type.
8155 QualType DesugaredTy = Ty;
8156 do {
8157 ArrayRef<StringRef> Names(SizeTypeNames);
8158 auto Match = llvm::find(Names, DesugaredTy.getAsString());
8159 if (Names.end() != Match)
8160 return true;
8161
8162 Ty = DesugaredTy;
8163 DesugaredTy = Ty.getSingleStepDesugaredType(C);
8164 } while (DesugaredTy != Ty);
8165
8166 return false;
8167 }
8168
getOpenCLKernelParameterType(Sema & S,QualType PT)8169 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8170 if (PT->isPointerType()) {
8171 QualType PointeeType = PT->getPointeeType();
8172 if (PointeeType->isPointerType())
8173 return PtrPtrKernelParam;
8174 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8175 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8176 PointeeType.getAddressSpace() == LangAS::Default)
8177 return InvalidAddrSpacePtrKernelParam;
8178 return PtrKernelParam;
8179 }
8180
8181 // OpenCL v1.2 s6.9.k:
8182 // Arguments to kernel functions in a program cannot be declared with the
8183 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8184 // uintptr_t or a struct and/or union that contain fields declared to be one
8185 // of these built-in scalar types.
8186 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8187 return InvalidKernelParam;
8188
8189 if (PT->isImageType())
8190 return PtrKernelParam;
8191
8192 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8193 return InvalidKernelParam;
8194
8195 // OpenCL extension spec v1.2 s9.5:
8196 // This extension adds support for half scalar and vector types as built-in
8197 // types that can be used for arithmetic operations, conversions etc.
8198 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8199 return InvalidKernelParam;
8200
8201 if (PT->isRecordType())
8202 return RecordKernelParam;
8203
8204 // Look into an array argument to check if it has a forbidden type.
8205 if (PT->isArrayType()) {
8206 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8207 // Call ourself to check an underlying type of an array. Since the
8208 // getPointeeOrArrayElementType returns an innermost type which is not an
8209 // array, this recursive call only happens once.
8210 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8211 }
8212
8213 return ValidKernelParam;
8214 }
8215
checkIsValidOpenCLKernelParameter(Sema & S,Declarator & D,ParmVarDecl * Param,llvm::SmallPtrSetImpl<const Type * > & ValidTypes)8216 static void checkIsValidOpenCLKernelParameter(
8217 Sema &S,
8218 Declarator &D,
8219 ParmVarDecl *Param,
8220 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8221 QualType PT = Param->getType();
8222
8223 // Cache the valid types we encounter to avoid rechecking structs that are
8224 // used again
8225 if (ValidTypes.count(PT.getTypePtr()))
8226 return;
8227
8228 switch (getOpenCLKernelParameterType(S, PT)) {
8229 case PtrPtrKernelParam:
8230 // OpenCL v1.2 s6.9.a:
8231 // A kernel function argument cannot be declared as a
8232 // pointer to a pointer type.
8233 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8234 D.setInvalidType();
8235 return;
8236
8237 case InvalidAddrSpacePtrKernelParam:
8238 // OpenCL v1.0 s6.5:
8239 // __kernel function arguments declared to be a pointer of a type can point
8240 // to one of the following address spaces only : __global, __local or
8241 // __constant.
8242 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8243 D.setInvalidType();
8244 return;
8245
8246 // OpenCL v1.2 s6.9.k:
8247 // Arguments to kernel functions in a program cannot be declared with the
8248 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8249 // uintptr_t or a struct and/or union that contain fields declared to be
8250 // one of these built-in scalar types.
8251
8252 case InvalidKernelParam:
8253 // OpenCL v1.2 s6.8 n:
8254 // A kernel function argument cannot be declared
8255 // of event_t type.
8256 // Do not diagnose half type since it is diagnosed as invalid argument
8257 // type for any function elsewhere.
8258 if (!PT->isHalfType()) {
8259 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8260
8261 // Explain what typedefs are involved.
8262 const TypedefType *Typedef = nullptr;
8263 while ((Typedef = PT->getAs<TypedefType>())) {
8264 SourceLocation Loc = Typedef->getDecl()->getLocation();
8265 // SourceLocation may be invalid for a built-in type.
8266 if (Loc.isValid())
8267 S.Diag(Loc, diag::note_entity_declared_at) << PT;
8268 PT = Typedef->desugar();
8269 }
8270 }
8271
8272 D.setInvalidType();
8273 return;
8274
8275 case PtrKernelParam:
8276 case ValidKernelParam:
8277 ValidTypes.insert(PT.getTypePtr());
8278 return;
8279
8280 case RecordKernelParam:
8281 break;
8282 }
8283
8284 // Track nested structs we will inspect
8285 SmallVector<const Decl *, 4> VisitStack;
8286
8287 // Track where we are in the nested structs. Items will migrate from
8288 // VisitStack to HistoryStack as we do the DFS for bad field.
8289 SmallVector<const FieldDecl *, 4> HistoryStack;
8290 HistoryStack.push_back(nullptr);
8291
8292 // At this point we already handled everything except of a RecordType or
8293 // an ArrayType of a RecordType.
8294 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8295 const RecordType *RecTy =
8296 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8297 const RecordDecl *OrigRecDecl = RecTy->getDecl();
8298
8299 VisitStack.push_back(RecTy->getDecl());
8300 assert(VisitStack.back() && "First decl null?");
8301
8302 do {
8303 const Decl *Next = VisitStack.pop_back_val();
8304 if (!Next) {
8305 assert(!HistoryStack.empty());
8306 // Found a marker, we have gone up a level
8307 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8308 ValidTypes.insert(Hist->getType().getTypePtr());
8309
8310 continue;
8311 }
8312
8313 // Adds everything except the original parameter declaration (which is not a
8314 // field itself) to the history stack.
8315 const RecordDecl *RD;
8316 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8317 HistoryStack.push_back(Field);
8318
8319 QualType FieldTy = Field->getType();
8320 // Other field types (known to be valid or invalid) are handled while we
8321 // walk around RecordDecl::fields().
8322 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8323 "Unexpected type.");
8324 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8325
8326 RD = FieldRecTy->castAs<RecordType>()->getDecl();
8327 } else {
8328 RD = cast<RecordDecl>(Next);
8329 }
8330
8331 // Add a null marker so we know when we've gone back up a level
8332 VisitStack.push_back(nullptr);
8333
8334 for (const auto *FD : RD->fields()) {
8335 QualType QT = FD->getType();
8336
8337 if (ValidTypes.count(QT.getTypePtr()))
8338 continue;
8339
8340 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8341 if (ParamType == ValidKernelParam)
8342 continue;
8343
8344 if (ParamType == RecordKernelParam) {
8345 VisitStack.push_back(FD);
8346 continue;
8347 }
8348
8349 // OpenCL v1.2 s6.9.p:
8350 // Arguments to kernel functions that are declared to be a struct or union
8351 // do not allow OpenCL objects to be passed as elements of the struct or
8352 // union.
8353 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8354 ParamType == InvalidAddrSpacePtrKernelParam) {
8355 S.Diag(Param->getLocation(),
8356 diag::err_record_with_pointers_kernel_param)
8357 << PT->isUnionType()
8358 << PT;
8359 } else {
8360 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8361 }
8362
8363 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8364 << OrigRecDecl->getDeclName();
8365
8366 // We have an error, now let's go back up through history and show where
8367 // the offending field came from
8368 for (ArrayRef<const FieldDecl *>::const_iterator
8369 I = HistoryStack.begin() + 1,
8370 E = HistoryStack.end();
8371 I != E; ++I) {
8372 const FieldDecl *OuterField = *I;
8373 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8374 << OuterField->getType();
8375 }
8376
8377 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8378 << QT->isPointerType()
8379 << QT;
8380 D.setInvalidType();
8381 return;
8382 }
8383 } while (!VisitStack.empty());
8384 }
8385
8386 /// Find the DeclContext in which a tag is implicitly declared if we see an
8387 /// elaborated type specifier in the specified context, and lookup finds
8388 /// nothing.
getTagInjectionContext(DeclContext * DC)8389 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8390 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8391 DC = DC->getParent();
8392 return DC;
8393 }
8394
8395 /// Find the Scope in which a tag is implicitly declared if we see an
8396 /// elaborated type specifier in the specified context, and lookup finds
8397 /// nothing.
getTagInjectionScope(Scope * S,const LangOptions & LangOpts)8398 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8399 while (S->isClassScope() ||
8400 (LangOpts.CPlusPlus &&
8401 S->isFunctionPrototypeScope()) ||
8402 ((S->getFlags() & Scope::DeclScope) == 0) ||
8403 (S->getEntity() && S->getEntity()->isTransparentContext()))
8404 S = S->getParent();
8405 return S;
8406 }
8407
8408 NamedDecl*
ActOnFunctionDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamLists,bool & AddToScope)8409 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8410 TypeSourceInfo *TInfo, LookupResult &Previous,
8411 MultiTemplateParamsArg TemplateParamLists,
8412 bool &AddToScope) {
8413 QualType R = TInfo->getType();
8414
8415 assert(R->isFunctionType());
8416
8417 // TODO: consider using NameInfo for diagnostic.
8418 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8419 DeclarationName Name = NameInfo.getName();
8420 StorageClass SC = getFunctionStorageClass(*this, D);
8421
8422 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8423 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8424 diag::err_invalid_thread)
8425 << DeclSpec::getSpecifierName(TSCS);
8426
8427 if (D.isFirstDeclarationOfMember())
8428 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8429 D.getIdentifierLoc());
8430
8431 bool isFriend = false;
8432 FunctionTemplateDecl *FunctionTemplate = nullptr;
8433 bool isMemberSpecialization = false;
8434 bool isFunctionTemplateSpecialization = false;
8435
8436 bool isDependentClassScopeExplicitSpecialization = false;
8437 bool HasExplicitTemplateArgs = false;
8438 TemplateArgumentListInfo TemplateArgs;
8439
8440 bool isVirtualOkay = false;
8441
8442 DeclContext *OriginalDC = DC;
8443 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8444
8445 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8446 isVirtualOkay);
8447 if (!NewFD) return nullptr;
8448
8449 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8450 NewFD->setTopLevelDeclInObjCContainer();
8451
8452 // Set the lexical context. If this is a function-scope declaration, or has a
8453 // C++ scope specifier, or is the object of a friend declaration, the lexical
8454 // context will be different from the semantic context.
8455 NewFD->setLexicalDeclContext(CurContext);
8456
8457 if (IsLocalExternDecl)
8458 NewFD->setLocalExternDecl();
8459
8460 if (getLangOpts().CPlusPlus) {
8461 bool isInline = D.getDeclSpec().isInlineSpecified();
8462 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8463 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8464 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8465 isFriend = D.getDeclSpec().isFriendSpecified();
8466 if (isFriend && !isInline && D.isFunctionDefinition()) {
8467 // C++ [class.friend]p5
8468 // A function can be defined in a friend declaration of a
8469 // class . . . . Such a function is implicitly inline.
8470 NewFD->setImplicitlyInline();
8471 }
8472
8473 // If this is a method defined in an __interface, and is not a constructor
8474 // or an overloaded operator, then set the pure flag (isVirtual will already
8475 // return true).
8476 if (const CXXRecordDecl *Parent =
8477 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8478 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8479 NewFD->setPure(true);
8480
8481 // C++ [class.union]p2
8482 // A union can have member functions, but not virtual functions.
8483 if (isVirtual && Parent->isUnion())
8484 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8485 }
8486
8487 SetNestedNameSpecifier(*this, NewFD, D);
8488 isMemberSpecialization = false;
8489 isFunctionTemplateSpecialization = false;
8490 if (D.isInvalidType())
8491 NewFD->setInvalidDecl();
8492
8493 // Match up the template parameter lists with the scope specifier, then
8494 // determine whether we have a template or a template specialization.
8495 bool Invalid = false;
8496 if (TemplateParameterList *TemplateParams =
8497 MatchTemplateParametersToScopeSpecifier(
8498 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8499 D.getCXXScopeSpec(),
8500 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8501 ? D.getName().TemplateId
8502 : nullptr,
8503 TemplateParamLists, isFriend, isMemberSpecialization,
8504 Invalid)) {
8505 if (TemplateParams->size() > 0) {
8506 // This is a function template
8507
8508 // Check that we can declare a template here.
8509 if (CheckTemplateDeclScope(S, TemplateParams))
8510 NewFD->setInvalidDecl();
8511
8512 // A destructor cannot be a template.
8513 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8514 Diag(NewFD->getLocation(), diag::err_destructor_template);
8515 NewFD->setInvalidDecl();
8516 }
8517
8518 // If we're adding a template to a dependent context, we may need to
8519 // rebuilding some of the types used within the template parameter list,
8520 // now that we know what the current instantiation is.
8521 if (DC->isDependentContext()) {
8522 ContextRAII SavedContext(*this, DC);
8523 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8524 Invalid = true;
8525 }
8526
8527 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8528 NewFD->getLocation(),
8529 Name, TemplateParams,
8530 NewFD);
8531 FunctionTemplate->setLexicalDeclContext(CurContext);
8532 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8533
8534 // For source fidelity, store the other template param lists.
8535 if (TemplateParamLists.size() > 1) {
8536 NewFD->setTemplateParameterListsInfo(Context,
8537 TemplateParamLists.drop_back(1));
8538 }
8539 } else {
8540 // This is a function template specialization.
8541 isFunctionTemplateSpecialization = true;
8542 // For source fidelity, store all the template param lists.
8543 if (TemplateParamLists.size() > 0)
8544 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8545
8546 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8547 if (isFriend) {
8548 // We want to remove the "template<>", found here.
8549 SourceRange RemoveRange = TemplateParams->getSourceRange();
8550
8551 // If we remove the template<> and the name is not a
8552 // template-id, we're actually silently creating a problem:
8553 // the friend declaration will refer to an untemplated decl,
8554 // and clearly the user wants a template specialization. So
8555 // we need to insert '<>' after the name.
8556 SourceLocation InsertLoc;
8557 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8558 InsertLoc = D.getName().getSourceRange().getEnd();
8559 InsertLoc = getLocForEndOfToken(InsertLoc);
8560 }
8561
8562 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8563 << Name << RemoveRange
8564 << FixItHint::CreateRemoval(RemoveRange)
8565 << FixItHint::CreateInsertion(InsertLoc, "<>");
8566 }
8567 }
8568 } else {
8569 // All template param lists were matched against the scope specifier:
8570 // this is NOT (an explicit specialization of) a template.
8571 if (TemplateParamLists.size() > 0)
8572 // For source fidelity, store all the template param lists.
8573 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8574 }
8575
8576 if (Invalid) {
8577 NewFD->setInvalidDecl();
8578 if (FunctionTemplate)
8579 FunctionTemplate->setInvalidDecl();
8580 }
8581
8582 // C++ [dcl.fct.spec]p5:
8583 // The virtual specifier shall only be used in declarations of
8584 // nonstatic class member functions that appear within a
8585 // member-specification of a class declaration; see 10.3.
8586 //
8587 if (isVirtual && !NewFD->isInvalidDecl()) {
8588 if (!isVirtualOkay) {
8589 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8590 diag::err_virtual_non_function);
8591 } else if (!CurContext->isRecord()) {
8592 // 'virtual' was specified outside of the class.
8593 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8594 diag::err_virtual_out_of_class)
8595 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8596 } else if (NewFD->getDescribedFunctionTemplate()) {
8597 // C++ [temp.mem]p3:
8598 // A member function template shall not be virtual.
8599 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8600 diag::err_virtual_member_function_template)
8601 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8602 } else {
8603 // Okay: Add virtual to the method.
8604 NewFD->setVirtualAsWritten(true);
8605 }
8606
8607 if (getLangOpts().CPlusPlus14 &&
8608 NewFD->getReturnType()->isUndeducedType())
8609 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8610 }
8611
8612 if (getLangOpts().CPlusPlus14 &&
8613 (NewFD->isDependentContext() ||
8614 (isFriend && CurContext->isDependentContext())) &&
8615 NewFD->getReturnType()->isUndeducedType()) {
8616 // If the function template is referenced directly (for instance, as a
8617 // member of the current instantiation), pretend it has a dependent type.
8618 // This is not really justified by the standard, but is the only sane
8619 // thing to do.
8620 // FIXME: For a friend function, we have not marked the function as being
8621 // a friend yet, so 'isDependentContext' on the FD doesn't work.
8622 const FunctionProtoType *FPT =
8623 NewFD->getType()->castAs<FunctionProtoType>();
8624 QualType Result =
8625 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8626 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8627 FPT->getExtProtoInfo()));
8628 }
8629
8630 // C++ [dcl.fct.spec]p3:
8631 // The inline specifier shall not appear on a block scope function
8632 // declaration.
8633 if (isInline && !NewFD->isInvalidDecl()) {
8634 if (CurContext->isFunctionOrMethod()) {
8635 // 'inline' is not allowed on block scope function declaration.
8636 Diag(D.getDeclSpec().getInlineSpecLoc(),
8637 diag::err_inline_declaration_block_scope) << Name
8638 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8639 }
8640 }
8641
8642 // C++ [dcl.fct.spec]p6:
8643 // The explicit specifier shall be used only in the declaration of a
8644 // constructor or conversion function within its class definition;
8645 // see 12.3.1 and 12.3.2.
8646 if (hasExplicit && !NewFD->isInvalidDecl() &&
8647 !isa<CXXDeductionGuideDecl>(NewFD)) {
8648 if (!CurContext->isRecord()) {
8649 // 'explicit' was specified outside of the class.
8650 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8651 diag::err_explicit_out_of_class)
8652 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8653 } else if (!isa<CXXConstructorDecl>(NewFD) &&
8654 !isa<CXXConversionDecl>(NewFD)) {
8655 // 'explicit' was specified on a function that wasn't a constructor
8656 // or conversion function.
8657 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8658 diag::err_explicit_non_ctor_or_conv_function)
8659 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8660 }
8661 }
8662
8663 if (ConstexprKind != CSK_unspecified) {
8664 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8665 // are implicitly inline.
8666 NewFD->setImplicitlyInline();
8667
8668 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8669 // be either constructors or to return a literal type. Therefore,
8670 // destructors cannot be declared constexpr.
8671 if (isa<CXXDestructorDecl>(NewFD))
8672 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8673 << (ConstexprKind == CSK_consteval);
8674 }
8675
8676 // If __module_private__ was specified, mark the function accordingly.
8677 if (D.getDeclSpec().isModulePrivateSpecified()) {
8678 if (isFunctionTemplateSpecialization) {
8679 SourceLocation ModulePrivateLoc
8680 = D.getDeclSpec().getModulePrivateSpecLoc();
8681 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8682 << 0
8683 << FixItHint::CreateRemoval(ModulePrivateLoc);
8684 } else {
8685 NewFD->setModulePrivate();
8686 if (FunctionTemplate)
8687 FunctionTemplate->setModulePrivate();
8688 }
8689 }
8690
8691 if (isFriend) {
8692 if (FunctionTemplate) {
8693 FunctionTemplate->setObjectOfFriendDecl();
8694 FunctionTemplate->setAccess(AS_public);
8695 }
8696 NewFD->setObjectOfFriendDecl();
8697 NewFD->setAccess(AS_public);
8698 }
8699
8700 // If a function is defined as defaulted or deleted, mark it as such now.
8701 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8702 // definition kind to FDK_Definition.
8703 switch (D.getFunctionDefinitionKind()) {
8704 case FDK_Declaration:
8705 case FDK_Definition:
8706 break;
8707
8708 case FDK_Defaulted:
8709 NewFD->setDefaulted();
8710 break;
8711
8712 case FDK_Deleted:
8713 NewFD->setDeletedAsWritten();
8714 break;
8715 }
8716
8717 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8718 D.isFunctionDefinition()) {
8719 // C++ [class.mfct]p2:
8720 // A member function may be defined (8.4) in its class definition, in
8721 // which case it is an inline member function (7.1.2)
8722 NewFD->setImplicitlyInline();
8723 }
8724
8725 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8726 !CurContext->isRecord()) {
8727 // C++ [class.static]p1:
8728 // A data or function member of a class may be declared static
8729 // in a class definition, in which case it is a static member of
8730 // the class.
8731
8732 // Complain about the 'static' specifier if it's on an out-of-line
8733 // member function definition.
8734
8735 // MSVC permits the use of a 'static' storage specifier on an out-of-line
8736 // member function template declaration and class member template
8737 // declaration (MSVC versions before 2015), warn about this.
8738 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8739 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8740 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8741 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8742 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8743 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8744 }
8745
8746 // C++11 [except.spec]p15:
8747 // A deallocation function with no exception-specification is treated
8748 // as if it were specified with noexcept(true).
8749 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8750 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8751 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8752 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8753 NewFD->setType(Context.getFunctionType(
8754 FPT->getReturnType(), FPT->getParamTypes(),
8755 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8756 }
8757
8758 // Filter out previous declarations that don't match the scope.
8759 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8760 D.getCXXScopeSpec().isNotEmpty() ||
8761 isMemberSpecialization ||
8762 isFunctionTemplateSpecialization);
8763
8764 // Handle GNU asm-label extension (encoded as an attribute).
8765 if (Expr *E = (Expr*) D.getAsmLabel()) {
8766 // The parser guarantees this is a string.
8767 StringLiteral *SE = cast<StringLiteral>(E);
8768 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8769 SE->getString(), 0));
8770 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8771 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8772 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8773 if (I != ExtnameUndeclaredIdentifiers.end()) {
8774 if (isDeclExternC(NewFD)) {
8775 NewFD->addAttr(I->second);
8776 ExtnameUndeclaredIdentifiers.erase(I);
8777 } else
8778 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8779 << /*Variable*/0 << NewFD;
8780 }
8781 }
8782
8783 // Copy the parameter declarations from the declarator D to the function
8784 // declaration NewFD, if they are available. First scavenge them into Params.
8785 SmallVector<ParmVarDecl*, 16> Params;
8786 unsigned FTIIdx;
8787 if (D.isFunctionDeclarator(FTIIdx)) {
8788 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8789
8790 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8791 // function that takes no arguments, not a function that takes a
8792 // single void argument.
8793 // We let through "const void" here because Sema::GetTypeForDeclarator
8794 // already checks for that case.
8795 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8796 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8797 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8798 assert(Param->getDeclContext() != NewFD && "Was set before ?");
8799 Param->setDeclContext(NewFD);
8800 Params.push_back(Param);
8801
8802 if (Param->isInvalidDecl())
8803 NewFD->setInvalidDecl();
8804 }
8805 }
8806
8807 if (!getLangOpts().CPlusPlus) {
8808 // In C, find all the tag declarations from the prototype and move them
8809 // into the function DeclContext. Remove them from the surrounding tag
8810 // injection context of the function, which is typically but not always
8811 // the TU.
8812 DeclContext *PrototypeTagContext =
8813 getTagInjectionContext(NewFD->getLexicalDeclContext());
8814 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8815 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8816
8817 // We don't want to reparent enumerators. Look at their parent enum
8818 // instead.
8819 if (!TD) {
8820 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8821 TD = cast<EnumDecl>(ECD->getDeclContext());
8822 }
8823 if (!TD)
8824 continue;
8825 DeclContext *TagDC = TD->getLexicalDeclContext();
8826 if (!TagDC->containsDecl(TD))
8827 continue;
8828 TagDC->removeDecl(TD);
8829 TD->setDeclContext(NewFD);
8830 NewFD->addDecl(TD);
8831
8832 // Preserve the lexical DeclContext if it is not the surrounding tag
8833 // injection context of the FD. In this example, the semantic context of
8834 // E will be f and the lexical context will be S, while both the
8835 // semantic and lexical contexts of S will be f:
8836 // void f(struct S { enum E { a } f; } s);
8837 if (TagDC != PrototypeTagContext)
8838 TD->setLexicalDeclContext(TagDC);
8839 }
8840 }
8841 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8842 // When we're declaring a function with a typedef, typeof, etc as in the
8843 // following example, we'll need to synthesize (unnamed)
8844 // parameters for use in the declaration.
8845 //
8846 // @code
8847 // typedef void fn(int);
8848 // fn f;
8849 // @endcode
8850
8851 // Synthesize a parameter for each argument type.
8852 for (const auto &AI : FT->param_types()) {
8853 ParmVarDecl *Param =
8854 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8855 Param->setScopeInfo(0, Params.size());
8856 Params.push_back(Param);
8857 }
8858 } else {
8859 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8860 "Should not need args for typedef of non-prototype fn");
8861 }
8862
8863 // Finally, we know we have the right number of parameters, install them.
8864 NewFD->setParams(Params);
8865
8866 if (D.getDeclSpec().isNoreturnSpecified())
8867 NewFD->addAttr(
8868 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8869 Context, 0));
8870
8871 // Functions returning a variably modified type violate C99 6.7.5.2p2
8872 // because all functions have linkage.
8873 if (!NewFD->isInvalidDecl() &&
8874 NewFD->getReturnType()->isVariablyModifiedType()) {
8875 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8876 NewFD->setInvalidDecl();
8877 }
8878
8879 // Apply an implicit SectionAttr if '#pragma clang section text' is active
8880 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8881 !NewFD->hasAttr<SectionAttr>()) {
8882 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8883 PragmaClangTextSection.SectionName,
8884 PragmaClangTextSection.PragmaLocation));
8885 }
8886
8887 // Apply an implicit SectionAttr if #pragma code_seg is active.
8888 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8889 !NewFD->hasAttr<SectionAttr>()) {
8890 NewFD->addAttr(
8891 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8892 CodeSegStack.CurrentValue->getString(),
8893 CodeSegStack.CurrentPragmaLocation));
8894 if (UnifySection(CodeSegStack.CurrentValue->getString(),
8895 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8896 ASTContext::PSF_Read,
8897 NewFD))
8898 NewFD->dropAttr<SectionAttr>();
8899 }
8900
8901 // Apply an implicit CodeSegAttr from class declspec or
8902 // apply an implicit SectionAttr from #pragma code_seg if active.
8903 if (!NewFD->hasAttr<CodeSegAttr>()) {
8904 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8905 D.isFunctionDefinition())) {
8906 NewFD->addAttr(SAttr);
8907 }
8908 }
8909
8910 // Handle attributes.
8911 ProcessDeclAttributes(S, NewFD, D);
8912
8913 if (getLangOpts().OpenCL) {
8914 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8915 // type declaration will generate a compilation error.
8916 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8917 if (AddressSpace != LangAS::Default) {
8918 Diag(NewFD->getLocation(),
8919 diag::err_opencl_return_value_with_address_space);
8920 NewFD->setInvalidDecl();
8921 }
8922 }
8923
8924 if (!getLangOpts().CPlusPlus) {
8925 // Perform semantic checking on the function declaration.
8926 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8927 CheckMain(NewFD, D.getDeclSpec());
8928
8929 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8930 CheckMSVCRTEntryPoint(NewFD);
8931
8932 if (!NewFD->isInvalidDecl())
8933 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8934 isMemberSpecialization));
8935 else if (!Previous.empty())
8936 // Recover gracefully from an invalid redeclaration.
8937 D.setRedeclaration(true);
8938 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8939 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8940 "previous declaration set still overloaded");
8941
8942 // Diagnose no-prototype function declarations with calling conventions that
8943 // don't support variadic calls. Only do this in C and do it after merging
8944 // possibly prototyped redeclarations.
8945 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8946 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8947 CallingConv CC = FT->getExtInfo().getCC();
8948 if (!supportsVariadicCall(CC)) {
8949 // Windows system headers sometimes accidentally use stdcall without
8950 // (void) parameters, so we relax this to a warning.
8951 int DiagID =
8952 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8953 Diag(NewFD->getLocation(), DiagID)
8954 << FunctionType::getNameForCallConv(CC);
8955 }
8956 }
8957
8958 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
8959 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
8960 checkNonTrivialCUnion(NewFD->getReturnType(),
8961 NewFD->getReturnTypeSourceRange().getBegin(),
8962 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
8963 } else {
8964 // C++11 [replacement.functions]p3:
8965 // The program's definitions shall not be specified as inline.
8966 //
8967 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8968 //
8969 // Suppress the diagnostic if the function is __attribute__((used)), since
8970 // that forces an external definition to be emitted.
8971 if (D.getDeclSpec().isInlineSpecified() &&
8972 NewFD->isReplaceableGlobalAllocationFunction() &&
8973 !NewFD->hasAttr<UsedAttr>())
8974 Diag(D.getDeclSpec().getInlineSpecLoc(),
8975 diag::ext_operator_new_delete_declared_inline)
8976 << NewFD->getDeclName();
8977
8978 // If the declarator is a template-id, translate the parser's template
8979 // argument list into our AST format.
8980 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8981 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8982 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8983 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8984 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8985 TemplateId->NumArgs);
8986 translateTemplateArguments(TemplateArgsPtr,
8987 TemplateArgs);
8988
8989 HasExplicitTemplateArgs = true;
8990
8991 if (NewFD->isInvalidDecl()) {
8992 HasExplicitTemplateArgs = false;
8993 } else if (FunctionTemplate) {
8994 // Function template with explicit template arguments.
8995 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8996 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8997
8998 HasExplicitTemplateArgs = false;
8999 } else {
9000 assert((isFunctionTemplateSpecialization ||
9001 D.getDeclSpec().isFriendSpecified()) &&
9002 "should have a 'template<>' for this decl");
9003 // "friend void foo<>(int);" is an implicit specialization decl.
9004 isFunctionTemplateSpecialization = true;
9005 }
9006 } else if (isFriend && isFunctionTemplateSpecialization) {
9007 // This combination is only possible in a recovery case; the user
9008 // wrote something like:
9009 // template <> friend void foo(int);
9010 // which we're recovering from as if the user had written:
9011 // friend void foo<>(int);
9012 // Go ahead and fake up a template id.
9013 HasExplicitTemplateArgs = true;
9014 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9015 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9016 }
9017
9018 // We do not add HD attributes to specializations here because
9019 // they may have different constexpr-ness compared to their
9020 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9021 // may end up with different effective targets. Instead, a
9022 // specialization inherits its target attributes from its template
9023 // in the CheckFunctionTemplateSpecialization() call below.
9024 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
9025 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9026
9027 // If it's a friend (and only if it's a friend), it's possible
9028 // that either the specialized function type or the specialized
9029 // template is dependent, and therefore matching will fail. In
9030 // this case, don't check the specialization yet.
9031 bool InstantiationDependent = false;
9032 if (isFunctionTemplateSpecialization && isFriend &&
9033 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9034 TemplateSpecializationType::anyDependentTemplateArguments(
9035 TemplateArgs,
9036 InstantiationDependent))) {
9037 assert(HasExplicitTemplateArgs &&
9038 "friend function specialization without template args");
9039 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9040 Previous))
9041 NewFD->setInvalidDecl();
9042 } else if (isFunctionTemplateSpecialization) {
9043 if (CurContext->isDependentContext() && CurContext->isRecord()
9044 && !isFriend) {
9045 isDependentClassScopeExplicitSpecialization = true;
9046 } else if (!NewFD->isInvalidDecl() &&
9047 CheckFunctionTemplateSpecialization(
9048 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9049 Previous))
9050 NewFD->setInvalidDecl();
9051
9052 // C++ [dcl.stc]p1:
9053 // A storage-class-specifier shall not be specified in an explicit
9054 // specialization (14.7.3)
9055 FunctionTemplateSpecializationInfo *Info =
9056 NewFD->getTemplateSpecializationInfo();
9057 if (Info && SC != SC_None) {
9058 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9059 Diag(NewFD->getLocation(),
9060 diag::err_explicit_specialization_inconsistent_storage_class)
9061 << SC
9062 << FixItHint::CreateRemoval(
9063 D.getDeclSpec().getStorageClassSpecLoc());
9064
9065 else
9066 Diag(NewFD->getLocation(),
9067 diag::ext_explicit_specialization_storage_class)
9068 << FixItHint::CreateRemoval(
9069 D.getDeclSpec().getStorageClassSpecLoc());
9070 }
9071 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9072 if (CheckMemberSpecialization(NewFD, Previous))
9073 NewFD->setInvalidDecl();
9074 }
9075
9076 // Perform semantic checking on the function declaration.
9077 if (!isDependentClassScopeExplicitSpecialization) {
9078 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9079 CheckMain(NewFD, D.getDeclSpec());
9080
9081 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9082 CheckMSVCRTEntryPoint(NewFD);
9083
9084 if (!NewFD->isInvalidDecl())
9085 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9086 isMemberSpecialization));
9087 else if (!Previous.empty())
9088 // Recover gracefully from an invalid redeclaration.
9089 D.setRedeclaration(true);
9090 }
9091
9092 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9093 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9094 "previous declaration set still overloaded");
9095
9096 NamedDecl *PrincipalDecl = (FunctionTemplate
9097 ? cast<NamedDecl>(FunctionTemplate)
9098 : NewFD);
9099
9100 if (isFriend && NewFD->getPreviousDecl()) {
9101 AccessSpecifier Access = AS_public;
9102 if (!NewFD->isInvalidDecl())
9103 Access = NewFD->getPreviousDecl()->getAccess();
9104
9105 NewFD->setAccess(Access);
9106 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9107 }
9108
9109 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9110 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9111 PrincipalDecl->setNonMemberOperator();
9112
9113 // If we have a function template, check the template parameter
9114 // list. This will check and merge default template arguments.
9115 if (FunctionTemplate) {
9116 FunctionTemplateDecl *PrevTemplate =
9117 FunctionTemplate->getPreviousDecl();
9118 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9119 PrevTemplate ? PrevTemplate->getTemplateParameters()
9120 : nullptr,
9121 D.getDeclSpec().isFriendSpecified()
9122 ? (D.isFunctionDefinition()
9123 ? TPC_FriendFunctionTemplateDefinition
9124 : TPC_FriendFunctionTemplate)
9125 : (D.getCXXScopeSpec().isSet() &&
9126 DC && DC->isRecord() &&
9127 DC->isDependentContext())
9128 ? TPC_ClassTemplateMember
9129 : TPC_FunctionTemplate);
9130 }
9131
9132 if (NewFD->isInvalidDecl()) {
9133 // Ignore all the rest of this.
9134 } else if (!D.isRedeclaration()) {
9135 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9136 AddToScope };
9137 // Fake up an access specifier if it's supposed to be a class member.
9138 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9139 NewFD->setAccess(AS_public);
9140
9141 // Qualified decls generally require a previous declaration.
9142 if (D.getCXXScopeSpec().isSet()) {
9143 // ...with the major exception of templated-scope or
9144 // dependent-scope friend declarations.
9145
9146 // TODO: we currently also suppress this check in dependent
9147 // contexts because (1) the parameter depth will be off when
9148 // matching friend templates and (2) we might actually be
9149 // selecting a friend based on a dependent factor. But there
9150 // are situations where these conditions don't apply and we
9151 // can actually do this check immediately.
9152 //
9153 // Unless the scope is dependent, it's always an error if qualified
9154 // redeclaration lookup found nothing at all. Diagnose that now;
9155 // nothing will diagnose that error later.
9156 if (isFriend &&
9157 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9158 (!Previous.empty() && CurContext->isDependentContext()))) {
9159 // ignore these
9160 } else {
9161 // The user tried to provide an out-of-line definition for a
9162 // function that is a member of a class or namespace, but there
9163 // was no such member function declared (C++ [class.mfct]p2,
9164 // C++ [namespace.memdef]p2). For example:
9165 //
9166 // class X {
9167 // void f() const;
9168 // };
9169 //
9170 // void X::f() { } // ill-formed
9171 //
9172 // Complain about this problem, and attempt to suggest close
9173 // matches (e.g., those that differ only in cv-qualifiers and
9174 // whether the parameter types are references).
9175
9176 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9177 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9178 AddToScope = ExtraArgs.AddToScope;
9179 return Result;
9180 }
9181 }
9182
9183 // Unqualified local friend declarations are required to resolve
9184 // to something.
9185 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9186 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9187 *this, Previous, NewFD, ExtraArgs, true, S)) {
9188 AddToScope = ExtraArgs.AddToScope;
9189 return Result;
9190 }
9191 }
9192 } else if (!D.isFunctionDefinition() &&
9193 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9194 !isFriend && !isFunctionTemplateSpecialization &&
9195 !isMemberSpecialization) {
9196 // An out-of-line member function declaration must also be a
9197 // definition (C++ [class.mfct]p2).
9198 // Note that this is not the case for explicit specializations of
9199 // function templates or member functions of class templates, per
9200 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9201 // extension for compatibility with old SWIG code which likes to
9202 // generate them.
9203 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9204 << D.getCXXScopeSpec().getRange();
9205 }
9206 }
9207
9208 ProcessPragmaWeak(S, NewFD);
9209 checkAttributesAfterMerging(*this, *NewFD);
9210
9211 AddKnownFunctionAttributes(NewFD);
9212
9213 if (NewFD->hasAttr<OverloadableAttr>() &&
9214 !NewFD->getType()->getAs<FunctionProtoType>()) {
9215 Diag(NewFD->getLocation(),
9216 diag::err_attribute_overloadable_no_prototype)
9217 << NewFD;
9218
9219 // Turn this into a variadic function with no parameters.
9220 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9221 FunctionProtoType::ExtProtoInfo EPI(
9222 Context.getDefaultCallingConvention(true, false));
9223 EPI.Variadic = true;
9224 EPI.ExtInfo = FT->getExtInfo();
9225
9226 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9227 NewFD->setType(R);
9228 }
9229
9230 // If there's a #pragma GCC visibility in scope, and this isn't a class
9231 // member, set the visibility of this function.
9232 if (!DC->isRecord() && NewFD->isExternallyVisible())
9233 AddPushedVisibilityAttribute(NewFD);
9234
9235 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9236 // marking the function.
9237 AddCFAuditedAttribute(NewFD);
9238
9239 // If this is a function definition, check if we have to apply optnone due to
9240 // a pragma.
9241 if(D.isFunctionDefinition())
9242 AddRangeBasedOptnone(NewFD);
9243
9244 // If this is the first declaration of an extern C variable, update
9245 // the map of such variables.
9246 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9247 isIncompleteDeclExternC(*this, NewFD))
9248 RegisterLocallyScopedExternCDecl(NewFD, S);
9249
9250 // Set this FunctionDecl's range up to the right paren.
9251 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9252
9253 if (D.isRedeclaration() && !Previous.empty()) {
9254 NamedDecl *Prev = Previous.getRepresentativeDecl();
9255 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9256 isMemberSpecialization ||
9257 isFunctionTemplateSpecialization,
9258 D.isFunctionDefinition());
9259 }
9260
9261 if (getLangOpts().CUDA) {
9262 IdentifierInfo *II = NewFD->getIdentifier();
9263 if (II && II->isStr(getCudaConfigureFuncName()) &&
9264 !NewFD->isInvalidDecl() &&
9265 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9266 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9267 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9268 << getCudaConfigureFuncName();
9269 Context.setcudaConfigureCallDecl(NewFD);
9270 }
9271
9272 // Variadic functions, other than a *declaration* of printf, are not allowed
9273 // in device-side CUDA code, unless someone passed
9274 // -fcuda-allow-variadic-functions.
9275 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9276 (NewFD->hasAttr<CUDADeviceAttr>() ||
9277 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9278 !(II && II->isStr("printf") && NewFD->isExternC() &&
9279 !D.isFunctionDefinition())) {
9280 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9281 }
9282 }
9283
9284 MarkUnusedFileScopedDecl(NewFD);
9285
9286
9287
9288 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9289 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9290 if ((getLangOpts().OpenCLVersion >= 120)
9291 && (SC == SC_Static)) {
9292 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9293 D.setInvalidType();
9294 }
9295
9296 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9297 if (!NewFD->getReturnType()->isVoidType()) {
9298 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9299 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9300 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9301 : FixItHint());
9302 D.setInvalidType();
9303 }
9304
9305 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9306 for (auto Param : NewFD->parameters())
9307 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9308
9309 if (getLangOpts().OpenCLCPlusPlus) {
9310 if (DC->isRecord()) {
9311 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9312 D.setInvalidType();
9313 }
9314 if (FunctionTemplate) {
9315 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9316 D.setInvalidType();
9317 }
9318 }
9319 }
9320
9321 if (getLangOpts().CPlusPlus) {
9322 if (FunctionTemplate) {
9323 if (NewFD->isInvalidDecl())
9324 FunctionTemplate->setInvalidDecl();
9325 return FunctionTemplate;
9326 }
9327
9328 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9329 CompleteMemberSpecialization(NewFD, Previous);
9330 }
9331
9332 for (const ParmVarDecl *Param : NewFD->parameters()) {
9333 QualType PT = Param->getType();
9334
9335 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9336 // types.
9337 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9338 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9339 QualType ElemTy = PipeTy->getElementType();
9340 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9341 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9342 D.setInvalidType();
9343 }
9344 }
9345 }
9346 }
9347
9348 // Here we have an function template explicit specialization at class scope.
9349 // The actual specialization will be postponed to template instatiation
9350 // time via the ClassScopeFunctionSpecializationDecl node.
9351 if (isDependentClassScopeExplicitSpecialization) {
9352 ClassScopeFunctionSpecializationDecl *NewSpec =
9353 ClassScopeFunctionSpecializationDecl::Create(
9354 Context, CurContext, NewFD->getLocation(),
9355 cast<CXXMethodDecl>(NewFD),
9356 HasExplicitTemplateArgs, TemplateArgs);
9357 CurContext->addDecl(NewSpec);
9358 AddToScope = false;
9359 }
9360
9361 // Diagnose availability attributes. Availability cannot be used on functions
9362 // that are run during load/unload.
9363 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9364 if (NewFD->hasAttr<ConstructorAttr>()) {
9365 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9366 << 1;
9367 NewFD->dropAttr<AvailabilityAttr>();
9368 }
9369 if (NewFD->hasAttr<DestructorAttr>()) {
9370 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9371 << 2;
9372 NewFD->dropAttr<AvailabilityAttr>();
9373 }
9374 }
9375
9376 return NewFD;
9377 }
9378
9379 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
9380 /// when __declspec(code_seg) "is applied to a class, all member functions of
9381 /// the class and nested classes -- this includes compiler-generated special
9382 /// member functions -- are put in the specified segment."
9383 /// The actual behavior is a little more complicated. The Microsoft compiler
9384 /// won't check outer classes if there is an active value from #pragma code_seg.
9385 /// The CodeSeg is always applied from the direct parent but only from outer
9386 /// classes when the #pragma code_seg stack is empty. See:
9387 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9388 /// available since MS has removed the page.
getImplicitCodeSegAttrFromClass(Sema & S,const FunctionDecl * FD)9389 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9390 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9391 if (!Method)
9392 return nullptr;
9393 const CXXRecordDecl *Parent = Method->getParent();
9394 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9395 Attr *NewAttr = SAttr->clone(S.getASTContext());
9396 NewAttr->setImplicit(true);
9397 return NewAttr;
9398 }
9399
9400 // The Microsoft compiler won't check outer classes for the CodeSeg
9401 // when the #pragma code_seg stack is active.
9402 if (S.CodeSegStack.CurrentValue)
9403 return nullptr;
9404
9405 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9406 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9407 Attr *NewAttr = SAttr->clone(S.getASTContext());
9408 NewAttr->setImplicit(true);
9409 return NewAttr;
9410 }
9411 }
9412 return nullptr;
9413 }
9414
9415 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9416 /// containing class. Otherwise it will return implicit SectionAttr if the
9417 /// function is a definition and there is an active value on CodeSegStack
9418 /// (from the current #pragma code-seg value).
9419 ///
9420 /// \param FD Function being declared.
9421 /// \param IsDefinition Whether it is a definition or just a declarartion.
9422 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9423 /// nullptr if no attribute should be added.
getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl * FD,bool IsDefinition)9424 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9425 bool IsDefinition) {
9426 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9427 return A;
9428 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9429 CodeSegStack.CurrentValue) {
9430 return SectionAttr::CreateImplicit(getASTContext(),
9431 SectionAttr::Declspec_allocate,
9432 CodeSegStack.CurrentValue->getString(),
9433 CodeSegStack.CurrentPragmaLocation);
9434 }
9435 return nullptr;
9436 }
9437
9438 /// Determines if we can perform a correct type check for \p D as a
9439 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9440 /// best-effort check.
9441 ///
9442 /// \param NewD The new declaration.
9443 /// \param OldD The old declaration.
9444 /// \param NewT The portion of the type of the new declaration to check.
9445 /// \param OldT The portion of the type of the old declaration to check.
canFullyTypeCheckRedeclaration(ValueDecl * NewD,ValueDecl * OldD,QualType NewT,QualType OldT)9446 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9447 QualType NewT, QualType OldT) {
9448 if (!NewD->getLexicalDeclContext()->isDependentContext())
9449 return true;
9450
9451 // For dependently-typed local extern declarations and friends, we can't
9452 // perform a correct type check in general until instantiation:
9453 //
9454 // int f();
9455 // template<typename T> void g() { T f(); }
9456 //
9457 // (valid if g() is only instantiated with T = int).
9458 if (NewT->isDependentType() &&
9459 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9460 return false;
9461
9462 // Similarly, if the previous declaration was a dependent local extern
9463 // declaration, we don't really know its type yet.
9464 if (OldT->isDependentType() && OldD->isLocalExternDecl())
9465 return false;
9466
9467 return true;
9468 }
9469
9470 /// Checks if the new declaration declared in dependent context must be
9471 /// put in the same redeclaration chain as the specified declaration.
9472 ///
9473 /// \param D Declaration that is checked.
9474 /// \param PrevDecl Previous declaration found with proper lookup method for the
9475 /// same declaration name.
9476 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9477 /// belongs to.
9478 ///
shouldLinkDependentDeclWithPrevious(Decl * D,Decl * PrevDecl)9479 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9480 if (!D->getLexicalDeclContext()->isDependentContext())
9481 return true;
9482
9483 // Don't chain dependent friend function definitions until instantiation, to
9484 // permit cases like
9485 //
9486 // void func();
9487 // template<typename T> class C1 { friend void func() {} };
9488 // template<typename T> class C2 { friend void func() {} };
9489 //
9490 // ... which is valid if only one of C1 and C2 is ever instantiated.
9491 //
9492 // FIXME: This need only apply to function definitions. For now, we proxy
9493 // this by checking for a file-scope function. We do not want this to apply
9494 // to friend declarations nominating member functions, because that gets in
9495 // the way of access checks.
9496 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9497 return false;
9498
9499 auto *VD = dyn_cast<ValueDecl>(D);
9500 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9501 return !VD || !PrevVD ||
9502 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9503 PrevVD->getType());
9504 }
9505
9506 /// Check the target attribute of the function for MultiVersion
9507 /// validity.
9508 ///
9509 /// Returns true if there was an error, false otherwise.
CheckMultiVersionValue(Sema & S,const FunctionDecl * FD)9510 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9511 const auto *TA = FD->getAttr<TargetAttr>();
9512 assert(TA && "MultiVersion Candidate requires a target attribute");
9513 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9514 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9515 enum ErrType { Feature = 0, Architecture = 1 };
9516
9517 if (!ParseInfo.Architecture.empty() &&
9518 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9519 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9520 << Architecture << ParseInfo.Architecture;
9521 return true;
9522 }
9523
9524 for (const auto &Feat : ParseInfo.Features) {
9525 auto BareFeat = StringRef{Feat}.substr(1);
9526 if (Feat[0] == '-') {
9527 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9528 << Feature << ("no-" + BareFeat).str();
9529 return true;
9530 }
9531
9532 if (!TargetInfo.validateCpuSupports(BareFeat) ||
9533 !TargetInfo.isValidFeatureName(BareFeat)) {
9534 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9535 << Feature << BareFeat;
9536 return true;
9537 }
9538 }
9539 return false;
9540 }
9541
HasNonMultiVersionAttributes(const FunctionDecl * FD,MultiVersionKind MVType)9542 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9543 MultiVersionKind MVType) {
9544 for (const Attr *A : FD->attrs()) {
9545 switch (A->getKind()) {
9546 case attr::CPUDispatch:
9547 case attr::CPUSpecific:
9548 if (MVType != MultiVersionKind::CPUDispatch &&
9549 MVType != MultiVersionKind::CPUSpecific)
9550 return true;
9551 break;
9552 case attr::Target:
9553 if (MVType != MultiVersionKind::Target)
9554 return true;
9555 break;
9556 default:
9557 return true;
9558 }
9559 }
9560 return false;
9561 }
9562
CheckMultiVersionAdditionalRules(Sema & S,const FunctionDecl * OldFD,const FunctionDecl * NewFD,bool CausesMV,MultiVersionKind MVType)9563 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9564 const FunctionDecl *NewFD,
9565 bool CausesMV,
9566 MultiVersionKind MVType) {
9567 enum DoesntSupport {
9568 FuncTemplates = 0,
9569 VirtFuncs = 1,
9570 DeducedReturn = 2,
9571 Constructors = 3,
9572 Destructors = 4,
9573 DeletedFuncs = 5,
9574 DefaultedFuncs = 6,
9575 ConstexprFuncs = 7,
9576 ConstevalFuncs = 8,
9577 };
9578 enum Different {
9579 CallingConv = 0,
9580 ReturnType = 1,
9581 ConstexprSpec = 2,
9582 InlineSpec = 3,
9583 StorageClass = 4,
9584 Linkage = 5
9585 };
9586
9587 bool IsCPUSpecificCPUDispatchMVType =
9588 MVType == MultiVersionKind::CPUDispatch ||
9589 MVType == MultiVersionKind::CPUSpecific;
9590
9591 if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9592 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9593 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9594 return true;
9595 }
9596
9597 if (!NewFD->getType()->getAs<FunctionProtoType>())
9598 return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9599
9600 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9601 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9602 if (OldFD)
9603 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9604 return true;
9605 }
9606
9607 // For now, disallow all other attributes. These should be opt-in, but
9608 // an analysis of all of them is a future FIXME.
9609 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9610 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9611 << IsCPUSpecificCPUDispatchMVType;
9612 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9613 return true;
9614 }
9615
9616 if (HasNonMultiVersionAttributes(NewFD, MVType))
9617 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9618 << IsCPUSpecificCPUDispatchMVType;
9619
9620 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9621 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9622 << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9623
9624 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9625 if (NewCXXFD->isVirtual())
9626 return S.Diag(NewCXXFD->getLocation(),
9627 diag::err_multiversion_doesnt_support)
9628 << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9629
9630 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9631 return S.Diag(NewCXXCtor->getLocation(),
9632 diag::err_multiversion_doesnt_support)
9633 << IsCPUSpecificCPUDispatchMVType << Constructors;
9634
9635 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9636 return S.Diag(NewCXXDtor->getLocation(),
9637 diag::err_multiversion_doesnt_support)
9638 << IsCPUSpecificCPUDispatchMVType << Destructors;
9639 }
9640
9641 if (NewFD->isDeleted())
9642 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9643 << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9644
9645 if (NewFD->isDefaulted())
9646 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9647 << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9648
9649 if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9650 MVType == MultiVersionKind::CPUSpecific))
9651 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9652 << IsCPUSpecificCPUDispatchMVType
9653 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9654
9655 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9656 const auto *NewType = cast<FunctionType>(NewQType);
9657 QualType NewReturnType = NewType->getReturnType();
9658
9659 if (NewReturnType->isUndeducedType())
9660 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9661 << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9662
9663 // Only allow transition to MultiVersion if it hasn't been used.
9664 if (OldFD && CausesMV && OldFD->isUsed(false))
9665 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9666
9667 // Ensure the return type is identical.
9668 if (OldFD) {
9669 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9670 const auto *OldType = cast<FunctionType>(OldQType);
9671 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9672 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9673
9674 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9675 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9676 << CallingConv;
9677
9678 QualType OldReturnType = OldType->getReturnType();
9679
9680 if (OldReturnType != NewReturnType)
9681 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9682 << ReturnType;
9683
9684 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9685 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9686 << ConstexprSpec;
9687
9688 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9689 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9690 << InlineSpec;
9691
9692 if (OldFD->getStorageClass() != NewFD->getStorageClass())
9693 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9694 << StorageClass;
9695
9696 if (OldFD->isExternC() != NewFD->isExternC())
9697 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9698 << Linkage;
9699
9700 if (S.CheckEquivalentExceptionSpec(
9701 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9702 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9703 return true;
9704 }
9705 return false;
9706 }
9707
9708 /// Check the validity of a multiversion function declaration that is the
9709 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9710 ///
9711 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9712 ///
9713 /// Returns true if there was an error, false otherwise.
CheckMultiVersionFirstFunction(Sema & S,FunctionDecl * FD,MultiVersionKind MVType,const TargetAttr * TA)9714 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9715 MultiVersionKind MVType,
9716 const TargetAttr *TA) {
9717 assert(MVType != MultiVersionKind::None &&
9718 "Function lacks multiversion attribute");
9719
9720 // Target only causes MV if it is default, otherwise this is a normal
9721 // function.
9722 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9723 return false;
9724
9725 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9726 FD->setInvalidDecl();
9727 return true;
9728 }
9729
9730 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9731 FD->setInvalidDecl();
9732 return true;
9733 }
9734
9735 FD->setIsMultiVersion();
9736 return false;
9737 }
9738
PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl * FD)9739 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9740 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9741 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9742 return true;
9743 }
9744
9745 return false;
9746 }
9747
CheckTargetCausesMultiVersioning(Sema & S,FunctionDecl * OldFD,FunctionDecl * NewFD,const TargetAttr * NewTA,bool & Redeclaration,NamedDecl * & OldDecl,bool & MergeTypeWithPrevious,LookupResult & Previous)9748 static bool CheckTargetCausesMultiVersioning(
9749 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9750 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9751 LookupResult &Previous) {
9752 const auto *OldTA = OldFD->getAttr<TargetAttr>();
9753 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9754 // Sort order doesn't matter, it just needs to be consistent.
9755 llvm::sort(NewParsed.Features);
9756
9757 // If the old decl is NOT MultiVersioned yet, and we don't cause that
9758 // to change, this is a simple redeclaration.
9759 if (!NewTA->isDefaultVersion() &&
9760 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9761 return false;
9762
9763 // Otherwise, this decl causes MultiVersioning.
9764 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9765 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9766 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9767 NewFD->setInvalidDecl();
9768 return true;
9769 }
9770
9771 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9772 MultiVersionKind::Target)) {
9773 NewFD->setInvalidDecl();
9774 return true;
9775 }
9776
9777 if (CheckMultiVersionValue(S, NewFD)) {
9778 NewFD->setInvalidDecl();
9779 return true;
9780 }
9781
9782 // If this is 'default', permit the forward declaration.
9783 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9784 Redeclaration = true;
9785 OldDecl = OldFD;
9786 OldFD->setIsMultiVersion();
9787 NewFD->setIsMultiVersion();
9788 return false;
9789 }
9790
9791 if (CheckMultiVersionValue(S, OldFD)) {
9792 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9793 NewFD->setInvalidDecl();
9794 return true;
9795 }
9796
9797 TargetAttr::ParsedTargetAttr OldParsed =
9798 OldTA->parse(std::less<std::string>());
9799
9800 if (OldParsed == NewParsed) {
9801 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9802 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9803 NewFD->setInvalidDecl();
9804 return true;
9805 }
9806
9807 for (const auto *FD : OldFD->redecls()) {
9808 const auto *CurTA = FD->getAttr<TargetAttr>();
9809 // We allow forward declarations before ANY multiversioning attributes, but
9810 // nothing after the fact.
9811 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9812 (!CurTA || CurTA->isInherited())) {
9813 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9814 << 0;
9815 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9816 NewFD->setInvalidDecl();
9817 return true;
9818 }
9819 }
9820
9821 OldFD->setIsMultiVersion();
9822 NewFD->setIsMultiVersion();
9823 Redeclaration = false;
9824 MergeTypeWithPrevious = false;
9825 OldDecl = nullptr;
9826 Previous.clear();
9827 return false;
9828 }
9829
9830 /// Check the validity of a new function declaration being added to an existing
9831 /// multiversioned declaration collection.
CheckMultiVersionAdditionalDecl(Sema & S,FunctionDecl * OldFD,FunctionDecl * NewFD,MultiVersionKind NewMVType,const TargetAttr * NewTA,const CPUDispatchAttr * NewCPUDisp,const CPUSpecificAttr * NewCPUSpec,bool & Redeclaration,NamedDecl * & OldDecl,bool & MergeTypeWithPrevious,LookupResult & Previous)9832 static bool CheckMultiVersionAdditionalDecl(
9833 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9834 MultiVersionKind NewMVType, const TargetAttr *NewTA,
9835 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9836 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9837 LookupResult &Previous) {
9838
9839 MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9840 // Disallow mixing of multiversioning types.
9841 if ((OldMVType == MultiVersionKind::Target &&
9842 NewMVType != MultiVersionKind::Target) ||
9843 (NewMVType == MultiVersionKind::Target &&
9844 OldMVType != MultiVersionKind::Target)) {
9845 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9846 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9847 NewFD->setInvalidDecl();
9848 return true;
9849 }
9850
9851 TargetAttr::ParsedTargetAttr NewParsed;
9852 if (NewTA) {
9853 NewParsed = NewTA->parse();
9854 llvm::sort(NewParsed.Features);
9855 }
9856
9857 bool UseMemberUsingDeclRules =
9858 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9859
9860 // Next, check ALL non-overloads to see if this is a redeclaration of a
9861 // previous member of the MultiVersion set.
9862 for (NamedDecl *ND : Previous) {
9863 FunctionDecl *CurFD = ND->getAsFunction();
9864 if (!CurFD)
9865 continue;
9866 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9867 continue;
9868
9869 if (NewMVType == MultiVersionKind::Target) {
9870 const auto *CurTA = CurFD->getAttr<TargetAttr>();
9871 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9872 NewFD->setIsMultiVersion();
9873 Redeclaration = true;
9874 OldDecl = ND;
9875 return false;
9876 }
9877
9878 TargetAttr::ParsedTargetAttr CurParsed =
9879 CurTA->parse(std::less<std::string>());
9880 if (CurParsed == NewParsed) {
9881 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9882 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9883 NewFD->setInvalidDecl();
9884 return true;
9885 }
9886 } else {
9887 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9888 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9889 // Handle CPUDispatch/CPUSpecific versions.
9890 // Only 1 CPUDispatch function is allowed, this will make it go through
9891 // the redeclaration errors.
9892 if (NewMVType == MultiVersionKind::CPUDispatch &&
9893 CurFD->hasAttr<CPUDispatchAttr>()) {
9894 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9895 std::equal(
9896 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9897 NewCPUDisp->cpus_begin(),
9898 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9899 return Cur->getName() == New->getName();
9900 })) {
9901 NewFD->setIsMultiVersion();
9902 Redeclaration = true;
9903 OldDecl = ND;
9904 return false;
9905 }
9906
9907 // If the declarations don't match, this is an error condition.
9908 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9909 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9910 NewFD->setInvalidDecl();
9911 return true;
9912 }
9913 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9914
9915 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9916 std::equal(
9917 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9918 NewCPUSpec->cpus_begin(),
9919 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9920 return Cur->getName() == New->getName();
9921 })) {
9922 NewFD->setIsMultiVersion();
9923 Redeclaration = true;
9924 OldDecl = ND;
9925 return false;
9926 }
9927
9928 // Only 1 version of CPUSpecific is allowed for each CPU.
9929 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9930 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9931 if (CurII == NewII) {
9932 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9933 << NewII;
9934 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9935 NewFD->setInvalidDecl();
9936 return true;
9937 }
9938 }
9939 }
9940 }
9941 // If the two decls aren't the same MVType, there is no possible error
9942 // condition.
9943 }
9944 }
9945
9946 // Else, this is simply a non-redecl case. Checking the 'value' is only
9947 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9948 // handled in the attribute adding step.
9949 if (NewMVType == MultiVersionKind::Target &&
9950 CheckMultiVersionValue(S, NewFD)) {
9951 NewFD->setInvalidDecl();
9952 return true;
9953 }
9954
9955 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
9956 !OldFD->isMultiVersion(), NewMVType)) {
9957 NewFD->setInvalidDecl();
9958 return true;
9959 }
9960
9961 // Permit forward declarations in the case where these two are compatible.
9962 if (!OldFD->isMultiVersion()) {
9963 OldFD->setIsMultiVersion();
9964 NewFD->setIsMultiVersion();
9965 Redeclaration = true;
9966 OldDecl = OldFD;
9967 return false;
9968 }
9969
9970 NewFD->setIsMultiVersion();
9971 Redeclaration = false;
9972 MergeTypeWithPrevious = false;
9973 OldDecl = nullptr;
9974 Previous.clear();
9975 return false;
9976 }
9977
9978
9979 /// Check the validity of a mulitversion function declaration.
9980 /// Also sets the multiversion'ness' of the function itself.
9981 ///
9982 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9983 ///
9984 /// Returns true if there was an error, false otherwise.
CheckMultiVersionFunction(Sema & S,FunctionDecl * NewFD,bool & Redeclaration,NamedDecl * & OldDecl,bool & MergeTypeWithPrevious,LookupResult & Previous)9985 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9986 bool &Redeclaration, NamedDecl *&OldDecl,
9987 bool &MergeTypeWithPrevious,
9988 LookupResult &Previous) {
9989 const auto *NewTA = NewFD->getAttr<TargetAttr>();
9990 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9991 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9992
9993 // Mixing Multiversioning types is prohibited.
9994 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9995 (NewCPUDisp && NewCPUSpec)) {
9996 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9997 NewFD->setInvalidDecl();
9998 return true;
9999 }
10000
10001 MultiVersionKind MVType = NewFD->getMultiVersionKind();
10002
10003 // Main isn't allowed to become a multiversion function, however it IS
10004 // permitted to have 'main' be marked with the 'target' optimization hint.
10005 if (NewFD->isMain()) {
10006 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10007 MVType == MultiVersionKind::CPUDispatch ||
10008 MVType == MultiVersionKind::CPUSpecific) {
10009 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10010 NewFD->setInvalidDecl();
10011 return true;
10012 }
10013 return false;
10014 }
10015
10016 if (!OldDecl || !OldDecl->getAsFunction() ||
10017 OldDecl->getDeclContext()->getRedeclContext() !=
10018 NewFD->getDeclContext()->getRedeclContext()) {
10019 // If there's no previous declaration, AND this isn't attempting to cause
10020 // multiversioning, this isn't an error condition.
10021 if (MVType == MultiVersionKind::None)
10022 return false;
10023 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10024 }
10025
10026 FunctionDecl *OldFD = OldDecl->getAsFunction();
10027
10028 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10029 return false;
10030
10031 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10032 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10033 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10034 NewFD->setInvalidDecl();
10035 return true;
10036 }
10037
10038 // Handle the target potentially causes multiversioning case.
10039 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10040 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10041 Redeclaration, OldDecl,
10042 MergeTypeWithPrevious, Previous);
10043
10044 // At this point, we have a multiversion function decl (in OldFD) AND an
10045 // appropriate attribute in the current function decl. Resolve that these are
10046 // still compatible with previous declarations.
10047 return CheckMultiVersionAdditionalDecl(
10048 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10049 OldDecl, MergeTypeWithPrevious, Previous);
10050 }
10051
10052 /// Perform semantic checking of a new function declaration.
10053 ///
10054 /// Performs semantic analysis of the new function declaration
10055 /// NewFD. This routine performs all semantic checking that does not
10056 /// require the actual declarator involved in the declaration, and is
10057 /// used both for the declaration of functions as they are parsed
10058 /// (called via ActOnDeclarator) and for the declaration of functions
10059 /// that have been instantiated via C++ template instantiation (called
10060 /// via InstantiateDecl).
10061 ///
10062 /// \param IsMemberSpecialization whether this new function declaration is
10063 /// a member specialization (that replaces any definition provided by the
10064 /// previous declaration).
10065 ///
10066 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10067 ///
10068 /// \returns true if the function declaration is a redeclaration.
CheckFunctionDeclaration(Scope * S,FunctionDecl * NewFD,LookupResult & Previous,bool IsMemberSpecialization)10069 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10070 LookupResult &Previous,
10071 bool IsMemberSpecialization) {
10072 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10073 "Variably modified return types are not handled here");
10074
10075 // Determine whether the type of this function should be merged with
10076 // a previous visible declaration. This never happens for functions in C++,
10077 // and always happens in C if the previous declaration was visible.
10078 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10079 !Previous.isShadowed();
10080
10081 bool Redeclaration = false;
10082 NamedDecl *OldDecl = nullptr;
10083 bool MayNeedOverloadableChecks = false;
10084
10085 // Merge or overload the declaration with an existing declaration of
10086 // the same name, if appropriate.
10087 if (!Previous.empty()) {
10088 // Determine whether NewFD is an overload of PrevDecl or
10089 // a declaration that requires merging. If it's an overload,
10090 // there's no more work to do here; we'll just add the new
10091 // function to the scope.
10092 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10093 NamedDecl *Candidate = Previous.getRepresentativeDecl();
10094 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10095 Redeclaration = true;
10096 OldDecl = Candidate;
10097 }
10098 } else {
10099 MayNeedOverloadableChecks = true;
10100 switch (CheckOverload(S, NewFD, Previous, OldDecl,
10101 /*NewIsUsingDecl*/ false)) {
10102 case Ovl_Match:
10103 Redeclaration = true;
10104 break;
10105
10106 case Ovl_NonFunction:
10107 Redeclaration = true;
10108 break;
10109
10110 case Ovl_Overload:
10111 Redeclaration = false;
10112 break;
10113 }
10114 }
10115 }
10116
10117 // Check for a previous extern "C" declaration with this name.
10118 if (!Redeclaration &&
10119 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10120 if (!Previous.empty()) {
10121 // This is an extern "C" declaration with the same name as a previous
10122 // declaration, and thus redeclares that entity...
10123 Redeclaration = true;
10124 OldDecl = Previous.getFoundDecl();
10125 MergeTypeWithPrevious = false;
10126
10127 // ... except in the presence of __attribute__((overloadable)).
10128 if (OldDecl->hasAttr<OverloadableAttr>() ||
10129 NewFD->hasAttr<OverloadableAttr>()) {
10130 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10131 MayNeedOverloadableChecks = true;
10132 Redeclaration = false;
10133 OldDecl = nullptr;
10134 }
10135 }
10136 }
10137 }
10138
10139 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10140 MergeTypeWithPrevious, Previous))
10141 return Redeclaration;
10142
10143 // C++11 [dcl.constexpr]p8:
10144 // A constexpr specifier for a non-static member function that is not
10145 // a constructor declares that member function to be const.
10146 //
10147 // This needs to be delayed until we know whether this is an out-of-line
10148 // definition of a static member function.
10149 //
10150 // This rule is not present in C++1y, so we produce a backwards
10151 // compatibility warning whenever it happens in C++11.
10152 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10153 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10154 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10155 !MD->getMethodQualifiers().hasConst()) {
10156 CXXMethodDecl *OldMD = nullptr;
10157 if (OldDecl)
10158 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10159 if (!OldMD || !OldMD->isStatic()) {
10160 const FunctionProtoType *FPT =
10161 MD->getType()->castAs<FunctionProtoType>();
10162 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10163 EPI.TypeQuals.addConst();
10164 MD->setType(Context.getFunctionType(FPT->getReturnType(),
10165 FPT->getParamTypes(), EPI));
10166
10167 // Warn that we did this, if we're not performing template instantiation.
10168 // In that case, we'll have warned already when the template was defined.
10169 if (!inTemplateInstantiation()) {
10170 SourceLocation AddConstLoc;
10171 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10172 .IgnoreParens().getAs<FunctionTypeLoc>())
10173 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10174
10175 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10176 << FixItHint::CreateInsertion(AddConstLoc, " const");
10177 }
10178 }
10179 }
10180
10181 if (Redeclaration) {
10182 // NewFD and OldDecl represent declarations that need to be
10183 // merged.
10184 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10185 NewFD->setInvalidDecl();
10186 return Redeclaration;
10187 }
10188
10189 Previous.clear();
10190 Previous.addDecl(OldDecl);
10191
10192 if (FunctionTemplateDecl *OldTemplateDecl =
10193 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10194 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10195 FunctionTemplateDecl *NewTemplateDecl
10196 = NewFD->getDescribedFunctionTemplate();
10197 assert(NewTemplateDecl && "Template/non-template mismatch");
10198
10199 // The call to MergeFunctionDecl above may have created some state in
10200 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10201 // can add it as a redeclaration.
10202 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10203
10204 NewFD->setPreviousDeclaration(OldFD);
10205 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10206 if (NewFD->isCXXClassMember()) {
10207 NewFD->setAccess(OldTemplateDecl->getAccess());
10208 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10209 }
10210
10211 // If this is an explicit specialization of a member that is a function
10212 // template, mark it as a member specialization.
10213 if (IsMemberSpecialization &&
10214 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10215 NewTemplateDecl->setMemberSpecialization();
10216 assert(OldTemplateDecl->isMemberSpecialization());
10217 // Explicit specializations of a member template do not inherit deleted
10218 // status from the parent member template that they are specializing.
10219 if (OldFD->isDeleted()) {
10220 // FIXME: This assert will not hold in the presence of modules.
10221 assert(OldFD->getCanonicalDecl() == OldFD);
10222 // FIXME: We need an update record for this AST mutation.
10223 OldFD->setDeletedAsWritten(false);
10224 }
10225 }
10226
10227 } else {
10228 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10229 auto *OldFD = cast<FunctionDecl>(OldDecl);
10230 // This needs to happen first so that 'inline' propagates.
10231 NewFD->setPreviousDeclaration(OldFD);
10232 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10233 if (NewFD->isCXXClassMember())
10234 NewFD->setAccess(OldFD->getAccess());
10235 }
10236 }
10237 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10238 !NewFD->getAttr<OverloadableAttr>()) {
10239 assert((Previous.empty() ||
10240 llvm::any_of(Previous,
10241 [](const NamedDecl *ND) {
10242 return ND->hasAttr<OverloadableAttr>();
10243 })) &&
10244 "Non-redecls shouldn't happen without overloadable present");
10245
10246 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10247 const auto *FD = dyn_cast<FunctionDecl>(ND);
10248 return FD && !FD->hasAttr<OverloadableAttr>();
10249 });
10250
10251 if (OtherUnmarkedIter != Previous.end()) {
10252 Diag(NewFD->getLocation(),
10253 diag::err_attribute_overloadable_multiple_unmarked_overloads);
10254 Diag((*OtherUnmarkedIter)->getLocation(),
10255 diag::note_attribute_overloadable_prev_overload)
10256 << false;
10257
10258 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10259 }
10260 }
10261
10262 // Semantic checking for this function declaration (in isolation).
10263
10264 if (getLangOpts().CPlusPlus) {
10265 // C++-specific checks.
10266 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10267 CheckConstructor(Constructor);
10268 } else if (CXXDestructorDecl *Destructor =
10269 dyn_cast<CXXDestructorDecl>(NewFD)) {
10270 CXXRecordDecl *Record = Destructor->getParent();
10271 QualType ClassType = Context.getTypeDeclType(Record);
10272
10273 // FIXME: Shouldn't we be able to perform this check even when the class
10274 // type is dependent? Both gcc and edg can handle that.
10275 if (!ClassType->isDependentType()) {
10276 DeclarationName Name
10277 = Context.DeclarationNames.getCXXDestructorName(
10278 Context.getCanonicalType(ClassType));
10279 if (NewFD->getDeclName() != Name) {
10280 Diag(NewFD->getLocation(), diag::err_destructor_name);
10281 NewFD->setInvalidDecl();
10282 return Redeclaration;
10283 }
10284 }
10285 } else if (CXXConversionDecl *Conversion
10286 = dyn_cast<CXXConversionDecl>(NewFD)) {
10287 ActOnConversionDeclarator(Conversion);
10288 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10289 if (auto *TD = Guide->getDescribedFunctionTemplate())
10290 CheckDeductionGuideTemplate(TD);
10291
10292 // A deduction guide is not on the list of entities that can be
10293 // explicitly specialized.
10294 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10295 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10296 << /*explicit specialization*/ 1;
10297 }
10298
10299 // Find any virtual functions that this function overrides.
10300 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10301 if (!Method->isFunctionTemplateSpecialization() &&
10302 !Method->getDescribedFunctionTemplate() &&
10303 Method->isCanonicalDecl()) {
10304 if (AddOverriddenMethods(Method->getParent(), Method)) {
10305 // If the function was marked as "static", we have a problem.
10306 if (NewFD->getStorageClass() == SC_Static) {
10307 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10308 }
10309 }
10310 }
10311
10312 if (Method->isStatic())
10313 checkThisInStaticMemberFunctionType(Method);
10314 }
10315
10316 // Extra checking for C++ overloaded operators (C++ [over.oper]).
10317 if (NewFD->isOverloadedOperator() &&
10318 CheckOverloadedOperatorDeclaration(NewFD)) {
10319 NewFD->setInvalidDecl();
10320 return Redeclaration;
10321 }
10322
10323 // Extra checking for C++0x literal operators (C++0x [over.literal]).
10324 if (NewFD->getLiteralIdentifier() &&
10325 CheckLiteralOperatorDeclaration(NewFD)) {
10326 NewFD->setInvalidDecl();
10327 return Redeclaration;
10328 }
10329
10330 // In C++, check default arguments now that we have merged decls. Unless
10331 // the lexical context is the class, because in this case this is done
10332 // during delayed parsing anyway.
10333 if (!CurContext->isRecord())
10334 CheckCXXDefaultArguments(NewFD);
10335
10336 // If this function declares a builtin function, check the type of this
10337 // declaration against the expected type for the builtin.
10338 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10339 ASTContext::GetBuiltinTypeError Error;
10340 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10341 QualType T = Context.GetBuiltinType(BuiltinID, Error);
10342 // If the type of the builtin differs only in its exception
10343 // specification, that's OK.
10344 // FIXME: If the types do differ in this way, it would be better to
10345 // retain the 'noexcept' form of the type.
10346 if (!T.isNull() &&
10347 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10348 NewFD->getType()))
10349 // The type of this function differs from the type of the builtin,
10350 // so forget about the builtin entirely.
10351 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10352 }
10353
10354 // If this function is declared as being extern "C", then check to see if
10355 // the function returns a UDT (class, struct, or union type) that is not C
10356 // compatible, and if it does, warn the user.
10357 // But, issue any diagnostic on the first declaration only.
10358 if (Previous.empty() && NewFD->isExternC()) {
10359 QualType R = NewFD->getReturnType();
10360 if (R->isIncompleteType() && !R->isVoidType())
10361 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10362 << NewFD << R;
10363 else if (!R.isPODType(Context) && !R->isVoidType() &&
10364 !R->isObjCObjectPointerType())
10365 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10366 }
10367
10368 // C++1z [dcl.fct]p6:
10369 // [...] whether the function has a non-throwing exception-specification
10370 // [is] part of the function type
10371 //
10372 // This results in an ABI break between C++14 and C++17 for functions whose
10373 // declared type includes an exception-specification in a parameter or
10374 // return type. (Exception specifications on the function itself are OK in
10375 // most cases, and exception specifications are not permitted in most other
10376 // contexts where they could make it into a mangling.)
10377 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10378 auto HasNoexcept = [&](QualType T) -> bool {
10379 // Strip off declarator chunks that could be between us and a function
10380 // type. We don't need to look far, exception specifications are very
10381 // restricted prior to C++17.
10382 if (auto *RT = T->getAs<ReferenceType>())
10383 T = RT->getPointeeType();
10384 else if (T->isAnyPointerType())
10385 T = T->getPointeeType();
10386 else if (auto *MPT = T->getAs<MemberPointerType>())
10387 T = MPT->getPointeeType();
10388 if (auto *FPT = T->getAs<FunctionProtoType>())
10389 if (FPT->isNothrow())
10390 return true;
10391 return false;
10392 };
10393
10394 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10395 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10396 for (QualType T : FPT->param_types())
10397 AnyNoexcept |= HasNoexcept(T);
10398 if (AnyNoexcept)
10399 Diag(NewFD->getLocation(),
10400 diag::warn_cxx17_compat_exception_spec_in_signature)
10401 << NewFD;
10402 }
10403
10404 if (!Redeclaration && LangOpts.CUDA)
10405 checkCUDATargetOverload(NewFD, Previous);
10406 }
10407 return Redeclaration;
10408 }
10409
CheckMain(FunctionDecl * FD,const DeclSpec & DS)10410 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10411 // C++11 [basic.start.main]p3:
10412 // A program that [...] declares main to be inline, static or
10413 // constexpr is ill-formed.
10414 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
10415 // appear in a declaration of main.
10416 // static main is not an error under C99, but we should warn about it.
10417 // We accept _Noreturn main as an extension.
10418 if (FD->getStorageClass() == SC_Static)
10419 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10420 ? diag::err_static_main : diag::warn_static_main)
10421 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10422 if (FD->isInlineSpecified())
10423 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10424 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10425 if (DS.isNoreturnSpecified()) {
10426 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10427 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10428 Diag(NoreturnLoc, diag::ext_noreturn_main);
10429 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10430 << FixItHint::CreateRemoval(NoreturnRange);
10431 }
10432 if (FD->isConstexpr()) {
10433 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10434 << FD->isConsteval()
10435 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10436 FD->setConstexprKind(CSK_unspecified);
10437 }
10438
10439 if (getLangOpts().OpenCL) {
10440 Diag(FD->getLocation(), diag::err_opencl_no_main)
10441 << FD->hasAttr<OpenCLKernelAttr>();
10442 FD->setInvalidDecl();
10443 return;
10444 }
10445
10446 QualType T = FD->getType();
10447 assert(T->isFunctionType() && "function decl is not of function type");
10448 const FunctionType* FT = T->castAs<FunctionType>();
10449
10450 // Set default calling convention for main()
10451 if (FT->getCallConv() != CC_C) {
10452 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10453 FD->setType(QualType(FT, 0));
10454 T = Context.getCanonicalType(FD->getType());
10455 }
10456
10457 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10458 // In C with GNU extensions we allow main() to have non-integer return
10459 // type, but we should warn about the extension, and we disable the
10460 // implicit-return-zero rule.
10461
10462 // GCC in C mode accepts qualified 'int'.
10463 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10464 FD->setHasImplicitReturnZero(true);
10465 else {
10466 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10467 SourceRange RTRange = FD->getReturnTypeSourceRange();
10468 if (RTRange.isValid())
10469 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10470 << FixItHint::CreateReplacement(RTRange, "int");
10471 }
10472 } else {
10473 // In C and C++, main magically returns 0 if you fall off the end;
10474 // set the flag which tells us that.
10475 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10476
10477 // All the standards say that main() should return 'int'.
10478 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10479 FD->setHasImplicitReturnZero(true);
10480 else {
10481 // Otherwise, this is just a flat-out error.
10482 SourceRange RTRange = FD->getReturnTypeSourceRange();
10483 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10484 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10485 : FixItHint());
10486 FD->setInvalidDecl(true);
10487 }
10488 }
10489
10490 // Treat protoless main() as nullary.
10491 if (isa<FunctionNoProtoType>(FT)) return;
10492
10493 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10494 unsigned nparams = FTP->getNumParams();
10495 assert(FD->getNumParams() == nparams);
10496
10497 bool HasExtraParameters = (nparams > 3);
10498
10499 if (FTP->isVariadic()) {
10500 Diag(FD->getLocation(), diag::ext_variadic_main);
10501 // FIXME: if we had information about the location of the ellipsis, we
10502 // could add a FixIt hint to remove it as a parameter.
10503 }
10504
10505 // Darwin passes an undocumented fourth argument of type char**. If
10506 // other platforms start sprouting these, the logic below will start
10507 // getting shifty.
10508 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10509 HasExtraParameters = false;
10510
10511 if (HasExtraParameters) {
10512 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10513 FD->setInvalidDecl(true);
10514 nparams = 3;
10515 }
10516
10517 // FIXME: a lot of the following diagnostics would be improved
10518 // if we had some location information about types.
10519
10520 QualType CharPP =
10521 Context.getPointerType(Context.getPointerType(Context.CharTy));
10522 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10523
10524 for (unsigned i = 0; i < nparams; ++i) {
10525 QualType AT = FTP->getParamType(i);
10526
10527 bool mismatch = true;
10528
10529 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10530 mismatch = false;
10531 else if (Expected[i] == CharPP) {
10532 // As an extension, the following forms are okay:
10533 // char const **
10534 // char const * const *
10535 // char * const *
10536
10537 QualifierCollector qs;
10538 const PointerType* PT;
10539 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10540 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10541 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10542 Context.CharTy)) {
10543 qs.removeConst();
10544 mismatch = !qs.empty();
10545 }
10546 }
10547
10548 if (mismatch) {
10549 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10550 // TODO: suggest replacing given type with expected type
10551 FD->setInvalidDecl(true);
10552 }
10553 }
10554
10555 if (nparams == 1 && !FD->isInvalidDecl()) {
10556 Diag(FD->getLocation(), diag::warn_main_one_arg);
10557 }
10558
10559 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10560 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10561 FD->setInvalidDecl();
10562 }
10563 }
10564
CheckMSVCRTEntryPoint(FunctionDecl * FD)10565 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10566 QualType T = FD->getType();
10567 assert(T->isFunctionType() && "function decl is not of function type");
10568 const FunctionType *FT = T->castAs<FunctionType>();
10569
10570 // Set an implicit return of 'zero' if the function can return some integral,
10571 // enumeration, pointer or nullptr type.
10572 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10573 FT->getReturnType()->isAnyPointerType() ||
10574 FT->getReturnType()->isNullPtrType())
10575 // DllMain is exempt because a return value of zero means it failed.
10576 if (FD->getName() != "DllMain")
10577 FD->setHasImplicitReturnZero(true);
10578
10579 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10580 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10581 FD->setInvalidDecl();
10582 }
10583 }
10584
CheckForConstantInitializer(Expr * Init,QualType DclT)10585 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10586 // FIXME: Need strict checking. In C89, we need to check for
10587 // any assignment, increment, decrement, function-calls, or
10588 // commas outside of a sizeof. In C99, it's the same list,
10589 // except that the aforementioned are allowed in unevaluated
10590 // expressions. Everything else falls under the
10591 // "may accept other forms of constant expressions" exception.
10592 // (We never end up here for C++, so the constant expression
10593 // rules there don't matter.)
10594 const Expr *Culprit;
10595 if (Init->isConstantInitializer(Context, false, &Culprit))
10596 return false;
10597 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10598 << Culprit->getSourceRange();
10599 return true;
10600 }
10601
10602 namespace {
10603 // Visits an initialization expression to see if OrigDecl is evaluated in
10604 // its own initialization and throws a warning if it does.
10605 class SelfReferenceChecker
10606 : public EvaluatedExprVisitor<SelfReferenceChecker> {
10607 Sema &S;
10608 Decl *OrigDecl;
10609 bool isRecordType;
10610 bool isPODType;
10611 bool isReferenceType;
10612
10613 bool isInitList;
10614 llvm::SmallVector<unsigned, 4> InitFieldIndex;
10615
10616 public:
10617 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10618
SelfReferenceChecker(Sema & S,Decl * OrigDecl)10619 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10620 S(S), OrigDecl(OrigDecl) {
10621 isPODType = false;
10622 isRecordType = false;
10623 isReferenceType = false;
10624 isInitList = false;
10625 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10626 isPODType = VD->getType().isPODType(S.Context);
10627 isRecordType = VD->getType()->isRecordType();
10628 isReferenceType = VD->getType()->isReferenceType();
10629 }
10630 }
10631
10632 // For most expressions, just call the visitor. For initializer lists,
10633 // track the index of the field being initialized since fields are
10634 // initialized in order allowing use of previously initialized fields.
CheckExpr(Expr * E)10635 void CheckExpr(Expr *E) {
10636 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10637 if (!InitList) {
10638 Visit(E);
10639 return;
10640 }
10641
10642 // Track and increment the index here.
10643 isInitList = true;
10644 InitFieldIndex.push_back(0);
10645 for (auto Child : InitList->children()) {
10646 CheckExpr(cast<Expr>(Child));
10647 ++InitFieldIndex.back();
10648 }
10649 InitFieldIndex.pop_back();
10650 }
10651
10652 // Returns true if MemberExpr is checked and no further checking is needed.
10653 // Returns false if additional checking is required.
CheckInitListMemberExpr(MemberExpr * E,bool CheckReference)10654 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10655 llvm::SmallVector<FieldDecl*, 4> Fields;
10656 Expr *Base = E;
10657 bool ReferenceField = false;
10658
10659 // Get the field members used.
10660 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10661 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10662 if (!FD)
10663 return false;
10664 Fields.push_back(FD);
10665 if (FD->getType()->isReferenceType())
10666 ReferenceField = true;
10667 Base = ME->getBase()->IgnoreParenImpCasts();
10668 }
10669
10670 // Keep checking only if the base Decl is the same.
10671 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10672 if (!DRE || DRE->getDecl() != OrigDecl)
10673 return false;
10674
10675 // A reference field can be bound to an unininitialized field.
10676 if (CheckReference && !ReferenceField)
10677 return true;
10678
10679 // Convert FieldDecls to their index number.
10680 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10681 for (const FieldDecl *I : llvm::reverse(Fields))
10682 UsedFieldIndex.push_back(I->getFieldIndex());
10683
10684 // See if a warning is needed by checking the first difference in index
10685 // numbers. If field being used has index less than the field being
10686 // initialized, then the use is safe.
10687 for (auto UsedIter = UsedFieldIndex.begin(),
10688 UsedEnd = UsedFieldIndex.end(),
10689 OrigIter = InitFieldIndex.begin(),
10690 OrigEnd = InitFieldIndex.end();
10691 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10692 if (*UsedIter < *OrigIter)
10693 return true;
10694 if (*UsedIter > *OrigIter)
10695 break;
10696 }
10697
10698 // TODO: Add a different warning which will print the field names.
10699 HandleDeclRefExpr(DRE);
10700 return true;
10701 }
10702
10703 // For most expressions, the cast is directly above the DeclRefExpr.
10704 // For conditional operators, the cast can be outside the conditional
10705 // operator if both expressions are DeclRefExpr's.
HandleValue(Expr * E)10706 void HandleValue(Expr *E) {
10707 E = E->IgnoreParens();
10708 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10709 HandleDeclRefExpr(DRE);
10710 return;
10711 }
10712
10713 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10714 Visit(CO->getCond());
10715 HandleValue(CO->getTrueExpr());
10716 HandleValue(CO->getFalseExpr());
10717 return;
10718 }
10719
10720 if (BinaryConditionalOperator *BCO =
10721 dyn_cast<BinaryConditionalOperator>(E)) {
10722 Visit(BCO->getCond());
10723 HandleValue(BCO->getFalseExpr());
10724 return;
10725 }
10726
10727 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10728 HandleValue(OVE->getSourceExpr());
10729 return;
10730 }
10731
10732 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10733 if (BO->getOpcode() == BO_Comma) {
10734 Visit(BO->getLHS());
10735 HandleValue(BO->getRHS());
10736 return;
10737 }
10738 }
10739
10740 if (isa<MemberExpr>(E)) {
10741 if (isInitList) {
10742 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10743 false /*CheckReference*/))
10744 return;
10745 }
10746
10747 Expr *Base = E->IgnoreParenImpCasts();
10748 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10749 // Check for static member variables and don't warn on them.
10750 if (!isa<FieldDecl>(ME->getMemberDecl()))
10751 return;
10752 Base = ME->getBase()->IgnoreParenImpCasts();
10753 }
10754 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10755 HandleDeclRefExpr(DRE);
10756 return;
10757 }
10758
10759 Visit(E);
10760 }
10761
10762 // Reference types not handled in HandleValue are handled here since all
10763 // uses of references are bad, not just r-value uses.
VisitDeclRefExpr(DeclRefExpr * E)10764 void VisitDeclRefExpr(DeclRefExpr *E) {
10765 if (isReferenceType)
10766 HandleDeclRefExpr(E);
10767 }
10768
VisitImplicitCastExpr(ImplicitCastExpr * E)10769 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10770 if (E->getCastKind() == CK_LValueToRValue) {
10771 HandleValue(E->getSubExpr());
10772 return;
10773 }
10774
10775 Inherited::VisitImplicitCastExpr(E);
10776 }
10777
VisitMemberExpr(MemberExpr * E)10778 void VisitMemberExpr(MemberExpr *E) {
10779 if (isInitList) {
10780 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10781 return;
10782 }
10783
10784 // Don't warn on arrays since they can be treated as pointers.
10785 if (E->getType()->canDecayToPointerType()) return;
10786
10787 // Warn when a non-static method call is followed by non-static member
10788 // field accesses, which is followed by a DeclRefExpr.
10789 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10790 bool Warn = (MD && !MD->isStatic());
10791 Expr *Base = E->getBase()->IgnoreParenImpCasts();
10792 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10793 if (!isa<FieldDecl>(ME->getMemberDecl()))
10794 Warn = false;
10795 Base = ME->getBase()->IgnoreParenImpCasts();
10796 }
10797
10798 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10799 if (Warn)
10800 HandleDeclRefExpr(DRE);
10801 return;
10802 }
10803
10804 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10805 // Visit that expression.
10806 Visit(Base);
10807 }
10808
VisitCXXOperatorCallExpr(CXXOperatorCallExpr * E)10809 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10810 Expr *Callee = E->getCallee();
10811
10812 if (isa<UnresolvedLookupExpr>(Callee))
10813 return Inherited::VisitCXXOperatorCallExpr(E);
10814
10815 Visit(Callee);
10816 for (auto Arg: E->arguments())
10817 HandleValue(Arg->IgnoreParenImpCasts());
10818 }
10819
VisitUnaryOperator(UnaryOperator * E)10820 void VisitUnaryOperator(UnaryOperator *E) {
10821 // For POD record types, addresses of its own members are well-defined.
10822 if (E->getOpcode() == UO_AddrOf && isRecordType &&
10823 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10824 if (!isPODType)
10825 HandleValue(E->getSubExpr());
10826 return;
10827 }
10828
10829 if (E->isIncrementDecrementOp()) {
10830 HandleValue(E->getSubExpr());
10831 return;
10832 }
10833
10834 Inherited::VisitUnaryOperator(E);
10835 }
10836
VisitObjCMessageExpr(ObjCMessageExpr * E)10837 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10838
VisitCXXConstructExpr(CXXConstructExpr * E)10839 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10840 if (E->getConstructor()->isCopyConstructor()) {
10841 Expr *ArgExpr = E->getArg(0);
10842 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10843 if (ILE->getNumInits() == 1)
10844 ArgExpr = ILE->getInit(0);
10845 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10846 if (ICE->getCastKind() == CK_NoOp)
10847 ArgExpr = ICE->getSubExpr();
10848 HandleValue(ArgExpr);
10849 return;
10850 }
10851 Inherited::VisitCXXConstructExpr(E);
10852 }
10853
VisitCallExpr(CallExpr * E)10854 void VisitCallExpr(CallExpr *E) {
10855 // Treat std::move as a use.
10856 if (E->isCallToStdMove()) {
10857 HandleValue(E->getArg(0));
10858 return;
10859 }
10860
10861 Inherited::VisitCallExpr(E);
10862 }
10863
VisitBinaryOperator(BinaryOperator * E)10864 void VisitBinaryOperator(BinaryOperator *E) {
10865 if (E->isCompoundAssignmentOp()) {
10866 HandleValue(E->getLHS());
10867 Visit(E->getRHS());
10868 return;
10869 }
10870
10871 Inherited::VisitBinaryOperator(E);
10872 }
10873
10874 // A custom visitor for BinaryConditionalOperator is needed because the
10875 // regular visitor would check the condition and true expression separately
10876 // but both point to the same place giving duplicate diagnostics.
VisitBinaryConditionalOperator(BinaryConditionalOperator * E)10877 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10878 Visit(E->getCond());
10879 Visit(E->getFalseExpr());
10880 }
10881
HandleDeclRefExpr(DeclRefExpr * DRE)10882 void HandleDeclRefExpr(DeclRefExpr *DRE) {
10883 Decl* ReferenceDecl = DRE->getDecl();
10884 if (OrigDecl != ReferenceDecl) return;
10885 unsigned diag;
10886 if (isReferenceType) {
10887 diag = diag::warn_uninit_self_reference_in_reference_init;
10888 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10889 diag = diag::warn_static_self_reference_in_init;
10890 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10891 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10892 DRE->getDecl()->getType()->isRecordType()) {
10893 diag = diag::warn_uninit_self_reference_in_init;
10894 } else {
10895 // Local variables will be handled by the CFG analysis.
10896 return;
10897 }
10898
10899 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10900 S.PDiag(diag)
10901 << DRE->getDecl() << OrigDecl->getLocation()
10902 << DRE->getSourceRange());
10903 }
10904 };
10905
10906 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
CheckSelfReference(Sema & S,Decl * OrigDecl,Expr * E,bool DirectInit)10907 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10908 bool DirectInit) {
10909 // Parameters arguments are occassionially constructed with itself,
10910 // for instance, in recursive functions. Skip them.
10911 if (isa<ParmVarDecl>(OrigDecl))
10912 return;
10913
10914 E = E->IgnoreParens();
10915
10916 // Skip checking T a = a where T is not a record or reference type.
10917 // Doing so is a way to silence uninitialized warnings.
10918 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10919 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10920 if (ICE->getCastKind() == CK_LValueToRValue)
10921 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10922 if (DRE->getDecl() == OrigDecl)
10923 return;
10924
10925 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10926 }
10927 } // end anonymous namespace
10928
10929 namespace {
10930 // Simple wrapper to add the name of a variable or (if no variable is
10931 // available) a DeclarationName into a diagnostic.
10932 struct VarDeclOrName {
10933 VarDecl *VDecl;
10934 DeclarationName Name;
10935
10936 friend const Sema::SemaDiagnosticBuilder &
operator <<(const Sema::SemaDiagnosticBuilder & Diag,VarDeclOrName VN)10937 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10938 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10939 }
10940 };
10941 } // end anonymous namespace
10942
deduceVarTypeFromInitializer(VarDecl * VDecl,DeclarationName Name,QualType Type,TypeSourceInfo * TSI,SourceRange Range,bool DirectInit,Expr * Init)10943 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10944 DeclarationName Name, QualType Type,
10945 TypeSourceInfo *TSI,
10946 SourceRange Range, bool DirectInit,
10947 Expr *Init) {
10948 bool IsInitCapture = !VDecl;
10949 assert((!VDecl || !VDecl->isInitCapture()) &&
10950 "init captures are expected to be deduced prior to initialization");
10951
10952 VarDeclOrName VN{VDecl, Name};
10953
10954 DeducedType *Deduced = Type->getContainedDeducedType();
10955 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10956
10957 // C++11 [dcl.spec.auto]p3
10958 if (!Init) {
10959 assert(VDecl && "no init for init capture deduction?");
10960
10961 // Except for class argument deduction, and then for an initializing
10962 // declaration only, i.e. no static at class scope or extern.
10963 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10964 VDecl->hasExternalStorage() ||
10965 VDecl->isStaticDataMember()) {
10966 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10967 << VDecl->getDeclName() << Type;
10968 return QualType();
10969 }
10970 }
10971
10972 ArrayRef<Expr*> DeduceInits;
10973 if (Init)
10974 DeduceInits = Init;
10975
10976 if (DirectInit) {
10977 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10978 DeduceInits = PL->exprs();
10979 }
10980
10981 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10982 assert(VDecl && "non-auto type for init capture deduction?");
10983 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10984 InitializationKind Kind = InitializationKind::CreateForInit(
10985 VDecl->getLocation(), DirectInit, Init);
10986 // FIXME: Initialization should not be taking a mutable list of inits.
10987 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10988 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10989 InitsCopy);
10990 }
10991
10992 if (DirectInit) {
10993 if (auto *IL = dyn_cast<InitListExpr>(Init))
10994 DeduceInits = IL->inits();
10995 }
10996
10997 // Deduction only works if we have exactly one source expression.
10998 if (DeduceInits.empty()) {
10999 // It isn't possible to write this directly, but it is possible to
11000 // end up in this situation with "auto x(some_pack...);"
11001 Diag(Init->getBeginLoc(), IsInitCapture
11002 ? diag::err_init_capture_no_expression
11003 : diag::err_auto_var_init_no_expression)
11004 << VN << Type << Range;
11005 return QualType();
11006 }
11007
11008 if (DeduceInits.size() > 1) {
11009 Diag(DeduceInits[1]->getBeginLoc(),
11010 IsInitCapture ? diag::err_init_capture_multiple_expressions
11011 : diag::err_auto_var_init_multiple_expressions)
11012 << VN << Type << Range;
11013 return QualType();
11014 }
11015
11016 Expr *DeduceInit = DeduceInits[0];
11017 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11018 Diag(Init->getBeginLoc(), IsInitCapture
11019 ? diag::err_init_capture_paren_braces
11020 : diag::err_auto_var_init_paren_braces)
11021 << isa<InitListExpr>(Init) << VN << Type << Range;
11022 return QualType();
11023 }
11024
11025 // Expressions default to 'id' when we're in a debugger.
11026 bool DefaultedAnyToId = false;
11027 if (getLangOpts().DebuggerCastResultToId &&
11028 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11029 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11030 if (Result.isInvalid()) {
11031 return QualType();
11032 }
11033 Init = Result.get();
11034 DefaultedAnyToId = true;
11035 }
11036
11037 // C++ [dcl.decomp]p1:
11038 // If the assignment-expression [...] has array type A and no ref-qualifier
11039 // is present, e has type cv A
11040 if (VDecl && isa<DecompositionDecl>(VDecl) &&
11041 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11042 DeduceInit->getType()->isConstantArrayType())
11043 return Context.getQualifiedType(DeduceInit->getType(),
11044 Type.getQualifiers());
11045
11046 QualType DeducedType;
11047 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11048 if (!IsInitCapture)
11049 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11050 else if (isa<InitListExpr>(Init))
11051 Diag(Range.getBegin(),
11052 diag::err_init_capture_deduction_failure_from_init_list)
11053 << VN
11054 << (DeduceInit->getType().isNull() ? TSI->getType()
11055 : DeduceInit->getType())
11056 << DeduceInit->getSourceRange();
11057 else
11058 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11059 << VN << TSI->getType()
11060 << (DeduceInit->getType().isNull() ? TSI->getType()
11061 : DeduceInit->getType())
11062 << DeduceInit->getSourceRange();
11063 }
11064
11065 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11066 // 'id' instead of a specific object type prevents most of our usual
11067 // checks.
11068 // We only want to warn outside of template instantiations, though:
11069 // inside a template, the 'id' could have come from a parameter.
11070 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11071 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11072 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11073 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11074 }
11075
11076 return DeducedType;
11077 }
11078
DeduceVariableDeclarationType(VarDecl * VDecl,bool DirectInit,Expr * Init)11079 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11080 Expr *Init) {
11081 QualType DeducedType = deduceVarTypeFromInitializer(
11082 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11083 VDecl->getSourceRange(), DirectInit, Init);
11084 if (DeducedType.isNull()) {
11085 VDecl->setInvalidDecl();
11086 return true;
11087 }
11088
11089 VDecl->setType(DeducedType);
11090 assert(VDecl->isLinkageValid());
11091
11092 // In ARC, infer lifetime.
11093 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11094 VDecl->setInvalidDecl();
11095
11096 // If this is a redeclaration, check that the type we just deduced matches
11097 // the previously declared type.
11098 if (VarDecl *Old = VDecl->getPreviousDecl()) {
11099 // We never need to merge the type, because we cannot form an incomplete
11100 // array of auto, nor deduce such a type.
11101 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11102 }
11103
11104 // Check the deduced type is valid for a variable declaration.
11105 CheckVariableDeclarationType(VDecl);
11106 return VDecl->isInvalidDecl();
11107 }
11108
checkNonTrivialCUnionInInitializer(const Expr * Init,SourceLocation Loc)11109 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11110 SourceLocation Loc) {
11111 if (auto *CE = dyn_cast<ConstantExpr>(Init))
11112 Init = CE->getSubExpr();
11113
11114 QualType InitType = Init->getType();
11115 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11116 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11117 "shouldn't be called if type doesn't have a non-trivial C struct");
11118 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11119 for (auto I : ILE->inits()) {
11120 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11121 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11122 continue;
11123 SourceLocation SL = I->getExprLoc();
11124 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11125 }
11126 return;
11127 }
11128
11129 if (isa<ImplicitValueInitExpr>(Init)) {
11130 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11131 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11132 NTCUK_Init);
11133 } else {
11134 // Assume all other explicit initializers involving copying some existing
11135 // object.
11136 // TODO: ignore any explicit initializers where we can guarantee
11137 // copy-elision.
11138 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11139 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11140 }
11141 }
11142
11143 namespace {
11144
11145 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11146 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11147 void> {
11148 using Super =
11149 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11150 void>;
11151
DiagNonTrivalCUnionDefaultInitializeVisitor__anon63d8c17d1211::DiagNonTrivalCUnionDefaultInitializeVisitor11152 DiagNonTrivalCUnionDefaultInitializeVisitor(
11153 QualType OrigTy, SourceLocation OrigLoc,
11154 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11155 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11156
visitWithKind__anon63d8c17d1211::DiagNonTrivalCUnionDefaultInitializeVisitor11157 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11158 const FieldDecl *FD, bool InNonTrivialUnion) {
11159 if (const auto *AT = S.Context.getAsArrayType(QT))
11160 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11161 InNonTrivialUnion);
11162 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11163 }
11164
visitARCStrong__anon63d8c17d1211::DiagNonTrivalCUnionDefaultInitializeVisitor11165 void visitARCStrong(QualType QT, const FieldDecl *FD,
11166 bool InNonTrivialUnion) {
11167 if (InNonTrivialUnion)
11168 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11169 << 1 << 0 << QT << FD->getName();
11170 }
11171
visitARCWeak__anon63d8c17d1211::DiagNonTrivalCUnionDefaultInitializeVisitor11172 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11173 if (InNonTrivialUnion)
11174 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11175 << 1 << 0 << QT << FD->getName();
11176 }
11177
visitStruct__anon63d8c17d1211::DiagNonTrivalCUnionDefaultInitializeVisitor11178 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11179 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11180 if (RD->isUnion()) {
11181 if (OrigLoc.isValid()) {
11182 bool IsUnion = false;
11183 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11184 IsUnion = OrigRD->isUnion();
11185 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11186 << 0 << OrigTy << IsUnion << UseContext;
11187 // Reset OrigLoc so that this diagnostic is emitted only once.
11188 OrigLoc = SourceLocation();
11189 }
11190 InNonTrivialUnion = true;
11191 }
11192
11193 if (InNonTrivialUnion)
11194 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11195 << 0 << 0 << QT.getUnqualifiedType() << "";
11196
11197 for (const FieldDecl *FD : RD->fields())
11198 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11199 }
11200
visitTrivial__anon63d8c17d1211::DiagNonTrivalCUnionDefaultInitializeVisitor11201 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11202
11203 // The non-trivial C union type or the struct/union type that contains a
11204 // non-trivial C union.
11205 QualType OrigTy;
11206 SourceLocation OrigLoc;
11207 Sema::NonTrivialCUnionContext UseContext;
11208 Sema &S;
11209 };
11210
11211 struct DiagNonTrivalCUnionDestructedTypeVisitor
11212 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11213 using Super =
11214 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11215
DiagNonTrivalCUnionDestructedTypeVisitor__anon63d8c17d1211::DiagNonTrivalCUnionDestructedTypeVisitor11216 DiagNonTrivalCUnionDestructedTypeVisitor(
11217 QualType OrigTy, SourceLocation OrigLoc,
11218 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11219 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11220
visitWithKind__anon63d8c17d1211::DiagNonTrivalCUnionDestructedTypeVisitor11221 void visitWithKind(QualType::DestructionKind DK, QualType QT,
11222 const FieldDecl *FD, bool InNonTrivialUnion) {
11223 if (const auto *AT = S.Context.getAsArrayType(QT))
11224 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11225 InNonTrivialUnion);
11226 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11227 }
11228
visitARCStrong__anon63d8c17d1211::DiagNonTrivalCUnionDestructedTypeVisitor11229 void visitARCStrong(QualType QT, const FieldDecl *FD,
11230 bool InNonTrivialUnion) {
11231 if (InNonTrivialUnion)
11232 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11233 << 1 << 1 << QT << FD->getName();
11234 }
11235
visitARCWeak__anon63d8c17d1211::DiagNonTrivalCUnionDestructedTypeVisitor11236 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11237 if (InNonTrivialUnion)
11238 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11239 << 1 << 1 << QT << FD->getName();
11240 }
11241
visitStruct__anon63d8c17d1211::DiagNonTrivalCUnionDestructedTypeVisitor11242 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11243 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11244 if (RD->isUnion()) {
11245 if (OrigLoc.isValid()) {
11246 bool IsUnion = false;
11247 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11248 IsUnion = OrigRD->isUnion();
11249 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11250 << 1 << OrigTy << IsUnion << UseContext;
11251 // Reset OrigLoc so that this diagnostic is emitted only once.
11252 OrigLoc = SourceLocation();
11253 }
11254 InNonTrivialUnion = true;
11255 }
11256
11257 if (InNonTrivialUnion)
11258 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11259 << 0 << 1 << QT.getUnqualifiedType() << "";
11260
11261 for (const FieldDecl *FD : RD->fields())
11262 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11263 }
11264
visitTrivial__anon63d8c17d1211::DiagNonTrivalCUnionDestructedTypeVisitor11265 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
visitCXXDestructor__anon63d8c17d1211::DiagNonTrivalCUnionDestructedTypeVisitor11266 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11267 bool InNonTrivialUnion) {}
11268
11269 // The non-trivial C union type or the struct/union type that contains a
11270 // non-trivial C union.
11271 QualType OrigTy;
11272 SourceLocation OrigLoc;
11273 Sema::NonTrivialCUnionContext UseContext;
11274 Sema &S;
11275 };
11276
11277 struct DiagNonTrivalCUnionCopyVisitor
11278 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11279 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11280
DiagNonTrivalCUnionCopyVisitor__anon63d8c17d1211::DiagNonTrivalCUnionCopyVisitor11281 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11282 Sema::NonTrivialCUnionContext UseContext,
11283 Sema &S)
11284 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11285
visitWithKind__anon63d8c17d1211::DiagNonTrivalCUnionCopyVisitor11286 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11287 const FieldDecl *FD, bool InNonTrivialUnion) {
11288 if (const auto *AT = S.Context.getAsArrayType(QT))
11289 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11290 InNonTrivialUnion);
11291 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11292 }
11293
visitARCStrong__anon63d8c17d1211::DiagNonTrivalCUnionCopyVisitor11294 void visitARCStrong(QualType QT, const FieldDecl *FD,
11295 bool InNonTrivialUnion) {
11296 if (InNonTrivialUnion)
11297 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11298 << 1 << 2 << QT << FD->getName();
11299 }
11300
visitARCWeak__anon63d8c17d1211::DiagNonTrivalCUnionCopyVisitor11301 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11302 if (InNonTrivialUnion)
11303 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11304 << 1 << 2 << QT << FD->getName();
11305 }
11306
visitStruct__anon63d8c17d1211::DiagNonTrivalCUnionCopyVisitor11307 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11308 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11309 if (RD->isUnion()) {
11310 if (OrigLoc.isValid()) {
11311 bool IsUnion = false;
11312 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11313 IsUnion = OrigRD->isUnion();
11314 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11315 << 2 << OrigTy << IsUnion << UseContext;
11316 // Reset OrigLoc so that this diagnostic is emitted only once.
11317 OrigLoc = SourceLocation();
11318 }
11319 InNonTrivialUnion = true;
11320 }
11321
11322 if (InNonTrivialUnion)
11323 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11324 << 0 << 2 << QT.getUnqualifiedType() << "";
11325
11326 for (const FieldDecl *FD : RD->fields())
11327 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11328 }
11329
preVisit__anon63d8c17d1211::DiagNonTrivalCUnionCopyVisitor11330 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11331 const FieldDecl *FD, bool InNonTrivialUnion) {}
visitTrivial__anon63d8c17d1211::DiagNonTrivalCUnionCopyVisitor11332 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
visitVolatileTrivial__anon63d8c17d1211::DiagNonTrivalCUnionCopyVisitor11333 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11334 bool InNonTrivialUnion) {}
11335
11336 // The non-trivial C union type or the struct/union type that contains a
11337 // non-trivial C union.
11338 QualType OrigTy;
11339 SourceLocation OrigLoc;
11340 Sema::NonTrivialCUnionContext UseContext;
11341 Sema &S;
11342 };
11343
11344 } // namespace
11345
checkNonTrivialCUnion(QualType QT,SourceLocation Loc,NonTrivialCUnionContext UseContext,unsigned NonTrivialKind)11346 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11347 NonTrivialCUnionContext UseContext,
11348 unsigned NonTrivialKind) {
11349 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11350 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11351 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11352 "shouldn't be called if type doesn't have a non-trivial C union");
11353
11354 if ((NonTrivialKind & NTCUK_Init) &&
11355 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11356 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11357 .visit(QT, nullptr, false);
11358 if ((NonTrivialKind & NTCUK_Destruct) &&
11359 QT.hasNonTrivialToPrimitiveDestructCUnion())
11360 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11361 .visit(QT, nullptr, false);
11362 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11363 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11364 .visit(QT, nullptr, false);
11365 }
11366
11367 /// AddInitializerToDecl - Adds the initializer Init to the
11368 /// declaration dcl. If DirectInit is true, this is C++ direct
11369 /// initialization rather than copy initialization.
AddInitializerToDecl(Decl * RealDecl,Expr * Init,bool DirectInit)11370 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11371 // If there is no declaration, there was an error parsing it. Just ignore
11372 // the initializer.
11373 if (!RealDecl || RealDecl->isInvalidDecl()) {
11374 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11375 return;
11376 }
11377
11378 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11379 // Pure-specifiers are handled in ActOnPureSpecifier.
11380 Diag(Method->getLocation(), diag::err_member_function_initialization)
11381 << Method->getDeclName() << Init->getSourceRange();
11382 Method->setInvalidDecl();
11383 return;
11384 }
11385
11386 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11387 if (!VDecl) {
11388 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11389 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11390 RealDecl->setInvalidDecl();
11391 return;
11392 }
11393
11394 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11395 if (VDecl->getType()->isUndeducedType()) {
11396 // Attempt typo correction early so that the type of the init expression can
11397 // be deduced based on the chosen correction if the original init contains a
11398 // TypoExpr.
11399 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11400 if (!Res.isUsable()) {
11401 RealDecl->setInvalidDecl();
11402 return;
11403 }
11404 Init = Res.get();
11405
11406 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11407 return;
11408 }
11409
11410 // dllimport cannot be used on variable definitions.
11411 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11412 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11413 VDecl->setInvalidDecl();
11414 return;
11415 }
11416
11417 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11418 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11419 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11420 VDecl->setInvalidDecl();
11421 return;
11422 }
11423
11424 if (!VDecl->getType()->isDependentType()) {
11425 // A definition must end up with a complete type, which means it must be
11426 // complete with the restriction that an array type might be completed by
11427 // the initializer; note that later code assumes this restriction.
11428 QualType BaseDeclType = VDecl->getType();
11429 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11430 BaseDeclType = Array->getElementType();
11431 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11432 diag::err_typecheck_decl_incomplete_type)) {
11433 RealDecl->setInvalidDecl();
11434 return;
11435 }
11436
11437 // The variable can not have an abstract class type.
11438 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11439 diag::err_abstract_type_in_decl,
11440 AbstractVariableType))
11441 VDecl->setInvalidDecl();
11442 }
11443
11444 // If adding the initializer will turn this declaration into a definition,
11445 // and we already have a definition for this variable, diagnose or otherwise
11446 // handle the situation.
11447 VarDecl *Def;
11448 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11449 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11450 !VDecl->isThisDeclarationADemotedDefinition() &&
11451 checkVarDeclRedefinition(Def, VDecl))
11452 return;
11453
11454 if (getLangOpts().CPlusPlus) {
11455 // C++ [class.static.data]p4
11456 // If a static data member is of const integral or const
11457 // enumeration type, its declaration in the class definition can
11458 // specify a constant-initializer which shall be an integral
11459 // constant expression (5.19). In that case, the member can appear
11460 // in integral constant expressions. The member shall still be
11461 // defined in a namespace scope if it is used in the program and the
11462 // namespace scope definition shall not contain an initializer.
11463 //
11464 // We already performed a redefinition check above, but for static
11465 // data members we also need to check whether there was an in-class
11466 // declaration with an initializer.
11467 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11468 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11469 << VDecl->getDeclName();
11470 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11471 diag::note_previous_initializer)
11472 << 0;
11473 return;
11474 }
11475
11476 if (VDecl->hasLocalStorage())
11477 setFunctionHasBranchProtectedScope();
11478
11479 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11480 VDecl->setInvalidDecl();
11481 return;
11482 }
11483 }
11484
11485 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11486 // a kernel function cannot be initialized."
11487 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11488 Diag(VDecl->getLocation(), diag::err_local_cant_init);
11489 VDecl->setInvalidDecl();
11490 return;
11491 }
11492
11493 // Get the decls type and save a reference for later, since
11494 // CheckInitializerTypes may change it.
11495 QualType DclT = VDecl->getType(), SavT = DclT;
11496
11497 // Expressions default to 'id' when we're in a debugger
11498 // and we are assigning it to a variable of Objective-C pointer type.
11499 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11500 Init->getType() == Context.UnknownAnyTy) {
11501 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11502 if (Result.isInvalid()) {
11503 VDecl->setInvalidDecl();
11504 return;
11505 }
11506 Init = Result.get();
11507 }
11508
11509 // Perform the initialization.
11510 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11511 if (!VDecl->isInvalidDecl()) {
11512 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11513 InitializationKind Kind = InitializationKind::CreateForInit(
11514 VDecl->getLocation(), DirectInit, Init);
11515
11516 MultiExprArg Args = Init;
11517 if (CXXDirectInit)
11518 Args = MultiExprArg(CXXDirectInit->getExprs(),
11519 CXXDirectInit->getNumExprs());
11520
11521 // Try to correct any TypoExprs in the initialization arguments.
11522 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11523 ExprResult Res = CorrectDelayedTyposInExpr(
11524 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11525 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11526 return Init.Failed() ? ExprError() : E;
11527 });
11528 if (Res.isInvalid()) {
11529 VDecl->setInvalidDecl();
11530 } else if (Res.get() != Args[Idx]) {
11531 Args[Idx] = Res.get();
11532 }
11533 }
11534 if (VDecl->isInvalidDecl())
11535 return;
11536
11537 InitializationSequence InitSeq(*this, Entity, Kind, Args,
11538 /*TopLevelOfInitList=*/false,
11539 /*TreatUnavailableAsInvalid=*/false);
11540 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11541 if (Result.isInvalid()) {
11542 VDecl->setInvalidDecl();
11543 return;
11544 }
11545
11546 Init = Result.getAs<Expr>();
11547 }
11548
11549 // Check for self-references within variable initializers.
11550 // Variables declared within a function/method body (except for references)
11551 // are handled by a dataflow analysis.
11552 // This is undefined behavior in C++, but valid in C.
11553 if (getLangOpts().CPlusPlus) {
11554 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11555 VDecl->getType()->isReferenceType()) {
11556 CheckSelfReference(*this, RealDecl, Init, DirectInit);
11557 }
11558 }
11559
11560 // If the type changed, it means we had an incomplete type that was
11561 // completed by the initializer. For example:
11562 // int ary[] = { 1, 3, 5 };
11563 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11564 if (!VDecl->isInvalidDecl() && (DclT != SavT))
11565 VDecl->setType(DclT);
11566
11567 if (!VDecl->isInvalidDecl()) {
11568 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11569
11570 if (VDecl->hasAttr<BlocksAttr>())
11571 checkRetainCycles(VDecl, Init);
11572
11573 // It is safe to assign a weak reference into a strong variable.
11574 // Although this code can still have problems:
11575 // id x = self.weakProp;
11576 // id y = self.weakProp;
11577 // we do not warn to warn spuriously when 'x' and 'y' are on separate
11578 // paths through the function. This should be revisited if
11579 // -Wrepeated-use-of-weak is made flow-sensitive.
11580 if (FunctionScopeInfo *FSI = getCurFunction())
11581 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11582 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11583 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11584 Init->getBeginLoc()))
11585 FSI->markSafeWeakUse(Init);
11586 }
11587
11588 // The initialization is usually a full-expression.
11589 //
11590 // FIXME: If this is a braced initialization of an aggregate, it is not
11591 // an expression, and each individual field initializer is a separate
11592 // full-expression. For instance, in:
11593 //
11594 // struct Temp { ~Temp(); };
11595 // struct S { S(Temp); };
11596 // struct T { S a, b; } t = { Temp(), Temp() }
11597 //
11598 // we should destroy the first Temp before constructing the second.
11599 ExprResult Result =
11600 ActOnFinishFullExpr(Init, VDecl->getLocation(),
11601 /*DiscardedValue*/ false, VDecl->isConstexpr());
11602 if (Result.isInvalid()) {
11603 VDecl->setInvalidDecl();
11604 return;
11605 }
11606 Init = Result.get();
11607
11608 // Attach the initializer to the decl.
11609 VDecl->setInit(Init);
11610
11611 if (VDecl->isLocalVarDecl()) {
11612 // Don't check the initializer if the declaration is malformed.
11613 if (VDecl->isInvalidDecl()) {
11614 // do nothing
11615
11616 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11617 // This is true even in C++ for OpenCL.
11618 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11619 CheckForConstantInitializer(Init, DclT);
11620
11621 // Otherwise, C++ does not restrict the initializer.
11622 } else if (getLangOpts().CPlusPlus) {
11623 // do nothing
11624
11625 // C99 6.7.8p4: All the expressions in an initializer for an object that has
11626 // static storage duration shall be constant expressions or string literals.
11627 } else if (VDecl->getStorageClass() == SC_Static) {
11628 CheckForConstantInitializer(Init, DclT);
11629
11630 // C89 is stricter than C99 for aggregate initializers.
11631 // C89 6.5.7p3: All the expressions [...] in an initializer list
11632 // for an object that has aggregate or union type shall be
11633 // constant expressions.
11634 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11635 isa<InitListExpr>(Init)) {
11636 const Expr *Culprit;
11637 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11638 Diag(Culprit->getExprLoc(),
11639 diag::ext_aggregate_init_not_constant)
11640 << Culprit->getSourceRange();
11641 }
11642 }
11643
11644 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11645 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11646 if (VDecl->hasLocalStorage())
11647 BE->getBlockDecl()->setCanAvoidCopyToHeap();
11648 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11649 VDecl->getLexicalDeclContext()->isRecord()) {
11650 // This is an in-class initialization for a static data member, e.g.,
11651 //
11652 // struct S {
11653 // static const int value = 17;
11654 // };
11655
11656 // C++ [class.mem]p4:
11657 // A member-declarator can contain a constant-initializer only
11658 // if it declares a static member (9.4) of const integral or
11659 // const enumeration type, see 9.4.2.
11660 //
11661 // C++11 [class.static.data]p3:
11662 // If a non-volatile non-inline const static data member is of integral
11663 // or enumeration type, its declaration in the class definition can
11664 // specify a brace-or-equal-initializer in which every initializer-clause
11665 // that is an assignment-expression is a constant expression. A static
11666 // data member of literal type can be declared in the class definition
11667 // with the constexpr specifier; if so, its declaration shall specify a
11668 // brace-or-equal-initializer in which every initializer-clause that is
11669 // an assignment-expression is a constant expression.
11670
11671 // Do nothing on dependent types.
11672 if (DclT->isDependentType()) {
11673
11674 // Allow any 'static constexpr' members, whether or not they are of literal
11675 // type. We separately check that every constexpr variable is of literal
11676 // type.
11677 } else if (VDecl->isConstexpr()) {
11678
11679 // Require constness.
11680 } else if (!DclT.isConstQualified()) {
11681 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11682 << Init->getSourceRange();
11683 VDecl->setInvalidDecl();
11684
11685 // We allow integer constant expressions in all cases.
11686 } else if (DclT->isIntegralOrEnumerationType()) {
11687 // Check whether the expression is a constant expression.
11688 SourceLocation Loc;
11689 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11690 // In C++11, a non-constexpr const static data member with an
11691 // in-class initializer cannot be volatile.
11692 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11693 else if (Init->isValueDependent())
11694 ; // Nothing to check.
11695 else if (Init->isIntegerConstantExpr(Context, &Loc))
11696 ; // Ok, it's an ICE!
11697 else if (Init->getType()->isScopedEnumeralType() &&
11698 Init->isCXX11ConstantExpr(Context))
11699 ; // Ok, it is a scoped-enum constant expression.
11700 else if (Init->isEvaluatable(Context)) {
11701 // If we can constant fold the initializer through heroics, accept it,
11702 // but report this as a use of an extension for -pedantic.
11703 Diag(Loc, diag::ext_in_class_initializer_non_constant)
11704 << Init->getSourceRange();
11705 } else {
11706 // Otherwise, this is some crazy unknown case. Report the issue at the
11707 // location provided by the isIntegerConstantExpr failed check.
11708 Diag(Loc, diag::err_in_class_initializer_non_constant)
11709 << Init->getSourceRange();
11710 VDecl->setInvalidDecl();
11711 }
11712
11713 // We allow foldable floating-point constants as an extension.
11714 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11715 // In C++98, this is a GNU extension. In C++11, it is not, but we support
11716 // it anyway and provide a fixit to add the 'constexpr'.
11717 if (getLangOpts().CPlusPlus11) {
11718 Diag(VDecl->getLocation(),
11719 diag::ext_in_class_initializer_float_type_cxx11)
11720 << DclT << Init->getSourceRange();
11721 Diag(VDecl->getBeginLoc(),
11722 diag::note_in_class_initializer_float_type_cxx11)
11723 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11724 } else {
11725 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11726 << DclT << Init->getSourceRange();
11727
11728 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11729 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11730 << Init->getSourceRange();
11731 VDecl->setInvalidDecl();
11732 }
11733 }
11734
11735 // Suggest adding 'constexpr' in C++11 for literal types.
11736 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11737 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11738 << DclT << Init->getSourceRange()
11739 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11740 VDecl->setConstexpr(true);
11741
11742 } else {
11743 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11744 << DclT << Init->getSourceRange();
11745 VDecl->setInvalidDecl();
11746 }
11747 } else if (VDecl->isFileVarDecl()) {
11748 // In C, extern is typically used to avoid tentative definitions when
11749 // declaring variables in headers, but adding an intializer makes it a
11750 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11751 // In C++, extern is often used to give implictly static const variables
11752 // external linkage, so don't warn in that case. If selectany is present,
11753 // this might be header code intended for C and C++ inclusion, so apply the
11754 // C++ rules.
11755 if (VDecl->getStorageClass() == SC_Extern &&
11756 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11757 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11758 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11759 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11760 Diag(VDecl->getLocation(), diag::warn_extern_init);
11761
11762 // In Microsoft C++ mode, a const variable defined in namespace scope has
11763 // external linkage by default if the variable is declared with
11764 // __declspec(dllexport).
11765 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11766 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11767 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11768 VDecl->setStorageClass(SC_Extern);
11769
11770 // C99 6.7.8p4. All file scoped initializers need to be constant.
11771 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11772 CheckForConstantInitializer(Init, DclT);
11773 }
11774
11775 QualType InitType = Init->getType();
11776 if (!InitType.isNull() &&
11777 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11778 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
11779 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
11780
11781 // We will represent direct-initialization similarly to copy-initialization:
11782 // int x(1); -as-> int x = 1;
11783 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11784 //
11785 // Clients that want to distinguish between the two forms, can check for
11786 // direct initializer using VarDecl::getInitStyle().
11787 // A major benefit is that clients that don't particularly care about which
11788 // exactly form was it (like the CodeGen) can handle both cases without
11789 // special case code.
11790
11791 // C++ 8.5p11:
11792 // The form of initialization (using parentheses or '=') is generally
11793 // insignificant, but does matter when the entity being initialized has a
11794 // class type.
11795 if (CXXDirectInit) {
11796 assert(DirectInit && "Call-style initializer must be direct init.");
11797 VDecl->setInitStyle(VarDecl::CallInit);
11798 } else if (DirectInit) {
11799 // This must be list-initialization. No other way is direct-initialization.
11800 VDecl->setInitStyle(VarDecl::ListInit);
11801 }
11802
11803 CheckCompleteVariableDeclaration(VDecl);
11804 }
11805
11806 /// ActOnInitializerError - Given that there was an error parsing an
11807 /// initializer for the given declaration, try to return to some form
11808 /// of sanity.
ActOnInitializerError(Decl * D)11809 void Sema::ActOnInitializerError(Decl *D) {
11810 // Our main concern here is re-establishing invariants like "a
11811 // variable's type is either dependent or complete".
11812 if (!D || D->isInvalidDecl()) return;
11813
11814 VarDecl *VD = dyn_cast<VarDecl>(D);
11815 if (!VD) return;
11816
11817 // Bindings are not usable if we can't make sense of the initializer.
11818 if (auto *DD = dyn_cast<DecompositionDecl>(D))
11819 for (auto *BD : DD->bindings())
11820 BD->setInvalidDecl();
11821
11822 // Auto types are meaningless if we can't make sense of the initializer.
11823 if (ParsingInitForAutoVars.count(D)) {
11824 D->setInvalidDecl();
11825 return;
11826 }
11827
11828 QualType Ty = VD->getType();
11829 if (Ty->isDependentType()) return;
11830
11831 // Require a complete type.
11832 if (RequireCompleteType(VD->getLocation(),
11833 Context.getBaseElementType(Ty),
11834 diag::err_typecheck_decl_incomplete_type)) {
11835 VD->setInvalidDecl();
11836 return;
11837 }
11838
11839 // Require a non-abstract type.
11840 if (RequireNonAbstractType(VD->getLocation(), Ty,
11841 diag::err_abstract_type_in_decl,
11842 AbstractVariableType)) {
11843 VD->setInvalidDecl();
11844 return;
11845 }
11846
11847 // Don't bother complaining about constructors or destructors,
11848 // though.
11849 }
11850
ActOnUninitializedDecl(Decl * RealDecl)11851 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11852 // If there is no declaration, there was an error parsing it. Just ignore it.
11853 if (!RealDecl)
11854 return;
11855
11856 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11857 QualType Type = Var->getType();
11858
11859 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11860 if (isa<DecompositionDecl>(RealDecl)) {
11861 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11862 Var->setInvalidDecl();
11863 return;
11864 }
11865
11866 if (Type->isUndeducedType() &&
11867 DeduceVariableDeclarationType(Var, false, nullptr))
11868 return;
11869
11870 // C++11 [class.static.data]p3: A static data member can be declared with
11871 // the constexpr specifier; if so, its declaration shall specify
11872 // a brace-or-equal-initializer.
11873 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11874 // the definition of a variable [...] or the declaration of a static data
11875 // member.
11876 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11877 !Var->isThisDeclarationADemotedDefinition()) {
11878 if (Var->isStaticDataMember()) {
11879 // C++1z removes the relevant rule; the in-class declaration is always
11880 // a definition there.
11881 if (!getLangOpts().CPlusPlus17) {
11882 Diag(Var->getLocation(),
11883 diag::err_constexpr_static_mem_var_requires_init)
11884 << Var->getDeclName();
11885 Var->setInvalidDecl();
11886 return;
11887 }
11888 } else {
11889 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11890 Var->setInvalidDecl();
11891 return;
11892 }
11893 }
11894
11895 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11896 // be initialized.
11897 if (!Var->isInvalidDecl() &&
11898 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11899 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11900 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11901 Var->setInvalidDecl();
11902 return;
11903 }
11904
11905 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
11906 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
11907 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11908 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
11909 NTCUC_DefaultInitializedObject, NTCUK_Init);
11910
11911
11912 switch (DefKind) {
11913 case VarDecl::Definition:
11914 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11915 break;
11916
11917 // We have an out-of-line definition of a static data member
11918 // that has an in-class initializer, so we type-check this like
11919 // a declaration.
11920 //
11921 LLVM_FALLTHROUGH;
11922
11923 case VarDecl::DeclarationOnly:
11924 // It's only a declaration.
11925
11926 // Block scope. C99 6.7p7: If an identifier for an object is
11927 // declared with no linkage (C99 6.2.2p6), the type for the
11928 // object shall be complete.
11929 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11930 !Var->hasLinkage() && !Var->isInvalidDecl() &&
11931 RequireCompleteType(Var->getLocation(), Type,
11932 diag::err_typecheck_decl_incomplete_type))
11933 Var->setInvalidDecl();
11934
11935 // Make sure that the type is not abstract.
11936 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11937 RequireNonAbstractType(Var->getLocation(), Type,
11938 diag::err_abstract_type_in_decl,
11939 AbstractVariableType))
11940 Var->setInvalidDecl();
11941 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11942 Var->getStorageClass() == SC_PrivateExtern) {
11943 Diag(Var->getLocation(), diag::warn_private_extern);
11944 Diag(Var->getLocation(), diag::note_private_extern);
11945 }
11946
11947 return;
11948
11949 case VarDecl::TentativeDefinition:
11950 // File scope. C99 6.9.2p2: A declaration of an identifier for an
11951 // object that has file scope without an initializer, and without a
11952 // storage-class specifier or with the storage-class specifier "static",
11953 // constitutes a tentative definition. Note: A tentative definition with
11954 // external linkage is valid (C99 6.2.2p5).
11955 if (!Var->isInvalidDecl()) {
11956 if (const IncompleteArrayType *ArrayT
11957 = Context.getAsIncompleteArrayType(Type)) {
11958 if (RequireCompleteType(Var->getLocation(),
11959 ArrayT->getElementType(),
11960 diag::err_illegal_decl_array_incomplete_type))
11961 Var->setInvalidDecl();
11962 } else if (Var->getStorageClass() == SC_Static) {
11963 // C99 6.9.2p3: If the declaration of an identifier for an object is
11964 // a tentative definition and has internal linkage (C99 6.2.2p3), the
11965 // declared type shall not be an incomplete type.
11966 // NOTE: code such as the following
11967 // static struct s;
11968 // struct s { int a; };
11969 // is accepted by gcc. Hence here we issue a warning instead of
11970 // an error and we do not invalidate the static declaration.
11971 // NOTE: to avoid multiple warnings, only check the first declaration.
11972 if (Var->isFirstDecl())
11973 RequireCompleteType(Var->getLocation(), Type,
11974 diag::ext_typecheck_decl_incomplete_type);
11975 }
11976 }
11977
11978 // Record the tentative definition; we're done.
11979 if (!Var->isInvalidDecl())
11980 TentativeDefinitions.push_back(Var);
11981 return;
11982 }
11983
11984 // Provide a specific diagnostic for uninitialized variable
11985 // definitions with incomplete array type.
11986 if (Type->isIncompleteArrayType()) {
11987 Diag(Var->getLocation(),
11988 diag::err_typecheck_incomplete_array_needs_initializer);
11989 Var->setInvalidDecl();
11990 return;
11991 }
11992
11993 // Provide a specific diagnostic for uninitialized variable
11994 // definitions with reference type.
11995 if (Type->isReferenceType()) {
11996 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11997 << Var->getDeclName()
11998 << SourceRange(Var->getLocation(), Var->getLocation());
11999 Var->setInvalidDecl();
12000 return;
12001 }
12002
12003 // Do not attempt to type-check the default initializer for a
12004 // variable with dependent type.
12005 if (Type->isDependentType())
12006 return;
12007
12008 if (Var->isInvalidDecl())
12009 return;
12010
12011 if (!Var->hasAttr<AliasAttr>()) {
12012 if (RequireCompleteType(Var->getLocation(),
12013 Context.getBaseElementType(Type),
12014 diag::err_typecheck_decl_incomplete_type)) {
12015 Var->setInvalidDecl();
12016 return;
12017 }
12018 } else {
12019 return;
12020 }
12021
12022 // The variable can not have an abstract class type.
12023 if (RequireNonAbstractType(Var->getLocation(), Type,
12024 diag::err_abstract_type_in_decl,
12025 AbstractVariableType)) {
12026 Var->setInvalidDecl();
12027 return;
12028 }
12029
12030 // Check for jumps past the implicit initializer. C++0x
12031 // clarifies that this applies to a "variable with automatic
12032 // storage duration", not a "local variable".
12033 // C++11 [stmt.dcl]p3
12034 // A program that jumps from a point where a variable with automatic
12035 // storage duration is not in scope to a point where it is in scope is
12036 // ill-formed unless the variable has scalar type, class type with a
12037 // trivial default constructor and a trivial destructor, a cv-qualified
12038 // version of one of these types, or an array of one of the preceding
12039 // types and is declared without an initializer.
12040 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12041 if (const RecordType *Record
12042 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12043 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12044 // Mark the function (if we're in one) for further checking even if the
12045 // looser rules of C++11 do not require such checks, so that we can
12046 // diagnose incompatibilities with C++98.
12047 if (!CXXRecord->isPOD())
12048 setFunctionHasBranchProtectedScope();
12049 }
12050 }
12051 // In OpenCL, we can't initialize objects in the __local address space,
12052 // even implicitly, so don't synthesize an implicit initializer.
12053 if (getLangOpts().OpenCL &&
12054 Var->getType().getAddressSpace() == LangAS::opencl_local)
12055 return;
12056 // C++03 [dcl.init]p9:
12057 // If no initializer is specified for an object, and the
12058 // object is of (possibly cv-qualified) non-POD class type (or
12059 // array thereof), the object shall be default-initialized; if
12060 // the object is of const-qualified type, the underlying class
12061 // type shall have a user-declared default
12062 // constructor. Otherwise, if no initializer is specified for
12063 // a non- static object, the object and its subobjects, if
12064 // any, have an indeterminate initial value); if the object
12065 // or any of its subobjects are of const-qualified type, the
12066 // program is ill-formed.
12067 // C++0x [dcl.init]p11:
12068 // If no initializer is specified for an object, the object is
12069 // default-initialized; [...].
12070 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12071 InitializationKind Kind
12072 = InitializationKind::CreateDefault(Var->getLocation());
12073
12074 InitializationSequence InitSeq(*this, Entity, Kind, None);
12075 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12076 if (Init.isInvalid())
12077 Var->setInvalidDecl();
12078 else if (Init.get()) {
12079 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12080 // This is important for template substitution.
12081 Var->setInitStyle(VarDecl::CallInit);
12082 }
12083
12084 CheckCompleteVariableDeclaration(Var);
12085 }
12086 }
12087
ActOnCXXForRangeDecl(Decl * D)12088 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12089 // If there is no declaration, there was an error parsing it. Ignore it.
12090 if (!D)
12091 return;
12092
12093 VarDecl *VD = dyn_cast<VarDecl>(D);
12094 if (!VD) {
12095 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12096 D->setInvalidDecl();
12097 return;
12098 }
12099
12100 VD->setCXXForRangeDecl(true);
12101
12102 // for-range-declaration cannot be given a storage class specifier.
12103 int Error = -1;
12104 switch (VD->getStorageClass()) {
12105 case SC_None:
12106 break;
12107 case SC_Extern:
12108 Error = 0;
12109 break;
12110 case SC_Static:
12111 Error = 1;
12112 break;
12113 case SC_PrivateExtern:
12114 Error = 2;
12115 break;
12116 case SC_Auto:
12117 Error = 3;
12118 break;
12119 case SC_Register:
12120 Error = 4;
12121 break;
12122 }
12123 if (Error != -1) {
12124 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12125 << VD->getDeclName() << Error;
12126 D->setInvalidDecl();
12127 }
12128 }
12129
12130 StmtResult
ActOnCXXForRangeIdentifier(Scope * S,SourceLocation IdentLoc,IdentifierInfo * Ident,ParsedAttributes & Attrs,SourceLocation AttrEnd)12131 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12132 IdentifierInfo *Ident,
12133 ParsedAttributes &Attrs,
12134 SourceLocation AttrEnd) {
12135 // C++1y [stmt.iter]p1:
12136 // A range-based for statement of the form
12137 // for ( for-range-identifier : for-range-initializer ) statement
12138 // is equivalent to
12139 // for ( auto&& for-range-identifier : for-range-initializer ) statement
12140 DeclSpec DS(Attrs.getPool().getFactory());
12141
12142 const char *PrevSpec;
12143 unsigned DiagID;
12144 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12145 getPrintingPolicy());
12146
12147 Declarator D(DS, DeclaratorContext::ForContext);
12148 D.SetIdentifier(Ident, IdentLoc);
12149 D.takeAttributes(Attrs, AttrEnd);
12150
12151 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12152 IdentLoc);
12153 Decl *Var = ActOnDeclarator(S, D);
12154 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12155 FinalizeDeclaration(Var);
12156 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12157 AttrEnd.isValid() ? AttrEnd : IdentLoc);
12158 }
12159
CheckCompleteVariableDeclaration(VarDecl * var)12160 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12161 if (var->isInvalidDecl()) return;
12162
12163 if (getLangOpts().OpenCL) {
12164 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12165 // initialiser
12166 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12167 !var->hasInit()) {
12168 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12169 << 1 /*Init*/;
12170 var->setInvalidDecl();
12171 return;
12172 }
12173 }
12174
12175 // In Objective-C, don't allow jumps past the implicit initialization of a
12176 // local retaining variable.
12177 if (getLangOpts().ObjC &&
12178 var->hasLocalStorage()) {
12179 switch (var->getType().getObjCLifetime()) {
12180 case Qualifiers::OCL_None:
12181 case Qualifiers::OCL_ExplicitNone:
12182 case Qualifiers::OCL_Autoreleasing:
12183 break;
12184
12185 case Qualifiers::OCL_Weak:
12186 case Qualifiers::OCL_Strong:
12187 setFunctionHasBranchProtectedScope();
12188 break;
12189 }
12190 }
12191
12192 if (var->hasLocalStorage() &&
12193 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12194 setFunctionHasBranchProtectedScope();
12195
12196 // Warn about externally-visible variables being defined without a
12197 // prior declaration. We only want to do this for global
12198 // declarations, but we also specifically need to avoid doing it for
12199 // class members because the linkage of an anonymous class can
12200 // change if it's later given a typedef name.
12201 if (var->isThisDeclarationADefinition() &&
12202 var->getDeclContext()->getRedeclContext()->isFileContext() &&
12203 var->isExternallyVisible() && var->hasLinkage() &&
12204 !var->isInline() && !var->getDescribedVarTemplate() &&
12205 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12206 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12207 var->getLocation())) {
12208 // Find a previous declaration that's not a definition.
12209 VarDecl *prev = var->getPreviousDecl();
12210 while (prev && prev->isThisDeclarationADefinition())
12211 prev = prev->getPreviousDecl();
12212
12213 if (!prev) {
12214 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12215 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12216 << /* variable */ 0;
12217 }
12218 }
12219
12220 // Cache the result of checking for constant initialization.
12221 Optional<bool> CacheHasConstInit;
12222 const Expr *CacheCulprit = nullptr;
12223 auto checkConstInit = [&]() mutable {
12224 if (!CacheHasConstInit)
12225 CacheHasConstInit = var->getInit()->isConstantInitializer(
12226 Context, var->getType()->isReferenceType(), &CacheCulprit);
12227 return *CacheHasConstInit;
12228 };
12229
12230 if (var->getTLSKind() == VarDecl::TLS_Static) {
12231 if (var->getType().isDestructedType()) {
12232 // GNU C++98 edits for __thread, [basic.start.term]p3:
12233 // The type of an object with thread storage duration shall not
12234 // have a non-trivial destructor.
12235 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12236 if (getLangOpts().CPlusPlus11)
12237 Diag(var->getLocation(), diag::note_use_thread_local);
12238 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12239 if (!checkConstInit()) {
12240 // GNU C++98 edits for __thread, [basic.start.init]p4:
12241 // An object of thread storage duration shall not require dynamic
12242 // initialization.
12243 // FIXME: Need strict checking here.
12244 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12245 << CacheCulprit->getSourceRange();
12246 if (getLangOpts().CPlusPlus11)
12247 Diag(var->getLocation(), diag::note_use_thread_local);
12248 }
12249 }
12250 }
12251
12252 // Apply section attributes and pragmas to global variables.
12253 bool GlobalStorage = var->hasGlobalStorage();
12254 if (GlobalStorage && var->isThisDeclarationADefinition() &&
12255 !inTemplateInstantiation()) {
12256 PragmaStack<StringLiteral *> *Stack = nullptr;
12257 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12258 if (var->getType().isConstQualified())
12259 Stack = &ConstSegStack;
12260 else if (!var->getInit()) {
12261 Stack = &BSSSegStack;
12262 SectionFlags |= ASTContext::PSF_Write;
12263 } else {
12264 Stack = &DataSegStack;
12265 SectionFlags |= ASTContext::PSF_Write;
12266 }
12267 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
12268 var->addAttr(SectionAttr::CreateImplicit(
12269 Context, SectionAttr::Declspec_allocate,
12270 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
12271 }
12272 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12273 if (UnifySection(SA->getName(), SectionFlags, var))
12274 var->dropAttr<SectionAttr>();
12275
12276 // Apply the init_seg attribute if this has an initializer. If the
12277 // initializer turns out to not be dynamic, we'll end up ignoring this
12278 // attribute.
12279 if (CurInitSeg && var->getInit())
12280 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12281 CurInitSegLoc));
12282 }
12283
12284 // All the following checks are C++ only.
12285 if (!getLangOpts().CPlusPlus) {
12286 // If this variable must be emitted, add it as an initializer for the
12287 // current module.
12288 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12289 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12290 return;
12291 }
12292
12293 if (auto *DD = dyn_cast<DecompositionDecl>(var))
12294 CheckCompleteDecompositionDeclaration(DD);
12295
12296 QualType type = var->getType();
12297 if (type->isDependentType()) return;
12298
12299 if (var->hasAttr<BlocksAttr>())
12300 getCurFunction()->addByrefBlockVar(var);
12301
12302 Expr *Init = var->getInit();
12303 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12304 QualType baseType = Context.getBaseElementType(type);
12305
12306 if (Init && !Init->isValueDependent()) {
12307 if (var->isConstexpr()) {
12308 SmallVector<PartialDiagnosticAt, 8> Notes;
12309 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12310 SourceLocation DiagLoc = var->getLocation();
12311 // If the note doesn't add any useful information other than a source
12312 // location, fold it into the primary diagnostic.
12313 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12314 diag::note_invalid_subexpr_in_const_expr) {
12315 DiagLoc = Notes[0].first;
12316 Notes.clear();
12317 }
12318 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12319 << var << Init->getSourceRange();
12320 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12321 Diag(Notes[I].first, Notes[I].second);
12322 }
12323 } else if (var->mightBeUsableInConstantExpressions(Context)) {
12324 // Check whether the initializer of a const variable of integral or
12325 // enumeration type is an ICE now, since we can't tell whether it was
12326 // initialized by a constant expression if we check later.
12327 var->checkInitIsICE();
12328 }
12329
12330 // Don't emit further diagnostics about constexpr globals since they
12331 // were just diagnosed.
12332 if (!var->isConstexpr() && GlobalStorage &&
12333 var->hasAttr<RequireConstantInitAttr>()) {
12334 // FIXME: Need strict checking in C++03 here.
12335 bool DiagErr = getLangOpts().CPlusPlus11
12336 ? !var->checkInitIsICE() : !checkConstInit();
12337 if (DiagErr) {
12338 auto attr = var->getAttr<RequireConstantInitAttr>();
12339 Diag(var->getLocation(), diag::err_require_constant_init_failed)
12340 << Init->getSourceRange();
12341 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
12342 << attr->getRange();
12343 if (getLangOpts().CPlusPlus11) {
12344 APValue Value;
12345 SmallVector<PartialDiagnosticAt, 8> Notes;
12346 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12347 for (auto &it : Notes)
12348 Diag(it.first, it.second);
12349 } else {
12350 Diag(CacheCulprit->getExprLoc(),
12351 diag::note_invalid_subexpr_in_const_expr)
12352 << CacheCulprit->getSourceRange();
12353 }
12354 }
12355 }
12356 else if (!var->isConstexpr() && IsGlobal &&
12357 !getDiagnostics().isIgnored(diag::warn_global_constructor,
12358 var->getLocation())) {
12359 // Warn about globals which don't have a constant initializer. Don't
12360 // warn about globals with a non-trivial destructor because we already
12361 // warned about them.
12362 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12363 if (!(RD && !RD->hasTrivialDestructor())) {
12364 if (!checkConstInit())
12365 Diag(var->getLocation(), diag::warn_global_constructor)
12366 << Init->getSourceRange();
12367 }
12368 }
12369 }
12370
12371 // Require the destructor.
12372 if (const RecordType *recordType = baseType->getAs<RecordType>())
12373 FinalizeVarWithDestructor(var, recordType);
12374
12375 // If this variable must be emitted, add it as an initializer for the current
12376 // module.
12377 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12378 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12379 }
12380
12381 /// Determines if a variable's alignment is dependent.
hasDependentAlignment(VarDecl * VD)12382 static bool hasDependentAlignment(VarDecl *VD) {
12383 if (VD->getType()->isDependentType())
12384 return true;
12385 for (auto *I : VD->specific_attrs<AlignedAttr>())
12386 if (I->isAlignmentDependent())
12387 return true;
12388 return false;
12389 }
12390
12391 /// Check if VD needs to be dllexport/dllimport due to being in a
12392 /// dllexport/import function.
CheckStaticLocalForDllExport(VarDecl * VD)12393 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12394 assert(VD->isStaticLocal());
12395
12396 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12397
12398 // Find outermost function when VD is in lambda function.
12399 while (FD && !getDLLAttr(FD) &&
12400 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12401 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12402 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12403 }
12404
12405 if (!FD)
12406 return;
12407
12408 // Static locals inherit dll attributes from their function.
12409 if (Attr *A = getDLLAttr(FD)) {
12410 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12411 NewAttr->setInherited(true);
12412 VD->addAttr(NewAttr);
12413 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12414 auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
12415 getASTContext(),
12416 A->getSpellingListIndex());
12417 NewAttr->setInherited(true);
12418 VD->addAttr(NewAttr);
12419
12420 // Export this function to enforce exporting this static variable even
12421 // if it is not used in this compilation unit.
12422 if (!FD->hasAttr<DLLExportAttr>())
12423 FD->addAttr(NewAttr);
12424
12425 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12426 auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12427 getASTContext(),
12428 A->getSpellingListIndex());
12429 NewAttr->setInherited(true);
12430 VD->addAttr(NewAttr);
12431 }
12432 }
12433
12434 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12435 /// any semantic actions necessary after any initializer has been attached.
FinalizeDeclaration(Decl * ThisDecl)12436 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12437 // Note that we are no longer parsing the initializer for this declaration.
12438 ParsingInitForAutoVars.erase(ThisDecl);
12439
12440 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12441 if (!VD)
12442 return;
12443
12444 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12445 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12446 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12447 if (PragmaClangBSSSection.Valid)
12448 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12449 PragmaClangBSSSection.SectionName,
12450 PragmaClangBSSSection.PragmaLocation));
12451 if (PragmaClangDataSection.Valid)
12452 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12453 PragmaClangDataSection.SectionName,
12454 PragmaClangDataSection.PragmaLocation));
12455 if (PragmaClangRodataSection.Valid)
12456 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12457 PragmaClangRodataSection.SectionName,
12458 PragmaClangRodataSection.PragmaLocation));
12459 }
12460
12461 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12462 for (auto *BD : DD->bindings()) {
12463 FinalizeDeclaration(BD);
12464 }
12465 }
12466
12467 checkAttributesAfterMerging(*this, *VD);
12468
12469 // Perform TLS alignment check here after attributes attached to the variable
12470 // which may affect the alignment have been processed. Only perform the check
12471 // if the target has a maximum TLS alignment (zero means no constraints).
12472 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12473 // Protect the check so that it's not performed on dependent types and
12474 // dependent alignments (we can't determine the alignment in that case).
12475 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12476 !VD->isInvalidDecl()) {
12477 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12478 if (Context.getDeclAlign(VD) > MaxAlignChars) {
12479 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12480 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12481 << (unsigned)MaxAlignChars.getQuantity();
12482 }
12483 }
12484 }
12485
12486 if (VD->isStaticLocal()) {
12487 CheckStaticLocalForDllExport(VD);
12488
12489 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12490 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12491 // function, only __shared__ variables or variables without any device
12492 // memory qualifiers may be declared with static storage class.
12493 // Note: It is unclear how a function-scope non-const static variable
12494 // without device memory qualifier is implemented, therefore only static
12495 // const variable without device memory qualifier is allowed.
12496 [&]() {
12497 if (!getLangOpts().CUDA)
12498 return;
12499 if (VD->hasAttr<CUDASharedAttr>())
12500 return;
12501 if (VD->getType().isConstQualified() &&
12502 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12503 return;
12504 if (CUDADiagIfDeviceCode(VD->getLocation(),
12505 diag::err_device_static_local_var)
12506 << CurrentCUDATarget())
12507 VD->setInvalidDecl();
12508 }();
12509 }
12510 }
12511
12512 // Perform check for initializers of device-side global variables.
12513 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12514 // 7.5). We must also apply the same checks to all __shared__
12515 // variables whether they are local or not. CUDA also allows
12516 // constant initializers for __constant__ and __device__ variables.
12517 if (getLangOpts().CUDA)
12518 checkAllowedCUDAInitializer(VD);
12519
12520 // Grab the dllimport or dllexport attribute off of the VarDecl.
12521 const InheritableAttr *DLLAttr = getDLLAttr(VD);
12522
12523 // Imported static data members cannot be defined out-of-line.
12524 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12525 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12526 VD->isThisDeclarationADefinition()) {
12527 // We allow definitions of dllimport class template static data members
12528 // with a warning.
12529 CXXRecordDecl *Context =
12530 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12531 bool IsClassTemplateMember =
12532 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12533 Context->getDescribedClassTemplate();
12534
12535 Diag(VD->getLocation(),
12536 IsClassTemplateMember
12537 ? diag::warn_attribute_dllimport_static_field_definition
12538 : diag::err_attribute_dllimport_static_field_definition);
12539 Diag(IA->getLocation(), diag::note_attribute);
12540 if (!IsClassTemplateMember)
12541 VD->setInvalidDecl();
12542 }
12543 }
12544
12545 // dllimport/dllexport variables cannot be thread local, their TLS index
12546 // isn't exported with the variable.
12547 if (DLLAttr && VD->getTLSKind()) {
12548 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12549 if (F && getDLLAttr(F)) {
12550 assert(VD->isStaticLocal());
12551 // But if this is a static local in a dlimport/dllexport function, the
12552 // function will never be inlined, which means the var would never be
12553 // imported, so having it marked import/export is safe.
12554 } else {
12555 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12556 << DLLAttr;
12557 VD->setInvalidDecl();
12558 }
12559 }
12560
12561 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12562 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12563 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12564 VD->dropAttr<UsedAttr>();
12565 }
12566 }
12567
12568 const DeclContext *DC = VD->getDeclContext();
12569 // If there's a #pragma GCC visibility in scope, and this isn't a class
12570 // member, set the visibility of this variable.
12571 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12572 AddPushedVisibilityAttribute(VD);
12573
12574 // FIXME: Warn on unused var template partial specializations.
12575 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12576 MarkUnusedFileScopedDecl(VD);
12577
12578 // Now we have parsed the initializer and can update the table of magic
12579 // tag values.
12580 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12581 !VD->getType()->isIntegralOrEnumerationType())
12582 return;
12583
12584 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12585 const Expr *MagicValueExpr = VD->getInit();
12586 if (!MagicValueExpr) {
12587 continue;
12588 }
12589 llvm::APSInt MagicValueInt;
12590 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12591 Diag(I->getRange().getBegin(),
12592 diag::err_type_tag_for_datatype_not_ice)
12593 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12594 continue;
12595 }
12596 if (MagicValueInt.getActiveBits() > 64) {
12597 Diag(I->getRange().getBegin(),
12598 diag::err_type_tag_for_datatype_too_large)
12599 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12600 continue;
12601 }
12602 uint64_t MagicValue = MagicValueInt.getZExtValue();
12603 RegisterTypeTagForDatatype(I->getArgumentKind(),
12604 MagicValue,
12605 I->getMatchingCType(),
12606 I->getLayoutCompatible(),
12607 I->getMustBeNull());
12608 }
12609 }
12610
hasDeducedAuto(DeclaratorDecl * DD)12611 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12612 auto *VD = dyn_cast<VarDecl>(DD);
12613 return VD && !VD->getType()->hasAutoForTrailingReturnType();
12614 }
12615
FinalizeDeclaratorGroup(Scope * S,const DeclSpec & DS,ArrayRef<Decl * > Group)12616 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12617 ArrayRef<Decl *> Group) {
12618 SmallVector<Decl*, 8> Decls;
12619
12620 if (DS.isTypeSpecOwned())
12621 Decls.push_back(DS.getRepAsDecl());
12622
12623 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12624 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12625 bool DiagnosedMultipleDecomps = false;
12626 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12627 bool DiagnosedNonDeducedAuto = false;
12628
12629 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12630 if (Decl *D = Group[i]) {
12631 // For declarators, there are some additional syntactic-ish checks we need
12632 // to perform.
12633 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12634 if (!FirstDeclaratorInGroup)
12635 FirstDeclaratorInGroup = DD;
12636 if (!FirstDecompDeclaratorInGroup)
12637 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12638 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12639 !hasDeducedAuto(DD))
12640 FirstNonDeducedAutoInGroup = DD;
12641
12642 if (FirstDeclaratorInGroup != DD) {
12643 // A decomposition declaration cannot be combined with any other
12644 // declaration in the same group.
12645 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12646 Diag(FirstDecompDeclaratorInGroup->getLocation(),
12647 diag::err_decomp_decl_not_alone)
12648 << FirstDeclaratorInGroup->getSourceRange()
12649 << DD->getSourceRange();
12650 DiagnosedMultipleDecomps = true;
12651 }
12652
12653 // A declarator that uses 'auto' in any way other than to declare a
12654 // variable with a deduced type cannot be combined with any other
12655 // declarator in the same group.
12656 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12657 Diag(FirstNonDeducedAutoInGroup->getLocation(),
12658 diag::err_auto_non_deduced_not_alone)
12659 << FirstNonDeducedAutoInGroup->getType()
12660 ->hasAutoForTrailingReturnType()
12661 << FirstDeclaratorInGroup->getSourceRange()
12662 << DD->getSourceRange();
12663 DiagnosedNonDeducedAuto = true;
12664 }
12665 }
12666 }
12667
12668 Decls.push_back(D);
12669 }
12670 }
12671
12672 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12673 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12674 handleTagNumbering(Tag, S);
12675 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12676 getLangOpts().CPlusPlus)
12677 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12678 }
12679 }
12680
12681 return BuildDeclaratorGroup(Decls);
12682 }
12683
12684 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12685 /// group, performing any necessary semantic checking.
12686 Sema::DeclGroupPtrTy
BuildDeclaratorGroup(MutableArrayRef<Decl * > Group)12687 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12688 // C++14 [dcl.spec.auto]p7: (DR1347)
12689 // If the type that replaces the placeholder type is not the same in each
12690 // deduction, the program is ill-formed.
12691 if (Group.size() > 1) {
12692 QualType Deduced;
12693 VarDecl *DeducedDecl = nullptr;
12694 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12695 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12696 if (!D || D->isInvalidDecl())
12697 break;
12698 DeducedType *DT = D->getType()->getContainedDeducedType();
12699 if (!DT || DT->getDeducedType().isNull())
12700 continue;
12701 if (Deduced.isNull()) {
12702 Deduced = DT->getDeducedType();
12703 DeducedDecl = D;
12704 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12705 auto *AT = dyn_cast<AutoType>(DT);
12706 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12707 diag::err_auto_different_deductions)
12708 << (AT ? (unsigned)AT->getKeyword() : 3)
12709 << Deduced << DeducedDecl->getDeclName()
12710 << DT->getDeducedType() << D->getDeclName()
12711 << DeducedDecl->getInit()->getSourceRange()
12712 << D->getInit()->getSourceRange();
12713 D->setInvalidDecl();
12714 break;
12715 }
12716 }
12717 }
12718
12719 ActOnDocumentableDecls(Group);
12720
12721 return DeclGroupPtrTy::make(
12722 DeclGroupRef::Create(Context, Group.data(), Group.size()));
12723 }
12724
ActOnDocumentableDecl(Decl * D)12725 void Sema::ActOnDocumentableDecl(Decl *D) {
12726 ActOnDocumentableDecls(D);
12727 }
12728
ActOnDocumentableDecls(ArrayRef<Decl * > Group)12729 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12730 // Don't parse the comment if Doxygen diagnostics are ignored.
12731 if (Group.empty() || !Group[0])
12732 return;
12733
12734 if (Diags.isIgnored(diag::warn_doc_param_not_found,
12735 Group[0]->getLocation()) &&
12736 Diags.isIgnored(diag::warn_unknown_comment_command_name,
12737 Group[0]->getLocation()))
12738 return;
12739
12740 if (Group.size() >= 2) {
12741 // This is a decl group. Normally it will contain only declarations
12742 // produced from declarator list. But in case we have any definitions or
12743 // additional declaration references:
12744 // 'typedef struct S {} S;'
12745 // 'typedef struct S *S;'
12746 // 'struct S *pS;'
12747 // FinalizeDeclaratorGroup adds these as separate declarations.
12748 Decl *MaybeTagDecl = Group[0];
12749 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12750 Group = Group.slice(1);
12751 }
12752 }
12753
12754 // See if there are any new comments that are not attached to a decl.
12755 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12756 if (!Comments.empty() &&
12757 !Comments.back()->isAttached()) {
12758 // There is at least one comment that not attached to a decl.
12759 // Maybe it should be attached to one of these decls?
12760 //
12761 // Note that this way we pick up not only comments that precede the
12762 // declaration, but also comments that *follow* the declaration -- thanks to
12763 // the lookahead in the lexer: we've consumed the semicolon and looked
12764 // ahead through comments.
12765 for (unsigned i = 0, e = Group.size(); i != e; ++i)
12766 Context.getCommentForDecl(Group[i], &PP);
12767 }
12768 }
12769
12770 /// Common checks for a parameter-declaration that should apply to both function
12771 /// parameters and non-type template parameters.
CheckFunctionOrTemplateParamDeclarator(Scope * S,Declarator & D)12772 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
12773 // Check that there are no default arguments inside the type of this
12774 // parameter.
12775 if (getLangOpts().CPlusPlus)
12776 CheckExtraCXXDefaultArguments(D);
12777
12778 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12779 if (D.getCXXScopeSpec().isSet()) {
12780 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12781 << D.getCXXScopeSpec().getRange();
12782 }
12783
12784 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
12785 // simple identifier except [...irrelevant cases...].
12786 switch (D.getName().getKind()) {
12787 case UnqualifiedIdKind::IK_Identifier:
12788 break;
12789
12790 case UnqualifiedIdKind::IK_OperatorFunctionId:
12791 case UnqualifiedIdKind::IK_ConversionFunctionId:
12792 case UnqualifiedIdKind::IK_LiteralOperatorId:
12793 case UnqualifiedIdKind::IK_ConstructorName:
12794 case UnqualifiedIdKind::IK_DestructorName:
12795 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12796 case UnqualifiedIdKind::IK_DeductionGuideName:
12797 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12798 << GetNameForDeclarator(D).getName();
12799 break;
12800
12801 case UnqualifiedIdKind::IK_TemplateId:
12802 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12803 // GetNameForDeclarator would not produce a useful name in this case.
12804 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
12805 break;
12806 }
12807 }
12808
12809 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12810 /// to introduce parameters into function prototype scope.
ActOnParamDeclarator(Scope * S,Declarator & D)12811 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12812 const DeclSpec &DS = D.getDeclSpec();
12813
12814 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12815
12816 // C++03 [dcl.stc]p2 also permits 'auto'.
12817 StorageClass SC = SC_None;
12818 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12819 SC = SC_Register;
12820 // In C++11, the 'register' storage class specifier is deprecated.
12821 // In C++17, it is not allowed, but we tolerate it as an extension.
12822 if (getLangOpts().CPlusPlus11) {
12823 Diag(DS.getStorageClassSpecLoc(),
12824 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12825 : diag::warn_deprecated_register)
12826 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12827 }
12828 } else if (getLangOpts().CPlusPlus &&
12829 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12830 SC = SC_Auto;
12831 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12832 Diag(DS.getStorageClassSpecLoc(),
12833 diag::err_invalid_storage_class_in_func_decl);
12834 D.getMutableDeclSpec().ClearStorageClassSpecs();
12835 }
12836
12837 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12838 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12839 << DeclSpec::getSpecifierName(TSCS);
12840 if (DS.isInlineSpecified())
12841 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12842 << getLangOpts().CPlusPlus17;
12843 if (DS.hasConstexprSpecifier())
12844 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12845 << 0 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
12846
12847 DiagnoseFunctionSpecifiers(DS);
12848
12849 CheckFunctionOrTemplateParamDeclarator(S, D);
12850
12851 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12852 QualType parmDeclType = TInfo->getType();
12853
12854 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12855 IdentifierInfo *II = D.getIdentifier();
12856 if (II) {
12857 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12858 ForVisibleRedeclaration);
12859 LookupName(R, S);
12860 if (R.isSingleResult()) {
12861 NamedDecl *PrevDecl = R.getFoundDecl();
12862 if (PrevDecl->isTemplateParameter()) {
12863 // Maybe we will complain about the shadowed template parameter.
12864 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12865 // Just pretend that we didn't see the previous declaration.
12866 PrevDecl = nullptr;
12867 } else if (S->isDeclScope(PrevDecl)) {
12868 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12869 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12870
12871 // Recover by removing the name
12872 II = nullptr;
12873 D.SetIdentifier(nullptr, D.getIdentifierLoc());
12874 D.setInvalidType(true);
12875 }
12876 }
12877 }
12878
12879 // Temporarily put parameter variables in the translation unit, not
12880 // the enclosing context. This prevents them from accidentally
12881 // looking like class members in C++.
12882 ParmVarDecl *New =
12883 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12884 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12885
12886 if (D.isInvalidType())
12887 New->setInvalidDecl();
12888
12889 assert(S->isFunctionPrototypeScope());
12890 assert(S->getFunctionPrototypeDepth() >= 1);
12891 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12892 S->getNextFunctionPrototypeIndex());
12893
12894 // Add the parameter declaration into this scope.
12895 S->AddDecl(New);
12896 if (II)
12897 IdResolver.AddDecl(New);
12898
12899 ProcessDeclAttributes(S, New, D);
12900
12901 if (D.getDeclSpec().isModulePrivateSpecified())
12902 Diag(New->getLocation(), diag::err_module_private_local)
12903 << 1 << New->getDeclName()
12904 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12905 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12906
12907 if (New->hasAttr<BlocksAttr>()) {
12908 Diag(New->getLocation(), diag::err_block_on_nonlocal);
12909 }
12910 return New;
12911 }
12912
12913 /// Synthesizes a variable for a parameter arising from a
12914 /// typedef.
BuildParmVarDeclForTypedef(DeclContext * DC,SourceLocation Loc,QualType T)12915 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12916 SourceLocation Loc,
12917 QualType T) {
12918 /* FIXME: setting StartLoc == Loc.
12919 Would it be worth to modify callers so as to provide proper source
12920 location for the unnamed parameters, embedding the parameter's type? */
12921 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12922 T, Context.getTrivialTypeSourceInfo(T, Loc),
12923 SC_None, nullptr);
12924 Param->setImplicit();
12925 return Param;
12926 }
12927
DiagnoseUnusedParameters(ArrayRef<ParmVarDecl * > Parameters)12928 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12929 // Don't diagnose unused-parameter errors in template instantiations; we
12930 // will already have done so in the template itself.
12931 if (inTemplateInstantiation())
12932 return;
12933
12934 for (const ParmVarDecl *Parameter : Parameters) {
12935 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12936 !Parameter->hasAttr<UnusedAttr>()) {
12937 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12938 << Parameter->getDeclName();
12939 }
12940 }
12941 }
12942
DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl * > Parameters,QualType ReturnTy,NamedDecl * D)12943 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12944 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12945 if (LangOpts.NumLargeByValueCopy == 0) // No check.
12946 return;
12947
12948 // Warn if the return value is pass-by-value and larger than the specified
12949 // threshold.
12950 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12951 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12952 if (Size > LangOpts.NumLargeByValueCopy)
12953 Diag(D->getLocation(), diag::warn_return_value_size)
12954 << D->getDeclName() << Size;
12955 }
12956
12957 // Warn if any parameter is pass-by-value and larger than the specified
12958 // threshold.
12959 for (const ParmVarDecl *Parameter : Parameters) {
12960 QualType T = Parameter->getType();
12961 if (T->isDependentType() || !T.isPODType(Context))
12962 continue;
12963 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12964 if (Size > LangOpts.NumLargeByValueCopy)
12965 Diag(Parameter->getLocation(), diag::warn_parameter_size)
12966 << Parameter->getDeclName() << Size;
12967 }
12968 }
12969
CheckParameter(DeclContext * DC,SourceLocation StartLoc,SourceLocation NameLoc,IdentifierInfo * Name,QualType T,TypeSourceInfo * TSInfo,StorageClass SC)12970 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12971 SourceLocation NameLoc, IdentifierInfo *Name,
12972 QualType T, TypeSourceInfo *TSInfo,
12973 StorageClass SC) {
12974 // In ARC, infer a lifetime qualifier for appropriate parameter types.
12975 if (getLangOpts().ObjCAutoRefCount &&
12976 T.getObjCLifetime() == Qualifiers::OCL_None &&
12977 T->isObjCLifetimeType()) {
12978
12979 Qualifiers::ObjCLifetime lifetime;
12980
12981 // Special cases for arrays:
12982 // - if it's const, use __unsafe_unretained
12983 // - otherwise, it's an error
12984 if (T->isArrayType()) {
12985 if (!T.isConstQualified()) {
12986 if (DelayedDiagnostics.shouldDelayDiagnostics())
12987 DelayedDiagnostics.add(
12988 sema::DelayedDiagnostic::makeForbiddenType(
12989 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12990 else
12991 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12992 << TSInfo->getTypeLoc().getSourceRange();
12993 }
12994 lifetime = Qualifiers::OCL_ExplicitNone;
12995 } else {
12996 lifetime = T->getObjCARCImplicitLifetime();
12997 }
12998 T = Context.getLifetimeQualifiedType(T, lifetime);
12999 }
13000
13001 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13002 Context.getAdjustedParameterType(T),
13003 TSInfo, SC, nullptr);
13004
13005 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13006 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13007 checkNonTrivialCUnion(New->getType(), New->getLocation(),
13008 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13009
13010 // Parameters can not be abstract class types.
13011 // For record types, this is done by the AbstractClassUsageDiagnoser once
13012 // the class has been completely parsed.
13013 if (!CurContext->isRecord() &&
13014 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13015 AbstractParamType))
13016 New->setInvalidDecl();
13017
13018 // Parameter declarators cannot be interface types. All ObjC objects are
13019 // passed by reference.
13020 if (T->isObjCObjectType()) {
13021 SourceLocation TypeEndLoc =
13022 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13023 Diag(NameLoc,
13024 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13025 << FixItHint::CreateInsertion(TypeEndLoc, "*");
13026 T = Context.getObjCObjectPointerType(T);
13027 New->setType(T);
13028 }
13029
13030 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13031 // duration shall not be qualified by an address-space qualifier."
13032 // Since all parameters have automatic store duration, they can not have
13033 // an address space.
13034 if (T.getAddressSpace() != LangAS::Default &&
13035 // OpenCL allows function arguments declared to be an array of a type
13036 // to be qualified with an address space.
13037 !(getLangOpts().OpenCL &&
13038 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13039 Diag(NameLoc, diag::err_arg_with_address_space);
13040 New->setInvalidDecl();
13041 }
13042
13043 return New;
13044 }
13045
ActOnFinishKNRParamDeclarations(Scope * S,Declarator & D,SourceLocation LocAfterDecls)13046 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13047 SourceLocation LocAfterDecls) {
13048 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13049
13050 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13051 // for a K&R function.
13052 if (!FTI.hasPrototype) {
13053 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13054 --i;
13055 if (FTI.Params[i].Param == nullptr) {
13056 SmallString<256> Code;
13057 llvm::raw_svector_ostream(Code)
13058 << " int " << FTI.Params[i].Ident->getName() << ";\n";
13059 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13060 << FTI.Params[i].Ident
13061 << FixItHint::CreateInsertion(LocAfterDecls, Code);
13062
13063 // Implicitly declare the argument as type 'int' for lack of a better
13064 // type.
13065 AttributeFactory attrs;
13066 DeclSpec DS(attrs);
13067 const char* PrevSpec; // unused
13068 unsigned DiagID; // unused
13069 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13070 DiagID, Context.getPrintingPolicy());
13071 // Use the identifier location for the type source range.
13072 DS.SetRangeStart(FTI.Params[i].IdentLoc);
13073 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13074 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13075 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13076 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13077 }
13078 }
13079 }
13080 }
13081
13082 Decl *
ActOnStartOfFunctionDef(Scope * FnBodyScope,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,SkipBodyInfo * SkipBody)13083 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13084 MultiTemplateParamsArg TemplateParameterLists,
13085 SkipBodyInfo *SkipBody) {
13086 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13087 assert(D.isFunctionDeclarator() && "Not a function declarator!");
13088 Scope *ParentScope = FnBodyScope->getParent();
13089
13090 D.setFunctionDefinitionKind(FDK_Definition);
13091 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13092 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13093 }
13094
ActOnFinishInlineFunctionDef(FunctionDecl * D)13095 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13096 Consumer.HandleInlineFunctionDefinition(D);
13097 }
13098
13099 static bool
ShouldWarnAboutMissingPrototype(const FunctionDecl * FD,const FunctionDecl * & PossiblePrototype)13100 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13101 const FunctionDecl *&PossiblePrototype) {
13102 // Don't warn about invalid declarations.
13103 if (FD->isInvalidDecl())
13104 return false;
13105
13106 // Or declarations that aren't global.
13107 if (!FD->isGlobal())
13108 return false;
13109
13110 // Don't warn about C++ member functions.
13111 if (isa<CXXMethodDecl>(FD))
13112 return false;
13113
13114 // Don't warn about 'main'.
13115 if (FD->isMain())
13116 return false;
13117
13118 // Don't warn about inline functions.
13119 if (FD->isInlined())
13120 return false;
13121
13122 // Don't warn about function templates.
13123 if (FD->getDescribedFunctionTemplate())
13124 return false;
13125
13126 // Don't warn about function template specializations.
13127 if (FD->isFunctionTemplateSpecialization())
13128 return false;
13129
13130 // Don't warn for OpenCL kernels.
13131 if (FD->hasAttr<OpenCLKernelAttr>())
13132 return false;
13133
13134 // Don't warn on explicitly deleted functions.
13135 if (FD->isDeleted())
13136 return false;
13137
13138 for (const FunctionDecl *Prev = FD->getPreviousDecl();
13139 Prev; Prev = Prev->getPreviousDecl()) {
13140 // Ignore any declarations that occur in function or method
13141 // scope, because they aren't visible from the header.
13142 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13143 continue;
13144
13145 PossiblePrototype = Prev;
13146 return Prev->getType()->isFunctionNoProtoType();
13147 }
13148
13149 return true;
13150 }
13151
13152 void
CheckForFunctionRedefinition(FunctionDecl * FD,const FunctionDecl * EffectiveDefinition,SkipBodyInfo * SkipBody)13153 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13154 const FunctionDecl *EffectiveDefinition,
13155 SkipBodyInfo *SkipBody) {
13156 const FunctionDecl *Definition = EffectiveDefinition;
13157 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13158 // If this is a friend function defined in a class template, it does not
13159 // have a body until it is used, nevertheless it is a definition, see
13160 // [temp.inst]p2:
13161 //
13162 // ... for the purpose of determining whether an instantiated redeclaration
13163 // is valid according to [basic.def.odr] and [class.mem], a declaration that
13164 // corresponds to a definition in the template is considered to be a
13165 // definition.
13166 //
13167 // The following code must produce redefinition error:
13168 //
13169 // template<typename T> struct C20 { friend void func_20() {} };
13170 // C20<int> c20i;
13171 // void func_20() {}
13172 //
13173 for (auto I : FD->redecls()) {
13174 if (I != FD && !I->isInvalidDecl() &&
13175 I->getFriendObjectKind() != Decl::FOK_None) {
13176 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13177 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13178 // A merged copy of the same function, instantiated as a member of
13179 // the same class, is OK.
13180 if (declaresSameEntity(OrigFD, Original) &&
13181 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13182 cast<Decl>(FD->getLexicalDeclContext())))
13183 continue;
13184 }
13185
13186 if (Original->isThisDeclarationADefinition()) {
13187 Definition = I;
13188 break;
13189 }
13190 }
13191 }
13192 }
13193 }
13194
13195 if (!Definition)
13196 // Similar to friend functions a friend function template may be a
13197 // definition and do not have a body if it is instantiated in a class
13198 // template.
13199 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13200 for (auto I : FTD->redecls()) {
13201 auto D = cast<FunctionTemplateDecl>(I);
13202 if (D != FTD) {
13203 assert(!D->isThisDeclarationADefinition() &&
13204 "More than one definition in redeclaration chain");
13205 if (D->getFriendObjectKind() != Decl::FOK_None)
13206 if (FunctionTemplateDecl *FT =
13207 D->getInstantiatedFromMemberTemplate()) {
13208 if (FT->isThisDeclarationADefinition()) {
13209 Definition = D->getTemplatedDecl();
13210 break;
13211 }
13212 }
13213 }
13214 }
13215 }
13216
13217 if (!Definition)
13218 return;
13219
13220 if (canRedefineFunction(Definition, getLangOpts()))
13221 return;
13222
13223 // Don't emit an error when this is redefinition of a typo-corrected
13224 // definition.
13225 if (TypoCorrectedFunctionDefinitions.count(Definition))
13226 return;
13227
13228 // If we don't have a visible definition of the function, and it's inline or
13229 // a template, skip the new definition.
13230 if (SkipBody && !hasVisibleDefinition(Definition) &&
13231 (Definition->getFormalLinkage() == InternalLinkage ||
13232 Definition->isInlined() ||
13233 Definition->getDescribedFunctionTemplate() ||
13234 Definition->getNumTemplateParameterLists())) {
13235 SkipBody->ShouldSkip = true;
13236 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13237 if (auto *TD = Definition->getDescribedFunctionTemplate())
13238 makeMergedDefinitionVisible(TD);
13239 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13240 return;
13241 }
13242
13243 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13244 Definition->getStorageClass() == SC_Extern)
13245 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13246 << FD->getDeclName() << getLangOpts().CPlusPlus;
13247 else
13248 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13249
13250 Diag(Definition->getLocation(), diag::note_previous_definition);
13251 FD->setInvalidDecl();
13252 }
13253
RebuildLambdaScopeInfo(CXXMethodDecl * CallOperator,Sema & S)13254 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13255 Sema &S) {
13256 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13257
13258 LambdaScopeInfo *LSI = S.PushLambdaScope();
13259 LSI->CallOperator = CallOperator;
13260 LSI->Lambda = LambdaClass;
13261 LSI->ReturnType = CallOperator->getReturnType();
13262 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13263
13264 if (LCD == LCD_None)
13265 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13266 else if (LCD == LCD_ByCopy)
13267 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13268 else if (LCD == LCD_ByRef)
13269 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13270 DeclarationNameInfo DNI = CallOperator->getNameInfo();
13271
13272 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13273 LSI->Mutable = !CallOperator->isConst();
13274
13275 // Add the captures to the LSI so they can be noted as already
13276 // captured within tryCaptureVar.
13277 auto I = LambdaClass->field_begin();
13278 for (const auto &C : LambdaClass->captures()) {
13279 if (C.capturesVariable()) {
13280 VarDecl *VD = C.getCapturedVar();
13281 if (VD->isInitCapture())
13282 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13283 QualType CaptureType = VD->getType();
13284 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13285 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13286 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13287 /*EllipsisLoc*/C.isPackExpansion()
13288 ? C.getEllipsisLoc() : SourceLocation(),
13289 CaptureType, /*Invalid*/false);
13290
13291 } else if (C.capturesThis()) {
13292 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13293 C.getCaptureKind() == LCK_StarThis);
13294 } else {
13295 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13296 I->getType());
13297 }
13298 ++I;
13299 }
13300 }
13301
ActOnStartOfFunctionDef(Scope * FnBodyScope,Decl * D,SkipBodyInfo * SkipBody)13302 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13303 SkipBodyInfo *SkipBody) {
13304 if (!D) {
13305 // Parsing the function declaration failed in some way. Push on a fake scope
13306 // anyway so we can try to parse the function body.
13307 PushFunctionScope();
13308 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13309 return D;
13310 }
13311
13312 FunctionDecl *FD = nullptr;
13313
13314 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13315 FD = FunTmpl->getTemplatedDecl();
13316 else
13317 FD = cast<FunctionDecl>(D);
13318
13319 // Do not push if it is a lambda because one is already pushed when building
13320 // the lambda in ActOnStartOfLambdaDefinition().
13321 if (!isLambdaCallOperator(FD))
13322 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13323
13324 // Check for defining attributes before the check for redefinition.
13325 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13326 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13327 FD->dropAttr<AliasAttr>();
13328 FD->setInvalidDecl();
13329 }
13330 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13331 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13332 FD->dropAttr<IFuncAttr>();
13333 FD->setInvalidDecl();
13334 }
13335
13336 // See if this is a redefinition. If 'will have body' is already set, then
13337 // these checks were already performed when it was set.
13338 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13339 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13340
13341 // If we're skipping the body, we're done. Don't enter the scope.
13342 if (SkipBody && SkipBody->ShouldSkip)
13343 return D;
13344 }
13345
13346 // Mark this function as "will have a body eventually". This lets users to
13347 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13348 // this function.
13349 FD->setWillHaveBody();
13350
13351 // If we are instantiating a generic lambda call operator, push
13352 // a LambdaScopeInfo onto the function stack. But use the information
13353 // that's already been calculated (ActOnLambdaExpr) to prime the current
13354 // LambdaScopeInfo.
13355 // When the template operator is being specialized, the LambdaScopeInfo,
13356 // has to be properly restored so that tryCaptureVariable doesn't try
13357 // and capture any new variables. In addition when calculating potential
13358 // captures during transformation of nested lambdas, it is necessary to
13359 // have the LSI properly restored.
13360 if (isGenericLambdaCallOperatorSpecialization(FD)) {
13361 assert(inTemplateInstantiation() &&
13362 "There should be an active template instantiation on the stack "
13363 "when instantiating a generic lambda!");
13364 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13365 } else {
13366 // Enter a new function scope
13367 PushFunctionScope();
13368 }
13369
13370 // Builtin functions cannot be defined.
13371 if (unsigned BuiltinID = FD->getBuiltinID()) {
13372 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13373 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13374 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13375 FD->setInvalidDecl();
13376 }
13377 }
13378
13379 // The return type of a function definition must be complete
13380 // (C99 6.9.1p3, C++ [dcl.fct]p6).
13381 QualType ResultType = FD->getReturnType();
13382 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13383 !FD->isInvalidDecl() &&
13384 RequireCompleteType(FD->getLocation(), ResultType,
13385 diag::err_func_def_incomplete_result))
13386 FD->setInvalidDecl();
13387
13388 if (FnBodyScope)
13389 PushDeclContext(FnBodyScope, FD);
13390
13391 // Check the validity of our function parameters
13392 CheckParmsForFunctionDef(FD->parameters(),
13393 /*CheckParameterNames=*/true);
13394
13395 // Add non-parameter declarations already in the function to the current
13396 // scope.
13397 if (FnBodyScope) {
13398 for (Decl *NPD : FD->decls()) {
13399 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13400 if (!NonParmDecl)
13401 continue;
13402 assert(!isa<ParmVarDecl>(NonParmDecl) &&
13403 "parameters should not be in newly created FD yet");
13404
13405 // If the decl has a name, make it accessible in the current scope.
13406 if (NonParmDecl->getDeclName())
13407 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13408
13409 // Similarly, dive into enums and fish their constants out, making them
13410 // accessible in this scope.
13411 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13412 for (auto *EI : ED->enumerators())
13413 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13414 }
13415 }
13416 }
13417
13418 // Introduce our parameters into the function scope
13419 for (auto Param : FD->parameters()) {
13420 Param->setOwningFunction(FD);
13421
13422 // If this has an identifier, add it to the scope stack.
13423 if (Param->getIdentifier() && FnBodyScope) {
13424 CheckShadow(FnBodyScope, Param);
13425
13426 PushOnScopeChains(Param, FnBodyScope);
13427 }
13428 }
13429
13430 // Ensure that the function's exception specification is instantiated.
13431 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13432 ResolveExceptionSpec(D->getLocation(), FPT);
13433
13434 // dllimport cannot be applied to non-inline function definitions.
13435 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13436 !FD->isTemplateInstantiation()) {
13437 assert(!FD->hasAttr<DLLExportAttr>());
13438 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13439 FD->setInvalidDecl();
13440 return D;
13441 }
13442 // We want to attach documentation to original Decl (which might be
13443 // a function template).
13444 ActOnDocumentableDecl(D);
13445 if (getCurLexicalContext()->isObjCContainer() &&
13446 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13447 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13448 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13449
13450 return D;
13451 }
13452
13453 /// Given the set of return statements within a function body,
13454 /// compute the variables that are subject to the named return value
13455 /// optimization.
13456 ///
13457 /// Each of the variables that is subject to the named return value
13458 /// optimization will be marked as NRVO variables in the AST, and any
13459 /// return statement that has a marked NRVO variable as its NRVO candidate can
13460 /// use the named return value optimization.
13461 ///
13462 /// This function applies a very simplistic algorithm for NRVO: if every return
13463 /// statement in the scope of a variable has the same NRVO candidate, that
13464 /// candidate is an NRVO variable.
computeNRVO(Stmt * Body,FunctionScopeInfo * Scope)13465 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13466 ReturnStmt **Returns = Scope->Returns.data();
13467
13468 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13469 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13470 if (!NRVOCandidate->isNRVOVariable())
13471 Returns[I]->setNRVOCandidate(nullptr);
13472 }
13473 }
13474 }
13475
canDelayFunctionBody(const Declarator & D)13476 bool Sema::canDelayFunctionBody(const Declarator &D) {
13477 // We can't delay parsing the body of a constexpr function template (yet).
13478 if (D.getDeclSpec().hasConstexprSpecifier())
13479 return false;
13480
13481 // We can't delay parsing the body of a function template with a deduced
13482 // return type (yet).
13483 if (D.getDeclSpec().hasAutoTypeSpec()) {
13484 // If the placeholder introduces a non-deduced trailing return type,
13485 // we can still delay parsing it.
13486 if (D.getNumTypeObjects()) {
13487 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13488 if (Outer.Kind == DeclaratorChunk::Function &&
13489 Outer.Fun.hasTrailingReturnType()) {
13490 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13491 return Ty.isNull() || !Ty->isUndeducedType();
13492 }
13493 }
13494 return false;
13495 }
13496
13497 return true;
13498 }
13499
canSkipFunctionBody(Decl * D)13500 bool Sema::canSkipFunctionBody(Decl *D) {
13501 // We cannot skip the body of a function (or function template) which is
13502 // constexpr, since we may need to evaluate its body in order to parse the
13503 // rest of the file.
13504 // We cannot skip the body of a function with an undeduced return type,
13505 // because any callers of that function need to know the type.
13506 if (const FunctionDecl *FD = D->getAsFunction()) {
13507 if (FD->isConstexpr())
13508 return false;
13509 // We can't simply call Type::isUndeducedType here, because inside template
13510 // auto can be deduced to a dependent type, which is not considered
13511 // "undeduced".
13512 if (FD->getReturnType()->getContainedDeducedType())
13513 return false;
13514 }
13515 return Consumer.shouldSkipFunctionBody(D);
13516 }
13517
ActOnSkippedFunctionBody(Decl * Decl)13518 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13519 if (!Decl)
13520 return nullptr;
13521 if (FunctionDecl *FD = Decl->getAsFunction())
13522 FD->setHasSkippedBody();
13523 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13524 MD->setHasSkippedBody();
13525 return Decl;
13526 }
13527
ActOnFinishFunctionBody(Decl * D,Stmt * BodyArg)13528 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13529 return ActOnFinishFunctionBody(D, BodyArg, false);
13530 }
13531
13532 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13533 /// body.
13534 class ExitFunctionBodyRAII {
13535 public:
ExitFunctionBodyRAII(Sema & S,bool IsLambda)13536 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
~ExitFunctionBodyRAII()13537 ~ExitFunctionBodyRAII() {
13538 if (!IsLambda)
13539 S.PopExpressionEvaluationContext();
13540 }
13541
13542 private:
13543 Sema &S;
13544 bool IsLambda = false;
13545 };
13546
diagnoseImplicitlyRetainedSelf(Sema & S)13547 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13548 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13549
13550 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13551 if (EscapeInfo.count(BD))
13552 return EscapeInfo[BD];
13553
13554 bool R = false;
13555 const BlockDecl *CurBD = BD;
13556
13557 do {
13558 R = !CurBD->doesNotEscape();
13559 if (R)
13560 break;
13561 CurBD = CurBD->getParent()->getInnermostBlockDecl();
13562 } while (CurBD);
13563
13564 return EscapeInfo[BD] = R;
13565 };
13566
13567 // If the location where 'self' is implicitly retained is inside a escaping
13568 // block, emit a diagnostic.
13569 for (const std::pair<SourceLocation, const BlockDecl *> &P :
13570 S.ImplicitlyRetainedSelfLocs)
13571 if (IsOrNestedInEscapingBlock(P.second))
13572 S.Diag(P.first, diag::warn_implicitly_retains_self)
13573 << FixItHint::CreateInsertion(P.first, "self->");
13574 }
13575
ActOnFinishFunctionBody(Decl * dcl,Stmt * Body,bool IsInstantiation)13576 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13577 bool IsInstantiation) {
13578 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13579
13580 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13581 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13582
13583 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13584 CheckCompletedCoroutineBody(FD, Body);
13585
13586 // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13587 // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13588 // meant to pop the context added in ActOnStartOfFunctionDef().
13589 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13590
13591 if (FD) {
13592 FD->setBody(Body);
13593 FD->setWillHaveBody(false);
13594
13595 if (getLangOpts().CPlusPlus14) {
13596 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13597 FD->getReturnType()->isUndeducedType()) {
13598 // If the function has a deduced result type but contains no 'return'
13599 // statements, the result type as written must be exactly 'auto', and
13600 // the deduced result type is 'void'.
13601 if (!FD->getReturnType()->getAs<AutoType>()) {
13602 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13603 << FD->getReturnType();
13604 FD->setInvalidDecl();
13605 } else {
13606 // Substitute 'void' for the 'auto' in the type.
13607 TypeLoc ResultType = getReturnTypeLoc(FD);
13608 Context.adjustDeducedFunctionResultType(
13609 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13610 }
13611 }
13612 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13613 // In C++11, we don't use 'auto' deduction rules for lambda call
13614 // operators because we don't support return type deduction.
13615 auto *LSI = getCurLambda();
13616 if (LSI->HasImplicitReturnType) {
13617 deduceClosureReturnType(*LSI);
13618
13619 // C++11 [expr.prim.lambda]p4:
13620 // [...] if there are no return statements in the compound-statement
13621 // [the deduced type is] the type void
13622 QualType RetType =
13623 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13624
13625 // Update the return type to the deduced type.
13626 const FunctionProtoType *Proto =
13627 FD->getType()->getAs<FunctionProtoType>();
13628 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13629 Proto->getExtProtoInfo()));
13630 }
13631 }
13632
13633 // If the function implicitly returns zero (like 'main') or is naked,
13634 // don't complain about missing return statements.
13635 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13636 WP.disableCheckFallThrough();
13637
13638 // MSVC permits the use of pure specifier (=0) on function definition,
13639 // defined at class scope, warn about this non-standard construct.
13640 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13641 Diag(FD->getLocation(), diag::ext_pure_function_definition);
13642
13643 if (!FD->isInvalidDecl()) {
13644 // Don't diagnose unused parameters of defaulted or deleted functions.
13645 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13646 DiagnoseUnusedParameters(FD->parameters());
13647 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13648 FD->getReturnType(), FD);
13649
13650 // If this is a structor, we need a vtable.
13651 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13652 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13653 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13654 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13655
13656 // Try to apply the named return value optimization. We have to check
13657 // if we can do this here because lambdas keep return statements around
13658 // to deduce an implicit return type.
13659 if (FD->getReturnType()->isRecordType() &&
13660 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13661 computeNRVO(Body, getCurFunction());
13662 }
13663
13664 // GNU warning -Wmissing-prototypes:
13665 // Warn if a global function is defined without a previous
13666 // prototype declaration. This warning is issued even if the
13667 // definition itself provides a prototype. The aim is to detect
13668 // global functions that fail to be declared in header files.
13669 const FunctionDecl *PossiblePrototype = nullptr;
13670 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13671 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13672
13673 if (PossiblePrototype) {
13674 // We found a declaration that is not a prototype,
13675 // but that could be a zero-parameter prototype
13676 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13677 TypeLoc TL = TI->getTypeLoc();
13678 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13679 Diag(PossiblePrototype->getLocation(),
13680 diag::note_declaration_not_a_prototype)
13681 << (FD->getNumParams() != 0)
13682 << (FD->getNumParams() == 0
13683 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13684 : FixItHint{});
13685 }
13686 } else {
13687 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13688 << /* function */ 1
13689 << (FD->getStorageClass() == SC_None
13690 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13691 "static ")
13692 : FixItHint{});
13693 }
13694
13695 // GNU warning -Wstrict-prototypes
13696 // Warn if K&R function is defined without a previous declaration.
13697 // This warning is issued only if the definition itself does not provide
13698 // a prototype. Only K&R definitions do not provide a prototype.
13699 // An empty list in a function declarator that is part of a definition
13700 // of that function specifies that the function has no parameters
13701 // (C99 6.7.5.3p14)
13702 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13703 !LangOpts.CPlusPlus) {
13704 TypeSourceInfo *TI = FD->getTypeSourceInfo();
13705 TypeLoc TL = TI->getTypeLoc();
13706 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13707 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13708 }
13709 }
13710
13711 // Warn on CPUDispatch with an actual body.
13712 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13713 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13714 if (!CmpndBody->body_empty())
13715 Diag(CmpndBody->body_front()->getBeginLoc(),
13716 diag::warn_dispatch_body_ignored);
13717
13718 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13719 const CXXMethodDecl *KeyFunction;
13720 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13721 MD->isVirtual() &&
13722 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13723 MD == KeyFunction->getCanonicalDecl()) {
13724 // Update the key-function state if necessary for this ABI.
13725 if (FD->isInlined() &&
13726 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13727 Context.setNonKeyFunction(MD);
13728
13729 // If the newly-chosen key function is already defined, then we
13730 // need to mark the vtable as used retroactively.
13731 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13732 const FunctionDecl *Definition;
13733 if (KeyFunction && KeyFunction->isDefined(Definition))
13734 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13735 } else {
13736 // We just defined they key function; mark the vtable as used.
13737 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13738 }
13739 }
13740 }
13741
13742 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13743 "Function parsing confused");
13744 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13745 assert(MD == getCurMethodDecl() && "Method parsing confused");
13746 MD->setBody(Body);
13747 if (!MD->isInvalidDecl()) {
13748 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13749 MD->getReturnType(), MD);
13750
13751 if (Body)
13752 computeNRVO(Body, getCurFunction());
13753 }
13754 if (getCurFunction()->ObjCShouldCallSuper) {
13755 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13756 << MD->getSelector().getAsString();
13757 getCurFunction()->ObjCShouldCallSuper = false;
13758 }
13759 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13760 const ObjCMethodDecl *InitMethod = nullptr;
13761 bool isDesignated =
13762 MD->isDesignatedInitializerForTheInterface(&InitMethod);
13763 assert(isDesignated && InitMethod);
13764 (void)isDesignated;
13765
13766 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13767 auto IFace = MD->getClassInterface();
13768 if (!IFace)
13769 return false;
13770 auto SuperD = IFace->getSuperClass();
13771 if (!SuperD)
13772 return false;
13773 return SuperD->getIdentifier() ==
13774 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13775 };
13776 // Don't issue this warning for unavailable inits or direct subclasses
13777 // of NSObject.
13778 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13779 Diag(MD->getLocation(),
13780 diag::warn_objc_designated_init_missing_super_call);
13781 Diag(InitMethod->getLocation(),
13782 diag::note_objc_designated_init_marked_here);
13783 }
13784 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13785 }
13786 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13787 // Don't issue this warning for unavaialable inits.
13788 if (!MD->isUnavailable())
13789 Diag(MD->getLocation(),
13790 diag::warn_objc_secondary_init_missing_init_call);
13791 getCurFunction()->ObjCWarnForNoInitDelegation = false;
13792 }
13793
13794 diagnoseImplicitlyRetainedSelf(*this);
13795 } else {
13796 // Parsing the function declaration failed in some way. Pop the fake scope
13797 // we pushed on.
13798 PopFunctionScopeInfo(ActivePolicy, dcl);
13799 return nullptr;
13800 }
13801
13802 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13803 DiagnoseUnguardedAvailabilityViolations(dcl);
13804
13805 assert(!getCurFunction()->ObjCShouldCallSuper &&
13806 "This should only be set for ObjC methods, which should have been "
13807 "handled in the block above.");
13808
13809 // Verify and clean out per-function state.
13810 if (Body && (!FD || !FD->isDefaulted())) {
13811 // C++ constructors that have function-try-blocks can't have return
13812 // statements in the handlers of that block. (C++ [except.handle]p14)
13813 // Verify this.
13814 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13815 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13816
13817 // Verify that gotos and switch cases don't jump into scopes illegally.
13818 if (getCurFunction()->NeedsScopeChecking() &&
13819 !PP.isCodeCompletionEnabled())
13820 DiagnoseInvalidJumps(Body);
13821
13822 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13823 if (!Destructor->getParent()->isDependentType())
13824 CheckDestructor(Destructor);
13825
13826 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13827 Destructor->getParent());
13828 }
13829
13830 // If any errors have occurred, clear out any temporaries that may have
13831 // been leftover. This ensures that these temporaries won't be picked up for
13832 // deletion in some later function.
13833 if (getDiagnostics().hasErrorOccurred() ||
13834 getDiagnostics().getSuppressAllDiagnostics()) {
13835 DiscardCleanupsInEvaluationContext();
13836 }
13837 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13838 !isa<FunctionTemplateDecl>(dcl)) {
13839 // Since the body is valid, issue any analysis-based warnings that are
13840 // enabled.
13841 ActivePolicy = &WP;
13842 }
13843
13844 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13845 (!CheckConstexprFunctionDecl(FD) ||
13846 !CheckConstexprFunctionBody(FD, Body)))
13847 FD->setInvalidDecl();
13848
13849 if (FD && FD->hasAttr<NakedAttr>()) {
13850 for (const Stmt *S : Body->children()) {
13851 // Allow local register variables without initializer as they don't
13852 // require prologue.
13853 bool RegisterVariables = false;
13854 if (auto *DS = dyn_cast<DeclStmt>(S)) {
13855 for (const auto *Decl : DS->decls()) {
13856 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13857 RegisterVariables =
13858 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13859 if (!RegisterVariables)
13860 break;
13861 }
13862 }
13863 }
13864 if (RegisterVariables)
13865 continue;
13866 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13867 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13868 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13869 FD->setInvalidDecl();
13870 break;
13871 }
13872 }
13873 }
13874
13875 assert(ExprCleanupObjects.size() ==
13876 ExprEvalContexts.back().NumCleanupObjects &&
13877 "Leftover temporaries in function");
13878 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13879 assert(MaybeODRUseExprs.empty() &&
13880 "Leftover expressions for odr-use checking");
13881 }
13882
13883 if (!IsInstantiation)
13884 PopDeclContext();
13885
13886 PopFunctionScopeInfo(ActivePolicy, dcl);
13887 // If any errors have occurred, clear out any temporaries that may have
13888 // been leftover. This ensures that these temporaries won't be picked up for
13889 // deletion in some later function.
13890 if (getDiagnostics().hasErrorOccurred()) {
13891 DiscardCleanupsInEvaluationContext();
13892 }
13893
13894 return dcl;
13895 }
13896
13897 /// When we finish delayed parsing of an attribute, we must attach it to the
13898 /// relevant Decl.
ActOnFinishDelayedAttribute(Scope * S,Decl * D,ParsedAttributes & Attrs)13899 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13900 ParsedAttributes &Attrs) {
13901 // Always attach attributes to the underlying decl.
13902 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13903 D = TD->getTemplatedDecl();
13904 ProcessDeclAttributeList(S, D, Attrs);
13905
13906 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13907 if (Method->isStatic())
13908 checkThisInStaticMemberFunctionAttributes(Method);
13909 }
13910
13911 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13912 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
ImplicitlyDefineFunction(SourceLocation Loc,IdentifierInfo & II,Scope * S)13913 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13914 IdentifierInfo &II, Scope *S) {
13915 // Find the scope in which the identifier is injected and the corresponding
13916 // DeclContext.
13917 // FIXME: C89 does not say what happens if there is no enclosing block scope.
13918 // In that case, we inject the declaration into the translation unit scope
13919 // instead.
13920 Scope *BlockScope = S;
13921 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13922 BlockScope = BlockScope->getParent();
13923
13924 Scope *ContextScope = BlockScope;
13925 while (!ContextScope->getEntity())
13926 ContextScope = ContextScope->getParent();
13927 ContextRAII SavedContext(*this, ContextScope->getEntity());
13928
13929 // Before we produce a declaration for an implicitly defined
13930 // function, see whether there was a locally-scoped declaration of
13931 // this name as a function or variable. If so, use that
13932 // (non-visible) declaration, and complain about it.
13933 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13934 if (ExternCPrev) {
13935 // We still need to inject the function into the enclosing block scope so
13936 // that later (non-call) uses can see it.
13937 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13938
13939 // C89 footnote 38:
13940 // If in fact it is not defined as having type "function returning int",
13941 // the behavior is undefined.
13942 if (!isa<FunctionDecl>(ExternCPrev) ||
13943 !Context.typesAreCompatible(
13944 cast<FunctionDecl>(ExternCPrev)->getType(),
13945 Context.getFunctionNoProtoType(Context.IntTy))) {
13946 Diag(Loc, diag::ext_use_out_of_scope_declaration)
13947 << ExternCPrev << !getLangOpts().C99;
13948 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13949 return ExternCPrev;
13950 }
13951 }
13952
13953 // Extension in C99. Legal in C90, but warn about it.
13954 unsigned diag_id;
13955 if (II.getName().startswith("__builtin_"))
13956 diag_id = diag::warn_builtin_unknown;
13957 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13958 else if (getLangOpts().OpenCL)
13959 diag_id = diag::err_opencl_implicit_function_decl;
13960 else if (getLangOpts().C99)
13961 diag_id = diag::ext_implicit_function_decl;
13962 else
13963 diag_id = diag::warn_implicit_function_decl;
13964 Diag(Loc, diag_id) << &II;
13965
13966 // If we found a prior declaration of this function, don't bother building
13967 // another one. We've already pushed that one into scope, so there's nothing
13968 // more to do.
13969 if (ExternCPrev)
13970 return ExternCPrev;
13971
13972 // Because typo correction is expensive, only do it if the implicit
13973 // function declaration is going to be treated as an error.
13974 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13975 TypoCorrection Corrected;
13976 DeclFilterCCC<FunctionDecl> CCC{};
13977 if (S && (Corrected =
13978 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
13979 S, nullptr, CCC, CTK_NonError)))
13980 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13981 /*ErrorRecovery*/false);
13982 }
13983
13984 // Set a Declarator for the implicit definition: int foo();
13985 const char *Dummy;
13986 AttributeFactory attrFactory;
13987 DeclSpec DS(attrFactory);
13988 unsigned DiagID;
13989 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13990 Context.getPrintingPolicy());
13991 (void)Error; // Silence warning.
13992 assert(!Error && "Error setting up implicit decl!");
13993 SourceLocation NoLoc;
13994 Declarator D(DS, DeclaratorContext::BlockContext);
13995 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13996 /*IsAmbiguous=*/false,
13997 /*LParenLoc=*/NoLoc,
13998 /*Params=*/nullptr,
13999 /*NumParams=*/0,
14000 /*EllipsisLoc=*/NoLoc,
14001 /*RParenLoc=*/NoLoc,
14002 /*RefQualifierIsLvalueRef=*/true,
14003 /*RefQualifierLoc=*/NoLoc,
14004 /*MutableLoc=*/NoLoc, EST_None,
14005 /*ESpecRange=*/SourceRange(),
14006 /*Exceptions=*/nullptr,
14007 /*ExceptionRanges=*/nullptr,
14008 /*NumExceptions=*/0,
14009 /*NoexceptExpr=*/nullptr,
14010 /*ExceptionSpecTokens=*/nullptr,
14011 /*DeclsInPrototype=*/None, Loc,
14012 Loc, D),
14013 std::move(DS.getAttributes()), SourceLocation());
14014 D.SetIdentifier(&II, Loc);
14015
14016 // Insert this function into the enclosing block scope.
14017 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14018 FD->setImplicit();
14019
14020 AddKnownFunctionAttributes(FD);
14021
14022 return FD;
14023 }
14024
14025 /// Adds any function attributes that we know a priori based on
14026 /// the declaration of this function.
14027 ///
14028 /// These attributes can apply both to implicitly-declared builtins
14029 /// (like __builtin___printf_chk) or to library-declared functions
14030 /// like NSLog or printf.
14031 ///
14032 /// We need to check for duplicate attributes both here and where user-written
14033 /// attributes are applied to declarations.
AddKnownFunctionAttributes(FunctionDecl * FD)14034 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14035 if (FD->isInvalidDecl())
14036 return;
14037
14038 // If this is a built-in function, map its builtin attributes to
14039 // actual attributes.
14040 if (unsigned BuiltinID = FD->getBuiltinID()) {
14041 // Handle printf-formatting attributes.
14042 unsigned FormatIdx;
14043 bool HasVAListArg;
14044 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14045 if (!FD->hasAttr<FormatAttr>()) {
14046 const char *fmt = "printf";
14047 unsigned int NumParams = FD->getNumParams();
14048 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14049 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14050 fmt = "NSString";
14051 FD->addAttr(FormatAttr::CreateImplicit(Context,
14052 &Context.Idents.get(fmt),
14053 FormatIdx+1,
14054 HasVAListArg ? 0 : FormatIdx+2,
14055 FD->getLocation()));
14056 }
14057 }
14058 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14059 HasVAListArg)) {
14060 if (!FD->hasAttr<FormatAttr>())
14061 FD->addAttr(FormatAttr::CreateImplicit(Context,
14062 &Context.Idents.get("scanf"),
14063 FormatIdx+1,
14064 HasVAListArg ? 0 : FormatIdx+2,
14065 FD->getLocation()));
14066 }
14067
14068 // Handle automatically recognized callbacks.
14069 SmallVector<int, 4> Encoding;
14070 if (!FD->hasAttr<CallbackAttr>() &&
14071 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14072 FD->addAttr(CallbackAttr::CreateImplicit(
14073 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14074
14075 // Mark const if we don't care about errno and that is the only thing
14076 // preventing the function from being const. This allows IRgen to use LLVM
14077 // intrinsics for such functions.
14078 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14079 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14080 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14081
14082 // We make "fma" on some platforms const because we know it does not set
14083 // errno in those environments even though it could set errno based on the
14084 // C standard.
14085 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14086 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14087 !FD->hasAttr<ConstAttr>()) {
14088 switch (BuiltinID) {
14089 case Builtin::BI__builtin_fma:
14090 case Builtin::BI__builtin_fmaf:
14091 case Builtin::BI__builtin_fmal:
14092 case Builtin::BIfma:
14093 case Builtin::BIfmaf:
14094 case Builtin::BIfmal:
14095 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14096 break;
14097 default:
14098 break;
14099 }
14100 }
14101
14102 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14103 !FD->hasAttr<ReturnsTwiceAttr>())
14104 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14105 FD->getLocation()));
14106 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14107 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14108 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14109 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14110 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14111 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14112 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14113 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14114 // Add the appropriate attribute, depending on the CUDA compilation mode
14115 // and which target the builtin belongs to. For example, during host
14116 // compilation, aux builtins are __device__, while the rest are __host__.
14117 if (getLangOpts().CUDAIsDevice !=
14118 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14119 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14120 else
14121 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14122 }
14123 }
14124
14125 // If C++ exceptions are enabled but we are told extern "C" functions cannot
14126 // throw, add an implicit nothrow attribute to any extern "C" function we come
14127 // across.
14128 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14129 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14130 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14131 if (!FPT || FPT->getExceptionSpecType() == EST_None)
14132 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14133 }
14134
14135 IdentifierInfo *Name = FD->getIdentifier();
14136 if (!Name)
14137 return;
14138 if ((!getLangOpts().CPlusPlus &&
14139 FD->getDeclContext()->isTranslationUnit()) ||
14140 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14141 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14142 LinkageSpecDecl::lang_c)) {
14143 // Okay: this could be a libc/libm/Objective-C function we know
14144 // about.
14145 } else
14146 return;
14147
14148 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14149 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14150 // target-specific builtins, perhaps?
14151 if (!FD->hasAttr<FormatAttr>())
14152 FD->addAttr(FormatAttr::CreateImplicit(Context,
14153 &Context.Idents.get("printf"), 2,
14154 Name->isStr("vasprintf") ? 0 : 3,
14155 FD->getLocation()));
14156 }
14157
14158 if (Name->isStr("__CFStringMakeConstantString")) {
14159 // We already have a __builtin___CFStringMakeConstantString,
14160 // but builds that use -fno-constant-cfstrings don't go through that.
14161 if (!FD->hasAttr<FormatArgAttr>())
14162 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14163 FD->getLocation()));
14164 }
14165 }
14166
ParseTypedefDecl(Scope * S,Declarator & D,QualType T,TypeSourceInfo * TInfo)14167 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14168 TypeSourceInfo *TInfo) {
14169 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14170 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14171
14172 if (!TInfo) {
14173 assert(D.isInvalidType() && "no declarator info for valid type");
14174 TInfo = Context.getTrivialTypeSourceInfo(T);
14175 }
14176
14177 // Scope manipulation handled by caller.
14178 TypedefDecl *NewTD =
14179 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14180 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14181
14182 // Bail out immediately if we have an invalid declaration.
14183 if (D.isInvalidType()) {
14184 NewTD->setInvalidDecl();
14185 return NewTD;
14186 }
14187
14188 if (D.getDeclSpec().isModulePrivateSpecified()) {
14189 if (CurContext->isFunctionOrMethod())
14190 Diag(NewTD->getLocation(), diag::err_module_private_local)
14191 << 2 << NewTD->getDeclName()
14192 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14193 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14194 else
14195 NewTD->setModulePrivate();
14196 }
14197
14198 // C++ [dcl.typedef]p8:
14199 // If the typedef declaration defines an unnamed class (or
14200 // enum), the first typedef-name declared by the declaration
14201 // to be that class type (or enum type) is used to denote the
14202 // class type (or enum type) for linkage purposes only.
14203 // We need to check whether the type was declared in the declaration.
14204 switch (D.getDeclSpec().getTypeSpecType()) {
14205 case TST_enum:
14206 case TST_struct:
14207 case TST_interface:
14208 case TST_union:
14209 case TST_class: {
14210 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14211 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14212 break;
14213 }
14214
14215 default:
14216 break;
14217 }
14218
14219 return NewTD;
14220 }
14221
14222 /// Check that this is a valid underlying type for an enum declaration.
CheckEnumUnderlyingType(TypeSourceInfo * TI)14223 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14224 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14225 QualType T = TI->getType();
14226
14227 if (T->isDependentType())
14228 return false;
14229
14230 if (const BuiltinType *BT = T->getAs<BuiltinType>())
14231 if (BT->isInteger())
14232 return false;
14233
14234 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14235 return true;
14236 }
14237
14238 /// Check whether this is a valid redeclaration of a previous enumeration.
14239 /// \return true if the redeclaration was invalid.
CheckEnumRedeclaration(SourceLocation EnumLoc,bool IsScoped,QualType EnumUnderlyingTy,bool IsFixed,const EnumDecl * Prev)14240 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14241 QualType EnumUnderlyingTy, bool IsFixed,
14242 const EnumDecl *Prev) {
14243 if (IsScoped != Prev->isScoped()) {
14244 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14245 << Prev->isScoped();
14246 Diag(Prev->getLocation(), diag::note_previous_declaration);
14247 return true;
14248 }
14249
14250 if (IsFixed && Prev->isFixed()) {
14251 if (!EnumUnderlyingTy->isDependentType() &&
14252 !Prev->getIntegerType()->isDependentType() &&
14253 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14254 Prev->getIntegerType())) {
14255 // TODO: Highlight the underlying type of the redeclaration.
14256 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14257 << EnumUnderlyingTy << Prev->getIntegerType();
14258 Diag(Prev->getLocation(), diag::note_previous_declaration)
14259 << Prev->getIntegerTypeRange();
14260 return true;
14261 }
14262 } else if (IsFixed != Prev->isFixed()) {
14263 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14264 << Prev->isFixed();
14265 Diag(Prev->getLocation(), diag::note_previous_declaration);
14266 return true;
14267 }
14268
14269 return false;
14270 }
14271
14272 /// Get diagnostic %select index for tag kind for
14273 /// redeclaration diagnostic message.
14274 /// WARNING: Indexes apply to particular diagnostics only!
14275 ///
14276 /// \returns diagnostic %select index.
getRedeclDiagFromTagKind(TagTypeKind Tag)14277 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14278 switch (Tag) {
14279 case TTK_Struct: return 0;
14280 case TTK_Interface: return 1;
14281 case TTK_Class: return 2;
14282 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14283 }
14284 }
14285
14286 /// Determine if tag kind is a class-key compatible with
14287 /// class for redeclaration (class, struct, or __interface).
14288 ///
14289 /// \returns true iff the tag kind is compatible.
isClassCompatTagKind(TagTypeKind Tag)14290 static bool isClassCompatTagKind(TagTypeKind Tag)
14291 {
14292 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14293 }
14294
getNonTagTypeDeclKind(const Decl * PrevDecl,TagTypeKind TTK)14295 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14296 TagTypeKind TTK) {
14297 if (isa<TypedefDecl>(PrevDecl))
14298 return NTK_Typedef;
14299 else if (isa<TypeAliasDecl>(PrevDecl))
14300 return NTK_TypeAlias;
14301 else if (isa<ClassTemplateDecl>(PrevDecl))
14302 return NTK_Template;
14303 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14304 return NTK_TypeAliasTemplate;
14305 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14306 return NTK_TemplateTemplateArgument;
14307 switch (TTK) {
14308 case TTK_Struct:
14309 case TTK_Interface:
14310 case TTK_Class:
14311 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14312 case TTK_Union:
14313 return NTK_NonUnion;
14314 case TTK_Enum:
14315 return NTK_NonEnum;
14316 }
14317 llvm_unreachable("invalid TTK");
14318 }
14319
14320 /// Determine whether a tag with a given kind is acceptable
14321 /// as a redeclaration of the given tag declaration.
14322 ///
14323 /// \returns true if the new tag kind is acceptable, false otherwise.
isAcceptableTagRedeclaration(const TagDecl * Previous,TagTypeKind NewTag,bool isDefinition,SourceLocation NewTagLoc,const IdentifierInfo * Name)14324 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14325 TagTypeKind NewTag, bool isDefinition,
14326 SourceLocation NewTagLoc,
14327 const IdentifierInfo *Name) {
14328 // C++ [dcl.type.elab]p3:
14329 // The class-key or enum keyword present in the
14330 // elaborated-type-specifier shall agree in kind with the
14331 // declaration to which the name in the elaborated-type-specifier
14332 // refers. This rule also applies to the form of
14333 // elaborated-type-specifier that declares a class-name or
14334 // friend class since it can be construed as referring to the
14335 // definition of the class. Thus, in any
14336 // elaborated-type-specifier, the enum keyword shall be used to
14337 // refer to an enumeration (7.2), the union class-key shall be
14338 // used to refer to a union (clause 9), and either the class or
14339 // struct class-key shall be used to refer to a class (clause 9)
14340 // declared using the class or struct class-key.
14341 TagTypeKind OldTag = Previous->getTagKind();
14342 if (OldTag != NewTag &&
14343 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14344 return false;
14345
14346 // Tags are compatible, but we might still want to warn on mismatched tags.
14347 // Non-class tags can't be mismatched at this point.
14348 if (!isClassCompatTagKind(NewTag))
14349 return true;
14350
14351 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14352 // by our warning analysis. We don't want to warn about mismatches with (eg)
14353 // declarations in system headers that are designed to be specialized, but if
14354 // a user asks us to warn, we should warn if their code contains mismatched
14355 // declarations.
14356 auto IsIgnoredLoc = [&](SourceLocation Loc) {
14357 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14358 Loc);
14359 };
14360 if (IsIgnoredLoc(NewTagLoc))
14361 return true;
14362
14363 auto IsIgnored = [&](const TagDecl *Tag) {
14364 return IsIgnoredLoc(Tag->getLocation());
14365 };
14366 while (IsIgnored(Previous)) {
14367 Previous = Previous->getPreviousDecl();
14368 if (!Previous)
14369 return true;
14370 OldTag = Previous->getTagKind();
14371 }
14372
14373 bool isTemplate = false;
14374 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14375 isTemplate = Record->getDescribedClassTemplate();
14376
14377 if (inTemplateInstantiation()) {
14378 if (OldTag != NewTag) {
14379 // In a template instantiation, do not offer fix-its for tag mismatches
14380 // since they usually mess up the template instead of fixing the problem.
14381 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14382 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14383 << getRedeclDiagFromTagKind(OldTag);
14384 // FIXME: Note previous location?
14385 }
14386 return true;
14387 }
14388
14389 if (isDefinition) {
14390 // On definitions, check all previous tags and issue a fix-it for each
14391 // one that doesn't match the current tag.
14392 if (Previous->getDefinition()) {
14393 // Don't suggest fix-its for redefinitions.
14394 return true;
14395 }
14396
14397 bool previousMismatch = false;
14398 for (const TagDecl *I : Previous->redecls()) {
14399 if (I->getTagKind() != NewTag) {
14400 // Ignore previous declarations for which the warning was disabled.
14401 if (IsIgnored(I))
14402 continue;
14403
14404 if (!previousMismatch) {
14405 previousMismatch = true;
14406 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14407 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14408 << getRedeclDiagFromTagKind(I->getTagKind());
14409 }
14410 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14411 << getRedeclDiagFromTagKind(NewTag)
14412 << FixItHint::CreateReplacement(I->getInnerLocStart(),
14413 TypeWithKeyword::getTagTypeKindName(NewTag));
14414 }
14415 }
14416 return true;
14417 }
14418
14419 // Identify the prevailing tag kind: this is the kind of the definition (if
14420 // there is a non-ignored definition), or otherwise the kind of the prior
14421 // (non-ignored) declaration.
14422 const TagDecl *PrevDef = Previous->getDefinition();
14423 if (PrevDef && IsIgnored(PrevDef))
14424 PrevDef = nullptr;
14425 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14426 if (Redecl->getTagKind() != NewTag) {
14427 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14428 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14429 << getRedeclDiagFromTagKind(OldTag);
14430 Diag(Redecl->getLocation(), diag::note_previous_use);
14431
14432 // If there is a previous definition, suggest a fix-it.
14433 if (PrevDef) {
14434 Diag(NewTagLoc, diag::note_struct_class_suggestion)
14435 << getRedeclDiagFromTagKind(Redecl->getTagKind())
14436 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14437 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14438 }
14439 }
14440
14441 return true;
14442 }
14443
14444 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14445 /// from an outer enclosing namespace or file scope inside a friend declaration.
14446 /// This should provide the commented out code in the following snippet:
14447 /// namespace N {
14448 /// struct X;
14449 /// namespace M {
14450 /// struct Y { friend struct /*N::*/ X; };
14451 /// }
14452 /// }
createFriendTagNNSFixIt(Sema & SemaRef,NamedDecl * ND,Scope * S,SourceLocation NameLoc)14453 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14454 SourceLocation NameLoc) {
14455 // While the decl is in a namespace, do repeated lookup of that name and see
14456 // if we get the same namespace back. If we do not, continue until
14457 // translation unit scope, at which point we have a fully qualified NNS.
14458 SmallVector<IdentifierInfo *, 4> Namespaces;
14459 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14460 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14461 // This tag should be declared in a namespace, which can only be enclosed by
14462 // other namespaces. Bail if there's an anonymous namespace in the chain.
14463 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14464 if (!Namespace || Namespace->isAnonymousNamespace())
14465 return FixItHint();
14466 IdentifierInfo *II = Namespace->getIdentifier();
14467 Namespaces.push_back(II);
14468 NamedDecl *Lookup = SemaRef.LookupSingleName(
14469 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14470 if (Lookup == Namespace)
14471 break;
14472 }
14473
14474 // Once we have all the namespaces, reverse them to go outermost first, and
14475 // build an NNS.
14476 SmallString<64> Insertion;
14477 llvm::raw_svector_ostream OS(Insertion);
14478 if (DC->isTranslationUnit())
14479 OS << "::";
14480 std::reverse(Namespaces.begin(), Namespaces.end());
14481 for (auto *II : Namespaces)
14482 OS << II->getName() << "::";
14483 return FixItHint::CreateInsertion(NameLoc, Insertion);
14484 }
14485
14486 /// Determine whether a tag originally declared in context \p OldDC can
14487 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14488 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14489 /// using-declaration).
isAcceptableTagRedeclContext(Sema & S,DeclContext * OldDC,DeclContext * NewDC)14490 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14491 DeclContext *NewDC) {
14492 OldDC = OldDC->getRedeclContext();
14493 NewDC = NewDC->getRedeclContext();
14494
14495 if (OldDC->Equals(NewDC))
14496 return true;
14497
14498 // In MSVC mode, we allow a redeclaration if the contexts are related (either
14499 // encloses the other).
14500 if (S.getLangOpts().MSVCCompat &&
14501 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14502 return true;
14503
14504 return false;
14505 }
14506
14507 /// This is invoked when we see 'struct foo' or 'struct {'. In the
14508 /// former case, Name will be non-null. In the later case, Name will be null.
14509 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14510 /// reference/declaration/definition of a tag.
14511 ///
14512 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14513 /// trailing-type-specifier) other than one in an alias-declaration.
14514 ///
14515 /// \param SkipBody If non-null, will be set to indicate if the caller should
14516 /// skip the definition of this tag and treat it as if it were a declaration.
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,SkipBodyInfo * SkipBody)14517 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14518 SourceLocation KWLoc, CXXScopeSpec &SS,
14519 IdentifierInfo *Name, SourceLocation NameLoc,
14520 const ParsedAttributesView &Attrs, AccessSpecifier AS,
14521 SourceLocation ModulePrivateLoc,
14522 MultiTemplateParamsArg TemplateParameterLists,
14523 bool &OwnedDecl, bool &IsDependent,
14524 SourceLocation ScopedEnumKWLoc,
14525 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14526 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14527 SkipBodyInfo *SkipBody) {
14528 // If this is not a definition, it must have a name.
14529 IdentifierInfo *OrigName = Name;
14530 assert((Name != nullptr || TUK == TUK_Definition) &&
14531 "Nameless record must be a definition!");
14532 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14533
14534 OwnedDecl = false;
14535 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14536 bool ScopedEnum = ScopedEnumKWLoc.isValid();
14537
14538 // FIXME: Check member specializations more carefully.
14539 bool isMemberSpecialization = false;
14540 bool Invalid = false;
14541
14542 // We only need to do this matching if we have template parameters
14543 // or a scope specifier, which also conveniently avoids this work
14544 // for non-C++ cases.
14545 if (TemplateParameterLists.size() > 0 ||
14546 (SS.isNotEmpty() && TUK != TUK_Reference)) {
14547 if (TemplateParameterList *TemplateParams =
14548 MatchTemplateParametersToScopeSpecifier(
14549 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14550 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14551 if (Kind == TTK_Enum) {
14552 Diag(KWLoc, diag::err_enum_template);
14553 return nullptr;
14554 }
14555
14556 if (TemplateParams->size() > 0) {
14557 // This is a declaration or definition of a class template (which may
14558 // be a member of another template).
14559
14560 if (Invalid)
14561 return nullptr;
14562
14563 OwnedDecl = false;
14564 DeclResult Result = CheckClassTemplate(
14565 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14566 AS, ModulePrivateLoc,
14567 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14568 TemplateParameterLists.data(), SkipBody);
14569 return Result.get();
14570 } else {
14571 // The "template<>" header is extraneous.
14572 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14573 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14574 isMemberSpecialization = true;
14575 }
14576 }
14577 }
14578
14579 // Figure out the underlying type if this a enum declaration. We need to do
14580 // this early, because it's needed to detect if this is an incompatible
14581 // redeclaration.
14582 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14583 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14584
14585 if (Kind == TTK_Enum) {
14586 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14587 // No underlying type explicitly specified, or we failed to parse the
14588 // type, default to int.
14589 EnumUnderlying = Context.IntTy.getTypePtr();
14590 } else if (UnderlyingType.get()) {
14591 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14592 // integral type; any cv-qualification is ignored.
14593 TypeSourceInfo *TI = nullptr;
14594 GetTypeFromParser(UnderlyingType.get(), &TI);
14595 EnumUnderlying = TI;
14596
14597 if (CheckEnumUnderlyingType(TI))
14598 // Recover by falling back to int.
14599 EnumUnderlying = Context.IntTy.getTypePtr();
14600
14601 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14602 UPPC_FixedUnderlyingType))
14603 EnumUnderlying = Context.IntTy.getTypePtr();
14604
14605 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14606 // For MSVC ABI compatibility, unfixed enums must use an underlying type
14607 // of 'int'. However, if this is an unfixed forward declaration, don't set
14608 // the underlying type unless the user enables -fms-compatibility. This
14609 // makes unfixed forward declared enums incomplete and is more conforming.
14610 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14611 EnumUnderlying = Context.IntTy.getTypePtr();
14612 }
14613 }
14614
14615 DeclContext *SearchDC = CurContext;
14616 DeclContext *DC = CurContext;
14617 bool isStdBadAlloc = false;
14618 bool isStdAlignValT = false;
14619
14620 RedeclarationKind Redecl = forRedeclarationInCurContext();
14621 if (TUK == TUK_Friend || TUK == TUK_Reference)
14622 Redecl = NotForRedeclaration;
14623
14624 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14625 /// implemented asks for structural equivalence checking, the returned decl
14626 /// here is passed back to the parser, allowing the tag body to be parsed.
14627 auto createTagFromNewDecl = [&]() -> TagDecl * {
14628 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14629 // If there is an identifier, use the location of the identifier as the
14630 // location of the decl, otherwise use the location of the struct/union
14631 // keyword.
14632 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14633 TagDecl *New = nullptr;
14634
14635 if (Kind == TTK_Enum) {
14636 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14637 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14638 // If this is an undefined enum, bail.
14639 if (TUK != TUK_Definition && !Invalid)
14640 return nullptr;
14641 if (EnumUnderlying) {
14642 EnumDecl *ED = cast<EnumDecl>(New);
14643 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14644 ED->setIntegerTypeSourceInfo(TI);
14645 else
14646 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14647 ED->setPromotionType(ED->getIntegerType());
14648 }
14649 } else { // struct/union
14650 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14651 nullptr);
14652 }
14653
14654 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14655 // Add alignment attributes if necessary; these attributes are checked
14656 // when the ASTContext lays out the structure.
14657 //
14658 // It is important for implementing the correct semantics that this
14659 // happen here (in ActOnTag). The #pragma pack stack is
14660 // maintained as a result of parser callbacks which can occur at
14661 // many points during the parsing of a struct declaration (because
14662 // the #pragma tokens are effectively skipped over during the
14663 // parsing of the struct).
14664 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14665 AddAlignmentAttributesForRecord(RD);
14666 AddMsStructLayoutForRecord(RD);
14667 }
14668 }
14669 New->setLexicalDeclContext(CurContext);
14670 return New;
14671 };
14672
14673 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14674 if (Name && SS.isNotEmpty()) {
14675 // We have a nested-name tag ('struct foo::bar').
14676
14677 // Check for invalid 'foo::'.
14678 if (SS.isInvalid()) {
14679 Name = nullptr;
14680 goto CreateNewDecl;
14681 }
14682
14683 // If this is a friend or a reference to a class in a dependent
14684 // context, don't try to make a decl for it.
14685 if (TUK == TUK_Friend || TUK == TUK_Reference) {
14686 DC = computeDeclContext(SS, false);
14687 if (!DC) {
14688 IsDependent = true;
14689 return nullptr;
14690 }
14691 } else {
14692 DC = computeDeclContext(SS, true);
14693 if (!DC) {
14694 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14695 << SS.getRange();
14696 return nullptr;
14697 }
14698 }
14699
14700 if (RequireCompleteDeclContext(SS, DC))
14701 return nullptr;
14702
14703 SearchDC = DC;
14704 // Look-up name inside 'foo::'.
14705 LookupQualifiedName(Previous, DC);
14706
14707 if (Previous.isAmbiguous())
14708 return nullptr;
14709
14710 if (Previous.empty()) {
14711 // Name lookup did not find anything. However, if the
14712 // nested-name-specifier refers to the current instantiation,
14713 // and that current instantiation has any dependent base
14714 // classes, we might find something at instantiation time: treat
14715 // this as a dependent elaborated-type-specifier.
14716 // But this only makes any sense for reference-like lookups.
14717 if (Previous.wasNotFoundInCurrentInstantiation() &&
14718 (TUK == TUK_Reference || TUK == TUK_Friend)) {
14719 IsDependent = true;
14720 return nullptr;
14721 }
14722
14723 // A tag 'foo::bar' must already exist.
14724 Diag(NameLoc, diag::err_not_tag_in_scope)
14725 << Kind << Name << DC << SS.getRange();
14726 Name = nullptr;
14727 Invalid = true;
14728 goto CreateNewDecl;
14729 }
14730 } else if (Name) {
14731 // C++14 [class.mem]p14:
14732 // If T is the name of a class, then each of the following shall have a
14733 // name different from T:
14734 // -- every member of class T that is itself a type
14735 if (TUK != TUK_Reference && TUK != TUK_Friend &&
14736 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14737 return nullptr;
14738
14739 // If this is a named struct, check to see if there was a previous forward
14740 // declaration or definition.
14741 // FIXME: We're looking into outer scopes here, even when we
14742 // shouldn't be. Doing so can result in ambiguities that we
14743 // shouldn't be diagnosing.
14744 LookupName(Previous, S);
14745
14746 // When declaring or defining a tag, ignore ambiguities introduced
14747 // by types using'ed into this scope.
14748 if (Previous.isAmbiguous() &&
14749 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14750 LookupResult::Filter F = Previous.makeFilter();
14751 while (F.hasNext()) {
14752 NamedDecl *ND = F.next();
14753 if (!ND->getDeclContext()->getRedeclContext()->Equals(
14754 SearchDC->getRedeclContext()))
14755 F.erase();
14756 }
14757 F.done();
14758 }
14759
14760 // C++11 [namespace.memdef]p3:
14761 // If the name in a friend declaration is neither qualified nor
14762 // a template-id and the declaration is a function or an
14763 // elaborated-type-specifier, the lookup to determine whether
14764 // the entity has been previously declared shall not consider
14765 // any scopes outside the innermost enclosing namespace.
14766 //
14767 // MSVC doesn't implement the above rule for types, so a friend tag
14768 // declaration may be a redeclaration of a type declared in an enclosing
14769 // scope. They do implement this rule for friend functions.
14770 //
14771 // Does it matter that this should be by scope instead of by
14772 // semantic context?
14773 if (!Previous.empty() && TUK == TUK_Friend) {
14774 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14775 LookupResult::Filter F = Previous.makeFilter();
14776 bool FriendSawTagOutsideEnclosingNamespace = false;
14777 while (F.hasNext()) {
14778 NamedDecl *ND = F.next();
14779 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14780 if (DC->isFileContext() &&
14781 !EnclosingNS->Encloses(ND->getDeclContext())) {
14782 if (getLangOpts().MSVCCompat)
14783 FriendSawTagOutsideEnclosingNamespace = true;
14784 else
14785 F.erase();
14786 }
14787 }
14788 F.done();
14789
14790 // Diagnose this MSVC extension in the easy case where lookup would have
14791 // unambiguously found something outside the enclosing namespace.
14792 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14793 NamedDecl *ND = Previous.getFoundDecl();
14794 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14795 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14796 }
14797 }
14798
14799 // Note: there used to be some attempt at recovery here.
14800 if (Previous.isAmbiguous())
14801 return nullptr;
14802
14803 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14804 // FIXME: This makes sure that we ignore the contexts associated
14805 // with C structs, unions, and enums when looking for a matching
14806 // tag declaration or definition. See the similar lookup tweak
14807 // in Sema::LookupName; is there a better way to deal with this?
14808 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14809 SearchDC = SearchDC->getParent();
14810 }
14811 }
14812
14813 if (Previous.isSingleResult() &&
14814 Previous.getFoundDecl()->isTemplateParameter()) {
14815 // Maybe we will complain about the shadowed template parameter.
14816 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14817 // Just pretend that we didn't see the previous declaration.
14818 Previous.clear();
14819 }
14820
14821 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14822 DC->Equals(getStdNamespace())) {
14823 if (Name->isStr("bad_alloc")) {
14824 // This is a declaration of or a reference to "std::bad_alloc".
14825 isStdBadAlloc = true;
14826
14827 // If std::bad_alloc has been implicitly declared (but made invisible to
14828 // name lookup), fill in this implicit declaration as the previous
14829 // declaration, so that the declarations get chained appropriately.
14830 if (Previous.empty() && StdBadAlloc)
14831 Previous.addDecl(getStdBadAlloc());
14832 } else if (Name->isStr("align_val_t")) {
14833 isStdAlignValT = true;
14834 if (Previous.empty() && StdAlignValT)
14835 Previous.addDecl(getStdAlignValT());
14836 }
14837 }
14838
14839 // If we didn't find a previous declaration, and this is a reference
14840 // (or friend reference), move to the correct scope. In C++, we
14841 // also need to do a redeclaration lookup there, just in case
14842 // there's a shadow friend decl.
14843 if (Name && Previous.empty() &&
14844 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14845 if (Invalid) goto CreateNewDecl;
14846 assert(SS.isEmpty());
14847
14848 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14849 // C++ [basic.scope.pdecl]p5:
14850 // -- for an elaborated-type-specifier of the form
14851 //
14852 // class-key identifier
14853 //
14854 // if the elaborated-type-specifier is used in the
14855 // decl-specifier-seq or parameter-declaration-clause of a
14856 // function defined in namespace scope, the identifier is
14857 // declared as a class-name in the namespace that contains
14858 // the declaration; otherwise, except as a friend
14859 // declaration, the identifier is declared in the smallest
14860 // non-class, non-function-prototype scope that contains the
14861 // declaration.
14862 //
14863 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14864 // C structs and unions.
14865 //
14866 // It is an error in C++ to declare (rather than define) an enum
14867 // type, including via an elaborated type specifier. We'll
14868 // diagnose that later; for now, declare the enum in the same
14869 // scope as we would have picked for any other tag type.
14870 //
14871 // GNU C also supports this behavior as part of its incomplete
14872 // enum types extension, while GNU C++ does not.
14873 //
14874 // Find the context where we'll be declaring the tag.
14875 // FIXME: We would like to maintain the current DeclContext as the
14876 // lexical context,
14877 SearchDC = getTagInjectionContext(SearchDC);
14878
14879 // Find the scope where we'll be declaring the tag.
14880 S = getTagInjectionScope(S, getLangOpts());
14881 } else {
14882 assert(TUK == TUK_Friend);
14883 // C++ [namespace.memdef]p3:
14884 // If a friend declaration in a non-local class first declares a
14885 // class or function, the friend class or function is a member of
14886 // the innermost enclosing namespace.
14887 SearchDC = SearchDC->getEnclosingNamespaceContext();
14888 }
14889
14890 // In C++, we need to do a redeclaration lookup to properly
14891 // diagnose some problems.
14892 // FIXME: redeclaration lookup is also used (with and without C++) to find a
14893 // hidden declaration so that we don't get ambiguity errors when using a
14894 // type declared by an elaborated-type-specifier. In C that is not correct
14895 // and we should instead merge compatible types found by lookup.
14896 if (getLangOpts().CPlusPlus) {
14897 Previous.setRedeclarationKind(forRedeclarationInCurContext());
14898 LookupQualifiedName(Previous, SearchDC);
14899 } else {
14900 Previous.setRedeclarationKind(forRedeclarationInCurContext());
14901 LookupName(Previous, S);
14902 }
14903 }
14904
14905 // If we have a known previous declaration to use, then use it.
14906 if (Previous.empty() && SkipBody && SkipBody->Previous)
14907 Previous.addDecl(SkipBody->Previous);
14908
14909 if (!Previous.empty()) {
14910 NamedDecl *PrevDecl = Previous.getFoundDecl();
14911 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14912
14913 // It's okay to have a tag decl in the same scope as a typedef
14914 // which hides a tag decl in the same scope. Finding this
14915 // insanity with a redeclaration lookup can only actually happen
14916 // in C++.
14917 //
14918 // This is also okay for elaborated-type-specifiers, which is
14919 // technically forbidden by the current standard but which is
14920 // okay according to the likely resolution of an open issue;
14921 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14922 if (getLangOpts().CPlusPlus) {
14923 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14924 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14925 TagDecl *Tag = TT->getDecl();
14926 if (Tag->getDeclName() == Name &&
14927 Tag->getDeclContext()->getRedeclContext()
14928 ->Equals(TD->getDeclContext()->getRedeclContext())) {
14929 PrevDecl = Tag;
14930 Previous.clear();
14931 Previous.addDecl(Tag);
14932 Previous.resolveKind();
14933 }
14934 }
14935 }
14936 }
14937
14938 // If this is a redeclaration of a using shadow declaration, it must
14939 // declare a tag in the same context. In MSVC mode, we allow a
14940 // redefinition if either context is within the other.
14941 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14942 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14943 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14944 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14945 !(OldTag && isAcceptableTagRedeclContext(
14946 *this, OldTag->getDeclContext(), SearchDC))) {
14947 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14948 Diag(Shadow->getTargetDecl()->getLocation(),
14949 diag::note_using_decl_target);
14950 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14951 << 0;
14952 // Recover by ignoring the old declaration.
14953 Previous.clear();
14954 goto CreateNewDecl;
14955 }
14956 }
14957
14958 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14959 // If this is a use of a previous tag, or if the tag is already declared
14960 // in the same scope (so that the definition/declaration completes or
14961 // rementions the tag), reuse the decl.
14962 if (TUK == TUK_Reference || TUK == TUK_Friend ||
14963 isDeclInScope(DirectPrevDecl, SearchDC, S,
14964 SS.isNotEmpty() || isMemberSpecialization)) {
14965 // Make sure that this wasn't declared as an enum and now used as a
14966 // struct or something similar.
14967 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14968 TUK == TUK_Definition, KWLoc,
14969 Name)) {
14970 bool SafeToContinue
14971 = (PrevTagDecl->getTagKind() != TTK_Enum &&
14972 Kind != TTK_Enum);
14973 if (SafeToContinue)
14974 Diag(KWLoc, diag::err_use_with_wrong_tag)
14975 << Name
14976 << FixItHint::CreateReplacement(SourceRange(KWLoc),
14977 PrevTagDecl->getKindName());
14978 else
14979 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14980 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14981
14982 if (SafeToContinue)
14983 Kind = PrevTagDecl->getTagKind();
14984 else {
14985 // Recover by making this an anonymous redefinition.
14986 Name = nullptr;
14987 Previous.clear();
14988 Invalid = true;
14989 }
14990 }
14991
14992 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14993 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14994
14995 // If this is an elaborated-type-specifier for a scoped enumeration,
14996 // the 'class' keyword is not necessary and not permitted.
14997 if (TUK == TUK_Reference || TUK == TUK_Friend) {
14998 if (ScopedEnum)
14999 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15000 << PrevEnum->isScoped()
15001 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15002 return PrevTagDecl;
15003 }
15004
15005 QualType EnumUnderlyingTy;
15006 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15007 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15008 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15009 EnumUnderlyingTy = QualType(T, 0);
15010
15011 // All conflicts with previous declarations are recovered by
15012 // returning the previous declaration, unless this is a definition,
15013 // in which case we want the caller to bail out.
15014 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15015 ScopedEnum, EnumUnderlyingTy,
15016 IsFixed, PrevEnum))
15017 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15018 }
15019
15020 // C++11 [class.mem]p1:
15021 // A member shall not be declared twice in the member-specification,
15022 // except that a nested class or member class template can be declared
15023 // and then later defined.
15024 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15025 S->isDeclScope(PrevDecl)) {
15026 Diag(NameLoc, diag::ext_member_redeclared);
15027 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15028 }
15029
15030 if (!Invalid) {
15031 // If this is a use, just return the declaration we found, unless
15032 // we have attributes.
15033 if (TUK == TUK_Reference || TUK == TUK_Friend) {
15034 if (!Attrs.empty()) {
15035 // FIXME: Diagnose these attributes. For now, we create a new
15036 // declaration to hold them.
15037 } else if (TUK == TUK_Reference &&
15038 (PrevTagDecl->getFriendObjectKind() ==
15039 Decl::FOK_Undeclared ||
15040 PrevDecl->getOwningModule() != getCurrentModule()) &&
15041 SS.isEmpty()) {
15042 // This declaration is a reference to an existing entity, but
15043 // has different visibility from that entity: it either makes
15044 // a friend visible or it makes a type visible in a new module.
15045 // In either case, create a new declaration. We only do this if
15046 // the declaration would have meant the same thing if no prior
15047 // declaration were found, that is, if it was found in the same
15048 // scope where we would have injected a declaration.
15049 if (!getTagInjectionContext(CurContext)->getRedeclContext()
15050 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15051 return PrevTagDecl;
15052 // This is in the injected scope, create a new declaration in
15053 // that scope.
15054 S = getTagInjectionScope(S, getLangOpts());
15055 } else {
15056 return PrevTagDecl;
15057 }
15058 }
15059
15060 // Diagnose attempts to redefine a tag.
15061 if (TUK == TUK_Definition) {
15062 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15063 // If we're defining a specialization and the previous definition
15064 // is from an implicit instantiation, don't emit an error
15065 // here; we'll catch this in the general case below.
15066 bool IsExplicitSpecializationAfterInstantiation = false;
15067 if (isMemberSpecialization) {
15068 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15069 IsExplicitSpecializationAfterInstantiation =
15070 RD->getTemplateSpecializationKind() !=
15071 TSK_ExplicitSpecialization;
15072 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15073 IsExplicitSpecializationAfterInstantiation =
15074 ED->getTemplateSpecializationKind() !=
15075 TSK_ExplicitSpecialization;
15076 }
15077
15078 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15079 // not keep more that one definition around (merge them). However,
15080 // ensure the decl passes the structural compatibility check in
15081 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15082 NamedDecl *Hidden = nullptr;
15083 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15084 // There is a definition of this tag, but it is not visible. We
15085 // explicitly make use of C++'s one definition rule here, and
15086 // assume that this definition is identical to the hidden one
15087 // we already have. Make the existing definition visible and
15088 // use it in place of this one.
15089 if (!getLangOpts().CPlusPlus) {
15090 // Postpone making the old definition visible until after we
15091 // complete parsing the new one and do the structural
15092 // comparison.
15093 SkipBody->CheckSameAsPrevious = true;
15094 SkipBody->New = createTagFromNewDecl();
15095 SkipBody->Previous = Def;
15096 return Def;
15097 } else {
15098 SkipBody->ShouldSkip = true;
15099 SkipBody->Previous = Def;
15100 makeMergedDefinitionVisible(Hidden);
15101 // Carry on and handle it like a normal definition. We'll
15102 // skip starting the definitiion later.
15103 }
15104 } else if (!IsExplicitSpecializationAfterInstantiation) {
15105 // A redeclaration in function prototype scope in C isn't
15106 // visible elsewhere, so merely issue a warning.
15107 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15108 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15109 else
15110 Diag(NameLoc, diag::err_redefinition) << Name;
15111 notePreviousDefinition(Def,
15112 NameLoc.isValid() ? NameLoc : KWLoc);
15113 // If this is a redefinition, recover by making this
15114 // struct be anonymous, which will make any later
15115 // references get the previous definition.
15116 Name = nullptr;
15117 Previous.clear();
15118 Invalid = true;
15119 }
15120 } else {
15121 // If the type is currently being defined, complain
15122 // about a nested redefinition.
15123 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15124 if (TD->isBeingDefined()) {
15125 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15126 Diag(PrevTagDecl->getLocation(),
15127 diag::note_previous_definition);
15128 Name = nullptr;
15129 Previous.clear();
15130 Invalid = true;
15131 }
15132 }
15133
15134 // Okay, this is definition of a previously declared or referenced
15135 // tag. We're going to create a new Decl for it.
15136 }
15137
15138 // Okay, we're going to make a redeclaration. If this is some kind
15139 // of reference, make sure we build the redeclaration in the same DC
15140 // as the original, and ignore the current access specifier.
15141 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15142 SearchDC = PrevTagDecl->getDeclContext();
15143 AS = AS_none;
15144 }
15145 }
15146 // If we get here we have (another) forward declaration or we
15147 // have a definition. Just create a new decl.
15148
15149 } else {
15150 // If we get here, this is a definition of a new tag type in a nested
15151 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15152 // new decl/type. We set PrevDecl to NULL so that the entities
15153 // have distinct types.
15154 Previous.clear();
15155 }
15156 // If we get here, we're going to create a new Decl. If PrevDecl
15157 // is non-NULL, it's a definition of the tag declared by
15158 // PrevDecl. If it's NULL, we have a new definition.
15159
15160 // Otherwise, PrevDecl is not a tag, but was found with tag
15161 // lookup. This is only actually possible in C++, where a few
15162 // things like templates still live in the tag namespace.
15163 } else {
15164 // Use a better diagnostic if an elaborated-type-specifier
15165 // found the wrong kind of type on the first
15166 // (non-redeclaration) lookup.
15167 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15168 !Previous.isForRedeclaration()) {
15169 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15170 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15171 << Kind;
15172 Diag(PrevDecl->getLocation(), diag::note_declared_at);
15173 Invalid = true;
15174
15175 // Otherwise, only diagnose if the declaration is in scope.
15176 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15177 SS.isNotEmpty() || isMemberSpecialization)) {
15178 // do nothing
15179
15180 // Diagnose implicit declarations introduced by elaborated types.
15181 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15182 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15183 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15184 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15185 Invalid = true;
15186
15187 // Otherwise it's a declaration. Call out a particularly common
15188 // case here.
15189 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15190 unsigned Kind = 0;
15191 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15192 Diag(NameLoc, diag::err_tag_definition_of_typedef)
15193 << Name << Kind << TND->getUnderlyingType();
15194 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15195 Invalid = true;
15196
15197 // Otherwise, diagnose.
15198 } else {
15199 // The tag name clashes with something else in the target scope,
15200 // issue an error and recover by making this tag be anonymous.
15201 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15202 notePreviousDefinition(PrevDecl, NameLoc);
15203 Name = nullptr;
15204 Invalid = true;
15205 }
15206
15207 // The existing declaration isn't relevant to us; we're in a
15208 // new scope, so clear out the previous declaration.
15209 Previous.clear();
15210 }
15211 }
15212
15213 CreateNewDecl:
15214
15215 TagDecl *PrevDecl = nullptr;
15216 if (Previous.isSingleResult())
15217 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15218
15219 // If there is an identifier, use the location of the identifier as the
15220 // location of the decl, otherwise use the location of the struct/union
15221 // keyword.
15222 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15223
15224 // Otherwise, create a new declaration. If there is a previous
15225 // declaration of the same entity, the two will be linked via
15226 // PrevDecl.
15227 TagDecl *New;
15228
15229 if (Kind == TTK_Enum) {
15230 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15231 // enum X { A, B, C } D; D should chain to X.
15232 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15233 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15234 ScopedEnumUsesClassTag, IsFixed);
15235
15236 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15237 StdAlignValT = cast<EnumDecl>(New);
15238
15239 // If this is an undefined enum, warn.
15240 if (TUK != TUK_Definition && !Invalid) {
15241 TagDecl *Def;
15242 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15243 // C++0x: 7.2p2: opaque-enum-declaration.
15244 // Conflicts are diagnosed above. Do nothing.
15245 }
15246 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15247 Diag(Loc, diag::ext_forward_ref_enum_def)
15248 << New;
15249 Diag(Def->getLocation(), diag::note_previous_definition);
15250 } else {
15251 unsigned DiagID = diag::ext_forward_ref_enum;
15252 if (getLangOpts().MSVCCompat)
15253 DiagID = diag::ext_ms_forward_ref_enum;
15254 else if (getLangOpts().CPlusPlus)
15255 DiagID = diag::err_forward_ref_enum;
15256 Diag(Loc, DiagID);
15257 }
15258 }
15259
15260 if (EnumUnderlying) {
15261 EnumDecl *ED = cast<EnumDecl>(New);
15262 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15263 ED->setIntegerTypeSourceInfo(TI);
15264 else
15265 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15266 ED->setPromotionType(ED->getIntegerType());
15267 assert(ED->isComplete() && "enum with type should be complete");
15268 }
15269 } else {
15270 // struct/union/class
15271
15272 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15273 // struct X { int A; } D; D should chain to X.
15274 if (getLangOpts().CPlusPlus) {
15275 // FIXME: Look for a way to use RecordDecl for simple structs.
15276 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15277 cast_or_null<CXXRecordDecl>(PrevDecl));
15278
15279 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15280 StdBadAlloc = cast<CXXRecordDecl>(New);
15281 } else
15282 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15283 cast_or_null<RecordDecl>(PrevDecl));
15284 }
15285
15286 // C++11 [dcl.type]p3:
15287 // A type-specifier-seq shall not define a class or enumeration [...].
15288 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15289 TUK == TUK_Definition) {
15290 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15291 << Context.getTagDeclType(New);
15292 Invalid = true;
15293 }
15294
15295 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15296 DC->getDeclKind() == Decl::Enum) {
15297 Diag(New->getLocation(), diag::err_type_defined_in_enum)
15298 << Context.getTagDeclType(New);
15299 Invalid = true;
15300 }
15301
15302 // Maybe add qualifier info.
15303 if (SS.isNotEmpty()) {
15304 if (SS.isSet()) {
15305 // If this is either a declaration or a definition, check the
15306 // nested-name-specifier against the current context.
15307 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15308 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15309 isMemberSpecialization))
15310 Invalid = true;
15311
15312 New->setQualifierInfo(SS.getWithLocInContext(Context));
15313 if (TemplateParameterLists.size() > 0) {
15314 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15315 }
15316 }
15317 else
15318 Invalid = true;
15319 }
15320
15321 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15322 // Add alignment attributes if necessary; these attributes are checked when
15323 // the ASTContext lays out the structure.
15324 //
15325 // It is important for implementing the correct semantics that this
15326 // happen here (in ActOnTag). The #pragma pack stack is
15327 // maintained as a result of parser callbacks which can occur at
15328 // many points during the parsing of a struct declaration (because
15329 // the #pragma tokens are effectively skipped over during the
15330 // parsing of the struct).
15331 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15332 AddAlignmentAttributesForRecord(RD);
15333 AddMsStructLayoutForRecord(RD);
15334 }
15335 }
15336
15337 if (ModulePrivateLoc.isValid()) {
15338 if (isMemberSpecialization)
15339 Diag(New->getLocation(), diag::err_module_private_specialization)
15340 << 2
15341 << FixItHint::CreateRemoval(ModulePrivateLoc);
15342 // __module_private__ does not apply to local classes. However, we only
15343 // diagnose this as an error when the declaration specifiers are
15344 // freestanding. Here, we just ignore the __module_private__.
15345 else if (!SearchDC->isFunctionOrMethod())
15346 New->setModulePrivate();
15347 }
15348
15349 // If this is a specialization of a member class (of a class template),
15350 // check the specialization.
15351 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15352 Invalid = true;
15353
15354 // If we're declaring or defining a tag in function prototype scope in C,
15355 // note that this type can only be used within the function and add it to
15356 // the list of decls to inject into the function definition scope.
15357 if ((Name || Kind == TTK_Enum) &&
15358 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15359 if (getLangOpts().CPlusPlus) {
15360 // C++ [dcl.fct]p6:
15361 // Types shall not be defined in return or parameter types.
15362 if (TUK == TUK_Definition && !IsTypeSpecifier) {
15363 Diag(Loc, diag::err_type_defined_in_param_type)
15364 << Name;
15365 Invalid = true;
15366 }
15367 } else if (!PrevDecl) {
15368 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15369 }
15370 }
15371
15372 if (Invalid)
15373 New->setInvalidDecl();
15374
15375 // Set the lexical context. If the tag has a C++ scope specifier, the
15376 // lexical context will be different from the semantic context.
15377 New->setLexicalDeclContext(CurContext);
15378
15379 // Mark this as a friend decl if applicable.
15380 // In Microsoft mode, a friend declaration also acts as a forward
15381 // declaration so we always pass true to setObjectOfFriendDecl to make
15382 // the tag name visible.
15383 if (TUK == TUK_Friend)
15384 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15385
15386 // Set the access specifier.
15387 if (!Invalid && SearchDC->isRecord())
15388 SetMemberAccessSpecifier(New, PrevDecl, AS);
15389
15390 if (PrevDecl)
15391 CheckRedeclarationModuleOwnership(New, PrevDecl);
15392
15393 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15394 New->startDefinition();
15395
15396 ProcessDeclAttributeList(S, New, Attrs);
15397 AddPragmaAttributes(S, New);
15398
15399 // If this has an identifier, add it to the scope stack.
15400 if (TUK == TUK_Friend) {
15401 // We might be replacing an existing declaration in the lookup tables;
15402 // if so, borrow its access specifier.
15403 if (PrevDecl)
15404 New->setAccess(PrevDecl->getAccess());
15405
15406 DeclContext *DC = New->getDeclContext()->getRedeclContext();
15407 DC->makeDeclVisibleInContext(New);
15408 if (Name) // can be null along some error paths
15409 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15410 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15411 } else if (Name) {
15412 S = getNonFieldDeclScope(S);
15413 PushOnScopeChains(New, S, true);
15414 } else {
15415 CurContext->addDecl(New);
15416 }
15417
15418 // If this is the C FILE type, notify the AST context.
15419 if (IdentifierInfo *II = New->getIdentifier())
15420 if (!New->isInvalidDecl() &&
15421 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15422 II->isStr("FILE"))
15423 Context.setFILEDecl(New);
15424
15425 if (PrevDecl)
15426 mergeDeclAttributes(New, PrevDecl);
15427
15428 // If there's a #pragma GCC visibility in scope, set the visibility of this
15429 // record.
15430 AddPushedVisibilityAttribute(New);
15431
15432 if (isMemberSpecialization && !New->isInvalidDecl())
15433 CompleteMemberSpecialization(New, Previous);
15434
15435 OwnedDecl = true;
15436 // In C++, don't return an invalid declaration. We can't recover well from
15437 // the cases where we make the type anonymous.
15438 if (Invalid && getLangOpts().CPlusPlus) {
15439 if (New->isBeingDefined())
15440 if (auto RD = dyn_cast<RecordDecl>(New))
15441 RD->completeDefinition();
15442 return nullptr;
15443 } else if (SkipBody && SkipBody->ShouldSkip) {
15444 return SkipBody->Previous;
15445 } else {
15446 return New;
15447 }
15448 }
15449
ActOnTagStartDefinition(Scope * S,Decl * TagD)15450 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15451 AdjustDeclIfTemplate(TagD);
15452 TagDecl *Tag = cast<TagDecl>(TagD);
15453
15454 // Enter the tag context.
15455 PushDeclContext(S, Tag);
15456
15457 ActOnDocumentableDecl(TagD);
15458
15459 // If there's a #pragma GCC visibility in scope, set the visibility of this
15460 // record.
15461 AddPushedVisibilityAttribute(Tag);
15462 }
15463
ActOnDuplicateDefinition(DeclSpec & DS,Decl * Prev,SkipBodyInfo & SkipBody)15464 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15465 SkipBodyInfo &SkipBody) {
15466 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15467 return false;
15468
15469 // Make the previous decl visible.
15470 makeMergedDefinitionVisible(SkipBody.Previous);
15471 return true;
15472 }
15473
ActOnObjCContainerStartDefinition(Decl * IDecl)15474 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15475 assert(isa<ObjCContainerDecl>(IDecl) &&
15476 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15477 DeclContext *OCD = cast<DeclContext>(IDecl);
15478 assert(getContainingDC(OCD) == CurContext &&
15479 "The next DeclContext should be lexically contained in the current one.");
15480 CurContext = OCD;
15481 return IDecl;
15482 }
15483
ActOnStartCXXMemberDeclarations(Scope * S,Decl * TagD,SourceLocation FinalLoc,bool IsFinalSpelledSealed,SourceLocation LBraceLoc)15484 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15485 SourceLocation FinalLoc,
15486 bool IsFinalSpelledSealed,
15487 SourceLocation LBraceLoc) {
15488 AdjustDeclIfTemplate(TagD);
15489 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15490
15491 FieldCollector->StartClass();
15492
15493 if (!Record->getIdentifier())
15494 return;
15495
15496 if (FinalLoc.isValid())
15497 Record->addAttr(new (Context)
15498 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15499
15500 // C++ [class]p2:
15501 // [...] The class-name is also inserted into the scope of the
15502 // class itself; this is known as the injected-class-name. For
15503 // purposes of access checking, the injected-class-name is treated
15504 // as if it were a public member name.
15505 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15506 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15507 Record->getLocation(), Record->getIdentifier(),
15508 /*PrevDecl=*/nullptr,
15509 /*DelayTypeCreation=*/true);
15510 Context.getTypeDeclType(InjectedClassName, Record);
15511 InjectedClassName->setImplicit();
15512 InjectedClassName->setAccess(AS_public);
15513 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15514 InjectedClassName->setDescribedClassTemplate(Template);
15515 PushOnScopeChains(InjectedClassName, S);
15516 assert(InjectedClassName->isInjectedClassName() &&
15517 "Broken injected-class-name");
15518 }
15519
ActOnTagFinishDefinition(Scope * S,Decl * TagD,SourceRange BraceRange)15520 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15521 SourceRange BraceRange) {
15522 AdjustDeclIfTemplate(TagD);
15523 TagDecl *Tag = cast<TagDecl>(TagD);
15524 Tag->setBraceRange(BraceRange);
15525
15526 // Make sure we "complete" the definition even it is invalid.
15527 if (Tag->isBeingDefined()) {
15528 assert(Tag->isInvalidDecl() && "We should already have completed it");
15529 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15530 RD->completeDefinition();
15531 }
15532
15533 if (isa<CXXRecordDecl>(Tag)) {
15534 FieldCollector->FinishClass();
15535 }
15536
15537 // Exit this scope of this tag's definition.
15538 PopDeclContext();
15539
15540 if (getCurLexicalContext()->isObjCContainer() &&
15541 Tag->getDeclContext()->isFileContext())
15542 Tag->setTopLevelDeclInObjCContainer();
15543
15544 // Notify the consumer that we've defined a tag.
15545 if (!Tag->isInvalidDecl())
15546 Consumer.HandleTagDeclDefinition(Tag);
15547 }
15548
ActOnObjCContainerFinishDefinition()15549 void Sema::ActOnObjCContainerFinishDefinition() {
15550 // Exit this scope of this interface definition.
15551 PopDeclContext();
15552 }
15553
ActOnObjCTemporaryExitContainerContext(DeclContext * DC)15554 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15555 assert(DC == CurContext && "Mismatch of container contexts");
15556 OriginalLexicalContext = DC;
15557 ActOnObjCContainerFinishDefinition();
15558 }
15559
ActOnObjCReenterContainerContext(DeclContext * DC)15560 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15561 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15562 OriginalLexicalContext = nullptr;
15563 }
15564
ActOnTagDefinitionError(Scope * S,Decl * TagD)15565 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15566 AdjustDeclIfTemplate(TagD);
15567 TagDecl *Tag = cast<TagDecl>(TagD);
15568 Tag->setInvalidDecl();
15569
15570 // Make sure we "complete" the definition even it is invalid.
15571 if (Tag->isBeingDefined()) {
15572 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15573 RD->completeDefinition();
15574 }
15575
15576 // We're undoing ActOnTagStartDefinition here, not
15577 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15578 // the FieldCollector.
15579
15580 PopDeclContext();
15581 }
15582
15583 // Note that FieldName may be null for anonymous bitfields.
VerifyBitField(SourceLocation FieldLoc,IdentifierInfo * FieldName,QualType FieldTy,bool IsMsStruct,Expr * BitWidth,bool * ZeroWidth)15584 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15585 IdentifierInfo *FieldName,
15586 QualType FieldTy, bool IsMsStruct,
15587 Expr *BitWidth, bool *ZeroWidth) {
15588 // Default to true; that shouldn't confuse checks for emptiness
15589 if (ZeroWidth)
15590 *ZeroWidth = true;
15591
15592 // C99 6.7.2.1p4 - verify the field type.
15593 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15594 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15595 // Handle incomplete types with specific error.
15596 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15597 return ExprError();
15598 if (FieldName)
15599 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15600 << FieldName << FieldTy << BitWidth->getSourceRange();
15601 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15602 << FieldTy << BitWidth->getSourceRange();
15603 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15604 UPPC_BitFieldWidth))
15605 return ExprError();
15606
15607 // If the bit-width is type- or value-dependent, don't try to check
15608 // it now.
15609 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15610 return BitWidth;
15611
15612 llvm::APSInt Value;
15613 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15614 if (ICE.isInvalid())
15615 return ICE;
15616 BitWidth = ICE.get();
15617
15618 if (Value != 0 && ZeroWidth)
15619 *ZeroWidth = false;
15620
15621 // Zero-width bitfield is ok for anonymous field.
15622 if (Value == 0 && FieldName)
15623 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15624
15625 if (Value.isSigned() && Value.isNegative()) {
15626 if (FieldName)
15627 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15628 << FieldName << Value.toString(10);
15629 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15630 << Value.toString(10);
15631 }
15632
15633 if (!FieldTy->isDependentType()) {
15634 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15635 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15636 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15637
15638 // Over-wide bitfields are an error in C or when using the MSVC bitfield
15639 // ABI.
15640 bool CStdConstraintViolation =
15641 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15642 bool MSBitfieldViolation =
15643 Value.ugt(TypeStorageSize) &&
15644 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15645 if (CStdConstraintViolation || MSBitfieldViolation) {
15646 unsigned DiagWidth =
15647 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15648 if (FieldName)
15649 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15650 << FieldName << (unsigned)Value.getZExtValue()
15651 << !CStdConstraintViolation << DiagWidth;
15652
15653 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15654 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15655 << DiagWidth;
15656 }
15657
15658 // Warn on types where the user might conceivably expect to get all
15659 // specified bits as value bits: that's all integral types other than
15660 // 'bool'.
15661 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15662 if (FieldName)
15663 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15664 << FieldName << (unsigned)Value.getZExtValue()
15665 << (unsigned)TypeWidth;
15666 else
15667 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15668 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15669 }
15670 }
15671
15672 return BitWidth;
15673 }
15674
15675 /// ActOnField - Each field of a C struct/union is passed into this in order
15676 /// to create a FieldDecl object for it.
ActOnField(Scope * S,Decl * TagD,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth)15677 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15678 Declarator &D, Expr *BitfieldWidth) {
15679 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15680 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15681 /*InitStyle=*/ICIS_NoInit, AS_public);
15682 return Res;
15683 }
15684
15685 /// HandleField - Analyze a field of a C struct or a C++ data member.
15686 ///
HandleField(Scope * S,RecordDecl * Record,SourceLocation DeclStart,Declarator & D,Expr * BitWidth,InClassInitStyle InitStyle,AccessSpecifier AS)15687 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15688 SourceLocation DeclStart,
15689 Declarator &D, Expr *BitWidth,
15690 InClassInitStyle InitStyle,
15691 AccessSpecifier AS) {
15692 if (D.isDecompositionDeclarator()) {
15693 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15694 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15695 << Decomp.getSourceRange();
15696 return nullptr;
15697 }
15698
15699 IdentifierInfo *II = D.getIdentifier();
15700 SourceLocation Loc = DeclStart;
15701 if (II) Loc = D.getIdentifierLoc();
15702
15703 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15704 QualType T = TInfo->getType();
15705 if (getLangOpts().CPlusPlus) {
15706 CheckExtraCXXDefaultArguments(D);
15707
15708 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15709 UPPC_DataMemberType)) {
15710 D.setInvalidType();
15711 T = Context.IntTy;
15712 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15713 }
15714 }
15715
15716 DiagnoseFunctionSpecifiers(D.getDeclSpec());
15717
15718 if (D.getDeclSpec().isInlineSpecified())
15719 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15720 << getLangOpts().CPlusPlus17;
15721 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15722 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15723 diag::err_invalid_thread)
15724 << DeclSpec::getSpecifierName(TSCS);
15725
15726 // Check to see if this name was declared as a member previously
15727 NamedDecl *PrevDecl = nullptr;
15728 LookupResult Previous(*this, II, Loc, LookupMemberName,
15729 ForVisibleRedeclaration);
15730 LookupName(Previous, S);
15731 switch (Previous.getResultKind()) {
15732 case LookupResult::Found:
15733 case LookupResult::FoundUnresolvedValue:
15734 PrevDecl = Previous.getAsSingle<NamedDecl>();
15735 break;
15736
15737 case LookupResult::FoundOverloaded:
15738 PrevDecl = Previous.getRepresentativeDecl();
15739 break;
15740
15741 case LookupResult::NotFound:
15742 case LookupResult::NotFoundInCurrentInstantiation:
15743 case LookupResult::Ambiguous:
15744 break;
15745 }
15746 Previous.suppressDiagnostics();
15747
15748 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15749 // Maybe we will complain about the shadowed template parameter.
15750 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15751 // Just pretend that we didn't see the previous declaration.
15752 PrevDecl = nullptr;
15753 }
15754
15755 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15756 PrevDecl = nullptr;
15757
15758 bool Mutable
15759 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15760 SourceLocation TSSL = D.getBeginLoc();
15761 FieldDecl *NewFD
15762 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15763 TSSL, AS, PrevDecl, &D);
15764
15765 if (NewFD->isInvalidDecl())
15766 Record->setInvalidDecl();
15767
15768 if (D.getDeclSpec().isModulePrivateSpecified())
15769 NewFD->setModulePrivate();
15770
15771 if (NewFD->isInvalidDecl() && PrevDecl) {
15772 // Don't introduce NewFD into scope; there's already something
15773 // with the same name in the same scope.
15774 } else if (II) {
15775 PushOnScopeChains(NewFD, S);
15776 } else
15777 Record->addDecl(NewFD);
15778
15779 return NewFD;
15780 }
15781
15782 /// Build a new FieldDecl and check its well-formedness.
15783 ///
15784 /// This routine builds a new FieldDecl given the fields name, type,
15785 /// record, etc. \p PrevDecl should refer to any previous declaration
15786 /// with the same name and in the same scope as the field to be
15787 /// created.
15788 ///
15789 /// \returns a new FieldDecl.
15790 ///
15791 /// \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)15792 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15793 TypeSourceInfo *TInfo,
15794 RecordDecl *Record, SourceLocation Loc,
15795 bool Mutable, Expr *BitWidth,
15796 InClassInitStyle InitStyle,
15797 SourceLocation TSSL,
15798 AccessSpecifier AS, NamedDecl *PrevDecl,
15799 Declarator *D) {
15800 IdentifierInfo *II = Name.getAsIdentifierInfo();
15801 bool InvalidDecl = false;
15802 if (D) InvalidDecl = D->isInvalidType();
15803
15804 // If we receive a broken type, recover by assuming 'int' and
15805 // marking this declaration as invalid.
15806 if (T.isNull()) {
15807 InvalidDecl = true;
15808 T = Context.IntTy;
15809 }
15810
15811 QualType EltTy = Context.getBaseElementType(T);
15812 if (!EltTy->isDependentType()) {
15813 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15814 // Fields of incomplete type force their record to be invalid.
15815 Record->setInvalidDecl();
15816 InvalidDecl = true;
15817 } else {
15818 NamedDecl *Def;
15819 EltTy->isIncompleteType(&Def);
15820 if (Def && Def->isInvalidDecl()) {
15821 Record->setInvalidDecl();
15822 InvalidDecl = true;
15823 }
15824 }
15825 }
15826
15827 // TR 18037 does not allow fields to be declared with address space
15828 if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15829 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15830 Diag(Loc, diag::err_field_with_address_space);
15831 Record->setInvalidDecl();
15832 InvalidDecl = true;
15833 }
15834
15835 if (LangOpts.OpenCL) {
15836 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15837 // used as structure or union field: image, sampler, event or block types.
15838 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15839 T->isBlockPointerType()) {
15840 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15841 Record->setInvalidDecl();
15842 InvalidDecl = true;
15843 }
15844 // OpenCL v1.2 s6.9.c: bitfields are not supported.
15845 if (BitWidth) {
15846 Diag(Loc, diag::err_opencl_bitfields);
15847 InvalidDecl = true;
15848 }
15849 }
15850
15851 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15852 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15853 T.hasQualifiers()) {
15854 InvalidDecl = true;
15855 Diag(Loc, diag::err_anon_bitfield_qualifiers);
15856 }
15857
15858 // C99 6.7.2.1p8: A member of a structure or union may have any type other
15859 // than a variably modified type.
15860 if (!InvalidDecl && T->isVariablyModifiedType()) {
15861 bool SizeIsNegative;
15862 llvm::APSInt Oversized;
15863
15864 TypeSourceInfo *FixedTInfo =
15865 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15866 SizeIsNegative,
15867 Oversized);
15868 if (FixedTInfo) {
15869 Diag(Loc, diag::warn_illegal_constant_array_size);
15870 TInfo = FixedTInfo;
15871 T = FixedTInfo->getType();
15872 } else {
15873 if (SizeIsNegative)
15874 Diag(Loc, diag::err_typecheck_negative_array_size);
15875 else if (Oversized.getBoolValue())
15876 Diag(Loc, diag::err_array_too_large)
15877 << Oversized.toString(10);
15878 else
15879 Diag(Loc, diag::err_typecheck_field_variable_size);
15880 InvalidDecl = true;
15881 }
15882 }
15883
15884 // Fields can not have abstract class types
15885 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15886 diag::err_abstract_type_in_decl,
15887 AbstractFieldType))
15888 InvalidDecl = true;
15889
15890 bool ZeroWidth = false;
15891 if (InvalidDecl)
15892 BitWidth = nullptr;
15893 // If this is declared as a bit-field, check the bit-field.
15894 if (BitWidth) {
15895 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15896 &ZeroWidth).get();
15897 if (!BitWidth) {
15898 InvalidDecl = true;
15899 BitWidth = nullptr;
15900 ZeroWidth = false;
15901 }
15902 }
15903
15904 // Check that 'mutable' is consistent with the type of the declaration.
15905 if (!InvalidDecl && Mutable) {
15906 unsigned DiagID = 0;
15907 if (T->isReferenceType())
15908 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15909 : diag::err_mutable_reference;
15910 else if (T.isConstQualified())
15911 DiagID = diag::err_mutable_const;
15912
15913 if (DiagID) {
15914 SourceLocation ErrLoc = Loc;
15915 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15916 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15917 Diag(ErrLoc, DiagID);
15918 if (DiagID != diag::ext_mutable_reference) {
15919 Mutable = false;
15920 InvalidDecl = true;
15921 }
15922 }
15923 }
15924
15925 // C++11 [class.union]p8 (DR1460):
15926 // At most one variant member of a union may have a
15927 // brace-or-equal-initializer.
15928 if (InitStyle != ICIS_NoInit)
15929 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15930
15931 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15932 BitWidth, Mutable, InitStyle);
15933 if (InvalidDecl)
15934 NewFD->setInvalidDecl();
15935
15936 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15937 Diag(Loc, diag::err_duplicate_member) << II;
15938 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15939 NewFD->setInvalidDecl();
15940 }
15941
15942 if (!InvalidDecl && getLangOpts().CPlusPlus) {
15943 if (Record->isUnion()) {
15944 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15945 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15946 if (RDecl->getDefinition()) {
15947 // C++ [class.union]p1: An object of a class with a non-trivial
15948 // constructor, a non-trivial copy constructor, a non-trivial
15949 // destructor, or a non-trivial copy assignment operator
15950 // cannot be a member of a union, nor can an array of such
15951 // objects.
15952 if (CheckNontrivialField(NewFD))
15953 NewFD->setInvalidDecl();
15954 }
15955 }
15956
15957 // C++ [class.union]p1: If a union contains a member of reference type,
15958 // the program is ill-formed, except when compiling with MSVC extensions
15959 // enabled.
15960 if (EltTy->isReferenceType()) {
15961 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15962 diag::ext_union_member_of_reference_type :
15963 diag::err_union_member_of_reference_type)
15964 << NewFD->getDeclName() << EltTy;
15965 if (!getLangOpts().MicrosoftExt)
15966 NewFD->setInvalidDecl();
15967 }
15968 }
15969 }
15970
15971 // FIXME: We need to pass in the attributes given an AST
15972 // representation, not a parser representation.
15973 if (D) {
15974 // FIXME: The current scope is almost... but not entirely... correct here.
15975 ProcessDeclAttributes(getCurScope(), NewFD, *D);
15976
15977 if (NewFD->hasAttrs())
15978 CheckAlignasUnderalignment(NewFD);
15979 }
15980
15981 // In auto-retain/release, infer strong retension for fields of
15982 // retainable type.
15983 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15984 NewFD->setInvalidDecl();
15985
15986 if (T.isObjCGCWeak())
15987 Diag(Loc, diag::warn_attribute_weak_on_field);
15988
15989 NewFD->setAccess(AS);
15990 return NewFD;
15991 }
15992
CheckNontrivialField(FieldDecl * FD)15993 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15994 assert(FD);
15995 assert(getLangOpts().CPlusPlus && "valid check only for C++");
15996
15997 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15998 return false;
15999
16000 QualType EltTy = Context.getBaseElementType(FD->getType());
16001 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16002 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16003 if (RDecl->getDefinition()) {
16004 // We check for copy constructors before constructors
16005 // because otherwise we'll never get complaints about
16006 // copy constructors.
16007
16008 CXXSpecialMember member = CXXInvalid;
16009 // We're required to check for any non-trivial constructors. Since the
16010 // implicit default constructor is suppressed if there are any
16011 // user-declared constructors, we just need to check that there is a
16012 // trivial default constructor and a trivial copy constructor. (We don't
16013 // worry about move constructors here, since this is a C++98 check.)
16014 if (RDecl->hasNonTrivialCopyConstructor())
16015 member = CXXCopyConstructor;
16016 else if (!RDecl->hasTrivialDefaultConstructor())
16017 member = CXXDefaultConstructor;
16018 else if (RDecl->hasNonTrivialCopyAssignment())
16019 member = CXXCopyAssignment;
16020 else if (RDecl->hasNonTrivialDestructor())
16021 member = CXXDestructor;
16022
16023 if (member != CXXInvalid) {
16024 if (!getLangOpts().CPlusPlus11 &&
16025 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16026 // Objective-C++ ARC: it is an error to have a non-trivial field of
16027 // a union. However, system headers in Objective-C programs
16028 // occasionally have Objective-C lifetime objects within unions,
16029 // and rather than cause the program to fail, we make those
16030 // members unavailable.
16031 SourceLocation Loc = FD->getLocation();
16032 if (getSourceManager().isInSystemHeader(Loc)) {
16033 if (!FD->hasAttr<UnavailableAttr>())
16034 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16035 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16036 return false;
16037 }
16038 }
16039
16040 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16041 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16042 diag::err_illegal_union_or_anon_struct_member)
16043 << FD->getParent()->isUnion() << FD->getDeclName() << member;
16044 DiagnoseNontrivial(RDecl, member);
16045 return !getLangOpts().CPlusPlus11;
16046 }
16047 }
16048 }
16049
16050 return false;
16051 }
16052
16053 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16054 /// AST enum value.
16055 static ObjCIvarDecl::AccessControl
TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)16056 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16057 switch (ivarVisibility) {
16058 default: llvm_unreachable("Unknown visitibility kind");
16059 case tok::objc_private: return ObjCIvarDecl::Private;
16060 case tok::objc_public: return ObjCIvarDecl::Public;
16061 case tok::objc_protected: return ObjCIvarDecl::Protected;
16062 case tok::objc_package: return ObjCIvarDecl::Package;
16063 }
16064 }
16065
16066 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16067 /// in order to create an IvarDecl object for it.
ActOnIvar(Scope * S,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth,tok::ObjCKeywordKind Visibility)16068 Decl *Sema::ActOnIvar(Scope *S,
16069 SourceLocation DeclStart,
16070 Declarator &D, Expr *BitfieldWidth,
16071 tok::ObjCKeywordKind Visibility) {
16072
16073 IdentifierInfo *II = D.getIdentifier();
16074 Expr *BitWidth = (Expr*)BitfieldWidth;
16075 SourceLocation Loc = DeclStart;
16076 if (II) Loc = D.getIdentifierLoc();
16077
16078 // FIXME: Unnamed fields can be handled in various different ways, for
16079 // example, unnamed unions inject all members into the struct namespace!
16080
16081 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16082 QualType T = TInfo->getType();
16083
16084 if (BitWidth) {
16085 // 6.7.2.1p3, 6.7.2.1p4
16086 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16087 if (!BitWidth)
16088 D.setInvalidType();
16089 } else {
16090 // Not a bitfield.
16091
16092 // validate II.
16093
16094 }
16095 if (T->isReferenceType()) {
16096 Diag(Loc, diag::err_ivar_reference_type);
16097 D.setInvalidType();
16098 }
16099 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16100 // than a variably modified type.
16101 else if (T->isVariablyModifiedType()) {
16102 Diag(Loc, diag::err_typecheck_ivar_variable_size);
16103 D.setInvalidType();
16104 }
16105
16106 // Get the visibility (access control) for this ivar.
16107 ObjCIvarDecl::AccessControl ac =
16108 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16109 : ObjCIvarDecl::None;
16110 // Must set ivar's DeclContext to its enclosing interface.
16111 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16112 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16113 return nullptr;
16114 ObjCContainerDecl *EnclosingContext;
16115 if (ObjCImplementationDecl *IMPDecl =
16116 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16117 if (LangOpts.ObjCRuntime.isFragile()) {
16118 // Case of ivar declared in an implementation. Context is that of its class.
16119 EnclosingContext = IMPDecl->getClassInterface();
16120 assert(EnclosingContext && "Implementation has no class interface!");
16121 }
16122 else
16123 EnclosingContext = EnclosingDecl;
16124 } else {
16125 if (ObjCCategoryDecl *CDecl =
16126 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16127 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16128 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16129 return nullptr;
16130 }
16131 }
16132 EnclosingContext = EnclosingDecl;
16133 }
16134
16135 // Construct the decl.
16136 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16137 DeclStart, Loc, II, T,
16138 TInfo, ac, (Expr *)BitfieldWidth);
16139
16140 if (II) {
16141 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16142 ForVisibleRedeclaration);
16143 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16144 && !isa<TagDecl>(PrevDecl)) {
16145 Diag(Loc, diag::err_duplicate_member) << II;
16146 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16147 NewID->setInvalidDecl();
16148 }
16149 }
16150
16151 // Process attributes attached to the ivar.
16152 ProcessDeclAttributes(S, NewID, D);
16153
16154 if (D.isInvalidType())
16155 NewID->setInvalidDecl();
16156
16157 // In ARC, infer 'retaining' for ivars of retainable type.
16158 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16159 NewID->setInvalidDecl();
16160
16161 if (D.getDeclSpec().isModulePrivateSpecified())
16162 NewID->setModulePrivate();
16163
16164 if (II) {
16165 // FIXME: When interfaces are DeclContexts, we'll need to add
16166 // these to the interface.
16167 S->AddDecl(NewID);
16168 IdResolver.AddDecl(NewID);
16169 }
16170
16171 if (LangOpts.ObjCRuntime.isNonFragile() &&
16172 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16173 Diag(Loc, diag::warn_ivars_in_interface);
16174
16175 return NewID;
16176 }
16177
16178 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16179 /// class and class extensions. For every class \@interface and class
16180 /// extension \@interface, if the last ivar is a bitfield of any type,
16181 /// then add an implicit `char :0` ivar to the end of that interface.
ActOnLastBitfield(SourceLocation DeclLoc,SmallVectorImpl<Decl * > & AllIvarDecls)16182 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16183 SmallVectorImpl<Decl *> &AllIvarDecls) {
16184 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16185 return;
16186
16187 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16188 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16189
16190 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16191 return;
16192 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16193 if (!ID) {
16194 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16195 if (!CD->IsClassExtension())
16196 return;
16197 }
16198 // No need to add this to end of @implementation.
16199 else
16200 return;
16201 }
16202 // All conditions are met. Add a new bitfield to the tail end of ivars.
16203 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16204 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16205
16206 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16207 DeclLoc, DeclLoc, nullptr,
16208 Context.CharTy,
16209 Context.getTrivialTypeSourceInfo(Context.CharTy,
16210 DeclLoc),
16211 ObjCIvarDecl::Private, BW,
16212 true);
16213 AllIvarDecls.push_back(Ivar);
16214 }
16215
ActOnFields(Scope * S,SourceLocation RecLoc,Decl * EnclosingDecl,ArrayRef<Decl * > Fields,SourceLocation LBrac,SourceLocation RBrac,const ParsedAttributesView & Attrs)16216 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16217 ArrayRef<Decl *> Fields, SourceLocation LBrac,
16218 SourceLocation RBrac,
16219 const ParsedAttributesView &Attrs) {
16220 assert(EnclosingDecl && "missing record or interface decl");
16221
16222 // If this is an Objective-C @implementation or category and we have
16223 // new fields here we should reset the layout of the interface since
16224 // it will now change.
16225 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16226 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16227 switch (DC->getKind()) {
16228 default: break;
16229 case Decl::ObjCCategory:
16230 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16231 break;
16232 case Decl::ObjCImplementation:
16233 Context.
16234 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16235 break;
16236 }
16237 }
16238
16239 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16240 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16241
16242 // Start counting up the number of named members; make sure to include
16243 // members of anonymous structs and unions in the total.
16244 unsigned NumNamedMembers = 0;
16245 if (Record) {
16246 for (const auto *I : Record->decls()) {
16247 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16248 if (IFD->getDeclName())
16249 ++NumNamedMembers;
16250 }
16251 }
16252
16253 // Verify that all the fields are okay.
16254 SmallVector<FieldDecl*, 32> RecFields;
16255
16256 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16257 i != end; ++i) {
16258 FieldDecl *FD = cast<FieldDecl>(*i);
16259
16260 // Get the type for the field.
16261 const Type *FDTy = FD->getType().getTypePtr();
16262
16263 if (!FD->isAnonymousStructOrUnion()) {
16264 // Remember all fields written by the user.
16265 RecFields.push_back(FD);
16266 }
16267
16268 // If the field is already invalid for some reason, don't emit more
16269 // diagnostics about it.
16270 if (FD->isInvalidDecl()) {
16271 EnclosingDecl->setInvalidDecl();
16272 continue;
16273 }
16274
16275 // C99 6.7.2.1p2:
16276 // A structure or union shall not contain a member with
16277 // incomplete or function type (hence, a structure shall not
16278 // contain an instance of itself, but may contain a pointer to
16279 // an instance of itself), except that the last member of a
16280 // structure with more than one named member may have incomplete
16281 // array type; such a structure (and any union containing,
16282 // possibly recursively, a member that is such a structure)
16283 // shall not be a member of a structure or an element of an
16284 // array.
16285 bool IsLastField = (i + 1 == Fields.end());
16286 if (FDTy->isFunctionType()) {
16287 // Field declared as a function.
16288 Diag(FD->getLocation(), diag::err_field_declared_as_function)
16289 << FD->getDeclName();
16290 FD->setInvalidDecl();
16291 EnclosingDecl->setInvalidDecl();
16292 continue;
16293 } else if (FDTy->isIncompleteArrayType() &&
16294 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16295 if (Record) {
16296 // Flexible array member.
16297 // Microsoft and g++ is more permissive regarding flexible array.
16298 // It will accept flexible array in union and also
16299 // as the sole element of a struct/class.
16300 unsigned DiagID = 0;
16301 if (!Record->isUnion() && !IsLastField) {
16302 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16303 << FD->getDeclName() << FD->getType() << Record->getTagKind();
16304 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16305 FD->setInvalidDecl();
16306 EnclosingDecl->setInvalidDecl();
16307 continue;
16308 } else if (Record->isUnion())
16309 DiagID = getLangOpts().MicrosoftExt
16310 ? diag::ext_flexible_array_union_ms
16311 : getLangOpts().CPlusPlus
16312 ? diag::ext_flexible_array_union_gnu
16313 : diag::err_flexible_array_union;
16314 else if (NumNamedMembers < 1)
16315 DiagID = getLangOpts().MicrosoftExt
16316 ? diag::ext_flexible_array_empty_aggregate_ms
16317 : getLangOpts().CPlusPlus
16318 ? diag::ext_flexible_array_empty_aggregate_gnu
16319 : diag::err_flexible_array_empty_aggregate;
16320
16321 if (DiagID)
16322 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16323 << Record->getTagKind();
16324 // While the layout of types that contain virtual bases is not specified
16325 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16326 // virtual bases after the derived members. This would make a flexible
16327 // array member declared at the end of an object not adjacent to the end
16328 // of the type.
16329 if (CXXRecord && CXXRecord->getNumVBases() != 0)
16330 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16331 << FD->getDeclName() << Record->getTagKind();
16332 if (!getLangOpts().C99)
16333 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16334 << FD->getDeclName() << Record->getTagKind();
16335
16336 // If the element type has a non-trivial destructor, we would not
16337 // implicitly destroy the elements, so disallow it for now.
16338 //
16339 // FIXME: GCC allows this. We should probably either implicitly delete
16340 // the destructor of the containing class, or just allow this.
16341 QualType BaseElem = Context.getBaseElementType(FD->getType());
16342 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16343 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16344 << FD->getDeclName() << FD->getType();
16345 FD->setInvalidDecl();
16346 EnclosingDecl->setInvalidDecl();
16347 continue;
16348 }
16349 // Okay, we have a legal flexible array member at the end of the struct.
16350 Record->setHasFlexibleArrayMember(true);
16351 } else {
16352 // In ObjCContainerDecl ivars with incomplete array type are accepted,
16353 // unless they are followed by another ivar. That check is done
16354 // elsewhere, after synthesized ivars are known.
16355 }
16356 } else if (!FDTy->isDependentType() &&
16357 RequireCompleteType(FD->getLocation(), FD->getType(),
16358 diag::err_field_incomplete)) {
16359 // Incomplete type
16360 FD->setInvalidDecl();
16361 EnclosingDecl->setInvalidDecl();
16362 continue;
16363 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16364 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16365 // A type which contains a flexible array member is considered to be a
16366 // flexible array member.
16367 Record->setHasFlexibleArrayMember(true);
16368 if (!Record->isUnion()) {
16369 // If this is a struct/class and this is not the last element, reject
16370 // it. Note that GCC supports variable sized arrays in the middle of
16371 // structures.
16372 if (!IsLastField)
16373 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16374 << FD->getDeclName() << FD->getType();
16375 else {
16376 // We support flexible arrays at the end of structs in
16377 // other structs as an extension.
16378 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16379 << FD->getDeclName();
16380 }
16381 }
16382 }
16383 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16384 RequireNonAbstractType(FD->getLocation(), FD->getType(),
16385 diag::err_abstract_type_in_decl,
16386 AbstractIvarType)) {
16387 // Ivars can not have abstract class types
16388 FD->setInvalidDecl();
16389 }
16390 if (Record && FDTTy->getDecl()->hasObjectMember())
16391 Record->setHasObjectMember(true);
16392 if (Record && FDTTy->getDecl()->hasVolatileMember())
16393 Record->setHasVolatileMember(true);
16394 } else if (FDTy->isObjCObjectType()) {
16395 /// A field cannot be an Objective-c object
16396 Diag(FD->getLocation(), diag::err_statically_allocated_object)
16397 << FixItHint::CreateInsertion(FD->getLocation(), "*");
16398 QualType T = Context.getObjCObjectPointerType(FD->getType());
16399 FD->setType(T);
16400 } else if (getLangOpts().ObjC &&
16401 getLangOpts().getGC() != LangOptions::NonGC &&
16402 Record && !Record->hasObjectMember()) {
16403 if (FD->getType()->isObjCObjectPointerType() ||
16404 FD->getType().isObjCGCStrong())
16405 Record->setHasObjectMember(true);
16406 else if (Context.getAsArrayType(FD->getType())) {
16407 QualType BaseType = Context.getBaseElementType(FD->getType());
16408 if (BaseType->isRecordType() &&
16409 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
16410 Record->setHasObjectMember(true);
16411 else if (BaseType->isObjCObjectPointerType() ||
16412 BaseType.isObjCGCStrong())
16413 Record->setHasObjectMember(true);
16414 }
16415 }
16416
16417 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
16418 QualType FT = FD->getType();
16419 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16420 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16421 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16422 Record->isUnion())
16423 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16424 }
16425 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16426 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16427 Record->setNonTrivialToPrimitiveCopy(true);
16428 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16429 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16430 }
16431 if (FT.isDestructedType()) {
16432 Record->setNonTrivialToPrimitiveDestroy(true);
16433 Record->setParamDestroyedInCallee(true);
16434 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16435 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16436 }
16437
16438 if (const auto *RT = FT->getAs<RecordType>()) {
16439 if (RT->getDecl()->getArgPassingRestrictions() ==
16440 RecordDecl::APK_CanNeverPassInRegs)
16441 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16442 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16443 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16444 }
16445
16446 if (Record && FD->getType().isVolatileQualified())
16447 Record->setHasVolatileMember(true);
16448 // Keep track of the number of named members.
16449 if (FD->getIdentifier())
16450 ++NumNamedMembers;
16451 }
16452
16453 // Okay, we successfully defined 'Record'.
16454 if (Record) {
16455 bool Completed = false;
16456 if (CXXRecord) {
16457 if (!CXXRecord->isInvalidDecl()) {
16458 // Set access bits correctly on the directly-declared conversions.
16459 for (CXXRecordDecl::conversion_iterator
16460 I = CXXRecord->conversion_begin(),
16461 E = CXXRecord->conversion_end(); I != E; ++I)
16462 I.setAccess((*I)->getAccess());
16463 }
16464
16465 if (!CXXRecord->isDependentType()) {
16466 // Add any implicitly-declared members to this class.
16467 AddImplicitlyDeclaredMembersToClass(CXXRecord);
16468
16469 if (!CXXRecord->isInvalidDecl()) {
16470 // If we have virtual base classes, we may end up finding multiple
16471 // final overriders for a given virtual function. Check for this
16472 // problem now.
16473 if (CXXRecord->getNumVBases()) {
16474 CXXFinalOverriderMap FinalOverriders;
16475 CXXRecord->getFinalOverriders(FinalOverriders);
16476
16477 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16478 MEnd = FinalOverriders.end();
16479 M != MEnd; ++M) {
16480 for (OverridingMethods::iterator SO = M->second.begin(),
16481 SOEnd = M->second.end();
16482 SO != SOEnd; ++SO) {
16483 assert(SO->second.size() > 0 &&
16484 "Virtual function without overriding functions?");
16485 if (SO->second.size() == 1)
16486 continue;
16487
16488 // C++ [class.virtual]p2:
16489 // In a derived class, if a virtual member function of a base
16490 // class subobject has more than one final overrider the
16491 // program is ill-formed.
16492 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16493 << (const NamedDecl *)M->first << Record;
16494 Diag(M->first->getLocation(),
16495 diag::note_overridden_virtual_function);
16496 for (OverridingMethods::overriding_iterator
16497 OM = SO->second.begin(),
16498 OMEnd = SO->second.end();
16499 OM != OMEnd; ++OM)
16500 Diag(OM->Method->getLocation(), diag::note_final_overrider)
16501 << (const NamedDecl *)M->first << OM->Method->getParent();
16502
16503 Record->setInvalidDecl();
16504 }
16505 }
16506 CXXRecord->completeDefinition(&FinalOverriders);
16507 Completed = true;
16508 }
16509 }
16510 }
16511 }
16512
16513 if (!Completed)
16514 Record->completeDefinition();
16515
16516 // Handle attributes before checking the layout.
16517 ProcessDeclAttributeList(S, Record, Attrs);
16518
16519 // We may have deferred checking for a deleted destructor. Check now.
16520 if (CXXRecord) {
16521 auto *Dtor = CXXRecord->getDestructor();
16522 if (Dtor && Dtor->isImplicit() &&
16523 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16524 CXXRecord->setImplicitDestructorIsDeleted();
16525 SetDeclDeleted(Dtor, CXXRecord->getLocation());
16526 }
16527 }
16528
16529 if (Record->hasAttrs()) {
16530 CheckAlignasUnderalignment(Record);
16531
16532 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16533 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16534 IA->getRange(), IA->getBestCase(),
16535 IA->getSemanticSpelling());
16536 }
16537
16538 // Check if the structure/union declaration is a type that can have zero
16539 // size in C. For C this is a language extension, for C++ it may cause
16540 // compatibility problems.
16541 bool CheckForZeroSize;
16542 if (!getLangOpts().CPlusPlus) {
16543 CheckForZeroSize = true;
16544 } else {
16545 // For C++ filter out types that cannot be referenced in C code.
16546 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16547 CheckForZeroSize =
16548 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16549 !CXXRecord->isDependentType() &&
16550 CXXRecord->isCLike();
16551 }
16552 if (CheckForZeroSize) {
16553 bool ZeroSize = true;
16554 bool IsEmpty = true;
16555 unsigned NonBitFields = 0;
16556 for (RecordDecl::field_iterator I = Record->field_begin(),
16557 E = Record->field_end();
16558 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16559 IsEmpty = false;
16560 if (I->isUnnamedBitfield()) {
16561 if (!I->isZeroLengthBitField(Context))
16562 ZeroSize = false;
16563 } else {
16564 ++NonBitFields;
16565 QualType FieldType = I->getType();
16566 if (FieldType->isIncompleteType() ||
16567 !Context.getTypeSizeInChars(FieldType).isZero())
16568 ZeroSize = false;
16569 }
16570 }
16571
16572 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16573 // allowed in C++, but warn if its declaration is inside
16574 // extern "C" block.
16575 if (ZeroSize) {
16576 Diag(RecLoc, getLangOpts().CPlusPlus ?
16577 diag::warn_zero_size_struct_union_in_extern_c :
16578 diag::warn_zero_size_struct_union_compat)
16579 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16580 }
16581
16582 // Structs without named members are extension in C (C99 6.7.2.1p7),
16583 // but are accepted by GCC.
16584 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16585 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16586 diag::ext_no_named_members_in_struct_union)
16587 << Record->isUnion();
16588 }
16589 }
16590 } else {
16591 ObjCIvarDecl **ClsFields =
16592 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16593 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16594 ID->setEndOfDefinitionLoc(RBrac);
16595 // Add ivar's to class's DeclContext.
16596 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16597 ClsFields[i]->setLexicalDeclContext(ID);
16598 ID->addDecl(ClsFields[i]);
16599 }
16600 // Must enforce the rule that ivars in the base classes may not be
16601 // duplicates.
16602 if (ID->getSuperClass())
16603 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16604 } else if (ObjCImplementationDecl *IMPDecl =
16605 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16606 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16607 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16608 // Ivar declared in @implementation never belongs to the implementation.
16609 // Only it is in implementation's lexical context.
16610 ClsFields[I]->setLexicalDeclContext(IMPDecl);
16611 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16612 IMPDecl->setIvarLBraceLoc(LBrac);
16613 IMPDecl->setIvarRBraceLoc(RBrac);
16614 } else if (ObjCCategoryDecl *CDecl =
16615 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16616 // case of ivars in class extension; all other cases have been
16617 // reported as errors elsewhere.
16618 // FIXME. Class extension does not have a LocEnd field.
16619 // CDecl->setLocEnd(RBrac);
16620 // Add ivar's to class extension's DeclContext.
16621 // Diagnose redeclaration of private ivars.
16622 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16623 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16624 if (IDecl) {
16625 if (const ObjCIvarDecl *ClsIvar =
16626 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16627 Diag(ClsFields[i]->getLocation(),
16628 diag::err_duplicate_ivar_declaration);
16629 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16630 continue;
16631 }
16632 for (const auto *Ext : IDecl->known_extensions()) {
16633 if (const ObjCIvarDecl *ClsExtIvar
16634 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16635 Diag(ClsFields[i]->getLocation(),
16636 diag::err_duplicate_ivar_declaration);
16637 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16638 continue;
16639 }
16640 }
16641 }
16642 ClsFields[i]->setLexicalDeclContext(CDecl);
16643 CDecl->addDecl(ClsFields[i]);
16644 }
16645 CDecl->setIvarLBraceLoc(LBrac);
16646 CDecl->setIvarRBraceLoc(RBrac);
16647 }
16648 }
16649 }
16650
16651 /// Determine whether the given integral value is representable within
16652 /// the given type T.
isRepresentableIntegerValue(ASTContext & Context,llvm::APSInt & Value,QualType T)16653 static bool isRepresentableIntegerValue(ASTContext &Context,
16654 llvm::APSInt &Value,
16655 QualType T) {
16656 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16657 "Integral type required!");
16658 unsigned BitWidth = Context.getIntWidth(T);
16659
16660 if (Value.isUnsigned() || Value.isNonNegative()) {
16661 if (T->isSignedIntegerOrEnumerationType())
16662 --BitWidth;
16663 return Value.getActiveBits() <= BitWidth;
16664 }
16665 return Value.getMinSignedBits() <= BitWidth;
16666 }
16667
16668 // Given an integral type, return the next larger integral type
16669 // (or a NULL type of no such type exists).
getNextLargerIntegralType(ASTContext & Context,QualType T)16670 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16671 // FIXME: Int128/UInt128 support, which also needs to be introduced into
16672 // enum checking below.
16673 assert((T->isIntegralType(Context) ||
16674 T->isEnumeralType()) && "Integral type required!");
16675 const unsigned NumTypes = 4;
16676 QualType SignedIntegralTypes[NumTypes] = {
16677 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16678 };
16679 QualType UnsignedIntegralTypes[NumTypes] = {
16680 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16681 Context.UnsignedLongLongTy
16682 };
16683
16684 unsigned BitWidth = Context.getTypeSize(T);
16685 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16686 : UnsignedIntegralTypes;
16687 for (unsigned I = 0; I != NumTypes; ++I)
16688 if (Context.getTypeSize(Types[I]) > BitWidth)
16689 return Types[I];
16690
16691 return QualType();
16692 }
16693
CheckEnumConstant(EnumDecl * Enum,EnumConstantDecl * LastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,Expr * Val)16694 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16695 EnumConstantDecl *LastEnumConst,
16696 SourceLocation IdLoc,
16697 IdentifierInfo *Id,
16698 Expr *Val) {
16699 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16700 llvm::APSInt EnumVal(IntWidth);
16701 QualType EltTy;
16702
16703 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16704 Val = nullptr;
16705
16706 if (Val)
16707 Val = DefaultLvalueConversion(Val).get();
16708
16709 if (Val) {
16710 if (Enum->isDependentType() || Val->isTypeDependent())
16711 EltTy = Context.DependentTy;
16712 else {
16713 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16714 !getLangOpts().MSVCCompat) {
16715 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16716 // constant-expression in the enumerator-definition shall be a converted
16717 // constant expression of the underlying type.
16718 EltTy = Enum->getIntegerType();
16719 ExprResult Converted =
16720 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16721 CCEK_Enumerator);
16722 if (Converted.isInvalid())
16723 Val = nullptr;
16724 else
16725 Val = Converted.get();
16726 } else if (!Val->isValueDependent() &&
16727 !(Val = VerifyIntegerConstantExpression(Val,
16728 &EnumVal).get())) {
16729 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16730 } else {
16731 if (Enum->isComplete()) {
16732 EltTy = Enum->getIntegerType();
16733
16734 // In Obj-C and Microsoft mode, require the enumeration value to be
16735 // representable in the underlying type of the enumeration. In C++11,
16736 // we perform a non-narrowing conversion as part of converted constant
16737 // expression checking.
16738 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16739 if (getLangOpts().MSVCCompat) {
16740 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16741 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16742 } else
16743 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16744 } else
16745 Val = ImpCastExprToType(Val, EltTy,
16746 EltTy->isBooleanType() ?
16747 CK_IntegralToBoolean : CK_IntegralCast)
16748 .get();
16749 } else if (getLangOpts().CPlusPlus) {
16750 // C++11 [dcl.enum]p5:
16751 // If the underlying type is not fixed, the type of each enumerator
16752 // is the type of its initializing value:
16753 // - If an initializer is specified for an enumerator, the
16754 // initializing value has the same type as the expression.
16755 EltTy = Val->getType();
16756 } else {
16757 // C99 6.7.2.2p2:
16758 // The expression that defines the value of an enumeration constant
16759 // shall be an integer constant expression that has a value
16760 // representable as an int.
16761
16762 // Complain if the value is not representable in an int.
16763 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16764 Diag(IdLoc, diag::ext_enum_value_not_int)
16765 << EnumVal.toString(10) << Val->getSourceRange()
16766 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16767 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16768 // Force the type of the expression to 'int'.
16769 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16770 }
16771 EltTy = Val->getType();
16772 }
16773 }
16774 }
16775 }
16776
16777 if (!Val) {
16778 if (Enum->isDependentType())
16779 EltTy = Context.DependentTy;
16780 else if (!LastEnumConst) {
16781 // C++0x [dcl.enum]p5:
16782 // If the underlying type is not fixed, the type of each enumerator
16783 // is the type of its initializing value:
16784 // - If no initializer is specified for the first enumerator, the
16785 // initializing value has an unspecified integral type.
16786 //
16787 // GCC uses 'int' for its unspecified integral type, as does
16788 // C99 6.7.2.2p3.
16789 if (Enum->isFixed()) {
16790 EltTy = Enum->getIntegerType();
16791 }
16792 else {
16793 EltTy = Context.IntTy;
16794 }
16795 } else {
16796 // Assign the last value + 1.
16797 EnumVal = LastEnumConst->getInitVal();
16798 ++EnumVal;
16799 EltTy = LastEnumConst->getType();
16800
16801 // Check for overflow on increment.
16802 if (EnumVal < LastEnumConst->getInitVal()) {
16803 // C++0x [dcl.enum]p5:
16804 // If the underlying type is not fixed, the type of each enumerator
16805 // is the type of its initializing value:
16806 //
16807 // - Otherwise the type of the initializing value is the same as
16808 // the type of the initializing value of the preceding enumerator
16809 // unless the incremented value is not representable in that type,
16810 // in which case the type is an unspecified integral type
16811 // sufficient to contain the incremented value. If no such type
16812 // exists, the program is ill-formed.
16813 QualType T = getNextLargerIntegralType(Context, EltTy);
16814 if (T.isNull() || Enum->isFixed()) {
16815 // There is no integral type larger enough to represent this
16816 // value. Complain, then allow the value to wrap around.
16817 EnumVal = LastEnumConst->getInitVal();
16818 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16819 ++EnumVal;
16820 if (Enum->isFixed())
16821 // When the underlying type is fixed, this is ill-formed.
16822 Diag(IdLoc, diag::err_enumerator_wrapped)
16823 << EnumVal.toString(10)
16824 << EltTy;
16825 else
16826 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16827 << EnumVal.toString(10);
16828 } else {
16829 EltTy = T;
16830 }
16831
16832 // Retrieve the last enumerator's value, extent that type to the
16833 // type that is supposed to be large enough to represent the incremented
16834 // value, then increment.
16835 EnumVal = LastEnumConst->getInitVal();
16836 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16837 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16838 ++EnumVal;
16839
16840 // If we're not in C++, diagnose the overflow of enumerator values,
16841 // which in C99 means that the enumerator value is not representable in
16842 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16843 // permits enumerator values that are representable in some larger
16844 // integral type.
16845 if (!getLangOpts().CPlusPlus && !T.isNull())
16846 Diag(IdLoc, diag::warn_enum_value_overflow);
16847 } else if (!getLangOpts().CPlusPlus &&
16848 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16849 // Enforce C99 6.7.2.2p2 even when we compute the next value.
16850 Diag(IdLoc, diag::ext_enum_value_not_int)
16851 << EnumVal.toString(10) << 1;
16852 }
16853 }
16854 }
16855
16856 if (!EltTy->isDependentType()) {
16857 // Make the enumerator value match the signedness and size of the
16858 // enumerator's type.
16859 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16860 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16861 }
16862
16863 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16864 Val, EnumVal);
16865 }
16866
shouldSkipAnonEnumBody(Scope * S,IdentifierInfo * II,SourceLocation IILoc)16867 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16868 SourceLocation IILoc) {
16869 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16870 !getLangOpts().CPlusPlus)
16871 return SkipBodyInfo();
16872
16873 // We have an anonymous enum definition. Look up the first enumerator to
16874 // determine if we should merge the definition with an existing one and
16875 // skip the body.
16876 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16877 forRedeclarationInCurContext());
16878 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16879 if (!PrevECD)
16880 return SkipBodyInfo();
16881
16882 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16883 NamedDecl *Hidden;
16884 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16885 SkipBodyInfo Skip;
16886 Skip.Previous = Hidden;
16887 return Skip;
16888 }
16889
16890 return SkipBodyInfo();
16891 }
16892
ActOnEnumConstant(Scope * S,Decl * theEnumDecl,Decl * lastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,const ParsedAttributesView & Attrs,SourceLocation EqualLoc,Expr * Val)16893 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16894 SourceLocation IdLoc, IdentifierInfo *Id,
16895 const ParsedAttributesView &Attrs,
16896 SourceLocation EqualLoc, Expr *Val) {
16897 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16898 EnumConstantDecl *LastEnumConst =
16899 cast_or_null<EnumConstantDecl>(lastEnumConst);
16900
16901 // The scope passed in may not be a decl scope. Zip up the scope tree until
16902 // we find one that is.
16903 S = getNonFieldDeclScope(S);
16904
16905 // Verify that there isn't already something declared with this name in this
16906 // scope.
16907 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16908 LookupName(R, S);
16909 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16910
16911 if (PrevDecl && PrevDecl->isTemplateParameter()) {
16912 // Maybe we will complain about the shadowed template parameter.
16913 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16914 // Just pretend that we didn't see the previous declaration.
16915 PrevDecl = nullptr;
16916 }
16917
16918 // C++ [class.mem]p15:
16919 // If T is the name of a class, then each of the following shall have a name
16920 // different from T:
16921 // - every enumerator of every member of class T that is an unscoped
16922 // enumerated type
16923 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16924 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16925 DeclarationNameInfo(Id, IdLoc));
16926
16927 EnumConstantDecl *New =
16928 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16929 if (!New)
16930 return nullptr;
16931
16932 if (PrevDecl) {
16933 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16934 // Check for other kinds of shadowing not already handled.
16935 CheckShadow(New, PrevDecl, R);
16936 }
16937
16938 // When in C++, we may get a TagDecl with the same name; in this case the
16939 // enum constant will 'hide' the tag.
16940 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16941 "Received TagDecl when not in C++!");
16942 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16943 if (isa<EnumConstantDecl>(PrevDecl))
16944 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16945 else
16946 Diag(IdLoc, diag::err_redefinition) << Id;
16947 notePreviousDefinition(PrevDecl, IdLoc);
16948 return nullptr;
16949 }
16950 }
16951
16952 // Process attributes.
16953 ProcessDeclAttributeList(S, New, Attrs);
16954 AddPragmaAttributes(S, New);
16955
16956 // Register this decl in the current scope stack.
16957 New->setAccess(TheEnumDecl->getAccess());
16958 PushOnScopeChains(New, S);
16959
16960 ActOnDocumentableDecl(New);
16961
16962 return New;
16963 }
16964
16965 // Returns true when the enum initial expression does not trigger the
16966 // duplicate enum warning. A few common cases are exempted as follows:
16967 // Element2 = Element1
16968 // Element2 = Element1 + 1
16969 // Element2 = Element1 - 1
16970 // Where Element2 and Element1 are from the same enum.
ValidDuplicateEnum(EnumConstantDecl * ECD,EnumDecl * Enum)16971 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16972 Expr *InitExpr = ECD->getInitExpr();
16973 if (!InitExpr)
16974 return true;
16975 InitExpr = InitExpr->IgnoreImpCasts();
16976
16977 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16978 if (!BO->isAdditiveOp())
16979 return true;
16980 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16981 if (!IL)
16982 return true;
16983 if (IL->getValue() != 1)
16984 return true;
16985
16986 InitExpr = BO->getLHS();
16987 }
16988
16989 // This checks if the elements are from the same enum.
16990 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16991 if (!DRE)
16992 return true;
16993
16994 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16995 if (!EnumConstant)
16996 return true;
16997
16998 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16999 Enum)
17000 return true;
17001
17002 return false;
17003 }
17004
17005 // Emits a warning when an element is implicitly set a value that
17006 // a previous element has already been set to.
CheckForDuplicateEnumValues(Sema & S,ArrayRef<Decl * > Elements,EnumDecl * Enum,QualType EnumType)17007 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17008 EnumDecl *Enum, QualType EnumType) {
17009 // Avoid anonymous enums
17010 if (!Enum->getIdentifier())
17011 return;
17012
17013 // Only check for small enums.
17014 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17015 return;
17016
17017 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17018 return;
17019
17020 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17021 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17022
17023 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17024 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17025
17026 // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17027 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17028 llvm::APSInt Val = D->getInitVal();
17029 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17030 };
17031
17032 DuplicatesVector DupVector;
17033 ValueToVectorMap EnumMap;
17034
17035 // Populate the EnumMap with all values represented by enum constants without
17036 // an initializer.
17037 for (auto *Element : Elements) {
17038 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17039
17040 // Null EnumConstantDecl means a previous diagnostic has been emitted for
17041 // this constant. Skip this enum since it may be ill-formed.
17042 if (!ECD) {
17043 return;
17044 }
17045
17046 // Constants with initalizers are handled in the next loop.
17047 if (ECD->getInitExpr())
17048 continue;
17049
17050 // Duplicate values are handled in the next loop.
17051 EnumMap.insert({EnumConstantToKey(ECD), ECD});
17052 }
17053
17054 if (EnumMap.size() == 0)
17055 return;
17056
17057 // Create vectors for any values that has duplicates.
17058 for (auto *Element : Elements) {
17059 // The last loop returned if any constant was null.
17060 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17061 if (!ValidDuplicateEnum(ECD, Enum))
17062 continue;
17063
17064 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17065 if (Iter == EnumMap.end())
17066 continue;
17067
17068 DeclOrVector& Entry = Iter->second;
17069 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17070 // Ensure constants are different.
17071 if (D == ECD)
17072 continue;
17073
17074 // Create new vector and push values onto it.
17075 auto Vec = llvm::make_unique<ECDVector>();
17076 Vec->push_back(D);
17077 Vec->push_back(ECD);
17078
17079 // Update entry to point to the duplicates vector.
17080 Entry = Vec.get();
17081
17082 // Store the vector somewhere we can consult later for quick emission of
17083 // diagnostics.
17084 DupVector.emplace_back(std::move(Vec));
17085 continue;
17086 }
17087
17088 ECDVector *Vec = Entry.get<ECDVector*>();
17089 // Make sure constants are not added more than once.
17090 if (*Vec->begin() == ECD)
17091 continue;
17092
17093 Vec->push_back(ECD);
17094 }
17095
17096 // Emit diagnostics.
17097 for (const auto &Vec : DupVector) {
17098 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17099
17100 // Emit warning for one enum constant.
17101 auto *FirstECD = Vec->front();
17102 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17103 << FirstECD << FirstECD->getInitVal().toString(10)
17104 << FirstECD->getSourceRange();
17105
17106 // Emit one note for each of the remaining enum constants with
17107 // the same value.
17108 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17109 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17110 << ECD << ECD->getInitVal().toString(10)
17111 << ECD->getSourceRange();
17112 }
17113 }
17114
IsValueInFlagEnum(const EnumDecl * ED,const llvm::APInt & Val,bool AllowMask) const17115 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17116 bool AllowMask) const {
17117 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17118 assert(ED->isCompleteDefinition() && "expected enum definition");
17119
17120 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17121 llvm::APInt &FlagBits = R.first->second;
17122
17123 if (R.second) {
17124 for (auto *E : ED->enumerators()) {
17125 const auto &EVal = E->getInitVal();
17126 // Only single-bit enumerators introduce new flag values.
17127 if (EVal.isPowerOf2())
17128 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17129 }
17130 }
17131
17132 // A value is in a flag enum if either its bits are a subset of the enum's
17133 // flag bits (the first condition) or we are allowing masks and the same is
17134 // true of its complement (the second condition). When masks are allowed, we
17135 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17136 //
17137 // While it's true that any value could be used as a mask, the assumption is
17138 // that a mask will have all of the insignificant bits set. Anything else is
17139 // likely a logic error.
17140 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17141 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17142 }
17143
ActOnEnumBody(SourceLocation EnumLoc,SourceRange BraceRange,Decl * EnumDeclX,ArrayRef<Decl * > Elements,Scope * S,const ParsedAttributesView & Attrs)17144 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17145 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17146 const ParsedAttributesView &Attrs) {
17147 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17148 QualType EnumType = Context.getTypeDeclType(Enum);
17149
17150 ProcessDeclAttributeList(S, Enum, Attrs);
17151
17152 if (Enum->isDependentType()) {
17153 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17154 EnumConstantDecl *ECD =
17155 cast_or_null<EnumConstantDecl>(Elements[i]);
17156 if (!ECD) continue;
17157
17158 ECD->setType(EnumType);
17159 }
17160
17161 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17162 return;
17163 }
17164
17165 // TODO: If the result value doesn't fit in an int, it must be a long or long
17166 // long value. ISO C does not support this, but GCC does as an extension,
17167 // emit a warning.
17168 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17169 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17170 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17171
17172 // Verify that all the values are okay, compute the size of the values, and
17173 // reverse the list.
17174 unsigned NumNegativeBits = 0;
17175 unsigned NumPositiveBits = 0;
17176
17177 // Keep track of whether all elements have type int.
17178 bool AllElementsInt = true;
17179
17180 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17181 EnumConstantDecl *ECD =
17182 cast_or_null<EnumConstantDecl>(Elements[i]);
17183 if (!ECD) continue; // Already issued a diagnostic.
17184
17185 const llvm::APSInt &InitVal = ECD->getInitVal();
17186
17187 // Keep track of the size of positive and negative values.
17188 if (InitVal.isUnsigned() || InitVal.isNonNegative())
17189 NumPositiveBits = std::max(NumPositiveBits,
17190 (unsigned)InitVal.getActiveBits());
17191 else
17192 NumNegativeBits = std::max(NumNegativeBits,
17193 (unsigned)InitVal.getMinSignedBits());
17194
17195 // Keep track of whether every enum element has type int (very common).
17196 if (AllElementsInt)
17197 AllElementsInt = ECD->getType() == Context.IntTy;
17198 }
17199
17200 // Figure out the type that should be used for this enum.
17201 QualType BestType;
17202 unsigned BestWidth;
17203
17204 // C++0x N3000 [conv.prom]p3:
17205 // An rvalue of an unscoped enumeration type whose underlying
17206 // type is not fixed can be converted to an rvalue of the first
17207 // of the following types that can represent all the values of
17208 // the enumeration: int, unsigned int, long int, unsigned long
17209 // int, long long int, or unsigned long long int.
17210 // C99 6.4.4.3p2:
17211 // An identifier declared as an enumeration constant has type int.
17212 // The C99 rule is modified by a gcc extension
17213 QualType BestPromotionType;
17214
17215 bool Packed = Enum->hasAttr<PackedAttr>();
17216 // -fshort-enums is the equivalent to specifying the packed attribute on all
17217 // enum definitions.
17218 if (LangOpts.ShortEnums)
17219 Packed = true;
17220
17221 // If the enum already has a type because it is fixed or dictated by the
17222 // target, promote that type instead of analyzing the enumerators.
17223 if (Enum->isComplete()) {
17224 BestType = Enum->getIntegerType();
17225 if (BestType->isPromotableIntegerType())
17226 BestPromotionType = Context.getPromotedIntegerType(BestType);
17227 else
17228 BestPromotionType = BestType;
17229
17230 BestWidth = Context.getIntWidth(BestType);
17231 }
17232 else if (NumNegativeBits) {
17233 // If there is a negative value, figure out the smallest integer type (of
17234 // int/long/longlong) that fits.
17235 // If it's packed, check also if it fits a char or a short.
17236 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17237 BestType = Context.SignedCharTy;
17238 BestWidth = CharWidth;
17239 } else if (Packed && NumNegativeBits <= ShortWidth &&
17240 NumPositiveBits < ShortWidth) {
17241 BestType = Context.ShortTy;
17242 BestWidth = ShortWidth;
17243 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17244 BestType = Context.IntTy;
17245 BestWidth = IntWidth;
17246 } else {
17247 BestWidth = Context.getTargetInfo().getLongWidth();
17248
17249 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17250 BestType = Context.LongTy;
17251 } else {
17252 BestWidth = Context.getTargetInfo().getLongLongWidth();
17253
17254 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17255 Diag(Enum->getLocation(), diag::ext_enum_too_large);
17256 BestType = Context.LongLongTy;
17257 }
17258 }
17259 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17260 } else {
17261 // If there is no negative value, figure out the smallest type that fits
17262 // all of the enumerator values.
17263 // If it's packed, check also if it fits a char or a short.
17264 if (Packed && NumPositiveBits <= CharWidth) {
17265 BestType = Context.UnsignedCharTy;
17266 BestPromotionType = Context.IntTy;
17267 BestWidth = CharWidth;
17268 } else if (Packed && NumPositiveBits <= ShortWidth) {
17269 BestType = Context.UnsignedShortTy;
17270 BestPromotionType = Context.IntTy;
17271 BestWidth = ShortWidth;
17272 } else if (NumPositiveBits <= IntWidth) {
17273 BestType = Context.UnsignedIntTy;
17274 BestWidth = IntWidth;
17275 BestPromotionType
17276 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17277 ? Context.UnsignedIntTy : Context.IntTy;
17278 } else if (NumPositiveBits <=
17279 (BestWidth = Context.getTargetInfo().getLongWidth())) {
17280 BestType = Context.UnsignedLongTy;
17281 BestPromotionType
17282 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17283 ? Context.UnsignedLongTy : Context.LongTy;
17284 } else {
17285 BestWidth = Context.getTargetInfo().getLongLongWidth();
17286 assert(NumPositiveBits <= BestWidth &&
17287 "How could an initializer get larger than ULL?");
17288 BestType = Context.UnsignedLongLongTy;
17289 BestPromotionType
17290 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17291 ? Context.UnsignedLongLongTy : Context.LongLongTy;
17292 }
17293 }
17294
17295 // Loop over all of the enumerator constants, changing their types to match
17296 // the type of the enum if needed.
17297 for (auto *D : Elements) {
17298 auto *ECD = cast_or_null<EnumConstantDecl>(D);
17299 if (!ECD) continue; // Already issued a diagnostic.
17300
17301 // Standard C says the enumerators have int type, but we allow, as an
17302 // extension, the enumerators to be larger than int size. If each
17303 // enumerator value fits in an int, type it as an int, otherwise type it the
17304 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
17305 // that X has type 'int', not 'unsigned'.
17306
17307 // Determine whether the value fits into an int.
17308 llvm::APSInt InitVal = ECD->getInitVal();
17309
17310 // If it fits into an integer type, force it. Otherwise force it to match
17311 // the enum decl type.
17312 QualType NewTy;
17313 unsigned NewWidth;
17314 bool NewSign;
17315 if (!getLangOpts().CPlusPlus &&
17316 !Enum->isFixed() &&
17317 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17318 NewTy = Context.IntTy;
17319 NewWidth = IntWidth;
17320 NewSign = true;
17321 } else if (ECD->getType() == BestType) {
17322 // Already the right type!
17323 if (getLangOpts().CPlusPlus)
17324 // C++ [dcl.enum]p4: Following the closing brace of an
17325 // enum-specifier, each enumerator has the type of its
17326 // enumeration.
17327 ECD->setType(EnumType);
17328 continue;
17329 } else {
17330 NewTy = BestType;
17331 NewWidth = BestWidth;
17332 NewSign = BestType->isSignedIntegerOrEnumerationType();
17333 }
17334
17335 // Adjust the APSInt value.
17336 InitVal = InitVal.extOrTrunc(NewWidth);
17337 InitVal.setIsSigned(NewSign);
17338 ECD->setInitVal(InitVal);
17339
17340 // Adjust the Expr initializer and type.
17341 if (ECD->getInitExpr() &&
17342 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17343 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17344 CK_IntegralCast,
17345 ECD->getInitExpr(),
17346 /*base paths*/ nullptr,
17347 VK_RValue));
17348 if (getLangOpts().CPlusPlus)
17349 // C++ [dcl.enum]p4: Following the closing brace of an
17350 // enum-specifier, each enumerator has the type of its
17351 // enumeration.
17352 ECD->setType(EnumType);
17353 else
17354 ECD->setType(NewTy);
17355 }
17356
17357 Enum->completeDefinition(BestType, BestPromotionType,
17358 NumPositiveBits, NumNegativeBits);
17359
17360 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17361
17362 if (Enum->isClosedFlag()) {
17363 for (Decl *D : Elements) {
17364 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17365 if (!ECD) continue; // Already issued a diagnostic.
17366
17367 llvm::APSInt InitVal = ECD->getInitVal();
17368 if (InitVal != 0 && !InitVal.isPowerOf2() &&
17369 !IsValueInFlagEnum(Enum, InitVal, true))
17370 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17371 << ECD << Enum;
17372 }
17373 }
17374
17375 // Now that the enum type is defined, ensure it's not been underaligned.
17376 if (Enum->hasAttrs())
17377 CheckAlignasUnderalignment(Enum);
17378 }
17379
ActOnFileScopeAsmDecl(Expr * expr,SourceLocation StartLoc,SourceLocation EndLoc)17380 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17381 SourceLocation StartLoc,
17382 SourceLocation EndLoc) {
17383 StringLiteral *AsmString = cast<StringLiteral>(expr);
17384
17385 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17386 AsmString, StartLoc,
17387 EndLoc);
17388 CurContext->addDecl(New);
17389 return New;
17390 }
17391
ActOnPragmaRedefineExtname(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)17392 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17393 IdentifierInfo* AliasName,
17394 SourceLocation PragmaLoc,
17395 SourceLocation NameLoc,
17396 SourceLocation AliasNameLoc) {
17397 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17398 LookupOrdinaryName);
17399 AsmLabelAttr *Attr =
17400 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17401
17402 // If a declaration that:
17403 // 1) declares a function or a variable
17404 // 2) has external linkage
17405 // already exists, add a label attribute to it.
17406 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17407 if (isDeclExternC(PrevDecl))
17408 PrevDecl->addAttr(Attr);
17409 else
17410 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17411 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17412 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17413 } else
17414 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17415 }
17416
ActOnPragmaWeakID(IdentifierInfo * Name,SourceLocation PragmaLoc,SourceLocation NameLoc)17417 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17418 SourceLocation PragmaLoc,
17419 SourceLocation NameLoc) {
17420 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17421
17422 if (PrevDecl) {
17423 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17424 } else {
17425 (void)WeakUndeclaredIdentifiers.insert(
17426 std::pair<IdentifierInfo*,WeakInfo>
17427 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17428 }
17429 }
17430
ActOnPragmaWeakAlias(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)17431 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17432 IdentifierInfo* AliasName,
17433 SourceLocation PragmaLoc,
17434 SourceLocation NameLoc,
17435 SourceLocation AliasNameLoc) {
17436 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17437 LookupOrdinaryName);
17438 WeakInfo W = WeakInfo(Name, NameLoc);
17439
17440 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17441 if (!PrevDecl->hasAttr<AliasAttr>())
17442 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17443 DeclApplyPragmaWeak(TUScope, ND, W);
17444 } else {
17445 (void)WeakUndeclaredIdentifiers.insert(
17446 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17447 }
17448 }
17449
getObjCDeclContext() const17450 Decl *Sema::getObjCDeclContext() const {
17451 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17452 }
17453